* fix(webui): reconcile cross-session history by message ID * fix(sessions): preserve target authority and input ownership Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed. Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430. * fix(sessions): complete input identity integration across boundaries Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery. Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run. * fix(sessions): unify input recording and block remote commands * fix(webui): keep input ownership checks page-bounded Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages. Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed. * fix(webui): preserve response ownership during history replay * fix: resolve strict typing in response replay * fix: preserve continuation ownership during recovery * test: diagnose stuck gateway asyncio shutdown * test: retain gateway thread stack diagnostics * test(webui): stabilize native autoscroll browser setup
7107 lines
246 KiB
Python
7107 lines
246 KiB
Python
import asyncio
|
|
import json
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any, cast
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import httpx
|
|
import pytest
|
|
import websockets
|
|
from websockets.datastructures import Headers
|
|
from websockets.exceptions import ConnectionClosed
|
|
from websockets.frames import Close
|
|
|
|
from nanobot.bus.events import (
|
|
INBOUND_META_RUNTIME_CONTROL,
|
|
INBOUND_META_USER_SHELL,
|
|
OUTBOUND_META_AGENT_UI,
|
|
RUNTIME_CONTROL_SESSION_DISCARD,
|
|
InboundMessage,
|
|
OutboundMessage,
|
|
)
|
|
from nanobot.bus.outbound_events import (
|
|
ContextCompactionEvent,
|
|
GoalStateSyncEvent,
|
|
GoalStatusEvent,
|
|
ProgressEvent,
|
|
RecoveryStateEvent,
|
|
RetryStatusEvent,
|
|
RetryWaitEvent,
|
|
RuntimeModelUpdatedEvent,
|
|
SessionUpdatedEvent,
|
|
TurnEndEvent,
|
|
TurnModelUpdatedEvent,
|
|
UserInputEvent,
|
|
)
|
|
from nanobot.bus.queue import MessageBus
|
|
from nanobot.channels.manager import ChannelManager
|
|
from nanobot.channels.websocket import runtime as websocket_runtime
|
|
from nanobot.channels.websocket.runtime import (
|
|
WebSocketChannel,
|
|
WebSocketConfig,
|
|
_is_valid_chat_id,
|
|
_parse_envelope,
|
|
_parse_inbound_payload,
|
|
)
|
|
from nanobot.config.loader import load_config, save_config
|
|
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
|
|
from nanobot.pairing.events import PairingChanged
|
|
from nanobot.providers.base import LLMUsage
|
|
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
|
|
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
|
|
from nanobot.session import webui_turns as wth
|
|
from nanobot.session.display_history import HistoryKind
|
|
from nanobot.session.manager import Session, SessionManager
|
|
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
|
from nanobot.session.session_handles import session_handle_for_name
|
|
from nanobot.webui.gateway_services import GatewayServices, build_gateway_services
|
|
from nanobot.webui.http_utils import (
|
|
http_error as _http_error,
|
|
)
|
|
from nanobot.webui.http_utils import (
|
|
http_json_response as _http_json_response,
|
|
)
|
|
from nanobot.webui.http_utils import (
|
|
issue_route_secret_matches as _issue_route_secret_matches,
|
|
)
|
|
from nanobot.webui.http_utils import (
|
|
normalize_config_path as _normalize_config_path,
|
|
)
|
|
from nanobot.webui.http_utils import (
|
|
parse_query as _parse_query,
|
|
)
|
|
from nanobot.webui.http_utils import (
|
|
parse_request_path as _parse_request_path,
|
|
)
|
|
from nanobot.webui.metadata import (
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
|
WEBUI_MESSAGE_SOURCE_METADATA_KEY,
|
|
WEBUI_SYSTEM_COMMAND_TURN_PREFIX,
|
|
WEBUI_TURN_METADATA_KEY,
|
|
)
|
|
from nanobot.webui.settings_api import settings_payload, update_provider_settings
|
|
|
|
from .ws_test_client import http_get as _http_get
|
|
|
|
_PORT = 0
|
|
|
|
|
|
async def _register_running_turn(
|
|
chat_id: str, started_at: float, *, owner: str | None = None,
|
|
) -> None:
|
|
metadata = {}
|
|
if owner:
|
|
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = owner
|
|
await wth.publish_turn_run_status(
|
|
MessageBus(),
|
|
InboundMessage(channel="websocket", sender_id="user", chat_id=chat_id,
|
|
content="hello", metadata=metadata),
|
|
"running", started_at=started_at,
|
|
)
|
|
|
|
|
|
def _thread_conversation_events(body: dict[str, Any]) -> list[dict[str, Any]]:
|
|
messages: list[dict[str, Any]] = []
|
|
for event in body["events"]:
|
|
name = event.get("event")
|
|
if name == "turn_end":
|
|
if messages and messages[-1]["role"] == "assistant":
|
|
messages[-1]["latencyMs"] = event.get("latency_ms")
|
|
continue
|
|
if name == "user_message":
|
|
role = "user"
|
|
elif name == "message" and event.get("kind") is None:
|
|
role = "assistant"
|
|
elif name == "stream_end" and isinstance(event.get("text"), str):
|
|
role = "assistant"
|
|
else:
|
|
continue
|
|
messages.append({
|
|
"role": role,
|
|
"content": event.get("text", ""),
|
|
"latencyMs": event.get("latency_ms"),
|
|
})
|
|
return messages
|
|
|
|
|
|
def _ch(bus: Any, **kw: Any) -> WebSocketChannel:
|
|
image_generation_reload = kw.pop("image_generation_reload", None)
|
|
session_manager = kw.pop("session_manager", None)
|
|
cfg: dict[str, Any] = {
|
|
"enabled": True,
|
|
"allowFrom": ["*"],
|
|
"host": "127.0.0.1",
|
|
"port": _PORT,
|
|
"path": "/ws",
|
|
"websocketRequiresToken": False,
|
|
}
|
|
cfg.update(kw)
|
|
parsed = WebSocketConfig.model_validate(cfg)
|
|
gateway = build_gateway_services(
|
|
config=parsed,
|
|
bus=bus,
|
|
session_manager=session_manager,
|
|
static_dist_path=None,
|
|
workspace_path=Path.cwd(),
|
|
default_restrict_to_workspace=False,
|
|
runtime_model_name=None,
|
|
runtime_surface="browser",
|
|
runtime_capabilities_overrides=None,
|
|
image_generation_reload=image_generation_reload,
|
|
)
|
|
return WebSocketChannel(cfg, bus, gateway=gateway)
|
|
|
|
|
|
def _basic_handler(bus: Any, **kw: Any) -> GatewayServices:
|
|
cfg = WebSocketConfig.model_validate({
|
|
"enabled": True, "allowFrom": ["*"],
|
|
"host": "127.0.0.1", "port": _PORT,
|
|
"path": "/ws", "websocketRequiresToken": False,
|
|
"tokenIssueSecret": kw.get("token_issue_secret", ""),
|
|
})
|
|
return build_gateway_services(
|
|
config=cfg,
|
|
bus=bus,
|
|
session_manager=kw.get("session_manager"),
|
|
static_dist_path=None,
|
|
workspace_path=kw.get("workspace_path", Path.cwd()),
|
|
default_restrict_to_workspace=kw.get("default_restrict_to_workspace", False),
|
|
runtime_model_name=None,
|
|
runtime_surface=kw.get("runtime_surface", "browser"),
|
|
runtime_capabilities_overrides=kw.get("runtime_capabilities_overrides"),
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
async def start_listener():
|
|
"""Start test-owned ephemeral listeners and join them even if setup/assertions fail."""
|
|
listeners = []
|
|
|
|
async def start(channel: WebSocketChannel):
|
|
assert channel.config.port == 0
|
|
task = asyncio.create_task(channel.start())
|
|
listeners.append((channel, task))
|
|
async with asyncio.timeout(5):
|
|
while True:
|
|
if task.done():
|
|
await task
|
|
raise AssertionError("listener stopped before becoming ready")
|
|
server = channel._server
|
|
if server is not None and server.sockets and server.is_serving():
|
|
return server.sockets[0].getsockname()[1], task
|
|
await asyncio.sleep(0.01)
|
|
|
|
try:
|
|
yield start
|
|
finally:
|
|
for channel, task in reversed(listeners):
|
|
try:
|
|
await asyncio.wait_for(channel.stop(), timeout=5)
|
|
await asyncio.wait_for(asyncio.shield(task), timeout=5)
|
|
finally:
|
|
if not task.done():
|
|
task.cancel()
|
|
await asyncio.gather(task, return_exceptions=True)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_shutdown_closes_undecided_connections_before_waiting_for_server(
|
|
bus, start_listener, monkeypatch,
|
|
) -> None:
|
|
bridges = []
|
|
bridge_type = websocket_runtime.BinaryHTTPBridge
|
|
|
|
def create_bridge(handler):
|
|
bridge = bridge_type(handler)
|
|
bridges.append(bridge)
|
|
return bridge
|
|
|
|
monkeypatch.setattr(websocket_runtime, "BinaryHTTPBridge", create_bridge)
|
|
channel = _ch(bus)
|
|
port, start_task = await start_listener(channel)
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws") as client:
|
|
assert json.loads(await client.recv())["event"] == "ready"
|
|
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
|
try:
|
|
writer.write(b"P")
|
|
await writer.drain()
|
|
async with asyncio.timeout(2):
|
|
while not any(
|
|
connection._prefix == b"P" for connection in bridges[0].pending_connections
|
|
):
|
|
await asyncio.sleep(0)
|
|
async with asyncio.timeout(2):
|
|
await channel.stop()
|
|
await start_task
|
|
assert await reader.read() == b""
|
|
await client.wait_closed()
|
|
assert not bridges[0].pending_connections
|
|
assert channel._server is None
|
|
finally:
|
|
writer.close()
|
|
await writer.wait_closed()
|
|
|
|
|
|
async def _wait_for_connection_cleanup(
|
|
channel: WebSocketChannel,
|
|
connection: Any,
|
|
) -> None:
|
|
while connection in channel._conn_chats:
|
|
await asyncio.sleep(0)
|
|
|
|
|
|
async def _webui_mutate(
|
|
client: Any,
|
|
action: str,
|
|
payload: dict[str, Any] | None = None,
|
|
) -> httpx.Response:
|
|
request_id = f"test-{uuid.uuid4().hex}"
|
|
await client.send(json.dumps({
|
|
"type": "webui_request",
|
|
"request_id": request_id,
|
|
"action": action,
|
|
"payload": payload or {},
|
|
}))
|
|
while True:
|
|
envelope = json.loads(await asyncio.wait_for(client.recv(), timeout=5))
|
|
if envelope.get("event") != "webui_response":
|
|
continue
|
|
if envelope.get("request_id") != request_id:
|
|
continue
|
|
if envelope.get("ok") is True:
|
|
status = 200
|
|
body = envelope.get("result")
|
|
else:
|
|
error = envelope.get("error") or {}
|
|
status = int(error.get("status") or 500)
|
|
body = {"error": str(error.get("message") or "WebUI mutation failed")}
|
|
return httpx.Response(
|
|
status,
|
|
json=body,
|
|
request=httpx.Request("WS", "http://nanobot.local/webui-mutation"),
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stop_treats_cancelled_server_task_as_shutdown() -> None:
|
|
channel = _ch(MessageBus())
|
|
channel._running = True
|
|
channel._stop_event = asyncio.Event()
|
|
|
|
async def _server_task() -> None:
|
|
await asyncio.Event().wait()
|
|
|
|
task = asyncio.create_task(_server_task())
|
|
await asyncio.sleep(0)
|
|
task.cancel()
|
|
await asyncio.sleep(0)
|
|
channel._server_task = task
|
|
|
|
await channel.stop()
|
|
|
|
assert channel._server_task is None
|
|
assert task.cancelled()
|
|
|
|
|
|
@pytest.fixture()
|
|
def bus() -> MagicMock:
|
|
b = MagicMock()
|
|
b.publish_inbound = AsyncMock()
|
|
return b
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_extends_http_open_timeout_for_slow_settings_routes(
|
|
bus,
|
|
monkeypatch,
|
|
) -> None:
|
|
import nanobot.channels.websocket.runtime as websocket_module
|
|
|
|
channel = _ch(bus, port=0)
|
|
seen: dict[str, Any] = {}
|
|
|
|
class Server:
|
|
def close(self) -> None:
|
|
pass
|
|
|
|
async def wait_closed(self) -> None:
|
|
pass
|
|
|
|
async def fake_serve(*args: Any, **kwargs: Any) -> Server:
|
|
seen.update(kwargs)
|
|
assert channel._stop_event is not None
|
|
channel._stop_event.set()
|
|
return Server()
|
|
|
|
monkeypatch.setattr(websocket_module, "serve", fake_serve)
|
|
monkeypatch.setattr(channel, "_listener_is_serving", lambda _server: True)
|
|
|
|
await channel.start()
|
|
|
|
assert seen["open_timeout"] >= 300
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def isolate_webui_workspace_state(tmp_path, monkeypatch) -> None:
|
|
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
|
wth._WEBSOCKET_TURN_IDS.clear()
|
|
wth._WEBSOCKET_TURN_OWNERS.clear()
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
monkeypatch.setattr(
|
|
"nanobot.webui.workspaces.get_webui_dir",
|
|
lambda: tmp_path / "webui",
|
|
)
|
|
yield
|
|
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
|
wth._WEBSOCKET_TURN_IDS.clear()
|
|
wth._WEBSOCKET_TURN_OWNERS.clear()
|
|
|
|
|
|
async def _new_temporary_chat(
|
|
channel: WebSocketChannel,
|
|
connection: AsyncMock,
|
|
) -> str:
|
|
channel._webui_connections.add(connection)
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{"type": "new_temporary_chat"},
|
|
)
|
|
payload = json.loads(connection.send.await_args.args[0])
|
|
assert payload["event"] == "attached"
|
|
assert payload["temporary"] is True
|
|
connection.send.reset_mock()
|
|
return payload["chat_id"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tmp_path) -> None:
|
|
workspace = tmp_path / "workspace"
|
|
workspace.mkdir()
|
|
(workspace / "notes.txt").write_text("synthetic preview")
|
|
outside = tmp_path / "outside.txt"
|
|
outside.write_text("outside")
|
|
sessions = SessionManager(workspace)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]}, bus,
|
|
gateway=_basic_handler(
|
|
bus, session_manager=sessions, workspace_path=workspace,
|
|
default_restrict_to_workspace=False,
|
|
),
|
|
)
|
|
owner, other = AsyncMock(), AsyncMock()
|
|
chat_id = await _new_temporary_chat(channel, owner)
|
|
channel._webui_connections.add(other)
|
|
disk_before = {path for path in tmp_path.rglob("*") if path.is_file()}
|
|
|
|
async def preview(connection, path="notes.txt", probe=False, metadata=False):
|
|
await channel._dispatch_envelope(connection, "webui-client", {
|
|
"type": "webui_request", "request_id": "private-preview",
|
|
"action": "temporary_chat.file_preview",
|
|
"payload": {"chat_id": chat_id, "path": path, "probe": probe, "metadata": metadata},
|
|
})
|
|
return json.loads(connection.send.await_args.args[0])
|
|
|
|
result = await preview(owner)
|
|
assert result["ok"] is True
|
|
assert result["result"]["content"] == "synthetic preview"
|
|
assert (await preview(owner, probe=True))["result"] == {"available": True}
|
|
assert (await preview(owner, metadata=True))["result"] == {
|
|
"path": str((workspace / "notes.txt").resolve()), "relative_path": "notes.txt",
|
|
}
|
|
assert (await preview(other, metadata=True))["error"]["status"] == 404
|
|
assert (await preview(owner, str(outside), metadata=True))["error"]["status"] == 403
|
|
assert (await preview(other))["error"]["status"] == 404
|
|
assert (await preview(owner, str(outside)))["error"]["status"] == 403
|
|
assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False}
|
|
assert (await preview(AsyncMock()))["error"]["status"] == 403
|
|
assert not channel._commands.request_operations
|
|
assert {path for path in tmp_path.rglob("*") if path.is_file()} == disk_before
|
|
assert sessions.list_sessions() == []
|
|
|
|
await channel._dispatch_envelope(owner, "webui-client", {
|
|
"type": "discard_temporary_chat", "chat_id": chat_id,
|
|
})
|
|
assert (await preview(owner))["error"]["status"] == 404
|
|
assert (await preview(owner, metadata=True))["error"]["status"] == 404
|
|
assert not channel._commands.request_operations
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_attach_exposes_the_session_canonical_model_preset(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
session = sessions.get_or_create("websocket:pinned-model")
|
|
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "Deep Research"
|
|
sessions.save(session)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"tui-client",
|
|
{"type": "attach", "chat_id": "pinned-model"},
|
|
)
|
|
|
|
payload = json.loads(connection.send.await_args_list[0].args[0])
|
|
assert payload == {
|
|
"event": "attached",
|
|
"chat_id": "pinned-model",
|
|
"model_preset": "Deep Research",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_temporary_chat_is_transient_and_discarded(history, bus, tmp_path) -> None:
|
|
sessions = history.sessions
|
|
selected_project = tmp_path / "selected-project"
|
|
selected_project.mkdir()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(
|
|
bus,
|
|
session_manager=sessions,
|
|
workspace_path=tmp_path,
|
|
),
|
|
)
|
|
connection = AsyncMock()
|
|
connection.remote_address = ("127.0.0.1", 5000)
|
|
chat_id = await _new_temporary_chat(channel, connection)
|
|
upload = tmp_path / "temporary-upload.txt"
|
|
upload.write_text("private attachment", encoding="utf-8")
|
|
async def upload_chunks():
|
|
yield upload.read_bytes()
|
|
|
|
owner = channel.gateway.uploads.issue(connection)["token"]
|
|
reference = await channel.gateway.uploads.store.upload(
|
|
upload_chunks(), owner=owner, mime="text/plain", size=upload.stat().st_size,
|
|
filename=upload.name,
|
|
)
|
|
upload.unlink()
|
|
upload = channel.gateway.uploads.store.inspect([reference], owner=owner)[0].path
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": chat_id,
|
|
"content": "read this",
|
|
"media": [{"reference": reference}],
|
|
"cli_apps": [{"name": "drawio"}],
|
|
"workspace_scope": {
|
|
"project_path": str(selected_project),
|
|
"access_mode": "full",
|
|
},
|
|
"turn_id": "turn-1",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
inbound = bus.publish_inbound.await_args_list[0].args[0]
|
|
assert inbound.session_key == f"websocket:{chat_id}"
|
|
assert inbound.session_key_override == f"websocket:{chat_id}"
|
|
assert inbound.require_existing_session is True
|
|
assert inbound.metadata["cli_apps"] == [{"name": "drawio"}]
|
|
assert inbound.metadata[WORKSPACE_SCOPE_METADATA_KEY] == {
|
|
"project_path": str(tmp_path.resolve()),
|
|
"access_mode": "restricted",
|
|
}
|
|
session = sessions.get_cached(inbound.session_key)
|
|
assert session is not None
|
|
assert session.policy.persist is False
|
|
assert upload.exists()
|
|
assert history.read(inbound.session_key) == []
|
|
assert [payload["event"] for payload in _sent_ws_payloads(connection)] == [
|
|
"message_accepted",
|
|
]
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{"type": "discard_temporary_chat", "chat_id": chat_id},
|
|
)
|
|
|
|
control = bus.publish_inbound.await_args_list[1].args[0]
|
|
assert bus.publish_inbound.await_count == 2
|
|
assert control.session_key == inbound.session_key
|
|
assert control.metadata[INBOUND_META_RUNTIME_CONTROL] == (
|
|
RUNTIME_CONTROL_SESSION_DISCARD
|
|
)
|
|
assert sessions.get_cached(inbound.session_key) is None
|
|
assert chat_id not in channel._subs
|
|
assert chat_id not in channel._conn_chats.get(connection, set())
|
|
assert not upload.exists()
|
|
assert history.read(inbound.session_key) == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("content", [
|
|
"/goal private", "/trigger later", "/dream", "/NEW@nanobot", "/__shell pwd",
|
|
])
|
|
async def test_temporary_chat_rejects_persistent_commands(bus, tmp_path, content) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
connection.remote_address = ("127.0.0.1", 5000)
|
|
chat_id = await _new_temporary_chat(channel, connection)
|
|
|
|
await channel._dispatch_envelope(connection, "webui-client", {
|
|
"type": "message",
|
|
"chat_id": chat_id,
|
|
"content": content,
|
|
"webui": True,
|
|
})
|
|
|
|
assert bus.publish_inbound.await_count == 0
|
|
assert sessions.get_cached(f"websocket:{chat_id}") is not None
|
|
assert json.loads(connection.send.await_args.args[0])["detail"] == (
|
|
"temporary_chat_command_rejected"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("content", ["/tmp", "/new/file.txt", "/model@nanobot fast"])
|
|
async def test_temporary_chat_accepts_paths_and_allowed_commands(history, bus, tmp_path, content) -> None:
|
|
sessions = history.sessions
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]}, bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
connection.remote_address = ("127.0.0.1", 5000)
|
|
chat_id = await _new_temporary_chat(channel, connection)
|
|
|
|
await channel._dispatch_envelope(connection, "webui-client", {
|
|
"type": "message", "chat_id": chat_id, "content": content, "webui": True,
|
|
})
|
|
|
|
inbound = bus.publish_inbound.await_args.args[0]
|
|
assert inbound.content == content
|
|
assert inbound.require_existing_session is True
|
|
assert history.read(inbound.session_key) == []
|
|
session = sessions.get_cached(inbound.session_key)
|
|
assert session is not None and not session.policy.persist
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_disconnect_discards_temporary_chat(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(
|
|
bus,
|
|
session_manager=sessions,
|
|
workspace_path=tmp_path,
|
|
),
|
|
)
|
|
connection = AsyncMock()
|
|
chat_id = await _new_temporary_chat(channel, connection)
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": chat_id,
|
|
"content": "hello",
|
|
"webui": True,
|
|
},
|
|
)
|
|
await channel._cleanup_connection(connection)
|
|
|
|
session_key = f"websocket:{chat_id}"
|
|
control = bus.publish_inbound.await_args_list[-1].args[0]
|
|
assert control.session_key == session_key
|
|
assert control.metadata[INBOUND_META_RUNTIME_CONTROL] == (
|
|
RUNTIME_CONTROL_SESSION_DISCARD
|
|
)
|
|
assert sessions.get_cached(session_key) is None
|
|
assert chat_id not in channel._subs
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_temporary_chat_creation_requires_authenticated_webui_connection(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"generic-websocket-client",
|
|
{"type": "new_temporary_chat"},
|
|
)
|
|
|
|
assert json.loads(connection.send.await_args.args[0])["detail"] == "access_denied"
|
|
assert sessions.list_sessions() == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_temporary_chat_cannot_be_claimed_by_another_connection(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
owner = AsyncMock()
|
|
other = AsyncMock()
|
|
channel._webui_connections.add(other)
|
|
chat_id = await _new_temporary_chat(channel, owner)
|
|
|
|
await channel._dispatch_envelope(
|
|
other,
|
|
"other-webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": chat_id,
|
|
"content": "claim it",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
assert json.loads(other.send.await_args.args[0])["detail"] == (
|
|
"temporary_chat_unavailable"
|
|
)
|
|
assert bus.publish_inbound.await_count == 0
|
|
assert sessions.get_cached(f"websocket:{chat_id}") is not None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_temporary_chat_cannot_persist_workspace_scope(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
chat_id = await _new_temporary_chat(channel, connection)
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": chat_id,
|
|
"workspace_scope": {
|
|
"project_path": str(tmp_path),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
|
|
payload = json.loads(connection.send.await_args.args[0])
|
|
assert payload["detail"] == "temporary_chat_workspace_rejected"
|
|
session = sessions.get_cached(f"websocket:{chat_id}")
|
|
assert session is not None
|
|
assert WORKSPACE_SCOPE_METADATA_KEY not in session.metadata
|
|
assert sessions.list_sessions() == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_temporary_looking_id_does_not_define_session_policy(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
channel._webui_connections.add(connection)
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "temporary-looking-but-persistent",
|
|
"content": "/goal ordinary chat",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
inbound = bus.publish_inbound.await_args.args[0]
|
|
assert inbound.require_existing_session is False
|
|
assert inbound.session_key_override is None
|
|
session = sessions.get_cached("websocket:temporary-looking-but-persistent")
|
|
assert session is not None
|
|
assert session.policy.persist is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_discard_temporary_chat_does_not_detach_persistent_chat(bus, tmp_path) -> None:
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
connection = AsyncMock()
|
|
channel._attach(connection, "ordinary-chat")
|
|
|
|
await channel._dispatch_envelope(
|
|
connection,
|
|
"webui-client",
|
|
{"type": "discard_temporary_chat", "chat_id": "ordinary-chat"},
|
|
)
|
|
|
|
assert json.loads(connection.send.await_args.args[0])["detail"] == (
|
|
"temporary_chat_unavailable"
|
|
)
|
|
assert connection in channel._subs["ordinary-chat"]
|
|
assert "ordinary-chat" in channel._conn_chats[connection]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_session_updated_broadcasts_to_other_webui_connections(bus) -> None:
|
|
class Conn:
|
|
remote_address = None
|
|
|
|
def __init__(self) -> None:
|
|
self.sent: list[str] = []
|
|
|
|
async def send(self, raw: str) -> None:
|
|
self.sent.append(raw)
|
|
|
|
channel = _ch(bus)
|
|
active_conn = Conn()
|
|
other_conn = Conn()
|
|
channel._attach(active_conn, "chat-a")
|
|
channel._attach(other_conn, "chat-b")
|
|
assert sorted(channel._subs) == ["chat-a", "chat-b"]
|
|
assert sum(len(conns) for conns in channel._subs.values()) == 2
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-a",
|
|
content="",
|
|
event=SessionUpdatedEvent(scope="thread"),
|
|
))
|
|
|
|
active_events = [json.loads(raw)["event"] for raw in active_conn.sent]
|
|
other_events = [json.loads(raw)["event"] for raw in other_conn.sent]
|
|
|
|
assert (active_events, other_events) == (
|
|
["session_updated"],
|
|
["session_updated"],
|
|
)
|
|
payload = json.loads(other_conn.sent[0])
|
|
assert payload == {
|
|
"event": "session_updated",
|
|
"chat_id": "chat-a",
|
|
"scope": "thread",
|
|
}
|
|
|
|
|
|
async def _recv_ws_event(client: Any, event: str) -> dict[str, Any]:
|
|
"""Receive until a specific websocket event appears."""
|
|
for _ in range(10):
|
|
payload = json.loads(await client.recv())
|
|
if payload.get("event") == event:
|
|
return payload
|
|
raise AssertionError(f"websocket event {event!r} was not received")
|
|
|
|
|
|
def _sent_ws_payloads(mock_ws: AsyncMock) -> list[dict[str, Any]]:
|
|
return [json.loads(call.args[0]) for call in mock_ws.send.await_args_list]
|
|
|
|
|
|
def test_parse_request_path_strips_trailing_slash_except_root() -> None:
|
|
assert _parse_request_path("/chat/")[0] == "/chat"
|
|
assert _parse_request_path("/chat?x=1")[0] == "/chat"
|
|
assert _parse_request_path("/")[0] == "/"
|
|
|
|
|
|
def test_parse_request_path_matches_query() -> None:
|
|
path, query = _parse_request_path("/ws/?token=secret&client_id=u1")
|
|
assert path == "/ws"
|
|
assert query == _parse_query("/ws/?token=secret&client_id=u1")
|
|
|
|
|
|
def test_normalize_config_path_matches_request() -> None:
|
|
assert _normalize_config_path("/ws/") == "/ws"
|
|
assert _normalize_config_path("/") == "/"
|
|
|
|
|
|
def test_websocket_config_accepts_absolute_unix_socket(tmp_path) -> None:
|
|
socket_path = tmp_path / "engine.sock"
|
|
|
|
cfg = WebSocketConfig(unix_socket_path=str(socket_path))
|
|
|
|
assert cfg.unix_socket_path == str(socket_path)
|
|
|
|
|
|
def test_websocket_config_rejects_relative_unix_socket() -> None:
|
|
with pytest.raises(ValueError, match="absolute path"):
|
|
WebSocketConfig(unix_socket_path="engine.sock")
|
|
|
|
|
|
def test_parse_query_extracts_token_and_client_id() -> None:
|
|
query = _parse_query("/?token=secret&client_id=u1")
|
|
assert query.get("token") == ["secret"]
|
|
assert query.get("client_id") == ["u1"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("raw", "expected"),
|
|
[
|
|
("plain", "plain"),
|
|
('{"content": "hi"}', "hi"),
|
|
('{"text": "there"}', "there"),
|
|
('{"message": "x"}', "x"),
|
|
(" ", None),
|
|
("{}", None),
|
|
],
|
|
)
|
|
def test_parse_inbound_payload(raw: str, expected: str | None) -> None:
|
|
assert _parse_inbound_payload(raw) == expected
|
|
|
|
|
|
def test_parse_inbound_invalid_json_falls_back_to_raw_string() -> None:
|
|
assert _parse_inbound_payload("{not json") == "{not json"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("raw", "expected"),
|
|
[
|
|
('{"content": ""}', None),
|
|
('{"content": 123}', None),
|
|
('{"content": " "}', None),
|
|
('["hello"]', '["hello"]'),
|
|
('{"unknown_key": "val"}', None),
|
|
('{"content": null}', None),
|
|
],
|
|
)
|
|
def test_parse_inbound_payload_edge_cases(raw: str, expected: str | None) -> None:
|
|
assert _parse_inbound_payload(raw) == expected
|
|
|
|
|
|
def test_web_socket_config_path_must_start_with_slash() -> None:
|
|
with pytest.raises(ValueError, match='path must start with "/"'):
|
|
WebSocketConfig(path="bad")
|
|
|
|
|
|
def test_ssl_context_requires_both_cert_and_key_files() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "sslCertfile": "/tmp/c.pem", "sslKeyfile": ""},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
with pytest.raises(ValueError, match="ssl_certfile and ssl_keyfile"):
|
|
channel._build_ssl_context()
|
|
|
|
|
|
def test_default_config_includes_safe_bind_and_streaming() -> None:
|
|
defaults = WebSocketChannel.default_config()
|
|
assert defaults["enabled"] is True
|
|
assert defaults["host"] == "127.0.0.1"
|
|
assert defaults["streaming"] is True
|
|
assert defaults["allowFrom"] == ["*"]
|
|
assert defaults.get("tokenIssuePath", "") == ""
|
|
|
|
|
|
def test_token_issue_path_must_differ_from_websocket_path() -> None:
|
|
with pytest.raises(ValueError, match="token_issue_path must differ"):
|
|
WebSocketConfig(path="/ws", token_issue_path="/ws")
|
|
|
|
|
|
def test_issue_route_secret_matches_bearer_and_header() -> None:
|
|
from websockets.datastructures import Headers
|
|
|
|
secret = "my-secret"
|
|
bearer_headers = Headers([("Authorization", "Bearer my-secret")])
|
|
assert _issue_route_secret_matches(bearer_headers, secret) is True
|
|
x_headers = Headers([("X-Nanobot-Auth", "my-secret")])
|
|
assert _issue_route_secret_matches(x_headers, secret) is True
|
|
wrong = Headers([("Authorization", "Bearer other")])
|
|
assert _issue_route_secret_matches(wrong, secret) is False
|
|
|
|
|
|
def test_issue_route_secret_matches_empty_secret() -> None:
|
|
from websockets.datastructures import Headers
|
|
|
|
assert _issue_route_secret_matches(Headers([]), "") is True
|
|
assert _issue_route_secret_matches(Headers([("Authorization", "Bearer anything")]), "") is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(
|
|
bus,
|
|
port=port,
|
|
token="static-token",
|
|
tokenIssuePath="/custom-token",
|
|
websocketRequiresToken=True,
|
|
)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
denied = await _http_get(f"http://127.0.0.1:{port}/custom-token")
|
|
assert denied.status_code == 401
|
|
|
|
allowed = await _http_get(
|
|
f"http://127.0.0.1:{port}/custom-token",
|
|
headers={"Authorization": "Bearer static-token"},
|
|
)
|
|
assert allowed.status_code == 200
|
|
assert allowed.json()["token"].startswith("nbwt_")
|
|
assert allowed.headers["Cache-Control"] == "no-store"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_message_envelope_marks_inbound_metadata(history, bus: MagicMock) -> None:
|
|
|
|
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
conn = MagicMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-1",
|
|
"content": "hello",
|
|
"webui": True,
|
|
"turn_id": "turn-1",
|
|
},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.channel == "websocket"
|
|
assert msg.chat_id == "chat-1"
|
|
assert msg.metadata["webui"] is True
|
|
assert msg.metadata["webui_turn_id"] == "turn-1"
|
|
assert msg.metadata["_wants_stream"] is True
|
|
lines = history.read("websocket:chat-1")
|
|
assert len(lines) == 1
|
|
assert {key: lines[0].get(key) for key in (
|
|
"event",
|
|
"chat_id",
|
|
"text",
|
|
"turn_id",
|
|
"turn_phase",
|
|
"turn_seq",
|
|
)} == {
|
|
"event": "user",
|
|
"chat_id": "chat-1",
|
|
"text": "hello",
|
|
"turn_id": "turn-1",
|
|
"turn_phase": "user",
|
|
"turn_seq": 1,
|
|
}
|
|
assert isinstance(lines[0].get("created_at_ms"), int)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_trusted_webui_shell_preserves_display_text_and_hides_dispatch_command(history,
|
|
bus: MagicMock,
|
|
) -> None:
|
|
|
|
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
conn = MagicMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
channel._webui_connections.add(conn)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "shell-chat",
|
|
"content": "!printf ok",
|
|
"webui": True,
|
|
"user_shell": True,
|
|
"turn_id": "shell-turn",
|
|
},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.content == "/__shell printf ok"
|
|
assert msg.metadata[INBOUND_META_USER_SHELL] is True
|
|
assert msg.metadata["webui_turn_id"] == "shell-turn"
|
|
assert history.read("websocket:shell-chat")[0]["text"] == "!printf ok"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_untrusted_websocket_cannot_enable_user_shell(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = MagicMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"plain-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "plain-chat",
|
|
"content": "!printf nope",
|
|
"webui": True,
|
|
"user_shell": True,
|
|
"turn_id": "plain-turn",
|
|
},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.content == "!printf nope"
|
|
assert INBOUND_META_USER_SHELL not in msg.metadata
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_message_envelope_persists_user_transcript_for_refresh(history,
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
async def answer_during_publish(_msg: Any) -> None:
|
|
await channel.send(await history.message(channel="websocket", chat_id="chat-1", content="hi back"))
|
|
|
|
bus.publish_inbound.side_effect = answer_during_publish
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": "message", "chat_id": "chat-1", "content": "hello", "webui": True},
|
|
)
|
|
|
|
lines = history.read("websocket:chat-1")
|
|
assert [line["event"] for line in lines] == ["user", "message"]
|
|
|
|
body = history.build("websocket:chat-1")
|
|
assert body is not None
|
|
assert [message["role"] for message in _thread_conversation_events(body)] == [
|
|
"user", "assistant",
|
|
]
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [
|
|
"hello", "hi back",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_stop_control_message_is_not_persisted_as_user_bubble(history,
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": "message", "chat_id": "chat-1", "content": "/stop", "webui": True},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.content == "/stop"
|
|
assert history.read("websocket:chat-1") == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_user_transcript_append_failure_does_not_block_inbound(
|
|
bus: MagicMock,
|
|
monkeypatch,
|
|
) -> None:
|
|
def fail_append(_session_key: str, _obj: dict[str, Any]) -> None:
|
|
raise OSError("disk full")
|
|
|
|
monkeypatch.setattr("nanobot.webui.transcript.append_transcript_object", fail_append)
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": "message", "chat_id": "chat-1", "content": "hello", "webui": True},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.chat_id == "chat-1"
|
|
assert msg.content == "hello"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_plain_websocket_message_does_not_mark_webui(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = MagicMock()
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"custom-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-1",
|
|
"content": "hello",
|
|
"quoted_context": "must be ignored",
|
|
},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert "webui" not in msg.metadata
|
|
assert RUNTIME_CONTEXT_INPUT_META not in msg.metadata
|
|
|
|
|
|
def test_only_bootstrap_tokens_mark_webui_connections(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
webui_connection = MagicMock()
|
|
client_connection = MagicMock()
|
|
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
|
|
client_token = channel.gateway.tokens.issue_token(300)
|
|
|
|
assert channel._authorize_websocket_handshake(
|
|
webui_connection,
|
|
{"token": [webui_token]},
|
|
) is None
|
|
assert channel._authorize_websocket_handshake(
|
|
client_connection,
|
|
{"token": [client_token]},
|
|
) is None
|
|
|
|
assert webui_connection in channel._webui_connections
|
|
assert client_connection not in channel._webui_connections
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_authenticated_webui_request_returns_correlated_success(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
channel.gateway.http.dispatch_webui_mutation = AsyncMock(
|
|
return_value=_http_json_response({"saved": True})
|
|
)
|
|
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-1",
|
|
"action": "settings.provider.update",
|
|
"payload": {"provider": "openrouter", "apiKey": "secret"},
|
|
},
|
|
)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
|
|
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once_with(
|
|
conn,
|
|
"settings.provider.update",
|
|
{"provider": "openrouter", "apiKey": "secret"},
|
|
)
|
|
assert json.loads(conn.send.await_args.args[0]) == {
|
|
"event": "webui_response",
|
|
"request_id": "request-1",
|
|
"ok": True,
|
|
"result": {"saved": True},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_mutations_preserve_request_and_response_order(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
first_started = asyncio.Event()
|
|
release_first = asyncio.Event()
|
|
dispatch_order: list[str] = []
|
|
|
|
async def dispatch(
|
|
_connection: object,
|
|
action: str,
|
|
_payload: dict[str, object],
|
|
) -> Any:
|
|
dispatch_order.append(action)
|
|
if action == "settings.provider.update":
|
|
first_started.set()
|
|
await release_first.wait()
|
|
return _http_json_response({"action": action})
|
|
|
|
channel.gateway.http.dispatch_webui_mutation = dispatch
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-first",
|
|
"action": "settings.provider.update",
|
|
"payload": {},
|
|
},
|
|
)
|
|
await first_started.wait()
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-second",
|
|
"action": "settings.agent.update",
|
|
"payload": {},
|
|
},
|
|
)
|
|
await asyncio.sleep(0)
|
|
assert dispatch_order == ["settings.provider.update"]
|
|
|
|
release_first.set()
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
|
|
assert dispatch_order == [
|
|
"settings.provider.update",
|
|
"settings.agent.update",
|
|
]
|
|
responses = [json.loads(call.args[0]) for call in conn.send.await_args_list]
|
|
assert [response["request_id"] for response in responses] == [
|
|
"request-first",
|
|
"request-second",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_request_survives_disconnect_and_preserves_reconnect_order(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
first_conn = AsyncMock()
|
|
retry_conn = AsyncMock()
|
|
first_conn.send.side_effect = ConnectionClosed(Close(1006, ""), Close(1006, ""), True)
|
|
channel._webui_connections.update({first_conn, retry_conn})
|
|
started = asyncio.Event()
|
|
release = asyncio.Event()
|
|
dispatch_order: list[str] = []
|
|
|
|
async def mutate(_connection: object, action: str, _payload: dict[str, Any]) -> Any:
|
|
dispatch_order.append(action)
|
|
if action == "automation.run":
|
|
started.set()
|
|
await release.wait()
|
|
return _http_json_response({"action": action})
|
|
|
|
channel.gateway.http.dispatch_webui_mutation = AsyncMock(side_effect=mutate)
|
|
envelope = {
|
|
"type": "webui_request",
|
|
"request_id": "request-retry",
|
|
"action": "automation.run",
|
|
"payload": {"id": "daily-summary"},
|
|
}
|
|
queued_envelope = {
|
|
"type": "webui_request",
|
|
"request_id": "request-queued",
|
|
"action": "automation.update",
|
|
"payload": {"id": "daily-summary"},
|
|
}
|
|
|
|
await channel._dispatch_envelope(first_conn, "webui-client", envelope)
|
|
await started.wait()
|
|
await channel._dispatch_envelope(first_conn, "webui-client", queued_envelope)
|
|
assert dispatch_order == ["automation.run"]
|
|
|
|
await channel._cleanup_connection(first_conn)
|
|
assert first_conn not in channel._webui_connections
|
|
await channel._dispatch_envelope(retry_conn, "webui-client", envelope)
|
|
await channel._dispatch_envelope(retry_conn, "webui-client", queued_envelope)
|
|
await channel._dispatch_envelope(
|
|
retry_conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-next",
|
|
"action": "automation.delete",
|
|
"payload": {"id": "daily-summary"},
|
|
},
|
|
)
|
|
await asyncio.sleep(0)
|
|
assert dispatch_order == ["automation.run"]
|
|
|
|
pending = tuple(channel._commands.request_tasks.values())
|
|
release.set()
|
|
await asyncio.gather(*pending)
|
|
|
|
assert dispatch_order == ["automation.run", "automation.update", "automation.delete"]
|
|
responses = [json.loads(call.args[0]) for call in retry_conn.send.await_args_list]
|
|
assert [response["request_id"] for response in responses] == [
|
|
"request-retry",
|
|
"request-queued",
|
|
"request-next",
|
|
]
|
|
assert first_conn not in channel._commands.request_locks
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_request_replays_completed_result_after_reconnect(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
first_conn = AsyncMock()
|
|
retry_conn = AsyncMock()
|
|
channel._webui_connections.update({first_conn, retry_conn})
|
|
channel.gateway.http.dispatch_webui_mutation = AsyncMock(
|
|
return_value=_http_json_response({"installed": True})
|
|
)
|
|
envelope = {
|
|
"type": "webui_request",
|
|
"request_id": "request-completed",
|
|
"action": "skill.install",
|
|
"payload": {"skill": "demo"},
|
|
}
|
|
|
|
await channel._dispatch_envelope(first_conn, "webui-client", envelope)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
await channel._dispatch_envelope(retry_conn, "webui-client", envelope)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
|
|
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once()
|
|
assert json.loads(retry_conn.send.await_args.args[0]) == {
|
|
"event": "webui_response",
|
|
"request_id": "request-completed",
|
|
"ok": True,
|
|
"result": {"installed": True},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_request_rejects_request_id_reuse_with_different_payload(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
first_conn = AsyncMock()
|
|
retry_conn = AsyncMock()
|
|
channel._webui_connections.update({first_conn, retry_conn})
|
|
channel.gateway.http.dispatch_webui_mutation = AsyncMock(
|
|
return_value=_http_json_response({"ran": True})
|
|
)
|
|
|
|
await channel._dispatch_envelope(
|
|
first_conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-conflict",
|
|
"action": "automation.run",
|
|
"payload": {"id": "job-a"},
|
|
},
|
|
)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
await channel._dispatch_envelope(
|
|
retry_conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-conflict",
|
|
"action": "automation.run",
|
|
"payload": {"id": "job-b"},
|
|
},
|
|
)
|
|
|
|
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once()
|
|
assert json.loads(retry_conn.send.await_args.args[0]) == {
|
|
"event": "webui_response",
|
|
"request_id": "request-conflict",
|
|
"ok": False,
|
|
"error": {
|
|
"status": 409,
|
|
"message": "request_id was already used for a different WebUI mutation",
|
|
},
|
|
}
|
|
|
|
|
|
def test_webui_request_cache_prunes_expired_completed_but_keeps_pending(
|
|
bus: MagicMock,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
import nanobot.webui.inbound_commands as websocket_module
|
|
|
|
channel = _ch(bus)
|
|
now = 1_000.0
|
|
monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now))
|
|
operations = cast(dict[str, Any], channel._commands.request_operations)
|
|
operations["pending"] = SimpleNamespace(completed_at=None)
|
|
operations["expired"] = SimpleNamespace(
|
|
completed_at=now - websocket_module._WEBUI_REQUEST_CACHE_TTL_S
|
|
)
|
|
operations["fresh"] = SimpleNamespace(completed_at=now - 1)
|
|
|
|
channel._commands.prune_request_operations()
|
|
|
|
assert "pending" in operations
|
|
assert "expired" not in operations
|
|
assert "fresh" in operations
|
|
|
|
|
|
def test_webui_request_cache_prunes_oldest_completed_at_capacity(
|
|
bus: MagicMock,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
import nanobot.webui.inbound_commands as websocket_module
|
|
|
|
channel = _ch(bus)
|
|
now = 1_000.0
|
|
monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now))
|
|
operations = cast(dict[str, Any], channel._commands.request_operations)
|
|
operations["pending"] = SimpleNamespace(completed_at=None)
|
|
for index in range(websocket_module._WEBUI_REQUEST_CACHE_MAX + 1):
|
|
operations[f"completed-{index}"] = SimpleNamespace(
|
|
completed_at=now - 1 + index / 1_000
|
|
)
|
|
|
|
channel._commands.prune_request_operations()
|
|
|
|
assert "pending" in operations
|
|
assert "completed-0" not in operations
|
|
assert "completed-1" in operations
|
|
completed = [operation for operation in operations.values() if operation.completed_at is not None]
|
|
assert len(completed) == websocket_module._WEBUI_REQUEST_CACHE_MAX
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
channel.gateway.http.dispatch_webui_mutation = AsyncMock(
|
|
return_value=_http_error(400, "invalid settings payload")
|
|
)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-2",
|
|
"action": "settings.agent.update",
|
|
"payload": {},
|
|
},
|
|
)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
|
|
assert json.loads(conn.send.await_args.args[0]) == {
|
|
"event": "webui_response",
|
|
"request_id": "request-2",
|
|
"ok": False,
|
|
"error": {"status": 400, "message": "invalid settings payload"},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_request_requires_bootstrap_authenticated_connection(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
channel.gateway.http.dispatch_webui_mutation = AsyncMock()
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"static-token-client",
|
|
{
|
|
"type": "webui_request",
|
|
"request_id": "request-3",
|
|
"action": "settings.agent.update",
|
|
"payload": {},
|
|
},
|
|
)
|
|
|
|
channel.gateway.http.dispatch_webui_mutation.assert_not_awaited()
|
|
assert json.loads(conn.send.await_args.args[0]) == {
|
|
"event": "webui_response",
|
|
"request_id": "request-3",
|
|
"ok": False,
|
|
"error": {"status": 403, "message": "access_denied"},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_persists_sidebar_state_larger_than_http_request_line(
|
|
bus: MagicMock,
|
|
tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
conn.request = SimpleNamespace(headers=Headers())
|
|
channel._webui_connections.add(conn)
|
|
session_order = [f"websocket:{index:04d}-{'x' * 48}" for index in range(160)]
|
|
request_id = "sidebar-large-state"
|
|
envelope = {
|
|
"type": "webui_request",
|
|
"request_id": request_id,
|
|
"action": "sidebar.update",
|
|
"payload": {"state": {
|
|
"session_order": session_order,
|
|
"view": {"sort": "manual"},
|
|
}},
|
|
}
|
|
assert len(json.dumps(envelope).encode()) > 8_192
|
|
|
|
await channel._dispatch_envelope(conn, "webui-client", envelope)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
|
|
saved = json.loads((tmp_path / "webui" / "sidebar-state.json").read_text(encoding="utf-8"))
|
|
assert saved["session_order"] == session_order
|
|
assert saved["view"]["sort"] == "manual"
|
|
assert json.loads(conn.send.await_args.args[0]) == {
|
|
"event": "webui_response",
|
|
"request_id": request_id,
|
|
"ok": True,
|
|
"result": {**saved, "archived_keys": []},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("command_type", ["webui_request", "set_sidebar_state"])
|
|
async def test_webui_sidebar_state_update_broadcasts_workbench_to_other_devices(
|
|
bus: MagicMock,
|
|
tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
command_type: str,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
sessions = SessionManager(tmp_path)
|
|
await sessions.state.import_messages("websocket:a", [{"role": "user", "content": "saved"}])
|
|
await sessions.state.fork("websocket:a", "websocket:b", 0)
|
|
sessions.get_or_create("websocket:draft")
|
|
channel = _ch(bus, session_manager=sessions)
|
|
source = AsyncMock()
|
|
source.request = SimpleNamespace(headers=Headers())
|
|
other_device = AsyncMock()
|
|
channel._webui_connections.update({source, other_device})
|
|
channel._register_connection_outbound(other_device)
|
|
state = {
|
|
"archived_keys": ["websocket:b", "websocket:draft"],
|
|
"workbench": {
|
|
"version": 1,
|
|
"tabs": {
|
|
"tab:websocket:a": {
|
|
"explicit": True,
|
|
"title": "Research",
|
|
"paneKeys": ["websocket:a", "websocket:b"],
|
|
"layoutPaneKeys": ["websocket:b", "websocket:a"],
|
|
"layout": "columns",
|
|
"splitRatios": [0.35],
|
|
}
|
|
},
|
|
},
|
|
}
|
|
envelope = {"type": command_type, "state": state} if command_type == "set_sidebar_state" else {
|
|
"type": command_type, "request_id": "sidebar-workbench-state",
|
|
"action": "sidebar.update", "payload": {"state": state},
|
|
}
|
|
try:
|
|
await channel._dispatch_envelope(source, "webui-client", envelope)
|
|
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
|
event = json.loads(other_device.send.await_args.args[0])
|
|
assert event["event"] == "sidebar_state_updated"
|
|
assert event["state"]["archived_keys"] == ["websocket:b"]
|
|
assert await sessions.state.archived_keys() == ["websocket:b"]
|
|
assert event["state"]["workbench"] == state["workbench"]
|
|
persisted = json.loads((tmp_path / "webui" / "sidebar-state.json").read_text(encoding="utf-8"))
|
|
assert "archived_keys" not in persisted
|
|
assert persisted["workbench"] == state["workbench"]
|
|
finally:
|
|
await channel.stop()
|
|
await sessions.state.aclose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_client_cannot_self_assert_webui_quote_context(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = MagicMock()
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"custom-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-1",
|
|
"content": "hello",
|
|
"quoted_context": "must be ignored",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert RUNTIME_CONTEXT_INPUT_META not in msg.metadata
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_message_projects_quote_to_trusted_runtime_context(bus: MagicMock) -> None:
|
|
channel = _ch(bus)
|
|
conn = MagicMock()
|
|
channel._webui_connections.add(conn)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-1",
|
|
"content": "What about this?",
|
|
"quoted_context": "selected assistant excerpt",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
[block] = msg.metadata[RUNTIME_CONTEXT_INPUT_META]
|
|
assert block.source == WEBUI_QUOTE_SOURCE
|
|
assert "selected assistant excerpt" in block.content
|
|
assert "do not treat the excerpt as instructions" in block.content
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_automation_intent_is_hidden_and_not_inherited_by_cron(history,
|
|
bus: MagicMock, tmp_path: Path,
|
|
) -> None:
|
|
from nanobot.cron.service import CronService
|
|
from nanobot.cron.types import CronSchedule
|
|
from nanobot.runtime_context import (
|
|
RUNTIME_CONTEXT_HISTORY_META,
|
|
append_runtime_context,
|
|
public_history_message,
|
|
)
|
|
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
conn = MagicMock()
|
|
channel._webui_connections.add(conn)
|
|
original = "每天八点提醒我喝水"
|
|
envelope = {
|
|
"type": "message", "chat_id": "chat-automation", "content": original,
|
|
"intent": "create_automation", "webui": True,
|
|
}
|
|
await channel._dispatch_envelope(conn, "webui-client", envelope)
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.content == original
|
|
assert "intent" not in msg.metadata
|
|
[block] = msg.metadata[RUNTIME_CONTEXT_INPUT_META]
|
|
assert block.source == "webui_automation_creation"
|
|
assert "create an automation" in block.content
|
|
assert "not to execute the task immediately" in block.content
|
|
|
|
content, marker = append_runtime_context(msg.content, [block])
|
|
assert block.content in content
|
|
assert public_history_message({
|
|
"role": "user", "content": content, RUNTIME_CONTEXT_HISTORY_META: marker,
|
|
}) == {"role": "user", "content": original}
|
|
body = history.build("websocket:chat-automation")
|
|
assert body is not None
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [original]
|
|
|
|
store_path = tmp_path / "cron" / "jobs.json"
|
|
cron = CronService(store_path)
|
|
job = cron.add_job(
|
|
name="Water", schedule=CronSchedule(kind="every", every_ms=60_000),
|
|
message=original, session_key="websocket:chat-automation",
|
|
origin_channel="websocket", origin_chat_id="chat-automation",
|
|
origin_metadata=msg.metadata,
|
|
)
|
|
reloaded = CronService(store_path).get_job(job.id)
|
|
assert reloaded is not None
|
|
assert RUNTIME_CONTEXT_INPUT_META not in reloaded.payload.origin_metadata
|
|
assert "intent" not in reloaded.payload.origin_metadata
|
|
|
|
await channel._dispatch_envelope(conn, "webui-client", {
|
|
**envelope, "content": "Thanks", "intent": None,
|
|
})
|
|
assert RUNTIME_CONTEXT_INPUT_META not in bus.publish_inbound.await_args.args[0].metadata
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(("trusted", "webui", "intent", "shell"), [
|
|
(False, True, "create_automation", False),
|
|
(True, False, "create_automation", False),
|
|
(True, True, None, False),
|
|
(True, True, "delete_automation", False),
|
|
(True, True, {"instruction": "arbitrary prompt"}, False),
|
|
(True, True, "create_automation", True),
|
|
])
|
|
async def test_webui_automation_context_requires_valid_trusted_intent(
|
|
bus: MagicMock, trusted: bool, webui: bool, intent: object, shell: bool,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
conn = MagicMock()
|
|
if trusted:
|
|
channel._webui_connections.add(conn)
|
|
await channel._dispatch_envelope(conn, "client", {
|
|
"type": "message", "chat_id": "chat-intent",
|
|
"content": "!echo hello" if shell else "hello",
|
|
"intent": intent, "webui": webui, "user_shell": shell,
|
|
})
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert RUNTIME_CONTEXT_INPUT_META not in msg.metadata
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_message_scope_inherits_persisted_session_scope(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
project = tmp_path / "project"
|
|
default_workspace.mkdir()
|
|
project.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
conn.request = SimpleNamespace(headers=Headers({"Host": "localhost:8765"}))
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-scope",
|
|
"workspace_scope": {
|
|
"project_path": str(project),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
assert sessions.list_sessions() == []
|
|
conn.reset_mock()
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": "message", "chat_id": "chat-scope", "content": "hello", "webui": True},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.metadata["workspace_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()
|
|
channel._webui_connections.add(conn)
|
|
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
|
|
async def test_new_chat_without_message_does_not_create_session(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
) -> None:
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"tui-client",
|
|
{
|
|
"type": "new_chat",
|
|
"workspace_scope": {
|
|
"project_path": str(tmp_path),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
|
|
attached = json.loads(conn.send.await_args_list[0].args[0])
|
|
assert attached["event"] == "attached"
|
|
assert sessions.list_sessions() == []
|
|
assert channel.gateway.workspaces.scope_for_session_key(
|
|
f"websocket:{attached['chat_id']}"
|
|
).access_mode == "full"
|
|
|
|
await channel._cleanup_connection(conn)
|
|
|
|
assert sessions.list_sessions() == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_failed_first_message_does_not_persist_draft_session(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
) -> None:
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"tui-client",
|
|
{
|
|
"type": "new_chat",
|
|
"workspace_scope": {
|
|
"project_path": str(tmp_path),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
chat_id = json.loads(conn.send.await_args_list[0].args[0])["chat_id"]
|
|
bus.publish_inbound.side_effect = RuntimeError("queue unavailable")
|
|
|
|
with pytest.raises(RuntimeError, match="queue unavailable"):
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"tui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": chat_id,
|
|
"content": "hello",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
assert sessions.list_sessions() == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_workspace_scope_change_invalidates_other_attached_clients(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
) -> None:
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
origin = AsyncMock()
|
|
origin.remote_address = ("127.0.0.1", 50123)
|
|
origin.request = SimpleNamespace(headers=Headers({"Host": "localhost:8765"}))
|
|
peer = AsyncMock()
|
|
peer.remote_address = ("127.0.0.1", 50124)
|
|
channel._attach(origin, "shared")
|
|
channel._attach(peer, "shared")
|
|
|
|
await channel._dispatch_envelope(
|
|
origin,
|
|
"terminal-a",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "shared",
|
|
"workspace_scope": {
|
|
"project_path": str(tmp_path),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
|
|
peer_event = json.loads(peer.send.await_args.args[0])
|
|
assert peer_event == {
|
|
"event": "session_updated",
|
|
"chat_id": "shared",
|
|
"scope": "metadata",
|
|
}
|
|
origin_event = json.loads(origin.send.await_args.args[0])
|
|
assert origin_event["workspace_scope"]["access_mode"] == "full"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_scope_expands_home_project_path(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
home = tmp_path / "home"
|
|
project = home / "Desktop" / "Photos"
|
|
default_workspace.mkdir()
|
|
project.mkdir(parents=True)
|
|
monkeypatch.setenv("HOME", str(home))
|
|
monkeypatch.setenv("USERPROFILE", str(home))
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=SessionManager(tmp_path / "sessions"), workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-scope",
|
|
"workspace_scope": {
|
|
"project_path": "~/Desktop/Photos",
|
|
"access_mode": "restricted",
|
|
},
|
|
},
|
|
)
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": "message", "chat_id": "chat-scope", "content": "hello", "webui": True},
|
|
)
|
|
|
|
msg = bus.publish_inbound.await_args.args[0]
|
|
assert msg.metadata["workspace_scope"] == {
|
|
"project_path": str(project.resolve()),
|
|
"access_mode": "restricted",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_scope_rejects_missing_project_path(bus: MagicMock, tmp_path) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
default_workspace.mkdir()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=SessionManager(tmp_path / "sessions"), workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-scope",
|
|
"workspace_scope": {
|
|
"project_path": str(tmp_path / "missing"),
|
|
"access_mode": "restricted",
|
|
},
|
|
},
|
|
)
|
|
|
|
conn.send.assert_awaited()
|
|
payload = json.loads(conn.send.await_args.args[0])
|
|
assert payload["event"] == "error"
|
|
assert payload["detail"] == "workspace_scope_rejected"
|
|
bus.publish_inbound.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_scope_rejects_running_scope_change(bus: MagicMock, tmp_path) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
project = tmp_path / "project"
|
|
other = tmp_path / "other"
|
|
default_workspace.mkdir()
|
|
project.mkdir()
|
|
other.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
conn.request = SimpleNamespace(headers=Headers({"Host": "localhost:8765"}))
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-running",
|
|
"workspace_scope": {
|
|
"project_path": str(project),
|
|
"access_mode": "restricted",
|
|
},
|
|
},
|
|
)
|
|
await _register_running_turn("chat-running", 123.0)
|
|
try:
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-running",
|
|
"content": "hello",
|
|
"webui": True,
|
|
"turn_id": "turn-scope-rejected",
|
|
"workspace_scope": {
|
|
"project_path": str(other),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
finally:
|
|
wth.clear_websocket_turns("chat-running")
|
|
|
|
payload = json.loads(conn.send.await_args.args[0])
|
|
assert payload["event"] == "error"
|
|
assert payload["detail"] == "workspace_scope_rejected"
|
|
assert payload["reason"] == "chat_running"
|
|
assert payload["chat_id"] == "chat-running"
|
|
assert payload["turn_id"] == "turn-scope-rejected"
|
|
bus.publish_inbound.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_set_workspace_scope_rejects_running_chat(bus: MagicMock, tmp_path) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
project = tmp_path / "project"
|
|
other = tmp_path / "other"
|
|
default_workspace.mkdir()
|
|
project.mkdir()
|
|
other.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-running",
|
|
"workspace_scope": {
|
|
"project_path": str(project),
|
|
"access_mode": "restricted",
|
|
},
|
|
},
|
|
)
|
|
await channel.gateway.workspaces.persist_scope(
|
|
"chat-running",
|
|
channel.gateway.workspaces.scope_for_session_key("websocket:chat-running"),
|
|
)
|
|
conn.send.reset_mock()
|
|
|
|
await _register_running_turn("chat-running", 123.0)
|
|
try:
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-running",
|
|
"workspace_scope": {
|
|
"project_path": str(other),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
finally:
|
|
wth.clear_websocket_turns("chat-running")
|
|
|
|
payload = json.loads(conn.send.await_args.args[0])
|
|
assert payload["event"] == "error"
|
|
assert payload["detail"] == "workspace_scope_rejected"
|
|
assert payload["reason"] == "chat_running"
|
|
assert payload["chat_id"] == "chat-running"
|
|
|
|
saved = sessions.read_session_file("websocket:chat-running")
|
|
assert saved["metadata"]["workspace_scope"] == {
|
|
"project_path": str(project.resolve()),
|
|
"access_mode": "restricted",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_remote_webui_scope_allows_access_reduction(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
|
default_workspace = tmp_path / "default"
|
|
default_workspace.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("203.0.113.8", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-remote",
|
|
"workspace_scope": {
|
|
"project_path": str(default_workspace),
|
|
"access_mode": "restricted",
|
|
},
|
|
},
|
|
)
|
|
|
|
payload = json.loads(conn.send.await_args.args[0])
|
|
assert payload["event"] == "session_updated"
|
|
assert payload["workspace_scope"]["access_mode"] == "restricted"
|
|
assert sessions.list_sessions() == []
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": "message", "chat_id": "chat-remote", "content": "hello", "webui": True},
|
|
)
|
|
saved = sessions.read_session_file("websocket:chat-remote")
|
|
assert saved["metadata"]["workspace_scope"] == {
|
|
"project_path": str(default_workspace.resolve()),
|
|
"access_mode": "restricted",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_in_flight_message_without_scope_uses_latest_access_mode(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.webui.workspaces.get_webui_dir", lambda: tmp_path / "webui")
|
|
default_workspace = tmp_path / "default"
|
|
default_workspace.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
|
|
)
|
|
hydrate_started = asyncio.Event()
|
|
release_hydrate = asyncio.Event()
|
|
|
|
async def blocked_hydrate(_chat_id: str) -> None:
|
|
hydrate_started.set()
|
|
await release_hydrate.wait()
|
|
|
|
monkeypatch.setattr(channel._outbound, "hydrate", blocked_hydrate)
|
|
message_conn = AsyncMock()
|
|
message_conn.remote_address = ("203.0.113.8", 50123)
|
|
settings_conn = AsyncMock()
|
|
settings_conn.remote_address = ("203.0.113.8", 50124)
|
|
chat_id = "race-chat"
|
|
|
|
message_task = asyncio.create_task(
|
|
channel._dispatch_envelope(
|
|
message_conn,
|
|
"remote-message",
|
|
{
|
|
"type": "message",
|
|
"chat_id": chat_id,
|
|
"content": "hello",
|
|
"webui": True,
|
|
},
|
|
)
|
|
)
|
|
await hydrate_started.wait()
|
|
|
|
await channel._dispatch_envelope(
|
|
settings_conn,
|
|
"remote-settings",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": chat_id,
|
|
"workspace_scope": {
|
|
"project_path": str(default_workspace),
|
|
"access_mode": "restricted",
|
|
},
|
|
},
|
|
)
|
|
release_hydrate.set()
|
|
await message_task
|
|
|
|
saved = sessions.read_session_file(f"websocket:{chat_id}")
|
|
assert saved["metadata"]["workspace_scope"]["access_mode"] == "restricted"
|
|
assert channel.gateway.workspaces.scope_for_session_key(
|
|
f"websocket:{chat_id}"
|
|
).access_mode == "restricted"
|
|
bus.publish_inbound.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_remote_webui_scope_allows_full_access_for_custom_scope(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
project = tmp_path / "project"
|
|
default_workspace.mkdir()
|
|
project.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=default_workspace),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("203.0.113.8", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-remote",
|
|
"workspace_scope": {
|
|
"project_path": str(project),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
|
|
payload = json.loads(conn.send.await_args.args[0])
|
|
assert payload["event"] == "session_updated"
|
|
assert payload["workspace_scope"]["access_mode"] == "full"
|
|
assert channel.gateway.workspaces.scope_for_session_key(
|
|
"websocket:chat-remote"
|
|
).project_path == project.resolve()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_native_webui_scope_allows_custom_scope_without_loopback(
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
) -> None:
|
|
default_workspace = tmp_path / "default"
|
|
project = tmp_path / "project"
|
|
default_workspace.mkdir()
|
|
project.mkdir()
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(
|
|
bus,
|
|
session_manager=sessions,
|
|
workspace_path=default_workspace,
|
|
runtime_surface="native",
|
|
),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = None
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"native-client",
|
|
{
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "chat-native",
|
|
"workspace_scope": {
|
|
"project_path": str(project),
|
|
"access_mode": "full",
|
|
},
|
|
},
|
|
)
|
|
|
|
payload = json.loads(conn.send.await_args.args[0])
|
|
assert payload["event"] == "session_updated"
|
|
assert payload["chat_id"] == "chat-native"
|
|
assert payload["workspace_scope"]["project_path"] == str(project.resolve())
|
|
assert payload["workspace_scope"]["project_name"] == "project"
|
|
assert payload["workspace_scope"]["access_mode"] == "full"
|
|
assert payload["workspace_scope"]["restrict_to_workspace"] is False
|
|
assert payload["workspace_scope"]["sandbox_status"]["restrict_to_workspace"] is False
|
|
assert payload["workspace_scope"]["sandbox_status"]["workspace_root"] == str(project.resolve())
|
|
assert sessions.read_session_file("websocket:chat-native") is None
|
|
assert channel.gateway.workspaces.scope_for_session_key(
|
|
"websocket:chat-native"
|
|
).metadata() == {
|
|
"project_path": str(project.resolve()),
|
|
"access_mode": "full",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delivers_json_message_with_media_and_reply() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
msg = OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="hello",
|
|
reply_to="m1",
|
|
media=["/tmp/a.png"],
|
|
buttons=[["Yes", "No"]],
|
|
)
|
|
await channel.send(msg)
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
payload = json.loads(mock_ws.send.call_args[0][0])
|
|
assert payload["event"] == "message"
|
|
assert payload["chat_id"] == "chat-1"
|
|
assert payload["text"] == "hello"
|
|
assert payload["reply_to"] == "m1"
|
|
assert payload["media"] == ["/tmp/a.png"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pairing_invalidation_reaches_only_authenticated_webui_connections() -> None:
|
|
bus = MessageBus()
|
|
channel = _ch(bus)
|
|
webui, ordinary = AsyncMock(), AsyncMock()
|
|
channel._attach(webui, "chat-1")
|
|
channel._attach(ordinary, "chat-1")
|
|
channel._webui_connections.add(webui)
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket", chat_id="*", content="", event=PairingChanged(),
|
|
))
|
|
assert json.loads(webui.send.call_args[0][0]) == {"event": "pairing_changed"}
|
|
ordinary.send.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_broadcasts_runtime_model_updates() -> None:
|
|
bus = MessageBus()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(
|
|
OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="*",
|
|
content="",
|
|
event=RuntimeModelUpdatedEvent(model="openai/gpt-4.1", model_preset="fast"),
|
|
)
|
|
)
|
|
|
|
payload = json.loads(mock_ws.send.call_args[0][0])
|
|
assert payload["event"] == "runtime_model_updated"
|
|
assert payload["model_name"] == "openai/gpt-4.1"
|
|
assert payload["model_preset"] == "fast"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_projects_external_user_input_to_existing_wire_event() -> None:
|
|
bus = MessageBus()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(
|
|
OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=UserInputEvent(
|
|
content="hello from another session",
|
|
created_at_ms=1234,
|
|
input_id="session-message:external-input",
|
|
provenance={"name": "luma"},
|
|
),
|
|
)
|
|
)
|
|
|
|
payload = json.loads(mock_ws.send.call_args.args[0])
|
|
assert payload == {
|
|
"event": "user_message",
|
|
"chat_id": "chat-1",
|
|
"text": "hello from another session",
|
|
"created_at_ms": 1234,
|
|
"starts_turn": False,
|
|
"input_id": "session-message:external-input",
|
|
"provenance": {"name": "luma"},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_scopes_turn_model_updates_to_the_subscribed_chat() -> None:
|
|
bus = MessageBus()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
chat_one = AsyncMock()
|
|
chat_two = AsyncMock()
|
|
channel._attach(chat_one, "chat-1")
|
|
channel._attach(chat_two, "chat-2")
|
|
|
|
await channel.send(
|
|
OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnModelUpdatedEvent(
|
|
model="deepseek/deepseek-chat",
|
|
model_preset="Deep Research",
|
|
context_window_tokens=128_000,
|
|
),
|
|
)
|
|
)
|
|
|
|
payload = json.loads(chat_one.send.call_args.args[0])
|
|
assert payload == {
|
|
"event": "turn_model_updated",
|
|
"chat_id": "chat-1",
|
|
"model_name": "deepseek/deepseek-chat",
|
|
"model_preset": "Deep Research",
|
|
"context_window_tokens": 128_000,
|
|
}
|
|
|
|
await channel.send(
|
|
OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnModelUpdatedEvent(
|
|
model="deepseek/deepseek-chat",
|
|
model_preset="Deep Research",
|
|
fallback=True,
|
|
reauth_provider="openai_codex",
|
|
),
|
|
)
|
|
)
|
|
fallback_payload = json.loads(chat_one.send.call_args.args[0])
|
|
assert fallback_payload["fallback"] is True
|
|
assert fallback_payload["reauth_provider"] == "openai_codex"
|
|
chat_two.send.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_stages_external_media_as_signed_url(monkeypatch, tmp_path) -> None:
|
|
bus = MagicMock()
|
|
media_root = tmp_path / "media"
|
|
ws_media = media_root / "websocket"
|
|
ws_media.mkdir(parents=True)
|
|
external = tmp_path / "clip.mp4"
|
|
external.write_bytes(b"video")
|
|
|
|
def fake_media_dir(channel: str | None = None):
|
|
return ws_media if channel == "websocket" else media_root
|
|
|
|
monkeypatch.setattr("nanobot.webui.media_gateway.get_media_dir", fake_media_dir)
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(
|
|
OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="video",
|
|
media=[str(external)],
|
|
)
|
|
)
|
|
|
|
payload = json.loads(mock_ws.send.call_args[0][0])
|
|
assert payload["media"] == [str(external)]
|
|
assert payload["media_urls"][0]["name"] == "clip.mp4"
|
|
assert payload["media_urls"][0]["url"].startswith("/api/media/")
|
|
assert any(p.name.endswith("-clip.mp4") for p in ws_media.iterdir())
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_missing_connection_is_noop_without_error() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
msg = OutboundMessage(channel="websocket", chat_id="missing", content="x")
|
|
await channel.send(msg)
|
|
assert channel._subs == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_removes_connection_on_connection_closed() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
mock_ws.send.side_effect = ConnectionClosed(Close(1006, ""), Close(1006, ""), True)
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
msg = OutboundMessage(channel="websocket", chat_id="chat-1", content="hello")
|
|
await channel.send(msg)
|
|
await asyncio.wait_for(_wait_for_connection_cleanup(channel, mock_ws), timeout=1)
|
|
|
|
assert "chat-1" not in channel._subs
|
|
assert mock_ws not in channel._conn_chats
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_progress_includes_structured_tool_events(history) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus, session_manager=history.sessions))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
msg = await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=ProgressEvent(
|
|
tool_hint=True,
|
|
tool_events=[
|
|
{
|
|
"version": 1,
|
|
"phase": "start",
|
|
"call_id": "call-1",
|
|
"name": "web_search",
|
|
"arguments": {"query": "hermes", "count": 8},
|
|
"result": None,
|
|
"error": None,
|
|
"files": [],
|
|
"embeds": [],
|
|
}
|
|
],
|
|
),
|
|
metadata={
|
|
"webui_turn_id": "turn-1",
|
|
},
|
|
)
|
|
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
|
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload["event"] == "message"
|
|
assert payload["kind"] == "tool_hint"
|
|
assert payload["text"] == ""
|
|
assert payload["turn_id"] == "turn-1"
|
|
assert payload["turn_phase"] == "activity"
|
|
assert payload["turn_seq"] == 1
|
|
assert payload["tool_events"] == [
|
|
{
|
|
"version": 1,
|
|
"phase": "start",
|
|
"call_id": "call-1",
|
|
"name": "web_search",
|
|
"arguments": {"query": "hermes", "count": 8},
|
|
"result": None,
|
|
"error": None,
|
|
"files": [],
|
|
"embeds": [],
|
|
}
|
|
]
|
|
[persisted] = history.read("websocket:chat-1")
|
|
assert persisted["text"] == ""
|
|
assert persisted["tool_events"] == payload["tool_events"]
|
|
replay = history.build("websocket:chat-1")
|
|
assert replay is not None
|
|
[replayed] = replay["events"]
|
|
assert replayed["kind"] == "tool_hint"
|
|
assert replayed["text"] == ""
|
|
assert replayed["tool_events"] == payload["tool_events"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_progress_omits_binary_tool_results_from_wire_and_transcript(history, ) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus, session_manager=history.sessions))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-binary-tool-result")
|
|
data_url = f"data:image/png;base64,{'A' * (2 * 1024 * 1024)}"
|
|
tool_events = [
|
|
{
|
|
"version": 1,
|
|
"phase": "end",
|
|
"call_id": "call-image",
|
|
"name": "read_file",
|
|
"arguments": {"path": "/media/screenshot.png"},
|
|
"result": [
|
|
{
|
|
"type": "image_url",
|
|
"image_url": {"url": data_url},
|
|
"_meta": {"path": "/media/screenshot.png"},
|
|
},
|
|
{"type": "text", "text": "(Image file: /media/screenshot.png)"},
|
|
],
|
|
"error": None,
|
|
"files": [],
|
|
"embeds": [],
|
|
}
|
|
]
|
|
|
|
msg = await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-binary-tool-result",
|
|
content="",
|
|
event=ProgressEvent(tool_events=tool_events),
|
|
)
|
|
await ChannelManager._send_once(channel, channel.prepare_tool_events(msg))
|
|
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload["kind"] == "progress"
|
|
assert payload["text"] == ""
|
|
[wire_event] = payload["tool_events"]
|
|
assert wire_event["result"][0]["image_url"]["url"] == (
|
|
"[binary content omitted from WebUI]"
|
|
)
|
|
assert len(mock_ws.send.await_args.args[0].encode("utf-8")) < 4096
|
|
|
|
[persisted] = history.read("websocket:chat-binary-tool-result")
|
|
assert persisted["text"] == ""
|
|
assert persisted["tool_events"] == payload["tool_events"]
|
|
assert data_url not in json.dumps(persisted)
|
|
replay = history.build("websocket:chat-binary-tool-result")
|
|
assert replay is not None
|
|
[replayed] = replay["events"]
|
|
assert replayed["text"] == ""
|
|
assert replayed["tool_events"] == payload["tool_events"]
|
|
|
|
assert tool_events[0]["result"][0]["image_url"]["url"] == data_url
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_file_edit_progress_uses_file_edit_event() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=ProgressEvent(
|
|
file_edit_events=[
|
|
{
|
|
"version": 1,
|
|
"phase": "start",
|
|
"call_id": "call-1",
|
|
"tool": "write_file",
|
|
"path": "src/app.py",
|
|
"added": 12,
|
|
"deleted": 2,
|
|
"approximate": True,
|
|
"status": "editing",
|
|
}
|
|
],
|
|
),
|
|
))
|
|
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload == {
|
|
"event": "file_edit",
|
|
"chat_id": "chat-1",
|
|
"edits": [
|
|
{
|
|
"version": 1,
|
|
"phase": "start",
|
|
"call_id": "call-1",
|
|
"tool": "write_file",
|
|
"path": "src/app.py",
|
|
"added": 12,
|
|
"deleted": 2,
|
|
"approximate": True,
|
|
"status": "editing",
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_progress_includes_agent_ui_blob() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
blob = {
|
|
"kind": "panel",
|
|
"data": {"version": 1, "event": "tick", "id": "r1"},
|
|
}
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="progress · panel",
|
|
event=ProgressEvent(content="progress · panel"),
|
|
metadata={OUTBOUND_META_AGENT_UI: blob},
|
|
))
|
|
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload["event"] == "message"
|
|
assert payload["kind"] == "progress"
|
|
assert payload["agent_ui"] == blob
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_removes_connection_on_connection_closed() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
mock_ws.send.side_effect = ConnectionClosed(Close(1006, ""), Close(1006, ""), True)
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_delta("chat-1", "chunk", stream_id="s1")
|
|
await asyncio.wait_for(_wait_for_connection_cleanup(channel, mock_ws), timeout=1)
|
|
|
|
assert "chat-1" not in channel._subs
|
|
assert mock_ws not in channel._conn_chats
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_emits_delta_and_stream_end() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_delta("chat-1", "part", stream_id="sid")
|
|
await channel.send_delta("chat-1", "", stream_id="sid", stream_end=True)
|
|
|
|
assert mock_ws.send.await_count == 2
|
|
first = json.loads(mock_ws.send.call_args_list[0][0][0])
|
|
second = json.loads(mock_ws.send.call_args_list[1][0][0])
|
|
assert first["event"] == "delta"
|
|
assert first["chat_id"] == "chat-1"
|
|
assert first["text"] == "part"
|
|
assert first["stream_id"] == "sid"
|
|
assert second["event"] == "stream_end"
|
|
assert second["chat_id"] == "chat-1"
|
|
assert second["stream_id"] == "sid"
|
|
assert "text" not in second
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_preserves_webui_source_metadata(history, ) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus, session_manager=history.sessions))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-source-stream")
|
|
source = {"kind": "cron", "label": "Repo check"}
|
|
metadata = {WEBUI_MESSAGE_SOURCE_METADATA_KEY: source}
|
|
|
|
await history.stream(channel, "send_delta", "chat-source-stream", "done", metadata=metadata, stream_id="sid")
|
|
await history.stream(channel, "send_delta",
|
|
"chat-source-stream",
|
|
"",
|
|
metadata=metadata,
|
|
stream_id="sid",
|
|
stream_end=True,
|
|
)
|
|
|
|
first = json.loads(mock_ws.send.call_args_list[0][0][0])
|
|
second = json.loads(mock_ws.send.call_args_list[1][0][0])
|
|
assert first["event"] == "delta"
|
|
assert first["source"] == source
|
|
assert second["event"] == "stream_end"
|
|
assert second["source"] == source
|
|
lines = history.read("websocket:chat-source-stream")
|
|
assert lines[-1]["source"] == source
|
|
assert lines[-1]["event"] == "stream_end"
|
|
assert lines[-1]["text"] == "done"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_marks_resuming_stream_end() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_delta(
|
|
"chat-1",
|
|
"partial answer",
|
|
stream_id="sid",
|
|
stream_end=True,
|
|
resuming=True,
|
|
)
|
|
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload["event"] == "stream_end"
|
|
assert payload["resuming"] is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_preserves_merged_text_then_starts_fresh_segment(history) -> None:
|
|
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await history.stream(channel, "send_delta", "chat-1", "first ", stream_id="sid")
|
|
await history.stream(channel, "send_delta",
|
|
"chat-1",
|
|
"",
|
|
stream_id="sid",
|
|
stream_end=True,
|
|
resuming=True,
|
|
merge_next=True,
|
|
)
|
|
await history.stream(channel, "send_delta", "chat-1", "second", stream_id="sid")
|
|
await history.stream(channel, "send_delta", "chat-1", "", stream_id="sid", stream_end=True)
|
|
|
|
payloads = [json.loads(call.args[0]) for call in mock_ws.send.await_args_list]
|
|
assert payloads[1]["merge_next"] is True
|
|
assert payloads[1]["resuming"] is True
|
|
assert [payload["text"] for payload in payloads if payload["event"] == "delta"] == [
|
|
"first ",
|
|
"second",
|
|
]
|
|
lines = history.read("websocket:chat-1")
|
|
assert [line["event"] for line in lines] == ["stream_end", "stream_end"]
|
|
assert [line["text"] for line in lines] == ["first ", "first second"]
|
|
body = history.build("websocket:chat-1")
|
|
assert body is not None
|
|
assert _thread_conversation_events(body)[-1]["content"] == "first second"
|
|
|
|
await history.stream(
|
|
channel, "send_delta", "chat-1", "new segment", stream_id="sid", stream_end=True,
|
|
)
|
|
|
|
assert _sent_ws_payloads(mock_ws)[-1]["text"] == "new segment"
|
|
assert [line["text"] for line in history.read("websocket:chat-1")] == [
|
|
"first ", "first second", "new segment",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_stream_end_includes_inline_final_text() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_delta(
|
|
"chat-1",
|
|
"merged plain text",
|
|
stream_id="sid",
|
|
stream_end=True,
|
|
)
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
final = json.loads(mock_ws.send.await_args.args[0])
|
|
assert final["event"] == "stream_end"
|
|
assert final["chat_id"] == "chat-1"
|
|
assert final["stream_id"] == "sid"
|
|
assert final["text"] == "merged plain text"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_stream_end_rewrites_local_markdown_image(monkeypatch, tmp_path) -> None:
|
|
bus = MagicMock()
|
|
workspace = tmp_path / "workspace"
|
|
workspace.mkdir()
|
|
(workspace / "diagram.png").write_bytes(b"\x89PNG\r\n\x1a\nimage")
|
|
media = tmp_path / "media"
|
|
|
|
def fake_media_dir(channel: str | None = None):
|
|
path = media / channel if channel else media
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
return path
|
|
|
|
monkeypatch.setattr("nanobot.webui.media_gateway.get_media_dir", fake_media_dir)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
|
bus,
|
|
gateway=_basic_handler(bus, workspace_path=workspace),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_delta("chat-1", "
|
|
await channel.send_delta("chat-1", "diagram.png)", stream_id="sid")
|
|
await channel.send_delta("chat-1", "", stream_id="sid", stream_end=True)
|
|
|
|
assert mock_ws.send.await_count == 3
|
|
final = json.loads(mock_ws.send.call_args_list[2][0][0])
|
|
assert final["event"] == "stream_end"
|
|
assert final["text"].startswith("
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_stream_end_rewrites_inline_final_text(monkeypatch, tmp_path) -> None:
|
|
bus = MagicMock()
|
|
workspace = tmp_path / "workspace"
|
|
workspace.mkdir()
|
|
(workspace / "diagram.png").write_bytes(b"\x89PNG\r\n\x1a\nimage")
|
|
media = tmp_path / "media"
|
|
|
|
def fake_media_dir(channel: str | None = None):
|
|
path = media / channel if channel else media
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
return path
|
|
|
|
monkeypatch.setattr("nanobot.webui.media_gateway.get_media_dir", fake_media_dir)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
|
bus,
|
|
gateway=_basic_handler(bus, workspace_path=workspace),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_delta(
|
|
"chat-1",
|
|
"",
|
|
stream_id="sid",
|
|
stream_end=True,
|
|
)
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
final = json.loads(mock_ws.send.await_args.args[0])
|
|
assert final["event"] == "stream_end"
|
|
assert final["text"].startswith("
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_reasoning_delta_emits_streaming_frame() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_reasoning_delta(
|
|
"chat-1",
|
|
"step-by-step thinking",
|
|
stream_id="r1",
|
|
)
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload["event"] == "reasoning_delta"
|
|
assert payload["chat_id"] == "chat-1"
|
|
assert payload["text"] == "step-by-step thinking"
|
|
assert payload["stream_id"] == "r1"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_reasoning_end_emits_close_frame() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_reasoning_end("chat-1", stream_id="r1")
|
|
|
|
payload = json.loads(mock_ws.send.await_args.args[0])
|
|
assert payload == {"event": "reasoning_end", "chat_id": "chat-1", "stream_id": "r1"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_reasoning_one_shot_expands_to_delta_plus_end() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_reasoning(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="thinking",
|
|
event=ProgressEvent(content="thinking", reasoning=True),
|
|
))
|
|
|
|
assert mock_ws.send.await_count == 2
|
|
first = json.loads(mock_ws.send.call_args_list[0][0][0])
|
|
second = json.loads(mock_ws.send.call_args_list[1][0][0])
|
|
assert first["event"] == "reasoning_delta"
|
|
assert first["text"] == "thinking"
|
|
assert second["event"] == "reasoning_end"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_reasoning_delta_drops_empty_chunks() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send_reasoning_delta("chat-1", "")
|
|
|
|
mock_ws.send.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_reasoning_without_subscribers_is_noop() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
|
|
await channel.send_reasoning_delta("unattached", "thinking", None)
|
|
await channel.send_reasoning_end("unattached", None)
|
|
assert channel._subs == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_transcript_persists_without_subscribers(history, ) -> None:
|
|
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
|
|
await history.stream(channel, "send_delta", "chat-1", "hello", stream_id="s1")
|
|
await history.stream(channel, "send_delta", "chat-1", " world", stream_id="s1")
|
|
await history.stream(channel, "send_delta", "chat-1", "", stream_id="s1", stream_end=True)
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnEndEvent(latency_ms=42),
|
|
))
|
|
|
|
assert channel._subs == {}
|
|
lines = history.read("websocket:chat-1")
|
|
assert [line["event"] for line in lines] == ["stream_end", "turn_end"]
|
|
assert lines[0]["text"] == "hello world"
|
|
body = history.build("websocket:chat-1")
|
|
assert body is not None
|
|
assert _thread_conversation_events(body)[-1]["role"] == "assistant"
|
|
assert _thread_conversation_events(body)[-1]["content"] == "hello world"
|
|
assert _thread_conversation_events(body)[-1]["latencyMs"] == 42
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("temporary", [False, True])
|
|
async def test_stream_policy_does_not_copy_history_on_runtime_loop(
|
|
bus, tmp_path, monkeypatch, temporary,
|
|
) -> None:
|
|
import nanobot.session.state as session_state
|
|
|
|
sessions = SessionManager(tmp_path)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]}, bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
owner = object()
|
|
chat_id = (
|
|
await channel.gateway.temporary_chats.create(owner, trusted_webui=True)
|
|
if temporary else "history-copy"
|
|
)
|
|
history = [
|
|
{"role": "user", "content": f"history {i}"} for i in range(1000)
|
|
]
|
|
draft = await sessions.state.import_messages(f"websocket:{chat_id}", history)
|
|
await sessions.state.checkpoint_view(draft, {"messages": history})
|
|
runtime_thread = threading.get_ident()
|
|
original_copy = session_state.deepcopy
|
|
|
|
def copy_off_loop(value, *args, **kwargs):
|
|
if (
|
|
isinstance(value, Session) and value.messages
|
|
or isinstance(value, dict) and "runtime_checkpoint" in value
|
|
):
|
|
assert threading.get_ident() != runtime_thread, "history copied on runtime loop"
|
|
return original_copy(value, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(session_state, "deepcopy", copy_off_loop)
|
|
append = AsyncMock(wraps=sessions.state.append_history)
|
|
monkeypatch.setattr(sessions.state, "append_history", append)
|
|
metadata = {"_history_generation": draft.generation}
|
|
try:
|
|
policy = channel.gateway.temporary_chats.message_policy(owner, chat_id, "hello")
|
|
assert (policy is not None) is temporary
|
|
await channel.send_delta(chat_id, "one", stream_id="s1", metadata=metadata)
|
|
await channel.send_delta(chat_id, " two", stream_id="s1", metadata=metadata)
|
|
await channel.send_delta(chat_id, "", stream_id="s1", stream_end=True, metadata=metadata)
|
|
await channel.send_reasoning_delta(chat_id, "plan", stream_id="r1", metadata=metadata)
|
|
await channel.send_reasoning_end(chat_id, stream_id="r1", metadata=metadata)
|
|
assert append.call_count == (0 if temporary else 2)
|
|
finally:
|
|
channel.gateway.temporary_chats.close()
|
|
await sessions.state.aclose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_transcript_writes_once_per_completed_segment(history, monkeypatch) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
append = AsyncMock(wraps=history.sessions.state.append_history)
|
|
monkeypatch.setattr(history.sessions.state, "append_history", append)
|
|
|
|
await history.stream(channel, "send_delta", "chat-write-rate", "one", stream_id="s1")
|
|
await history.stream(channel, "send_delta", "chat-write-rate", " two", stream_id="s1")
|
|
await history.stream(channel, "send_delta", "chat-write-rate", " three", stream_id="s1")
|
|
|
|
append.assert_not_called()
|
|
|
|
await history.stream(channel, "send_delta", "chat-write-rate", "", stream_id="s1", stream_end=True)
|
|
|
|
append.assert_called_once()
|
|
persisted = append.call_args.args[1][0]
|
|
assert persisted.kind is HistoryKind.ANSWER_SEGMENT
|
|
assert persisted.content["text"] == "one two three"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_reasoning_transcript_persists_one_canonical_record(history, monkeypatch) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
append = AsyncMock(wraps=history.sessions.state.append_history)
|
|
monkeypatch.setattr(history.sessions.state, "append_history", append)
|
|
|
|
await history.stream(channel, "send_reasoning_delta", "chat-reasoning-write-rate", "plan ", stream_id="r1")
|
|
await history.stream(channel, "send_reasoning_delta", "chat-reasoning-write-rate", "then act", stream_id="r1")
|
|
|
|
append.assert_not_called()
|
|
|
|
await history.stream(channel, "send_reasoning_end", "chat-reasoning-write-rate", stream_id="r1")
|
|
|
|
append.assert_called_once()
|
|
persisted = append.call_args.args[1][0]
|
|
assert persisted.kind is HistoryKind.REASONING_SEGMENT
|
|
assert persisted.content["text"] == "plan then act"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_turn_end_keeps_unclosed_text_out_of_the_next_stream_segment(history) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "streaming": True},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-unclosed")
|
|
|
|
await history.stream(channel, "send_delta", "chat-unclosed", "partial", stream_id="s1")
|
|
await history.stream(channel, "send_reasoning_delta", "chat-unclosed", "thinking", stream_id="r1")
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-unclosed",
|
|
content="",
|
|
event=TurnEndEvent(),
|
|
))
|
|
await history.stream(channel, "send_delta", "chat-unclosed", "fresh", stream_id="s1")
|
|
await history.stream(
|
|
channel, "send_delta", "chat-unclosed", " answer", stream_id="s1", stream_end=True,
|
|
)
|
|
await history.stream(channel, "send_reasoning_delta", "chat-unclosed", "new thought", stream_id="r1")
|
|
await history.stream(channel, "send_reasoning_end", "chat-unclosed", stream_id="r1")
|
|
|
|
payloads = _sent_ws_payloads(mock_ws)
|
|
assert next(payload for payload in payloads if payload["event"] == "stream_end")["text"] == "fresh answer"
|
|
assert payloads[-2]["event"] == "reasoning_delta"
|
|
assert payloads[-2]["text"] == "new thought"
|
|
assert payloads[-1] == {
|
|
"event": "reasoning_end", "chat_id": "chat-unclosed", "stream_id": "r1",
|
|
}
|
|
lines = history.read("websocket:chat-unclosed")
|
|
assert [(line["event"], line.get("text")) for line in lines] == [
|
|
("turn_end", None), ("stream_end", "fresh answer"), ("reasoning_end", "new thought"),
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_turn_end_emits_turn_end_event() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnEndEvent(),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [
|
|
{"event": "turn_end", "chat_id": "chat-1"},
|
|
{"event": "session_updated", "chat_id": "chat-1", "scope": "thread"},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retry_status_is_transient_and_turn_scoped(
|
|
history, monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.webui.outbound_wire.time.time", lambda: 120.0)
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
metadata={WEBUI_TURN_METADATA_KEY: "turn-1"},
|
|
event=RetryStatusEvent(
|
|
state="waiting",
|
|
attempt=2,
|
|
max_attempts=4,
|
|
error_kind="connection",
|
|
next_retry_at=123.5,
|
|
),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [{
|
|
"event": "retry_status",
|
|
"chat_id": "chat-1",
|
|
"turn_id": "turn-1",
|
|
"state": "waiting",
|
|
"attempt": 2,
|
|
"max_attempts": 4,
|
|
"error_kind": "connection",
|
|
"retry_after_s": 3.5,
|
|
}]
|
|
assert history.read("websocket:chat-1") == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_legacy_retry_wait_is_not_sent_or_persisted(history) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="Model request failed, retry in 2s (attempt 1).",
|
|
event=RetryWaitEvent(
|
|
content="Model request failed, retry in 2s (attempt 1).",
|
|
),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == []
|
|
assert history.read("websocket:chat-1") == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_failed_turn_end_exposes_safe_terminal_outcome() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnEndEvent(
|
|
outcome="failed",
|
|
failure_kind="model",
|
|
failure_error_kind="connection",
|
|
failure_attempts=4,
|
|
failure_message="Model provider request failed.",
|
|
),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws)[0] == {
|
|
"event": "turn_end",
|
|
"chat_id": "chat-1",
|
|
"outcome": "failed",
|
|
"failure_kind": "model",
|
|
"failure_error_kind": "connection",
|
|
"failure_attempts": 4,
|
|
"failure_message": "Model provider request failed.",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("notify", [False, True])
|
|
@pytest.mark.parametrize("show_notices", [False, True])
|
|
async def test_context_compaction_started_is_live_only(history, notify, show_notices) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-compaction-started")
|
|
channel.show_compaction_notices = show_notices
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-compaction-started",
|
|
content="Compressing context…",
|
|
event=ContextCompactionEvent(
|
|
compaction_id="compact-started",
|
|
phase="started",
|
|
notify=notify,
|
|
),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [{
|
|
"event": "context_compaction",
|
|
"chat_id": "chat-compaction-started",
|
|
"compaction_id": "compact-started",
|
|
"phase": "started",
|
|
}]
|
|
assert history.read("websocket:chat-compaction-started") == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("notify", [False, True])
|
|
@pytest.mark.parametrize("show_notices", [False, True])
|
|
@pytest.mark.parametrize("phase", ["succeeded", "failed", "cancelled"])
|
|
async def test_context_compaction_is_structured_persisted_and_summary_free(history, notify, show_notices, phase) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-compaction")
|
|
channel.show_compaction_notices = show_notices
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-compaction",
|
|
content="Context compacted · LLM summary",
|
|
event=ContextCompactionEvent(
|
|
compaction_id="compact-1",
|
|
phase=phase,
|
|
notify=notify,
|
|
reason="manual",
|
|
),
|
|
))
|
|
|
|
expected = {
|
|
"event": "context_compaction",
|
|
"chat_id": "chat-compaction",
|
|
"compaction_id": "compact-1",
|
|
"phase": phase,
|
|
"reason": "manual",
|
|
}
|
|
assert _sent_ws_payloads(mock_ws) == [expected]
|
|
[persisted] = history.read("websocket:chat-compaction")
|
|
assert {key: persisted[key] for key in expected} == expected
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_recovery_state_is_a_structured_event_not_assistant_text(history) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=RecoveryStateEvent(
|
|
status="awaiting_user",
|
|
recovery_id="recovery-1",
|
|
reason="tool_state_unknown",
|
|
attempts=1,
|
|
),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [{
|
|
"event": "recovery_state",
|
|
"chat_id": "chat-1",
|
|
"status": "awaiting_user",
|
|
"recovery_id": "recovery-1",
|
|
"reason": "tool_state_unknown",
|
|
"attempts": 1,
|
|
}]
|
|
assert history.read("websocket:chat-1") == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_system_command_turn_end_only_refreshes_session_metadata() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-model")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-model",
|
|
content="",
|
|
metadata={
|
|
WEBUI_TURN_METADATA_KEY: f"{WEBUI_SYSTEM_COMMAND_TURN_PREFIX}model-switch",
|
|
},
|
|
event=TurnEndEvent(),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [
|
|
{
|
|
"event": "turn_end",
|
|
"chat_id": "chat-model",
|
|
"turn_id": f"{WEBUI_SYSTEM_COMMAND_TURN_PREFIX}model-switch",
|
|
"turn_phase": "complete",
|
|
"turn_seq": 1,
|
|
},
|
|
{
|
|
"event": "session_updated",
|
|
"chat_id": "chat-model",
|
|
"scope": "metadata",
|
|
},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("active_owner", "event_owner", "expected_cleared"),
|
|
[
|
|
("owner-current", "owner-current", True),
|
|
("owner-new", "owner-old", False),
|
|
],
|
|
)
|
|
async def test_turn_end_persists_and_conditionally_clears_when_delivery_fails(history,
|
|
active_owner: str,
|
|
event_owner: str,
|
|
expected_cleared: bool,
|
|
) -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
mock_ws.send.side_effect = RuntimeError("fanout failed")
|
|
chat_id = f"turn-end-failure-{expected_cleared}"
|
|
channel._attach(mock_ws, chat_id)
|
|
await _register_running_turn(chat_id, 1234.5, owner=active_owner)
|
|
|
|
try:
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata={WEBSOCKET_TURN_OWNER_METADATA_KEY: event_owner},
|
|
event=TurnEndEvent(),
|
|
))
|
|
await asyncio.wait_for(_wait_for_connection_cleanup(channel, mock_ws), timeout=1)
|
|
|
|
assert history.read(f"websocket:{chat_id}")[-1]["event"] == "turn_end"
|
|
assert (wth.websocket_turn_wall_started_at(chat_id) is None) is expected_cleared
|
|
if not expected_cleared:
|
|
assert wth._WEBSOCKET_TURN_OWNERS[chat_id] == active_owner
|
|
finally:
|
|
wth.clear_websocket_turns(chat_id)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_turn_end_keeps_registry_when_transcript_persistence_fails(history,
|
|
monkeypatch,
|
|
) -> None:
|
|
from nanobot.bus.events import InboundMessage
|
|
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
chat_id = "turn-end-persistence-failure"
|
|
owner = "owner-persist"
|
|
turn_id = "turn-persist"
|
|
inbound = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id=chat_id,
|
|
content="hi",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: owner,
|
|
"webui_turn_id": turn_id,
|
|
"webui": True,
|
|
},
|
|
)
|
|
await wth.publish_turn_run_status(bus, inbound, "running", started_at=1234.5)
|
|
append = AsyncMock(side_effect=OSError("disk full"))
|
|
monkeypatch.setattr(history.sessions.state, "append_history", append)
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: owner,
|
|
"webui_turn_id": turn_id,
|
|
"webui": True,
|
|
},
|
|
event=TurnEndEvent(),
|
|
))
|
|
|
|
append.assert_called_once()
|
|
assert wth.websocket_turn_wall_started_at(chat_id) == 1234.5
|
|
assert wth.websocket_turn_id(chat_id) == turn_id
|
|
assert wth._WEBSOCKET_TURN_OWNERS[chat_id] == owner
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=GoalStatusEvent(status="idle"),
|
|
))
|
|
|
|
# The normal WebUI idle event follows turn_end. It must not convert a
|
|
# failed canonical completion write into an apparently settled HTTP
|
|
# snapshot.
|
|
assert wth.websocket_turn_wall_started_at(chat_id) == 1234.5
|
|
assert wth.websocket_turn_id(chat_id) == turn_id
|
|
assert wth._WEBSOCKET_TURN_OWNERS[chat_id] == owner
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_durable_incomplete_marker_stays_pending_without_safe_session_recovery(history,
|
|
monkeypatch,
|
|
) -> None:
|
|
from nanobot.bus.events import InboundMessage
|
|
|
|
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
chat_id = "answer-persistence-failure"
|
|
key = f"websocket:{chat_id}"
|
|
owner = "owner-answer"
|
|
turn_id = "turn-answer"
|
|
history.append(
|
|
key,
|
|
{"event": "user", "chat_id": chat_id, "text": "question", "turn_id": turn_id},
|
|
)
|
|
inbound = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id=chat_id,
|
|
content="question",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: owner,
|
|
"webui_turn_id": turn_id,
|
|
"webui": True,
|
|
},
|
|
)
|
|
await wth.publish_turn_run_status(bus, inbound, "running", started_at=1234.5)
|
|
|
|
original_append = history.sessions.state.append_history
|
|
|
|
async def fail_answer(session_key, facts, *, expected_generation, skip_invalid=False):
|
|
if any(fact.kind is HistoryKind.ANSWER for fact in facts):
|
|
raise OSError("transient disk failure")
|
|
return await original_append(session_key, facts, expected_generation=expected_generation, skip_invalid=skip_invalid)
|
|
|
|
monkeypatch.setattr(history.sessions.state, "append_history", fail_answer)
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="answer",
|
|
metadata=dict(inbound.metadata),
|
|
))
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=TurnEndEvent(),
|
|
))
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=GoalStatusEvent(status="idle"),
|
|
))
|
|
|
|
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
|
wth._WEBSOCKET_TURN_IDS.clear()
|
|
wth._WEBSOCKET_TURN_OWNERS.clear()
|
|
body = history.build(
|
|
key,
|
|
active_turn_started_at=wth.websocket_turn_wall_started_at(chat_id),
|
|
active_turn_id=wth.websocket_turn_id(chat_id),
|
|
active_turn_transcript_persistence_failed=(
|
|
wth.websocket_turn_transcript_persistence_failed(chat_id)
|
|
),
|
|
)
|
|
assert body is not None
|
|
assert history.read(key)[-1]["transcript_incomplete"] is True
|
|
assert body["completed_turn_ids"] == []
|
|
assert [
|
|
(message["role"], message["content"])
|
|
for message in _thread_conversation_events(body)
|
|
] == [
|
|
("user", "question"),
|
|
]
|
|
assert body["has_pending_tool_calls"] is True
|
|
assert chat_id not in wth._WEBSOCKET_TURN_OWNERS
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_http_replay_recovers_marked_answer_from_session_after_gateway_restart(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.bus.events import InboundMessage
|
|
|
|
chat_id = "answer-recovery-after-restart"
|
|
key = f"websocket:{chat_id}"
|
|
owner = "owner-answer-recovery"
|
|
turn_id = "turn-answer-recovery"
|
|
sessions_path = history.sessions.workspace
|
|
sessions = history.sessions
|
|
session = sessions.get_or_create(key)
|
|
session.add_message("user", "question")
|
|
session.add_message("assistant", "durable answer")
|
|
sessions.save(session)
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "user",
|
|
"chat_id": chat_id,
|
|
"text": "question",
|
|
"turn_id": turn_id,
|
|
},
|
|
)
|
|
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions),
|
|
)
|
|
inbound = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id=chat_id,
|
|
content="question",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: owner,
|
|
"webui_turn_id": turn_id,
|
|
"webui": True,
|
|
},
|
|
)
|
|
await wth.publish_turn_run_status(bus, inbound, "running", started_at=1234.5)
|
|
|
|
original_append = history.sessions.state.append_history
|
|
|
|
async def fail_answer(session_key, facts, *, expected_generation, skip_invalid=False):
|
|
if any(fact.kind is HistoryKind.ANSWER for fact in facts):
|
|
raise OSError("transient disk failure")
|
|
return await original_append(session_key, facts, expected_generation=expected_generation, skip_invalid=skip_invalid)
|
|
|
|
monkeypatch.setattr(history.sessions.state, "append_history", fail_answer)
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="durable answer",
|
|
metadata=dict(inbound.metadata),
|
|
))
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=TurnEndEvent(),
|
|
))
|
|
|
|
persisted_lines = history.read(key)
|
|
assert persisted_lines[-1]["event"] == "turn_end"
|
|
assert persisted_lines[-1]["transcript_incomplete"] is True
|
|
|
|
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
|
wth._WEBSOCKET_TURN_IDS.clear()
|
|
wth._WEBSOCKET_TURN_OWNERS.clear()
|
|
restarted_channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(
|
|
bus,
|
|
session_manager=SessionManager(sessions_path),
|
|
),
|
|
)
|
|
restarted_channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
encoded_key = quote(key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{encoded_key}/webui-thread",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
response = await restarted_channel.gateway.http._handle_webui_thread_get_async(request, encoded_key)
|
|
|
|
assert response.status_code == 200
|
|
body = json.loads(response.body.decode())
|
|
assert [
|
|
(message["role"], message["content"])
|
|
for message in _thread_conversation_events(body)
|
|
] == [
|
|
("user", "question"),
|
|
("assistant", "durable answer"),
|
|
]
|
|
assert body["completed_turn_ids"] == [turn_id]
|
|
assert body["has_pending_tool_calls"] is False
|
|
assert body["active_turn_id"] is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_idle_clears_owner_when_no_completion_write_failed() -> None:
|
|
from nanobot.bus.events import InboundMessage
|
|
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
chat_id = "cancelled-webui-turn"
|
|
owner = "owner-cancelled"
|
|
inbound = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id=chat_id,
|
|
content="hi",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: owner,
|
|
"webui_turn_id": "turn-cancelled",
|
|
"webui": True,
|
|
},
|
|
)
|
|
await wth.publish_turn_run_status(bus, inbound, "running", started_at=1234.5)
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=GoalStatusEvent(status="idle"),
|
|
))
|
|
|
|
assert wth.websocket_turn_wall_started_at(chat_id) is None
|
|
assert wth.websocket_turn_id(chat_id) is None
|
|
assert chat_id not in wth._WEBSOCKET_ACTIVE_TURNS
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_non_webui_transcript_failure_does_not_block_idle_cleanup(
|
|
monkeypatch,
|
|
) -> None:
|
|
from nanobot.bus.events import InboundMessage
|
|
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
chat_id = "direct-non-webui-failure"
|
|
owner = "owner-direct"
|
|
inbound = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="runtime",
|
|
chat_id=chat_id,
|
|
content="direct",
|
|
metadata={WEBSOCKET_TURN_OWNER_METADATA_KEY: owner},
|
|
)
|
|
await wth.publish_turn_run_status(bus, inbound, "running", started_at=1234.5)
|
|
monkeypatch.setattr(
|
|
"nanobot.webui.transcript.append_transcript_object",
|
|
MagicMock(side_effect=OSError("disk full")),
|
|
)
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="direct answer",
|
|
metadata=dict(inbound.metadata),
|
|
))
|
|
|
|
assert wth.websocket_turn_transcript_persistence_failed(chat_id, owner) is False
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=GoalStatusEvent(status="idle"),
|
|
))
|
|
assert wth.websocket_turn_wall_started_at(chat_id) is None
|
|
assert chat_id not in wth._WEBSOCKET_ACTIVE_TURNS
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_idle_clears_matching_owner_when_delivery_fails() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
mock_ws.send.side_effect = RuntimeError("fanout failed")
|
|
chat_id = "idle-failure"
|
|
owner = "owner-idle"
|
|
channel._attach(mock_ws, chat_id)
|
|
await _register_running_turn(chat_id, 1234.5, owner=owner)
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
metadata={WEBSOCKET_TURN_OWNER_METADATA_KEY: owner},
|
|
event=GoalStatusEvent(status="idle"),
|
|
))
|
|
await asyncio.wait_for(_wait_for_connection_cleanup(channel, mock_ws), timeout=1)
|
|
|
|
assert wth.websocket_turn_wall_started_at(chat_id) is None
|
|
assert chat_id not in wth._WEBSOCKET_TURN_OWNERS
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_turn_end_includes_latency_ms_when_present() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
usage = LLMUsage.reported(
|
|
input_tokens=80,
|
|
output_tokens=20,
|
|
cache_read_tokens=40,
|
|
).with_timing(generation_ms=500, ttft_ms=125)
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnEndEvent(
|
|
latency_ms=1500,
|
|
usage=usage,
|
|
round_usages=(usage,),
|
|
context_window_tokens=128_000,
|
|
),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [
|
|
{
|
|
"event": "turn_end",
|
|
"chat_id": "chat-1",
|
|
"latency_ms": 1500,
|
|
"usage": {
|
|
"prompt_tokens": 80,
|
|
"completion_tokens": 20,
|
|
"total_tokens": 100,
|
|
"context_tokens": 80,
|
|
"cached_tokens": 40,
|
|
"request_count": 1,
|
|
"estimated_tokens": 0,
|
|
"generation_ms": 500,
|
|
"measured_completion_tokens": 20,
|
|
"ttft_ms": 125,
|
|
"timed_requests": 1,
|
|
},
|
|
"round_usages": [
|
|
{
|
|
"prompt_tokens": 80,
|
|
"completion_tokens": 20,
|
|
"total_tokens": 100,
|
|
"context_tokens": 80,
|
|
"cached_tokens": 40,
|
|
"request_count": 1,
|
|
"estimated_tokens": 0,
|
|
"generation_ms": 500,
|
|
"measured_completion_tokens": 20,
|
|
"ttft_ms": 125,
|
|
"timed_requests": 1,
|
|
}
|
|
],
|
|
"context_window_tokens": 128_000,
|
|
},
|
|
{"event": "session_updated", "chat_id": "chat-1", "scope": "thread"},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_turn_end_includes_goal_state_when_present() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
blob = {"active": True, "ui_summary": "Explore codebase"}
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=TurnEndEvent(goal_state=blob),
|
|
))
|
|
|
|
assert _sent_ws_payloads(mock_ws) == [
|
|
{"event": "turn_end", "chat_id": "chat-1", "goal_state": blob},
|
|
{"event": "session_updated", "chat_id": "chat-1", "scope": "thread"},
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_goal_status_running_emits_event_with_started_at() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
metadata={"webui_turn_id": "turn-running"},
|
|
event=GoalStatusEvent(status="running", started_at=1_700_000_000.5),
|
|
))
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body == {
|
|
"event": "goal_status",
|
|
"chat_id": "chat-1",
|
|
"status": "running",
|
|
"started_at": 1_700_000_000.5,
|
|
"turn_id": "turn-running",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_goal_status_idle_omits_started_at() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
metadata={"webui_turn_id": "turn-idle"},
|
|
event=GoalStatusEvent(status="idle", started_at=99.0),
|
|
))
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body == {
|
|
"event": "goal_status",
|
|
"chat_id": "chat-1",
|
|
"status": "idle",
|
|
"turn_id": "turn-idle",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_goal_state_emits_blob_per_chat() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_a = AsyncMock()
|
|
mock_b = AsyncMock()
|
|
channel._attach(mock_a, "chat-a")
|
|
channel._attach(mock_b, "chat-b")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-a",
|
|
content="",
|
|
event=GoalStateSyncEvent(goal_state={"active": True, "ui_summary": "A"}),
|
|
))
|
|
|
|
mock_a.send.assert_awaited_once()
|
|
mock_b.send.assert_not_called()
|
|
body = json.loads(mock_a.send.await_args.args[0])
|
|
assert body == {
|
|
"event": "goal_state",
|
|
"chat_id": "chat-a",
|
|
"goal_state": {"active": True, "ui_summary": "A"},
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hydrate_noop_without_session_manager() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
await channel._outbound.hydrate("chat-1")
|
|
mock_ws.send.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hydrate_skips_when_no_goal_on_disk() -> None:
|
|
bus = MagicMock()
|
|
sm = MagicMock()
|
|
sm.state.read_metadata = AsyncMock()
|
|
sm.state.read_metadata.return_value = None
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sm),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
await channel._outbound.hydrate("chat-1")
|
|
mock_ws.send.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hydrate_notifies_when_goal_active_on_disk() -> None:
|
|
bus = MagicMock()
|
|
sm = MagicMock()
|
|
sm.state.read_metadata = AsyncMock()
|
|
sm.state.read_metadata.return_value = {
|
|
"metadata": {
|
|
"goal_state": {
|
|
"status": "active",
|
|
"objective": "finish docs",
|
|
"ui_summary": "Docs",
|
|
},
|
|
},
|
|
"messages": [],
|
|
}
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sm),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
await channel._outbound.hydrate("chat-1")
|
|
mock_ws.send.assert_awaited_once()
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body["event"] == "goal_state"
|
|
assert body["chat_id"] == "chat-1"
|
|
assert body["goal_state"]["active"] is True
|
|
assert body["goal_state"]["objective"] == "finish docs"
|
|
assert body["goal_state"]["ui_summary"] == "Docs"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hydrate_restores_blocked_attention_on_disk() -> None:
|
|
bus = MagicMock()
|
|
sm = MagicMock()
|
|
sm.state.read_metadata = AsyncMock()
|
|
sm.state.read_metadata.return_value = {
|
|
"metadata": {
|
|
"goal_state": {
|
|
"status": "blocked",
|
|
"objective": "deploy safely",
|
|
"ui_summary": "Approval required",
|
|
},
|
|
},
|
|
"messages": [],
|
|
}
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sm),
|
|
)
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel._outbound.hydrate("chat-1")
|
|
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body["goal_state"] == {
|
|
"active": False,
|
|
"status": "blocked",
|
|
"ui_summary": "Approval required",
|
|
"objective": "deploy safely",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hydrate_skips_when_no_active_turn() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
from nanobot.session import webui_turns as wth
|
|
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
|
await channel._outbound.hydrate("chat-1")
|
|
mock_ws.send.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_hydrate_replays_running_turn() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
from nanobot.session import webui_turns as wth
|
|
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
|
try:
|
|
await _register_running_turn("chat-1", 1_700_000_000.0)
|
|
await channel._outbound.hydrate("chat-1")
|
|
finally:
|
|
wth.clear_websocket_turns("chat-1")
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body == {
|
|
"event": "goal_status",
|
|
"chat_id": "chat-1",
|
|
"status": "running",
|
|
"started_at": 1_700_000_000.0,
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_session_updated_emits_session_updated_event() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=SessionUpdatedEvent(),
|
|
))
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body == {"event": "session_updated", "chat_id": "chat-1"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_session_updated_includes_scope_when_present() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id="chat-1",
|
|
content="",
|
|
event=SessionUpdatedEvent(scope="metadata"),
|
|
))
|
|
|
|
mock_ws.send.assert_awaited_once()
|
|
body = json.loads(mock_ws.send.await_args.args[0])
|
|
assert body == {"event": "session_updated", "chat_id": "chat-1", "scope": "metadata"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_non_connection_closed_exception_is_isolated() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
mock_ws = AsyncMock()
|
|
mock_ws.send.side_effect = RuntimeError("unexpected")
|
|
channel._attach(mock_ws, "chat-1")
|
|
|
|
msg = OutboundMessage(channel="websocket", chat_id="chat-1", content="hello")
|
|
await channel.send(msg)
|
|
await asyncio.wait_for(_wait_for_connection_cleanup(channel, mock_ws), timeout=1)
|
|
|
|
mock_ws.close.assert_awaited_once_with(code=1011, reason="outbound send failed")
|
|
assert "chat-1" not in channel._subs
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_delta_missing_connection_is_noop() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=_basic_handler(bus))
|
|
await channel.send_delta("nonexistent", "chunk", stream_id="s1")
|
|
assert channel._subs == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stop_is_idempotent() -> None:
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"]}, bus, gateway=_basic_handler(bus))
|
|
await channel.stop()
|
|
await channel.stop()
|
|
assert channel._subs == {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
client = await websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=tester")
|
|
async with client:
|
|
ready_raw = await client.recv()
|
|
ready = json.loads(ready_raw)
|
|
assert ready["event"] == "ready"
|
|
assert ready["client_id"] == "tester"
|
|
chat_id = ready["chat_id"]
|
|
|
|
await client.send(json.dumps({"content": "ping from client"}))
|
|
await asyncio.sleep(0.08)
|
|
|
|
bus.publish_inbound.assert_awaited()
|
|
inbound = bus.publish_inbound.call_args[0][0]
|
|
assert inbound.channel == "websocket"
|
|
assert inbound.sender_id == "tester"
|
|
assert inbound.chat_id == chat_id
|
|
assert inbound.content == "ping from client"
|
|
|
|
await client.send("plain text frame")
|
|
await asyncio.sleep(0.08)
|
|
assert bus.publish_inbound.await_count >= 2
|
|
second = [c[0][0] for c in bus.publish_inbound.call_args_list][-1]
|
|
assert second.content == "plain text frame"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_token_rejects_handshake_when_mismatch(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port, path="/", token="secret")
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/?token=wrong"):
|
|
pass
|
|
assert excinfo.value.response.status_code == 401
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wrong_path_returns_404(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/other"):
|
|
pass
|
|
assert excinfo.value.response.status_code == 404
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
def test_registry_discovers_websocket_channel() -> None:
|
|
from nanobot.channels.registry import load_channel_class
|
|
|
|
cls = load_channel_class("websocket")
|
|
assert cls.name == "websocket"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(
|
|
bus, port=port,
|
|
tokenIssuePath="/auth/token",
|
|
tokenIssueSecret="route-secret",
|
|
websocketRequiresToken=True,
|
|
)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
deny = await _http_get(f"http://127.0.0.1:{port}/auth/token")
|
|
assert deny.status_code == 401
|
|
|
|
issue = await _http_get(
|
|
f"http://127.0.0.1:{port}/auth/token",
|
|
headers={"Authorization": "Bearer route-secret"},
|
|
)
|
|
assert issue.status_code == 200
|
|
token = issue.json()["token"]
|
|
assert token.startswith("nbwt_")
|
|
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as missing_token:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=x"):
|
|
pass
|
|
assert missing_token.value.response.status_code == 401
|
|
|
|
uri = f"ws://127.0.0.1:{port}/ws?token={token}&client_id=caller"
|
|
async with websockets.connect(uri) as client:
|
|
ready = json.loads(await client.recv())
|
|
assert ready["event"] == "ready"
|
|
assert ready["client_id"] == "caller"
|
|
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as reuse:
|
|
async with websockets.connect(uri):
|
|
pass
|
|
assert reuse.value.response.status_code == 401
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_settings_api_returns_safe_subset_and_updates_whitelist(
|
|
bus: MagicMock,
|
|
monkeypatch,
|
|
tmp_path,
|
|
start_listener,
|
|
) -> None:
|
|
port = 0
|
|
config_path = tmp_path / "config.json"
|
|
config = Config()
|
|
config.agents.defaults.model = "openai/gpt-4o"
|
|
config.providers.openai.api_key = "secret-key"
|
|
config.model_presets["deep"] = ModelPresetConfig(
|
|
model="anthropic/claude-opus-4-5",
|
|
provider="anthropic",
|
|
reasoning_effort="high",
|
|
)
|
|
config.tools.web.search.provider = "brave"
|
|
config.tools.web.search.api_key = "brave-secret"
|
|
expected_timezone = config.agents.defaults.timezone
|
|
save_config(config, config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
monkeypatch.setattr(
|
|
"nanobot.webui.settings_api._oauth_provider_status",
|
|
lambda _spec: {
|
|
"configured": False,
|
|
"account": None,
|
|
"expires_at": None,
|
|
"login_supported": True,
|
|
},
|
|
)
|
|
image_reload = AsyncMock(
|
|
return_value={
|
|
"ok": True,
|
|
"message": "Image generation settings applied.",
|
|
"requires_restart": False,
|
|
}
|
|
)
|
|
channel = _ch(bus, port=port, image_generation_reload=image_reload)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
webui_client = None
|
|
try:
|
|
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
|
|
webui_client = await websockets.connect(
|
|
f"ws://127.0.0.1:{port}/ws?token={webui_token}&client_id=settings-test"
|
|
)
|
|
ready = json.loads(await asyncio.wait_for(webui_client.recv(), timeout=5))
|
|
assert ready["event"] == "ready"
|
|
|
|
settings = await _http_get(
|
|
f"http://127.0.0.1:{port}/api/settings",
|
|
headers={"Authorization": "Bearer tok"},
|
|
)
|
|
assert settings.status_code == 200
|
|
body = settings.json()
|
|
assert body["agent"]["model"] == "openai/gpt-4o"
|
|
assert body["agent"]["provider"] == "openai"
|
|
assert body["agent"]["model_preset"] == "default"
|
|
assert body["agent"]["max_tokens"] == 8192
|
|
assert body["agent"]["timezone"] == expected_timezone
|
|
assert "bot_name" not in body["agent"]
|
|
assert "bot_icon" not in body["agent"]
|
|
assert body["agent"]["tool_hint_max_length"] == 40
|
|
presets = {preset["name"]: preset for preset in body["model_presets"]}
|
|
assert presets["default"]["active"] is True
|
|
assert presets["deep"]["reasoning_effort"] == "high"
|
|
providers = {provider["name"]: provider for provider in body["providers"]}
|
|
assert providers["openai"]["configured"] is True
|
|
assert providers["openai"]["api_key_hint"] == "secr••••-key"
|
|
assert providers["azure_openai"]["api_key_required"] is False
|
|
assert providers["openrouter"]["configured"] is False
|
|
assert providers["openrouter"]["api_key_required"] is True
|
|
assert providers["orcarouter"]["label"] == "OrcaRouter"
|
|
assert providers["orcarouter"]["configured"] is False
|
|
assert providers["orcarouter"]["api_key_required"] is True
|
|
assert providers["orcarouter"]["default_api_base"] == "https://api.orcarouter.ai/v1"
|
|
assert providers["skywork"]["label"] == "Skywork"
|
|
assert providers["skywork"]["default_api_base"] == "https://api.apifree.ai/agent/v1"
|
|
assert providers["ant_ling"]["label"] == "Ant Ling"
|
|
assert providers["ant_ling"]["default_api_base"] == "https://api.ant-ling.com/v1"
|
|
assert providers["atomic_chat"]["configured"] is False
|
|
assert providers["atomic_chat"]["api_key_required"] is False
|
|
assert providers["atomic_chat"]["default_api_base"] == "http://localhost:1337/v1"
|
|
assert providers["openai_codex"]["auth_type"] == "oauth"
|
|
assert providers["openai_codex"]["configured"] is False
|
|
assert body["agent"]["has_api_key"] is True
|
|
assert body["web_search"]["provider"] == "brave"
|
|
assert body["web_search"]["api_key_hint"] == "brav••••cret"
|
|
assert body["web_search"]["max_results"] == 5
|
|
assert body["web"]["fetch"]["use_jina_reader"] is True
|
|
search_providers = {provider["name"]: provider for provider in body["web_search"]["providers"]}
|
|
assert search_providers["duckduckgo"]["credential"] == "none"
|
|
assert search_providers["exa"]["credential"] == "api_key"
|
|
assert search_providers["bocha"]["credential"] == "api_key"
|
|
assert search_providers["volcengine"]["credential"] == "api_key"
|
|
assert search_providers["keenable"]["credential"] == "optional_api_key"
|
|
assert search_providers["searxng"]["credential"] == "base_url"
|
|
assert body["image_generation"]["enabled"] is False
|
|
assert body["image_generation"]["provider"] == "openrouter"
|
|
assert body["image_generation"]["provider_configured"] is False
|
|
assert body["image_generation"]["default_aspect_ratio"] == "1:1"
|
|
image_providers = {
|
|
provider["name"]: provider
|
|
for provider in body["image_generation"]["providers"]
|
|
}
|
|
assert image_providers["openrouter"]["label"] == "OpenRouter"
|
|
assert image_providers["openrouter"]["configured"] is False
|
|
assert image_providers["openrouter"]["default_model"] == "openai/gpt-5.4-image-2"
|
|
assert image_providers["openrouter"]["models"] == ["openai/gpt-5.4-image-2"]
|
|
assert image_providers["openai_codex"]["auth_type"] == "oauth"
|
|
assert image_providers["openai_codex"]["configured"] is False
|
|
assert image_providers["gemini"]["models"] == [
|
|
"gemini-2.5-flash-image",
|
|
"imagen-4.0-generate-001",
|
|
]
|
|
assert image_providers["gemini"]["label"] == "Gemini"
|
|
assert body["runtime"]["config_path"] == str(config_path)
|
|
workspace_path = body["runtime"]["workspace_path"].replace("\\", "/")
|
|
assert workspace_path.endswith("/.nanobot/workspace")
|
|
assert body["runtime"]["gateway_port"] == 18790
|
|
assert body["advanced"]["exec_enabled"] is True
|
|
assert body["advanced"]["webui_allow_local_service_access"] is True
|
|
assert body["advanced"]["webui_default_access_mode"] == "default"
|
|
assert body["advanced"]["private_service_protection_enabled"] is True
|
|
assert body["advanced"]["mcp_server_count"] == 0
|
|
assert body["restart_required_sections"] == []
|
|
assert "secret-key" not in settings.text
|
|
assert "brave-secret" not in settings.text
|
|
|
|
unknown_api = await _http_get(
|
|
f"http://127.0.0.1:{port}/api/settings/model-configurations/missing",
|
|
headers={"Authorization": "Bearer tok"},
|
|
)
|
|
assert unknown_api.status_code == 404
|
|
assert "<!doctype html>" not in unknown_api.text.lower()
|
|
|
|
provider_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.provider.update",
|
|
{
|
|
"provider": "openrouter",
|
|
"apiKey": "sk-or-test",
|
|
"apiBase": "https://openrouter.ai/api/v1",
|
|
},
|
|
)
|
|
assert provider_updated.status_code == 200
|
|
provider_body = provider_updated.json()
|
|
assert provider_body["requires_restart"] is False
|
|
provider_rows = {provider["name"]: provider for provider in provider_body["providers"]}
|
|
assert provider_rows["openrouter"]["configured"] is True
|
|
assert provider_body["image_generation"]["provider_configured"] is True
|
|
assert "sk-or-test" not in provider_updated.text
|
|
|
|
custom_provider_created = await _webui_mutate(
|
|
webui_client,
|
|
"settings.provider.create",
|
|
{
|
|
"name": "Company Gateway",
|
|
"apiBase": "https://gateway.example/v1",
|
|
"apiKey": "sk-company",
|
|
"extraHeaders": json.dumps({"X-Tenant": "engineering"}),
|
|
"extraBody": json.dumps({"service_tier": "priority"}),
|
|
"extraQuery": json.dumps({"api-version": "2026-01-01"}),
|
|
"proxy": "http://127.0.0.1:7890",
|
|
"thinkingStyle": "enable_thinking",
|
|
},
|
|
)
|
|
assert custom_provider_created.status_code == 200
|
|
custom_provider_body = custom_provider_created.json()
|
|
custom_provider_name = custom_provider_body["created_provider"]
|
|
custom_provider_rows = {
|
|
provider["name"]: provider for provider in custom_provider_body["providers"]
|
|
}
|
|
assert custom_provider_rows[custom_provider_name]["label"] == "Company Gateway"
|
|
assert custom_provider_rows[custom_provider_name]["extra_headers"] == {
|
|
"X-Tenant": "engineering"
|
|
}
|
|
assert "sk-company" not in custom_provider_created.text
|
|
|
|
local_provider_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.provider.update",
|
|
{"provider": "atomic_chat", "apiBase": "http://localhost:1337/v1"},
|
|
)
|
|
assert local_provider_updated.status_code == 200
|
|
local_provider_body = local_provider_updated.json()
|
|
local_provider_rows = {
|
|
provider["name"]: provider for provider in local_provider_body["providers"]
|
|
}
|
|
assert local_provider_rows["atomic_chat"]["configured"] is True
|
|
assert "localhost:1337" in local_provider_updated.text
|
|
|
|
updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.agent.update",
|
|
{
|
|
"model": "atomic_chat/test",
|
|
"provider": "atomic_chat",
|
|
"timezone": "Asia/Shanghai",
|
|
"tool_hint_max_length": 120,
|
|
},
|
|
)
|
|
assert updated.status_code == 200
|
|
updated_body = updated.json()
|
|
assert updated_body["requires_restart"] is True
|
|
assert updated_body["restart_required_sections"] == ["runtime"]
|
|
|
|
preset_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.agent.update",
|
|
{"model_preset": "deep"},
|
|
)
|
|
assert preset_updated.status_code == 200
|
|
assert preset_updated.json()["agent"]["model"] == "anthropic/claude-opus-4-5"
|
|
|
|
bad_preset = await _webui_mutate(
|
|
webui_client,
|
|
"settings.agent.update",
|
|
{"model_preset": "missing"},
|
|
)
|
|
assert bad_preset.status_code == 400
|
|
|
|
created_preset = await _webui_mutate(
|
|
webui_client,
|
|
"settings.model_configuration.create",
|
|
{
|
|
"label": "Fast writing",
|
|
"provider": "openai",
|
|
"model": "openai/gpt-4.1-mini",
|
|
},
|
|
)
|
|
assert created_preset.status_code == 200
|
|
created_body = created_preset.json()
|
|
assert created_body["created_model_preset"] == "fast-writing"
|
|
assert created_body["agent"]["model_preset"] == "deep"
|
|
assert created_body["agent"]["model"] == "anthropic/claude-opus-4-5"
|
|
assert created_body["model_call_order"] == ["deep"]
|
|
created_presets = {
|
|
preset["name"]: preset for preset in created_body["model_presets"]
|
|
}
|
|
assert created_presets["fast-writing"]["label"] == "fast-writing"
|
|
assert created_presets["fast-writing"]["provider"] == "openai"
|
|
|
|
updated_preset = await _webui_mutate(
|
|
webui_client,
|
|
"settings.model_configuration.update",
|
|
{
|
|
"name": "fast-writing",
|
|
"new_name": "Codex",
|
|
"provider": "openai",
|
|
"model": "openai/gpt-5.5",
|
|
},
|
|
)
|
|
assert updated_preset.status_code == 200
|
|
updated_preset_body = updated_preset.json()
|
|
assert updated_preset_body["agent"]["model_preset"] == "deep"
|
|
assert updated_preset_body["agent"]["model"] == "anthropic/claude-opus-4-5"
|
|
updated_presets = {
|
|
preset["name"]: preset for preset in updated_preset_body["model_presets"]
|
|
}
|
|
assert updated_presets["Codex"]["label"] == "Codex"
|
|
|
|
call_order_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.model_call_order.update",
|
|
{"order": ["Codex", "deep"]},
|
|
)
|
|
assert call_order_updated.status_code == 200
|
|
call_order_body = call_order_updated.json()
|
|
assert call_order_body["agent"]["model_preset"] == "Codex"
|
|
assert call_order_body["agent"]["model"] == "openai/gpt-5.5"
|
|
assert call_order_body["model_call_order"] == ["Codex", "deep"]
|
|
|
|
duplicate_preset = await _webui_mutate(
|
|
webui_client,
|
|
"settings.model_configuration.create",
|
|
{
|
|
"name": "codex",
|
|
"provider": "openai",
|
|
"model": "openai/gpt-4.1-mini",
|
|
},
|
|
)
|
|
assert duplicate_preset.status_code == 409
|
|
|
|
search_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.web_search.update",
|
|
{
|
|
"provider": "searxng",
|
|
"base_url": "https://search.example.com",
|
|
"max_results": 8,
|
|
"timeout": 45,
|
|
"use_jina_reader": False,
|
|
},
|
|
)
|
|
assert search_updated.status_code == 200
|
|
search_body = search_updated.json()
|
|
assert search_body["requires_restart"] is True
|
|
assert search_body["restart_required_sections"] == ["browser", "runtime"]
|
|
assert search_body["web_search"]["provider"] == "searxng"
|
|
assert search_body["web_search"]["api_key_hint"] is None
|
|
assert search_body["web_search"]["base_url"] == "https://search.example.com"
|
|
assert search_body["web_search"]["max_results"] == 8
|
|
assert search_body["web"]["fetch"]["use_jina_reader"] is False
|
|
|
|
network_safety_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.network_safety.update",
|
|
{
|
|
"webui_allow_local_service_access": False,
|
|
"webui_default_access_mode": "full",
|
|
},
|
|
)
|
|
assert network_safety_updated.status_code == 200
|
|
network_safety_body = network_safety_updated.json()
|
|
assert network_safety_body["requires_restart"] is True
|
|
assert network_safety_body["restart_required_sections"] == ["browser", "runtime"]
|
|
assert network_safety_body["advanced"]["webui_allow_local_service_access"] is False
|
|
assert network_safety_body["advanced"]["webui_default_access_mode"] == "full"
|
|
assert network_safety_body["advanced"]["private_service_protection_enabled"] is True
|
|
|
|
image_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.image_generation.update",
|
|
{
|
|
"enabled": True,
|
|
"provider": "openrouter",
|
|
"model": "openai/gpt-image-1",
|
|
"default_aspect_ratio": "16:9",
|
|
"default_image_size": "2K",
|
|
"max_images_per_turn": 3,
|
|
},
|
|
)
|
|
assert image_updated.status_code == 200
|
|
image_body = image_updated.json()
|
|
assert image_body["requires_restart"] is True
|
|
assert image_body["restart_required_sections"] == ["browser", "runtime"]
|
|
assert image_body["image_generation"]["enabled"] is True
|
|
assert image_body["image_generation"]["model"] == "openai/gpt-image-1"
|
|
assert image_body["image_generation"]["default_aspect_ratio"] == "16:9"
|
|
assert image_body["image_generation"]["default_image_size"] == "2K"
|
|
assert image_body["image_generation"]["max_images_per_turn"] == 3
|
|
|
|
image_provider_updated = await _webui_mutate(
|
|
webui_client,
|
|
"settings.provider.update",
|
|
{
|
|
"provider": "openrouter",
|
|
"apiKey": "sk-or-next",
|
|
"apiBase": "https://openrouter.ai/api/v1",
|
|
},
|
|
)
|
|
assert image_provider_updated.status_code == 200
|
|
assert image_provider_updated.json()["requires_restart"] is True
|
|
assert image_provider_updated.json()["restart_required_sections"] == ["browser", "runtime"]
|
|
assert "sk-or-next" not in image_provider_updated.text
|
|
assert image_reload.await_count == 2
|
|
|
|
bad_web = await _webui_mutate(
|
|
webui_client,
|
|
"settings.web_search.update",
|
|
{"provider": "duckduckgo", "max_results": 99},
|
|
)
|
|
assert bad_web.status_code == 400
|
|
|
|
bad_image = await _webui_mutate(
|
|
webui_client,
|
|
"settings.image_generation.update",
|
|
{"provider": "missing"},
|
|
)
|
|
assert bad_image.status_code == 400
|
|
|
|
saved = load_config(config_path)
|
|
assert saved.agents.defaults.model == "atomic_chat/test"
|
|
assert saved.agents.defaults.provider == "atomic_chat"
|
|
assert saved.agents.defaults.model_preset == "Codex"
|
|
assert saved.agents.defaults.fallback_models == ["deep"]
|
|
assert saved.model_presets["Codex"].model == "openai/gpt-5.5"
|
|
assert saved.model_presets["Codex"].provider == "openai"
|
|
assert saved.agents.defaults.timezone == "Asia/Shanghai"
|
|
assert saved.agents.defaults.bot_name == "nanobot"
|
|
assert saved.agents.defaults.bot_icon == "🐈"
|
|
assert saved.agents.defaults.tool_hint_max_length == 120
|
|
assert saved.providers.openrouter.api_key == "sk-or-next"
|
|
assert saved.providers.openrouter.api_base == "https://openrouter.ai/api/v1"
|
|
assert saved.providers.atomic_chat.api_base == "http://localhost:1337/v1"
|
|
custom_provider = saved.providers.model_extra[custom_provider_name]
|
|
assert custom_provider.display_name == "Company Gateway"
|
|
assert custom_provider.api_base == "https://gateway.example/v1"
|
|
assert custom_provider.extra_body == {"service_tier": "priority"}
|
|
assert saved.tools.web.search.provider == "searxng"
|
|
assert saved.tools.web.search.api_key == ""
|
|
assert saved.tools.web.search.base_url == "https://search.example.com"
|
|
assert saved.tools.web.search.max_results == 8
|
|
assert saved.tools.web.search.timeout == 45
|
|
assert saved.tools.web.fetch.use_jina_reader is False
|
|
assert saved.tools.webui_allow_local_service_access is False
|
|
assert saved.tools.image_generation.enabled is True
|
|
assert saved.tools.image_generation.provider == "openrouter"
|
|
assert saved.tools.image_generation.model == "openai/gpt-image-1"
|
|
assert saved.tools.image_generation.default_aspect_ratio == "16:9"
|
|
assert saved.tools.image_generation.default_image_size == "2K"
|
|
assert saved.tools.image_generation.max_images_per_turn == 3
|
|
finally:
|
|
if webui_client is not None:
|
|
await webui_client.close()
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("provider_name", ["openrouter", "SenseNova"])
|
|
async def test_image_settings_hot_reload_without_restart(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
tmp_path: Path,
|
|
provider_name: str,
|
|
start_listener,
|
|
) -> None:
|
|
from nanobot.agent.loop import AgentLoop
|
|
from nanobot.agent.tools.image_generation import (
|
|
ImageGenerationTool,
|
|
reload_image_generation_tool,
|
|
)
|
|
|
|
port = 0
|
|
config_path = tmp_path / "config.json"
|
|
config = Config.model_validate({"providers": {"SenseNova": {
|
|
"apiKey": "named-image-key", "apiBase": "https://images.test/v1",
|
|
"extraHeaders": {"X-Connection": "named"},
|
|
}}})
|
|
config.providers.openrouter.api_key = "image-key"
|
|
save_config(config, config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
runtime_bus = MessageBus()
|
|
provider = MagicMock(aclose=AsyncMock())
|
|
provider.get_default_model.return_value = "test-model"
|
|
agent = AgentLoop(bus=runtime_bus, provider=provider, workspace=tmp_path)
|
|
|
|
async def image_reload() -> dict[str, Any]:
|
|
return await reload_image_generation_tool(
|
|
config_path=config_path, workspace=agent.workspace, registry=agent.tools,
|
|
)
|
|
|
|
channel = _ch(runtime_bus, port=port, image_generation_reload=image_reload)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
|
port, server_task = await start_listener(channel)
|
|
webui_client = None
|
|
try:
|
|
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
|
|
webui_client = await websockets.connect(
|
|
f"ws://127.0.0.1:{port}/ws?token={webui_token}&client_id=image-reload-test"
|
|
)
|
|
assert json.loads(await webui_client.recv())["event"] == "ready"
|
|
response = await _webui_mutate(
|
|
webui_client,
|
|
"settings.image_generation.update",
|
|
{
|
|
"enabled": True, "provider": provider_name, "model": "openai/gpt-image-1",
|
|
"extra_headers": {"X-Image": "configured"},
|
|
"extra_body": {"watermark": False},
|
|
},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
assert response.json()["requires_restart"] is False
|
|
assert response.json()["restart_required_sections"] == []
|
|
tool = agent.tools.get("generate_image")
|
|
assert isinstance(tool, ImageGenerationTool)
|
|
assert tool.config.model == "openai/gpt-image-1"
|
|
client = tool._provider_client()
|
|
assert client is not None
|
|
assert client.api_key == ("image-key" if provider_name == "openrouter" else "named-image-key")
|
|
assert client.extra_headers["X-Image"] == "configured"
|
|
if provider_name == "SenseNova":
|
|
assert client.extra_headers["X-Connection"] == "named"
|
|
assert client.extra_body == {"watermark": False}
|
|
assert agent.tools.has("read_file")
|
|
assert runtime_bus.inbound_size == 0
|
|
|
|
disabled = await _webui_mutate(
|
|
webui_client,
|
|
"settings.image_generation.update",
|
|
{"enabled": False},
|
|
)
|
|
assert disabled.status_code == 200
|
|
assert disabled.json()["requires_restart"] is False
|
|
assert not agent.tools.has("generate_image")
|
|
finally:
|
|
if webui_client is not None:
|
|
await webui_client.close()
|
|
await channel.stop()
|
|
await server_task
|
|
await agent.aclose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("runtime_available", [True, False])
|
|
async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(
|
|
bus: MagicMock,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
tmp_path: Path,
|
|
runtime_available: bool,
|
|
start_listener,
|
|
) -> None:
|
|
port = 0
|
|
config_path = tmp_path / "config.json"
|
|
config = Config()
|
|
config.providers.openrouter.api_key = "image-key"
|
|
save_config(config, config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
image_reload = AsyncMock(
|
|
return_value={
|
|
"ok": False,
|
|
"message": "Image generation hot reload timed out.",
|
|
"requires_restart": True,
|
|
}
|
|
)
|
|
|
|
channel = _ch(bus, port=port, image_generation_reload=image_reload if runtime_available else None)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
|
port, server_task = await start_listener(channel)
|
|
webui_client = None
|
|
try:
|
|
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
|
|
webui_client = await websockets.connect(
|
|
f"ws://127.0.0.1:{port}/ws?token={webui_token}&client_id=image-fallback-test"
|
|
)
|
|
assert json.loads(await webui_client.recv())["event"] == "ready"
|
|
response = await _webui_mutate(
|
|
webui_client,
|
|
"settings.image_generation.update",
|
|
{"enabled": True, "provider": "openrouter", "model": "openai/gpt-image-1"},
|
|
)
|
|
|
|
assert response.status_code == 200
|
|
assert response.json()["requires_restart"] is True
|
|
assert response.json()["restart_required_sections"] == ["image"]
|
|
finally:
|
|
if webui_client is not None:
|
|
await webui_client.close()
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_commands_api_returns_slash_command_metadata(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
denied = await _http_get(f"http://127.0.0.1:{port}/api/commands")
|
|
assert denied.status_code == 401
|
|
|
|
response = await _http_get(
|
|
f"http://127.0.0.1:{port}/api/commands",
|
|
headers={"Authorization": "Bearer tok"},
|
|
)
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
commands = {row["command"]: row for row in body["commands"]}
|
|
assert commands["/stop"]["title"] == "Stop current task"
|
|
assert commands["/new"]["lifecycle"] == "finalize_active_turn"
|
|
assert commands["/stop"]["lifecycle"] == "stop_active_turn"
|
|
assert commands["/history"]["lifecycle"] == "side_channel"
|
|
assert commands["/history"]["arg_hint"] == "[n]"
|
|
assert commands["/history"]["accepts_args"] is True
|
|
assert commands["/goal"]["lifecycle"] == "agent_turn_with_args"
|
|
assert commands["/goal"]["accepts_args"] is True
|
|
assert all("description" in row for row in body["commands"])
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_bootstrap_exposes_native_surface(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = WebSocketChannel(
|
|
{
|
|
"enabled": True,
|
|
"allowFrom": ["*"],
|
|
"host": "127.0.0.1",
|
|
"port": port,
|
|
"path": "/ws",
|
|
"tokenIssueSecret": "native-secret",
|
|
"websocketRequiresToken": True,
|
|
},
|
|
bus,
|
|
gateway=_basic_handler(
|
|
bus,
|
|
token_issue_secret="native-secret",
|
|
runtime_surface="native",
|
|
),
|
|
)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
response = await _http_get(
|
|
f"http://127.0.0.1:{port}/webui/bootstrap",
|
|
headers={"X-Nanobot-Auth": "native-secret"},
|
|
)
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["runtime_surface"] == "native"
|
|
assert body["runtime_capabilities"]["can_restart_engine"] is True
|
|
assert body["token"].startswith("nbwt_")
|
|
assert body["api_token"].startswith("nbwt_")
|
|
assert body["api_token"] != body["token"]
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
def test_settings_payload_normalizes_camel_case_provider(
|
|
bus: MagicMock,
|
|
monkeypatch,
|
|
tmp_path,
|
|
) -> None:
|
|
config_path = tmp_path / "config.json"
|
|
config = Config()
|
|
config.agents.defaults.provider = "minimaxAnthropic"
|
|
save_config(config, config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
|
|
body = settings_payload()
|
|
|
|
assert body["agent"]["provider"] == "minimax_anthropic"
|
|
|
|
|
|
def test_settings_payload_exposes_openai_api_defaults(monkeypatch, tmp_path) -> None:
|
|
config_path = tmp_path / "config.json"
|
|
config = Config()
|
|
config.providers.openai.api = ModelAPIConfig(supported_apis=("responses",), preferred_api="responses")
|
|
save_config(config, config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
|
|
body = settings_payload()
|
|
providers = {provider["name"]: provider for provider in body["providers"]}
|
|
|
|
assert providers["openai"]["api"] == {"supported_apis": ["responses"], "preferred_api": "responses"}
|
|
assert providers["openai"]["request_apis"] == ["chat_completions", "responses"]
|
|
assert providers["custom"]["api"] is None
|
|
|
|
|
|
def test_settings_payload_reports_workspace_sandbox(monkeypatch, tmp_path) -> None:
|
|
config_path = tmp_path / "config.json"
|
|
config = Config()
|
|
config.tools.restrict_to_workspace = True
|
|
save_config(config, config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
monkeypatch.setenv("NANOBOT_SANDBOX_ENFORCED", "macos_app_sandbox")
|
|
|
|
body = settings_payload()
|
|
sandbox = body["advanced"]["workspace_sandbox"]
|
|
|
|
assert sandbox["restrict_to_workspace"] is True
|
|
assert sandbox["level"] == "system"
|
|
assert sandbox["enforced"] is True
|
|
assert sandbox["provider"] == "macos_app_sandbox"
|
|
assert sandbox["provider_label"] == "macOS App Sandbox"
|
|
|
|
|
|
def test_settings_payload_includes_native_runtime_surface(monkeypatch, tmp_path) -> None:
|
|
config_path = tmp_path / "config.json"
|
|
save_config(Config(), config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
|
|
body = settings_payload(
|
|
surface="native",
|
|
runtime_capability_overrides={"can_open_logs": True},
|
|
restart_required_sections=["runtime"],
|
|
)
|
|
|
|
assert body["surface"] == "native"
|
|
assert body["runtime_surface"] == "native"
|
|
assert body["runtime_capabilities"]["can_open_logs"] is True
|
|
assert body["runtime_capabilities"]["can_restart_engine"] is True
|
|
assert body["restart_behavior_by_section"]["runtime"] == "engineRestart"
|
|
assert body["requires_restart"] is True
|
|
assert body["apply_state"] == {"status": "pending", "sections": ["runtime"]}
|
|
|
|
|
|
def test_update_provider_settings_ignores_api_type_for_non_openai(monkeypatch, tmp_path) -> None:
|
|
config_path = tmp_path / "config.json"
|
|
save_config(Config(), config_path)
|
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
|
|
|
body = update_provider_settings({
|
|
"provider": ["custom"],
|
|
"api_base": ["https://example.test/v1"],
|
|
"api_type": ["responses"],
|
|
})
|
|
|
|
assert body["providers"]
|
|
config = load_config(config_path)
|
|
assert config.providers.custom.api_base == "https://example.test/v1"
|
|
assert config.providers.custom.api is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port, streaming=True)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=stream-tester") as client:
|
|
ready_raw = await client.recv()
|
|
ready = json.loads(ready_raw)
|
|
chat_id = ready["chat_id"]
|
|
|
|
await channel.send_delta(
|
|
chat_id, "Hello ", stream_id="s1"
|
|
)
|
|
await channel.send_delta(
|
|
chat_id, "world", stream_id="s1"
|
|
)
|
|
await channel.send_delta(
|
|
chat_id, "", stream_id="s1", stream_end=True
|
|
)
|
|
|
|
delta1 = json.loads(await client.recv())
|
|
assert delta1["event"] == "delta"
|
|
assert delta1["text"] == "Hello "
|
|
assert delta1["stream_id"] == "s1"
|
|
|
|
delta2 = json.loads(await client.recv())
|
|
assert delta2["event"] == "delta"
|
|
assert delta2["text"] == "world"
|
|
assert delta2["stream_id"] == "s1"
|
|
|
|
end = json.loads(await client.recv())
|
|
assert end["event"] == "stream_end"
|
|
assert end["stream_id"] == "s1"
|
|
|
|
await channel.send(OutboundMessage(
|
|
channel="websocket",
|
|
chat_id=chat_id,
|
|
content="",
|
|
event=TurnEndEvent(),
|
|
))
|
|
|
|
turn_end = json.loads(await client.recv())
|
|
assert turn_end == {"event": "turn_end", "chat_id": chat_id}
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_token_issue_rejects_when_at_capacity(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port, tokenIssuePath="/auth/token", tokenIssueSecret="s")
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
channel.gateway.tokens.issued_tokens = {
|
|
f"nbwt_fill_{i}": time.monotonic() + 300
|
|
for i in range(channel.gateway.tokens.max_tokens)
|
|
}
|
|
|
|
resp = await _http_get(
|
|
f"http://127.0.0.1:{port}/auth/token",
|
|
headers={"Authorization": "Bearer s"},
|
|
)
|
|
assert resp.status_code == 429
|
|
assert resp.headers["Cache-Control"] == "no-store"
|
|
data = resp.json()
|
|
assert "error" in data
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port, allowFrom=["alice", "bob"])
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=eve"):
|
|
pass
|
|
assert exc_info.value.response.status_code == 403
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_open_connection_rejects_revoked_webui_turn_without_acceptance_ack(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus, allowFrom=["alice"])
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"revoked-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-revoked",
|
|
"content": "must not enter the bus",
|
|
"webui": True,
|
|
"turn_id": "turn-revoked",
|
|
},
|
|
)
|
|
|
|
payloads = [json.loads(call.args[0]) for call in conn.send.await_args_list]
|
|
assert payloads == [
|
|
{
|
|
"event": "error",
|
|
"detail": "access_denied",
|
|
"chat_id": "chat-revoked",
|
|
"turn_id": "turn-revoked",
|
|
}
|
|
]
|
|
bus.publish_inbound.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_midflight_allowlist_revocation_rejects_turn_without_ack(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
channel.is_allowed = MagicMock(side_effect=[True, False])
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-midflight-revoked",
|
|
"content": "must not be acknowledged",
|
|
"webui": True,
|
|
"turn_id": "turn-midflight-revoked",
|
|
},
|
|
)
|
|
|
|
payloads = [json.loads(call.args[0]) for call in conn.send.await_args_list]
|
|
assert payloads[-1] == {
|
|
"event": "error",
|
|
"detail": "access_denied",
|
|
"chat_id": "chat-midflight-revoked",
|
|
"turn_id": "turn-midflight-revoked",
|
|
}
|
|
assert all(payload["event"] != "message_accepted" for payload in payloads)
|
|
bus.publish_inbound.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_authorized_webui_turn_is_acked_after_bus_acceptance(history,
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-accepted",
|
|
"content": "accepted",
|
|
"webui": True,
|
|
"turn_id": "turn-accepted",
|
|
},
|
|
)
|
|
|
|
bus.publish_inbound.assert_awaited_once()
|
|
inbound = bus.publish_inbound.await_args.args[0]
|
|
owner = inbound.metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY]
|
|
assert wth.websocket_turn_id("chat-accepted") == "turn-accepted"
|
|
assert wth.websocket_turn_wall_started_at("chat-accepted") is not None
|
|
assert wth.websocket_turn_owner_is_registered(
|
|
"chat-accepted",
|
|
owner,
|
|
"turn-accepted",
|
|
)
|
|
thread = history.build(
|
|
"websocket:chat-accepted",
|
|
active_turn_started_at=wth.websocket_turn_wall_started_at("chat-accepted"),
|
|
active_turn_id=wth.websocket_turn_id("chat-accepted"),
|
|
)
|
|
assert thread is not None
|
|
assert thread["active_turn_id"] == "turn-accepted"
|
|
assert thread["has_pending_tool_calls"] is True
|
|
payloads = [json.loads(call.args[0]) for call in conn.send.await_args_list]
|
|
assert payloads[-1] == {
|
|
"event": "message_accepted",
|
|
"chat_id": "chat-accepted",
|
|
"turn_id": "turn-accepted",
|
|
"starts_turn": True,
|
|
"active_turn_id": "turn-accepted",
|
|
"started_at": wth.websocket_turn_wall_started_at("chat-accepted"),
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
origin = AsyncMock()
|
|
origin.remote_address = ("127.0.0.1", 50123)
|
|
peer = AsyncMock()
|
|
outsider = AsyncMock()
|
|
channel._attach(peer, "shared-chat")
|
|
channel._attach(outsider, "other-chat")
|
|
|
|
await channel._dispatch_envelope(
|
|
origin,
|
|
"terminal-a",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "shared-chat",
|
|
"content": "hello from A",
|
|
"webui": True,
|
|
"turn_id": "turn-a",
|
|
},
|
|
)
|
|
await channel._dispatch_envelope(
|
|
origin,
|
|
"terminal-a",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "shared-chat",
|
|
"content": "one more detail",
|
|
"webui": True,
|
|
"turn_id": "steer-a",
|
|
},
|
|
)
|
|
|
|
peer_payloads = [
|
|
payload
|
|
for payload in _sent_ws_payloads(peer)
|
|
if payload["event"] == "user_message"
|
|
]
|
|
assert len(peer_payloads) == 2
|
|
assert peer_payloads[0] == {
|
|
"event": "user_message",
|
|
"chat_id": "shared-chat",
|
|
"text": "hello from A",
|
|
"starts_turn": True,
|
|
"turn_id": "turn-a",
|
|
"input_id": "user:turn-a",
|
|
"active_turn_id": "turn-a",
|
|
"started_at": pytest.approx(wth.websocket_turn_wall_started_at("shared-chat")),
|
|
}
|
|
assert peer_payloads[1] == {
|
|
"event": "user_message",
|
|
"chat_id": "shared-chat",
|
|
"text": "one more detail",
|
|
"starts_turn": False,
|
|
"turn_id": "steer-a",
|
|
"input_id": "user:steer-a",
|
|
"active_turn_id": "turn-a",
|
|
"started_at": pytest.approx(wth.websocket_turn_wall_started_at("shared-chat")),
|
|
}
|
|
origin_payloads = _sent_ws_payloads(origin)
|
|
assert [
|
|
(
|
|
payload["event"],
|
|
payload["turn_id"],
|
|
payload["starts_turn"],
|
|
payload["active_turn_id"],
|
|
)
|
|
for payload in origin_payloads
|
|
if payload["event"] == "message_accepted"
|
|
] == [
|
|
("message_accepted", "turn-a", True, "turn-a"),
|
|
("message_accepted", "steer-a", False, "turn-a"),
|
|
]
|
|
outsider.send.assert_not_awaited()
|
|
assert bus.publish_inbound.await_count == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_side_channel_command_does_not_register_queued_turn(
|
|
bus: MagicMock,
|
|
) -> None:
|
|
channel = _ch(bus)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "chat-status",
|
|
"content": "/status",
|
|
"webui": True,
|
|
"turn_id": "turn-status",
|
|
},
|
|
)
|
|
|
|
inbound = bus.publish_inbound.await_args.args[0]
|
|
assert WEBSOCKET_TURN_OWNER_METADATA_KEY not in inbound.metadata
|
|
assert wth.websocket_turn_wall_started_at("chat-status") is None
|
|
payloads = [json.loads(call.args[0]) for call in conn.send.await_args_list]
|
|
assert payloads[-1] == {
|
|
"event": "message_accepted",
|
|
"chat_id": "chat-status",
|
|
"turn_id": "turn-status",
|
|
"starts_turn": False,
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_client_id_truncation(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
long_id = "x" * 200
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id={long_id}") as client:
|
|
ready = json.loads(await client.recv())
|
|
assert ready["client_id"] == "x" * 128
|
|
assert len(ready["client_id"]) == 128
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_non_utf8_binary_frame_ignored(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bin-test") as client:
|
|
await client.recv()
|
|
await client.send(b"\xff\xfe\xfd")
|
|
await asyncio.sleep(0.05)
|
|
bus.publish_inbound.assert_not_awaited()
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(
|
|
bus, port=port,
|
|
token="static-secret",
|
|
tokenIssuePath="/auth/token",
|
|
tokenIssueSecret="route-secret",
|
|
)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
resp = await _http_get(
|
|
f"http://127.0.0.1:{port}/auth/token",
|
|
headers={"Authorization": "Bearer route-secret"},
|
|
)
|
|
assert resp.status_code == 200
|
|
issued_token = resp.json()["token"]
|
|
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?token={issued_token}&client_id=caller") as client:
|
|
ready = json.loads(await client.recv())
|
|
assert ready["event"] == "ready"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_allow_from_empty_list_denies_all(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port, allowFrom=[])
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=anyone"):
|
|
pass
|
|
assert exc_info.value.response.status_code == 403
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_websocket_requires_token_without_issue_path(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port, websocketRequiresToken=True)
|
|
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=u"):
|
|
pass
|
|
assert exc_info.value.response.status_code == 401
|
|
|
|
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=u&token=wrong"):
|
|
pass
|
|
assert exc_info.value.response.status_code == 401
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
# -- Multi-chat multiplexing -------------------------------------------------
|
|
# The multiplex protocol lets one WS connection route N logical chats over
|
|
# typed envelopes (`new_chat` / `attach` / `message`). Legacy frames must keep
|
|
# working on the connection's default chat_id.
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=legacy") as client:
|
|
ready = json.loads(await client.recv())
|
|
default_chat = ready["chat_id"]
|
|
|
|
await client.send("hello from legacy")
|
|
await asyncio.sleep(0.1)
|
|
inbound = bus.publish_inbound.call_args[0][0]
|
|
assert inbound.chat_id == default_chat
|
|
assert inbound.content == "hello from legacy"
|
|
|
|
await client.send(json.dumps({"content": "structured legacy"}))
|
|
await asyncio.sleep(0.1)
|
|
assert bus.publish_inbound.call_args[0][0].chat_id == default_chat
|
|
assert bus.publish_inbound.call_args[0][0].content == "structured legacy"
|
|
|
|
await channel.send(
|
|
OutboundMessage(channel="websocket", chat_id=default_chat, content="reply")
|
|
)
|
|
reply = json.loads(await client.recv())
|
|
assert reply["event"] == "message"
|
|
assert reply["chat_id"] == default_chat
|
|
assert reply["text"] == "reply"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=mp") as client:
|
|
ready = json.loads(await client.recv())
|
|
default_chat = ready["chat_id"]
|
|
|
|
await client.send(json.dumps({"type": "new_chat"}))
|
|
attached = json.loads(await client.recv())
|
|
assert attached["event"] == "attached"
|
|
new_chat = attached["chat_id"]
|
|
assert new_chat and new_chat != default_chat
|
|
|
|
await client.send(
|
|
json.dumps({"type": "message", "chat_id": new_chat, "content": "hi on new"})
|
|
)
|
|
await asyncio.sleep(0.1)
|
|
inbound = bus.publish_inbound.call_args[0][0]
|
|
assert inbound.chat_id == new_chat
|
|
assert inbound.content == "hi on new"
|
|
|
|
await channel.send(
|
|
OutboundMessage(channel="websocket", chat_id=new_chat, content="ok")
|
|
)
|
|
reply = json.loads(await client.recv())
|
|
if reply["event"] == "session_updated":
|
|
reply = json.loads(await client.recv())
|
|
assert reply["event"] == "message"
|
|
assert reply["chat_id"] == new_chat
|
|
assert reply["text"] == "ok"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fork_chat_copies_only_prefix_session_and_transcript(history,
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
sessions = history.sessions
|
|
source = sessions.get_or_create("websocket:source")
|
|
source.metadata["webui"] = True
|
|
source.add_message("user", "round1")
|
|
source.add_message("assistant", "answer1")
|
|
source.add_message("user", "future")
|
|
sessions.save(source)
|
|
for ev in (
|
|
{"event": "user", "chat_id": "source", "text": "round1"},
|
|
{"event": "message", "chat_id": "source", "text": "answer1"},
|
|
{"event": "user", "chat_id": "source", "text": "future"},
|
|
):
|
|
history.append("websocket:source", ev)
|
|
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
conn = AsyncMock()
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "fork_chat",
|
|
"source_chat_id": "source",
|
|
"before_user_index": 1,
|
|
"title": "Fork: Old title",
|
|
},
|
|
)
|
|
|
|
sent = [json.loads(call.args[0]) for call in conn.send.await_args_list]
|
|
attached = next(item for item in sent if item["event"] == "attached")
|
|
fork_id = attached["chat_id"]
|
|
saved = sessions.read_session_file(f"websocket:{fork_id}")
|
|
assert [m["content"] for m in saved["messages"]] == ["round1", "answer1"]
|
|
assert saved["metadata"]["title"] == "Fork: Old title"
|
|
fork_lines = history.read(f"websocket:{fork_id}")
|
|
assert [line.get("text") for line in fork_lines] == ["round1", "answer1", None]
|
|
assert fork_lines[-1]["event"] == "fork_marker"
|
|
assert all(line.get("chat_id") == fork_id for line in fork_lines)
|
|
assert "future" not in json.dumps(saved, ensure_ascii=False)
|
|
bus.publish_inbound.assert_not_awaited()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_message_envelope_appends_user_transcript(history,
|
|
bus: MagicMock,
|
|
tmp_path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
sessions = history.sessions
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{
|
|
"type": "message",
|
|
"chat_id": "source",
|
|
"content": "round1",
|
|
"webui": True,
|
|
},
|
|
)
|
|
|
|
[line] = history.read("websocket:source")
|
|
assert {
|
|
"event": line.get("event"),
|
|
"chat_id": line.get("chat_id"),
|
|
"text": line.get("text"),
|
|
} == {"event": "user", "chat_id": "source", "text": "round1"}
|
|
assert isinstance(line.get("turn_id"), str)
|
|
assert line.get("turn_phase") == "user"
|
|
assert line.get("turn_seq") == 1
|
|
assert isinstance(line.get("created_at_ms"), int)
|
|
inbound = bus.publish_inbound.await_args.args[0]
|
|
assert inbound.chat_id == "source"
|
|
assert inbound.content == "round1"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=two") as client:
|
|
await client.recv()
|
|
|
|
await client.send(json.dumps({"type": "new_chat"}))
|
|
chat_a = (await _recv_ws_event(client, "attached"))["chat_id"]
|
|
await client.send(json.dumps({"type": "new_chat"}))
|
|
chat_b = (await _recv_ws_event(client, "attached"))["chat_id"]
|
|
assert chat_a != chat_b
|
|
|
|
await channel.send(
|
|
OutboundMessage(channel="websocket", chat_id=chat_a, content="for-A")
|
|
)
|
|
msg_a = await _recv_ws_event(client, "message")
|
|
assert msg_a["chat_id"] == chat_a
|
|
assert msg_a["text"] == "for-A"
|
|
|
|
await channel.send(
|
|
OutboundMessage(channel="websocket", chat_id=chat_b, content="for-B")
|
|
)
|
|
msg_b = await _recv_ws_event(client, "message")
|
|
assert msg_b["chat_id"] == chat_b
|
|
assert msg_b["text"] == "for-B"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multiplex_invalid_frames_return_error(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bad") as client:
|
|
await client.recv()
|
|
|
|
await client.send(json.dumps({"type": "attach", "chat_id": "has space"}))
|
|
err1 = json.loads(await client.recv())
|
|
assert err1["event"] == "error"
|
|
|
|
await client.send(json.dumps({"type": "message", "chat_id": "abc", "content": ""}))
|
|
err2 = json.loads(await client.recv())
|
|
assert err2["event"] == "error"
|
|
|
|
await client.send(json.dumps({"type": "nope"}))
|
|
err3 = json.loads(await client.recv())
|
|
assert err3["event"] == "error"
|
|
|
|
await client.send("still-alive")
|
|
await asyncio.sleep(0.1)
|
|
bus.publish_inbound.assert_awaited()
|
|
assert bus.publish_inbound.call_args[0][0].content == "still-alive"
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multiplex_cleanup_on_disconnect(bus: MagicMock, start_listener) -> None:
|
|
port = 0
|
|
channel = _ch(bus, port=port)
|
|
port, server_task = await start_listener(channel)
|
|
|
|
try:
|
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=dc") as client:
|
|
ready = json.loads(await client.recv())
|
|
default_chat = ready["chat_id"]
|
|
await client.send(json.dumps({"type": "new_chat"}))
|
|
extra_chat = json.loads(await client.recv())["chat_id"]
|
|
assert default_chat in channel._subs
|
|
assert extra_chat in channel._subs
|
|
await asyncio.sleep(0.2)
|
|
assert default_chat not in channel._subs
|
|
assert extra_chat not in channel._subs
|
|
assert not channel._conn_chats
|
|
assert not channel._conn_default
|
|
finally:
|
|
await channel.stop()
|
|
await server_task
|
|
|
|
|
|
def test_parse_envelope_detects_typed_frames() -> None:
|
|
assert _parse_envelope('{"type":"new_chat"}') == {"type": "new_chat"}
|
|
env = _parse_envelope('{"type":"message","chat_id":"abc","content":"hi"}')
|
|
assert env == {"type": "message", "chat_id": "abc", "content": "hi"}
|
|
|
|
|
|
def test_parse_envelope_rejects_legacy_and_garbage() -> None:
|
|
assert _parse_envelope('{"content":"hi"}') is None
|
|
assert _parse_envelope("plain text") is None
|
|
assert _parse_envelope("{broken") is None
|
|
assert _parse_envelope("[1,2,3]") is None
|
|
assert _parse_envelope('{"type":123}') is None
|
|
|
|
|
|
def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.session import webui_turns as wth
|
|
from nanobot.webui import ws_http as ws_http_module
|
|
|
|
bus = MagicMock()
|
|
session_manager = MagicMock()
|
|
sessions = [
|
|
{
|
|
"key": "websocket:chat-1",
|
|
"created_at": "2026-05-19T10:00:00Z",
|
|
"updated_at": "2026-05-19T10:01:00Z",
|
|
"title": "Running",
|
|
"preview": "work",
|
|
"model_preset": "fast",
|
|
"path": "/private/path",
|
|
},
|
|
{
|
|
"key": "cli:chat-2",
|
|
"created_at": "2026-05-19T10:00:00Z",
|
|
"updated_at": "2026-05-19T10:01:00Z",
|
|
},
|
|
]
|
|
session_manager.state.query_metadata = AsyncMock(side_effect=lambda project: project([]))
|
|
monkeypatch.setattr(ws_http_module, "list_webui_sessions", lambda _session_manager, _stored: sessions)
|
|
handle = session_handle_for_name("websocket:chat-1", "luma")
|
|
monkeypatch.setattr(
|
|
ws_http_module,
|
|
"SessionHandleResolver",
|
|
lambda _session_manager: SimpleNamespace(
|
|
handles_from_metadata=MagicMock(return_value={handle.session_key: handle}),
|
|
alist_all_by_key=AsyncMock(
|
|
return_value={handle.session_key: handle}
|
|
)
|
|
),
|
|
)
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=session_manager),
|
|
)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
|
|
wth.clear_websocket_turns("chat-1")
|
|
try:
|
|
asyncio.run(_register_running_turn("chat-1", 1_700_000_000.0))
|
|
req = Request("/api/sessions", Headers([("Authorization", "Bearer tok")]))
|
|
resp = asyncio.run(channel.gateway.http._handle_sessions_list(req))
|
|
finally:
|
|
wth.clear_websocket_turns("chat-1")
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
workspace_scope = body["sessions"][0].pop("workspace_scope")
|
|
assert workspace_scope["project_path"] == str(channel.gateway.media.workspace_path)
|
|
assert workspace_scope["access_mode"] in {"restricted", "full"}
|
|
assert body["sessions"] == [
|
|
{
|
|
"key": "websocket:chat-1",
|
|
"created_at": "2026-05-19T10:00:00Z",
|
|
"updated_at": "2026-05-19T10:01:00Z",
|
|
"title": "Running",
|
|
"preview": "work",
|
|
"model_preset": "fast",
|
|
"run_started_at": 1_700_000_000.0,
|
|
"project_locked": True,
|
|
"handle": handle.public_payload(),
|
|
}
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("value", "expected"),
|
|
[
|
|
("abc", True),
|
|
("a1b2_c:d-e", True),
|
|
("x" * 64, True),
|
|
("unified:default", True),
|
|
("", False),
|
|
("x" * 65, False),
|
|
("has space", False),
|
|
("a/b", False),
|
|
("a.b", False),
|
|
(None, False),
|
|
(123, False),
|
|
],
|
|
)
|
|
def test_is_valid_chat_id(value: Any, expected: bool) -> None:
|
|
assert _is_valid_chat_id(value) is expected
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_returns_json(history, tmp_path, monkeypatch) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
key = "websocket:c1"
|
|
history.append(key, {"event": "user", "chat_id": "c1", "text": "hi"})
|
|
bus = MagicMock()
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert body["sessionKey"] == key
|
|
assert len(_thread_conversation_events(body)) == 1
|
|
assert _thread_conversation_events(body)[0]["role"] == "user"
|
|
assert _thread_conversation_events(body)[0]["content"] == "hi"
|
|
assert body["has_pending_tool_calls"] is False
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_thread_dispatch_runs_replay_off_event_loop(history, tmp_path, monkeypatch) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.http11 import Request
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
key = "websocket:threaded-history"
|
|
history.append(
|
|
key,
|
|
{"event": "user", "chat_id": "threaded-history", "text": "hi"},
|
|
)
|
|
gateway = _basic_handler(MagicMock(), workspace_path=tmp_path, session_manager=history.sessions)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
encoded = quote(key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{encoded}/webui-thread",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
original = gateway.http._handle_webui_thread_get
|
|
|
|
def slow_replay(*args: Any, **kwargs: Any):
|
|
time.sleep(0.15)
|
|
return original(*args, **kwargs)
|
|
|
|
monkeypatch.setattr(gateway.http, "_handle_webui_thread_get", slow_replay)
|
|
request_task = asyncio.create_task(
|
|
gateway.http._dispatch_session_routes(request, request.path)
|
|
)
|
|
|
|
await asyncio.sleep(0.03)
|
|
|
|
assert request_task.done() is False
|
|
response = await request_task
|
|
assert response is not None
|
|
assert response.status_code == 200
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_thread_diagnostics_hash_session_key(history, tmp_path, monkeypatch) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.http11 import Request
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_PAGE_RECORDS", 1)
|
|
key = "websocket:private-session-name"
|
|
for event in (
|
|
{"event": "user", "chat_id": "private-session-name", "text": "hi"},
|
|
{"event": "message", "chat_id": "private-session-name", "text": "hello"},
|
|
{"event": "turn_end", "chat_id": "private-session-name"},
|
|
):
|
|
history.append(key, event)
|
|
gateway = _basic_handler(MagicMock(), workspace_path=tmp_path, session_manager=history.sessions)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
gateway.http._log = MagicMock()
|
|
encoded = quote(key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{encoded}/webui-thread",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
response = await gateway.http._dispatch_session_routes(request, request.path)
|
|
|
|
assert response is not None
|
|
assert response.status_code == 200
|
|
call = gateway.http._log.warning.call_args
|
|
assert call is not None
|
|
assert key not in " ".join(str(value) for value in call.args)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_session_context_get_reads_detached_session() -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.session import Session
|
|
|
|
usage = LLMUsage.reported(
|
|
input_tokens=12,
|
|
output_tokens=3,
|
|
total_tokens=175,
|
|
cache_read_tokens=6,
|
|
).with_timing(generation_ms=300, ttft_ms=45)
|
|
session = Session(
|
|
key="websocket:context-route",
|
|
messages=[{"role": "user", "content": "hello"}],
|
|
metadata={"_last_usage": usage.to_dict()},
|
|
)
|
|
manager = MagicMock()
|
|
manager.read_session_snapshot.return_value = session
|
|
gateway = _basic_handler(MagicMock(), session_manager=manager)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
encoded = quote(session.key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{encoded}/context",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
response = await gateway.http._handle_session_context_get(request, encoded)
|
|
|
|
assert response.status_code == 200
|
|
body = json.loads(response.body.decode())
|
|
assert body["replay_messages"] == 1
|
|
assert body["last_usage"] == {
|
|
"prompt_tokens": 12,
|
|
"completion_tokens": 3,
|
|
"total_tokens": 175,
|
|
"context_tokens": 12,
|
|
"cached_tokens": 6,
|
|
"request_count": 1,
|
|
"estimated_tokens": 0,
|
|
"generation_ms": 300,
|
|
"measured_completion_tokens": 3,
|
|
"ttft_ms": 45,
|
|
"timed_requests": 1,
|
|
}
|
|
manager.read_session_snapshot.assert_called_once_with(session.key)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_reports_registered_turn_as_pending(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
monkeypatch.setattr(
|
|
"nanobot.session.webui_turns.websocket_turn_wall_started_at",
|
|
lambda chat_id: 1_700_000_000.0 if chat_id == "running" else None,
|
|
)
|
|
monkeypatch.setattr(
|
|
"nanobot.session.webui_turns.websocket_turn_id",
|
|
lambda chat_id: "turn-running" if chat_id == "running" else None,
|
|
)
|
|
key = "websocket:running"
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "user",
|
|
"chat_id": "running",
|
|
"text": "hi",
|
|
"turn_id": "turn-running",
|
|
},
|
|
)
|
|
bus = MagicMock()
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert _thread_conversation_events(body)[0]["content"] == "hi"
|
|
assert body["has_pending_tool_calls"] is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_idle_registry_stays_pending_until_turn_end_is_persisted(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.bus.events import InboundMessage
|
|
from nanobot.session import webui_turns as wth
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
key = "websocket:idle-order"
|
|
turn_id = "turn-idle-order"
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "user",
|
|
"chat_id": "idle-order",
|
|
"text": "hi",
|
|
"turn_id": turn_id,
|
|
},
|
|
)
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
inbound = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id="idle-order",
|
|
content="hi",
|
|
metadata={"webui_turn_id": turn_id},
|
|
)
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{enc}/webui-thread",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
try:
|
|
await wth.publish_turn_run_status(bus, inbound, "running")
|
|
await wth.publish_turn_run_status(bus, inbound, "idle")
|
|
|
|
before_delivery = await channel.gateway.http._handle_webui_thread_get_async(request, enc)
|
|
assert json.loads(before_delivery.body.decode())["has_pending_tool_calls"] is True
|
|
|
|
await channel.send(await history.message(
|
|
channel="websocket",
|
|
chat_id="idle-order",
|
|
content="",
|
|
metadata=dict(inbound.metadata),
|
|
event=TurnEndEvent(),
|
|
))
|
|
|
|
after_delivery = await channel.gateway.http._handle_webui_thread_get_async(request, enc)
|
|
assert json.loads(after_delivery.body.decode())["has_pending_tool_calls"] is False
|
|
assert wth.websocket_turn_wall_started_at("idle-order") is None
|
|
assert wth.websocket_turn_id("idle-order") is None
|
|
finally:
|
|
wth._WEBSOCKET_TURN_WALL_STARTED_AT.pop("idle-order", None)
|
|
wth._WEBSOCKET_TURN_IDS.pop("idle-order", None)
|
|
wth._WEBSOCKET_TURN_OWNERS.pop("idle-order", None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_webui_thread_api_restores_older_owner_after_latest_completes(history, ) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.bus.events import InboundMessage
|
|
|
|
chat_id = "concurrent-projection"
|
|
key = f"websocket:{chat_id}"
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "user",
|
|
"chat_id": chat_id,
|
|
"text": "first",
|
|
"turn_id": "turn-first",
|
|
},
|
|
)
|
|
bus = MagicMock()
|
|
bus.publish_outbound = AsyncMock()
|
|
first = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id=chat_id,
|
|
content="first",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: "owner-first",
|
|
"webui_turn_id": "turn-first",
|
|
},
|
|
session_key_override="websocket:session-first",
|
|
)
|
|
second = InboundMessage(
|
|
channel="websocket",
|
|
sender_id="u",
|
|
chat_id=chat_id,
|
|
content="second",
|
|
metadata={
|
|
WEBSOCKET_TURN_OWNER_METADATA_KEY: "owner-second",
|
|
"webui_turn_id": "turn-second",
|
|
},
|
|
session_key_override="websocket:session-second",
|
|
)
|
|
await wth.publish_turn_run_status(bus, first, "running", started_at=100.0)
|
|
await wth.publish_turn_run_status(bus, second, "running", started_at=200.0)
|
|
assert wth.clear_websocket_turn_if_current(chat_id, "owner-second") is True
|
|
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{enc}/webui-thread",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
response = await channel.gateway.http._handle_webui_thread_get_async(request, enc)
|
|
|
|
assert response.status_code == 200
|
|
payload = json.loads(response.body.decode())
|
|
assert payload["has_pending_tool_calls"] is True
|
|
assert wth.websocket_turn_wall_started_at(chat_id) == 100.0
|
|
assert wth.websocket_turn_id(chat_id) == "turn-first"
|
|
assert wth._WEBSOCKET_TURN_OWNERS[chat_id] == "owner-first"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("active_turn_id", "expected_pending"),
|
|
[
|
|
("turn-complete", False),
|
|
("turn-next", True),
|
|
],
|
|
)
|
|
async def test_handle_webui_thread_get_reconciles_registered_turn_with_turn_end(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
active_turn_id: str,
|
|
expected_pending: bool,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
monkeypatch.setattr(
|
|
"nanobot.session.webui_turns.websocket_turn_wall_started_at",
|
|
lambda chat_id: 1_700_000_000.0 if chat_id == "running" else None,
|
|
)
|
|
monkeypatch.setattr(
|
|
"nanobot.session.webui_turns.websocket_turn_id",
|
|
lambda chat_id: active_turn_id if chat_id == "running" else None,
|
|
)
|
|
key = "websocket:running"
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "user",
|
|
"chat_id": "running",
|
|
"text": "hi",
|
|
"turn_id": "turn-complete",
|
|
},
|
|
)
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "message",
|
|
"chat_id": "running",
|
|
"text": "done",
|
|
"turn_id": "turn-complete",
|
|
},
|
|
)
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "turn_end",
|
|
"chat_id": "running",
|
|
"turn_id": "turn-complete",
|
|
},
|
|
)
|
|
bus = MagicMock()
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert _thread_conversation_events(body)[-1]["content"] == "done"
|
|
assert body["has_pending_tool_calls"] is expected_pending
|
|
assert body["active_turn_id"] == active_turn_id
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_accepts_pagination_query(history, tmp_path, monkeypatch) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
key = "websocket:paged-route"
|
|
for idx in range(1, 4):
|
|
history.append(
|
|
key,
|
|
{"event": "user", "chat_id": "paged-route", "text": f"q{idx}"},
|
|
)
|
|
history.append(
|
|
key,
|
|
{"event": "message", "chat_id": "paged-route", "text": f"a{idx}"},
|
|
)
|
|
history.append(key, {"event": "turn_end", "chat_id": "paged-route"})
|
|
|
|
bus = MagicMock()
|
|
channel = _ch(bus, session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/webui-thread?limit=2&direction=latest",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [
|
|
"q3", "a3",
|
|
]
|
|
assert body["page"]["has_more_before"] is True
|
|
assert body["page"]["before_cursor"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("sources", [
|
|
None,
|
|
[],
|
|
[{"provider": "xai", "model": "grok", "preset": "saved backup", "fallback": True}],
|
|
])
|
|
async def test_handle_webui_thread_get_returns_canonical_events_by_default(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
sources,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
key = "websocket:event-route"
|
|
history.append(
|
|
key,
|
|
{"event": "user", "chat_id": "event-route", "text": "question"},
|
|
)
|
|
history.append(
|
|
key,
|
|
{
|
|
"event": "message", "chat_id": "event-route", "text": "answer",
|
|
**({"response_sources": sources} if sources is not None else {}),
|
|
},
|
|
)
|
|
history.append(key, {"event": "turn_end", "chat_id": "event-route"})
|
|
|
|
channel = _ch(MagicMock(), session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
encoded = quote(key, safe="")
|
|
request = Request(
|
|
f"/api/sessions/{encoded}/webui-thread",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
response = await channel.gateway.http._handle_webui_thread_get_async(request, encoded)
|
|
|
|
assert response.status_code == 200
|
|
body = json.loads(response.body.decode())
|
|
assert "messages" not in body
|
|
assert body["projection"] == "events"
|
|
assert [event["event"] for event in body["events"]] == [
|
|
"user_message",
|
|
"message",
|
|
"turn_end",
|
|
]
|
|
answer = body["events"][1]
|
|
if sources is None:
|
|
assert "response_sources" not in answer
|
|
else:
|
|
assert answer["response_sources"] == sources
|
|
|
|
|
|
@pytest.mark.parametrize("authorized", [True, False])
|
|
def test_handle_file_reference_metadata_is_authenticated_and_no_store(tmp_path, authorized) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
source = tmp_path / "notes.bin"
|
|
source.write_bytes(b"\0binary")
|
|
gateway = _basic_handler(MagicMock(), workspace_path=tmp_path)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote("websocket:file-actions", safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path=notes.bin&metadata=1",
|
|
Headers([("Authorization", "Bearer tok")]) if authorized else Headers(),
|
|
)
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
assert resp.status_code == (200 if authorized else 401)
|
|
if authorized:
|
|
assert json.loads(resp.body.decode()) == {
|
|
"path": str(source.resolve()), "relative_path": "notes.bin",
|
|
}
|
|
assert resp.headers["Cache-Control"] == "no-store"
|
|
|
|
|
|
def test_handle_file_preview_returns_workspace_file(tmp_path) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
workspace = tmp_path / "workspace"
|
|
source = workspace / "nanobot" / "agent" / "hook.py"
|
|
source.parent.mkdir(parents=True)
|
|
source.write_text("print('hello')\n", encoding="utf-8")
|
|
|
|
gateway = _basic_handler(MagicMock(), workspace_path=workspace)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
key = "websocket:file-preview"
|
|
enc = quote(key, safe="")
|
|
path = quote("nanobot/agent/hook.py:12", safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path={path}",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert body["display_path"] == "nanobot/agent/hook.py"
|
|
assert body["language"] == "python"
|
|
assert body["content"].splitlines() == ["print('hello')"]
|
|
assert body["truncated"] is False
|
|
assert resp.headers["Cache-Control"] == "no-store"
|
|
|
|
|
|
def test_handle_file_preview_probe_checks_availability_without_content(tmp_path) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
workspace = tmp_path / "workspace"
|
|
source = workspace / "notes" / "ready.md"
|
|
source.parent.mkdir(parents=True)
|
|
source.write_text("ready\n", encoding="utf-8")
|
|
|
|
gateway = _basic_handler(MagicMock(), workspace_path=workspace)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
key = "websocket:file-preview"
|
|
enc = quote(key, safe="")
|
|
path = quote("notes/ready.md", safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path={path}&probe=1",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
assert json.loads(resp.body.decode()) == {"available": True}
|
|
assert resp.headers["Cache-Control"] == "no-store"
|
|
|
|
|
|
def test_handle_file_preview_probe_reports_missing_file_as_unavailable(tmp_path) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
workspace = tmp_path / "workspace"
|
|
workspace.mkdir()
|
|
gateway = _basic_handler(MagicMock(), workspace_path=workspace)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
key = "websocket:file-preview"
|
|
enc = quote(key, safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path=notes%2Fmissing.md&probe=1",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
assert json.loads(resp.body.decode()) == {"available": False}
|
|
|
|
|
|
def test_handle_file_preview_probe_reports_binary_file_as_unavailable(tmp_path) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
workspace = tmp_path / "workspace"
|
|
source = workspace / "image.png"
|
|
workspace.mkdir()
|
|
source.write_bytes(b"\x89PNG\r\n\0binary")
|
|
gateway = _basic_handler(MagicMock(), workspace_path=workspace)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
key = "websocket:file-preview"
|
|
enc = quote(key, safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path=image.png&probe=1",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
assert json.loads(resp.body.decode()) == {"available": False}
|
|
|
|
|
|
def test_file_preview_normalizes_windows_file_url() -> None:
|
|
from nanobot.webui.file_preview import _clean_preview_path
|
|
|
|
assert _clean_preview_path("file:///C:/Users/me/project/app.py") == (
|
|
"C:/Users/me/project/app.py"
|
|
)
|
|
assert _clean_preview_path("file:///tmp/project/app.py") == "/tmp/project/app.py"
|
|
|
|
|
|
def test_handle_file_preview_rejects_paths_outside_workspace(tmp_path) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
workspace = tmp_path / "workspace"
|
|
workspace.mkdir()
|
|
outside = tmp_path / "secret.py"
|
|
outside.write_text("secret = True\n", encoding="utf-8")
|
|
|
|
gateway = _basic_handler(
|
|
MagicMock(),
|
|
workspace_path=workspace,
|
|
default_restrict_to_workspace=True,
|
|
)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
key = "websocket:file-preview"
|
|
enc = quote(key, safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path={quote(str(outside), safe='')}",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
|
|
assert resp.status_code == 403
|
|
|
|
|
|
def test_handle_file_preview_allows_paths_outside_workspace_in_full_access(tmp_path) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
workspace = tmp_path / "workspace"
|
|
workspace.mkdir()
|
|
outside = tmp_path / "notes.py"
|
|
outside.write_text("value = 42\n", encoding="utf-8")
|
|
|
|
gateway = _basic_handler(
|
|
MagicMock(),
|
|
workspace_path=workspace,
|
|
default_restrict_to_workspace=False,
|
|
)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
key = "websocket:file-preview"
|
|
enc = quote(key, safe="")
|
|
req = Request(
|
|
f"/api/sessions/{enc}/file-preview?path={quote(str(outside), safe='')}",
|
|
Headers([("Authorization", "Bearer tok")]),
|
|
)
|
|
|
|
resp = gateway.http._handle_file_preview(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert body["path"] == str(outside.resolve())
|
|
assert body["display_path"] == outside.resolve().as_posix()
|
|
assert body["content"].splitlines() == ["value = 42"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_backfills_legacy_missing_user_rows(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
workspace = tmp_path / "workspace"
|
|
sessions = history.sessions
|
|
key = "websocket:c-legacy"
|
|
session = sessions.get_or_create(key)
|
|
session.add_message("user", "legacy question")
|
|
session.add_message("assistant", "legacy answer")
|
|
sessions.save(session)
|
|
history.append(
|
|
key,
|
|
{"event": "message", "chat_id": "c-legacy", "text": "legacy answer"},
|
|
)
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=workspace),
|
|
)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert [message["role"] for message in _thread_conversation_events(body)] == [
|
|
"user", "assistant",
|
|
]
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [
|
|
"legacy question",
|
|
"legacy answer",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_does_not_backfill_cron_internal_prompt(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.cron.session_turns import CRON_HISTORY_META
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
workspace = tmp_path / "workspace"
|
|
sessions = history.sessions
|
|
key = "websocket:c-cron"
|
|
session = sessions.get_or_create(key)
|
|
session.add_message(
|
|
"user",
|
|
"Scheduled cron job triggered: 30s-test\n\nInternal reminder prompt",
|
|
**{CRON_HISTORY_META: True},
|
|
)
|
|
session.add_message("assistant", "提醒已经到期。")
|
|
sessions.save(session)
|
|
history.append(
|
|
key,
|
|
{"event": "message", "chat_id": "c-cron", "text": "提醒已经到期。"},
|
|
)
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=workspace),
|
|
)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert [message["role"] for message in _thread_conversation_events(body)] == ["assistant"]
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [
|
|
"提醒已经到期。",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_does_not_backfill_trigger_internal_prompt(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
workspace = tmp_path / "workspace"
|
|
sessions = history.sessions
|
|
key = "websocket:c-trigger"
|
|
session = sessions.get_or_create(key)
|
|
session.add_message(
|
|
"user",
|
|
"Local trigger received: PR review",
|
|
**{AUTOMATION_HISTORY_META: {"kind": "local_trigger", "trigger_id": "trg_123"}},
|
|
)
|
|
session.add_message("assistant", "PR #4502 已经开始 review。")
|
|
sessions.save(session)
|
|
history.append(
|
|
key,
|
|
{"event": "message", "chat_id": "c-trigger", "text": "PR #4502 已经开始 review。"},
|
|
)
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=workspace),
|
|
)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert [message["role"] for message in _thread_conversation_events(body)] == ["assistant"]
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [
|
|
"PR #4502 已经开始 review。",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_handle_webui_thread_get_does_not_backfill_hidden_subagent_result(history,
|
|
tmp_path,
|
|
monkeypatch,
|
|
) -> None:
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
|
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
workspace = tmp_path / "workspace"
|
|
sessions = history.sessions
|
|
key = "websocket:c-subagent"
|
|
session = sessions.get_or_create(key)
|
|
session.add_message(
|
|
"user",
|
|
"internal subagent result",
|
|
**{HIDDEN_HISTORY_META: {"kind": "subagent_result", "subagent_task_id": "sub-1"}},
|
|
)
|
|
session.add_message("assistant", "subagent summary")
|
|
sessions.save(session)
|
|
history.append(
|
|
key,
|
|
{"event": "message", "chat_id": "c-subagent", "text": "subagent summary"},
|
|
)
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=workspace),
|
|
)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
enc = quote(key, safe="")
|
|
req = Request(f"/api/sessions/{enc}/webui-thread", Headers([("Authorization", "Bearer tok")]))
|
|
resp = await channel.gateway.http._handle_webui_thread_get_async(req, enc)
|
|
|
|
assert resp.status_code == 200
|
|
body = json.loads(resp.body.decode())
|
|
assert [message["role"] for message in _thread_conversation_events(body)] == ["assistant"]
|
|
assert [message["content"] for message in _thread_conversation_events(body)] == [
|
|
"subagent summary",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("headers", [
|
|
{"Host": "localhost:8765"},
|
|
{"Host": "remote.example"},
|
|
{"Host": "localhost:8765", "X-Forwarded-For": "203.0.113.8"},
|
|
])
|
|
async def test_webui_access_mode_can_toggle_back_to_full(bus, tmp_path, headers):
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path,
|
|
default_restrict_to_workspace=True),
|
|
)
|
|
conn = AsyncMock()
|
|
channel._webui_connections.add(conn)
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
conn.request = SimpleNamespace(headers=headers)
|
|
for mode in ("full", "restricted", "full"):
|
|
conn.send.reset_mock()
|
|
await channel._dispatch_envelope(conn, "client", {
|
|
"type": "set_workspace_scope",
|
|
"chat_id": "handshake-scope",
|
|
"workspace_scope": {"project_path": str(tmp_path), "access_mode": mode},
|
|
})
|
|
result = json.loads(conn.send.await_args.args[0])
|
|
assert result["event"] == "session_updated"
|
|
assert result["workspace_scope"]["access_mode"] == mode
|
|
assert channel.gateway.workspaces.scope_for_session_key(
|
|
"websocket:handshake-scope"
|
|
).access_mode == mode
|
|
|
|
|
|
@pytest.mark.parametrize("command_type", ["new_chat", "attach", "set_workspace_scope", "message"])
|
|
async def test_webui_commands_keep_session_io_off_event_loop(
|
|
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command_type: str,
|
|
) -> None:
|
|
import threading
|
|
|
|
sessions = SessionManager(tmp_path / "sessions")
|
|
sessions.save(sessions.get_or_create("websocket:io-chat"))
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
|
|
bus,
|
|
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
|
|
)
|
|
conn = AsyncMock()
|
|
conn.remote_address = ("127.0.0.1", 50123)
|
|
loop_thread = threading.get_ident()
|
|
calls: list[str] = []
|
|
|
|
def require_worker(name):
|
|
operation = getattr(sessions._store, name)
|
|
|
|
def checked(*args, **kwargs):
|
|
assert threading.get_ident() != loop_thread, name
|
|
calls.append(name)
|
|
return operation(*args, **kwargs)
|
|
|
|
return checked
|
|
|
|
for name in ("read_metadata", "load", "save", "replace_metadata"):
|
|
monkeypatch.setattr(sessions._store, name, require_worker(name))
|
|
|
|
await channel._dispatch_envelope(
|
|
conn,
|
|
"webui-client",
|
|
{"type": command_type, "chat_id": "io-chat", "content": "/help", "webui": True},
|
|
)
|
|
|
|
assert "read_metadata" in calls
|
|
if command_type in {"set_workspace_scope", "message"}:
|
|
assert "load" in calls
|
|
assert "save" in calls or "replace_metadata" in calls
|
|
assert all(json.loads(call.args[0])["event"] != "error" for call in conn.send.await_args_list)
|
|
await channel._cleanup_connection(conn)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("connected", [False, True])
|
|
async def test_model_request_delivery_persists_started_and_terminal_offline(history, connected):
|
|
from nanobot.events import ModelRequestEvent
|
|
|
|
bus = MagicMock()
|
|
channel = WebSocketChannel(
|
|
{"enabled": True, "allowFrom": ["*"]}, bus,
|
|
gateway=_basic_handler(bus, session_manager=history.sessions),
|
|
)
|
|
ws = AsyncMock()
|
|
if connected:
|
|
channel._attach(ws, "model-requests")
|
|
for sequence, phase in enumerate(("started", "completed"), 1):
|
|
await channel.send(await history.message(
|
|
channel="websocket", chat_id="model-requests", content="",
|
|
event=ModelRequestEvent("request", "run", sequence, phase),
|
|
))
|
|
rows = history.read("websocket:model-requests")
|
|
assert [r["event"] for r in rows] == ["model_request", "model_request"]
|
|
assert [r["phase"] for r in rows] == ["started", "completed"]
|
|
if connected:
|
|
assert [r["phase"] for r in _sent_ws_payloads(ws)] == ["started", "completed"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_history_model_request_opt_in_preserves_old_clients_cursors_and_etags(history):
|
|
from urllib.parse import quote
|
|
|
|
from websockets.datastructures import Headers
|
|
from websockets.http11 import Request
|
|
|
|
key = "websocket:model-capability"
|
|
for number in range(3):
|
|
history.append(key, {"event": "user", "chat_id": "model-capability", "text": f"question {number}"})
|
|
history.append(key, {
|
|
"event": "model_request", "chat_id": "model-capability",
|
|
"request_id": f"request-{number}", "run_id": f"run-{number}",
|
|
"sequence": 2, "phase": "completed", "round_usages": [],
|
|
})
|
|
history.append(key, {"event": "message", "chat_id": "model-capability", "text": "answer"})
|
|
history.append(key, {"event": "turn_end", "chat_id": "model-capability"})
|
|
channel = _ch(MagicMock(), session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
|
encoded = quote(key, safe="")
|
|
|
|
async def fetch(query, etag=None):
|
|
headers = [("Authorization", "Bearer tok")]
|
|
if etag:
|
|
headers.append(("If-None-Match", etag))
|
|
response = await channel.gateway.http._handle_webui_thread_get_async(Request(
|
|
f"/api/sessions/{encoded}/webui-thread?{query}", Headers(headers),
|
|
), encoded)
|
|
return response, json.loads(response.body) if response.body else None
|
|
|
|
old_response, old = await fetch("limit=2&direction=latest")
|
|
modern_response, modern = await fetch(
|
|
"limit=2&direction=latest&include_model_requests=1", old_response.headers["ETag"],
|
|
)
|
|
assert old_response.status_code == modern_response.status_code == 200
|
|
assert old_response.headers["ETag"] != modern_response.headers["ETag"]
|
|
assert all(event["event"] != "model_request" for event in old["events"])
|
|
assert any(event["event"] == "model_request" for event in modern["events"])
|
|
assert old["events"] == [event for event in modern["events"] if event["event"] != "model_request"]
|
|
assert old["page"]["before_cursor"] == modern["page"]["before_cursor"]
|
|
cursor = quote(old["page"]["before_cursor"], safe="")
|
|
_, old_page = await fetch(f"limit=2&before={cursor}")
|
|
_, modern_page = await fetch(f"limit=2&before={cursor}&include_model_requests=1")
|
|
assert old_page["events"] == [event for event in modern_page["events"] if event["event"] != "model_request"]
|
|
assert old_page["page"]["loaded_event_count"] == len(old_page["events"])
|
|
assert modern_page["page"]["loaded_event_count"] == len(modern_page["events"])
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("state", ["missing", "present", "new_request"])
|
|
async def test_thread_replays_durable_compaction_boundaries(history, tmp_path, monkeypatch, state):
|
|
from urllib.parse import quote
|
|
|
|
from websockets.http11 import Request
|
|
|
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
|
key = "websocket:legacy-context"
|
|
snapshot = {"graph": {"nodes": [], "edges": []}, "estimated_tokens": 100, "context_window_tokens": 1000}
|
|
history.append(key, {"event": "user", "chat_id": "legacy-context", "text": "hello"})
|
|
compact = {"event": "context_compaction", "compaction_id": "compact", "phase": "succeeded"}
|
|
if state == "present":
|
|
compact["context_snapshot"] = snapshot
|
|
history.append(key, compact)
|
|
if state == "new_request":
|
|
history.append(key, {"event": "model_request", "request_id": "request", "run_id": "run", "sequence": 1, "phase": "started"})
|
|
gateway = _basic_handler(MagicMock(), workspace_path=tmp_path, session_manager=history.sessions)
|
|
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
|
|
|
|
encoded = quote(key, safe="")
|
|
path = f"/api/sessions/{encoded}/webui-thread?include_model_requests=1"
|
|
request = Request(path, Headers([("Authorization", "Bearer tok")]))
|
|
response = await gateway.http._handle_webui_thread_get_async(request, encoded)
|
|
assert response.status_code == 200
|
|
body = json.loads(response.body)
|
|
event = next(event for event in body["events"] if event["event"] == "context_compaction")
|
|
assert event["phase"] == "succeeded"
|
|
assert event["compaction_id"] == "compact"
|
|
if state == "present":
|
|
assert event["context_snapshot"] == snapshot
|
|
else:
|
|
# Historical reads must not invent a snapshot from today's disk files.
|
|
assert "context_snapshot" not in event
|
|
cached_request = Request(path, Headers([("Authorization", "Bearer tok"), ("If-None-Match", response.headers["ETag"])]))
|
|
cached = await gateway.http._handle_webui_thread_get_async(cached_request, encoded)
|
|
assert cached.status_code == 304
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_context_graph_dictionary_pages_are_self_contained_and_opt_in(history):
|
|
from urllib.parse import quote
|
|
|
|
from websockets.http11 import Request
|
|
|
|
key = "websocket:graph-pages"
|
|
graph = {"nodes": [{"path": "/guide.md", "name": "guide.md", "tokens": 10, "state": "loaded"}], "edges": []}
|
|
for number in range(3):
|
|
history.append(key, {"event": "user", "text": f"question {number}"})
|
|
history.append(key, {"event": "model_request", "request_id": str(number), "run_id": str(number), "sequence": 2, "phase": "completed", "context_graph": graph, "request_usage": {"context_tokens": number + 10}})
|
|
history.append(key, {"event": "context_compaction", "compaction_id": str(number), "phase": "succeeded", "context_snapshot": {"graph": graph, "estimated_tokens": 5, "context_window_tokens": 100}})
|
|
history.append(key, {"event": "turn_end"})
|
|
channel = _ch(MagicMock(), session_manager=history.sessions)
|
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
|
encoded = quote(key, safe="")
|
|
|
|
async def fetch(before=None, compact=False, etag=None):
|
|
query = "include_model_requests=1&limit=1"
|
|
if before:
|
|
query += "&before=" + quote(before, safe="")
|
|
if compact:
|
|
query += "&context_graph_encoding=references-v1"
|
|
headers = [("Authorization", "Bearer tok")]
|
|
if etag:
|
|
headers.append(("If-None-Match", etag))
|
|
return await channel.gateway.http._handle_webui_thread_get_async(Request(f"/api/sessions/{encoded}/webui-thread?{query}", Headers(headers)), encoded)
|
|
|
|
before = None
|
|
seen = []
|
|
for _ in range(3):
|
|
old_response = await fetch(before)
|
|
compact_response = await fetch(before, compact=True, etag=old_response.headers["ETag"])
|
|
assert compact_response.status_code == 200
|
|
old = json.loads(old_response.body)
|
|
compact = json.loads(compact_response.body)
|
|
assert "context_graphs" not in old
|
|
assert len(compact["context_graphs"]) == 1
|
|
assert compact["context_graph_nodes"] == graph["nodes"]
|
|
assert compact["context_graph_edges"] == graph["edges"]
|
|
decoded_graphs = {key: {
|
|
"nodes": [compact["context_graph_nodes"][index] for index in descriptor["nodes"]],
|
|
"edges": [compact["context_graph_edges"][index] for index in descriptor["edges"]],
|
|
} for key, descriptor in compact["context_graphs"].items()}
|
|
for event in compact["events"]:
|
|
if "context_graph_ref" in event:
|
|
event["context_graph"] = decoded_graphs[event.pop("context_graph_ref")]
|
|
seen.append(event["request_id"])
|
|
if "context_snapshot" in event:
|
|
snapshot = event["context_snapshot"]
|
|
snapshot["graph"] = decoded_graphs[snapshot.pop("graph_ref")]
|
|
assert compact["events"] == old["events"]
|
|
assert compact["page"]["before_cursor"] == old["page"]["before_cursor"]
|
|
before = compact["page"]["before_cursor"]
|
|
assert seen == ["2", "1", "0"]
|