fix(webui): reconcile threads after browser resume
This commit is contained in:
1 parent
78cf68c291
commit
ae089aa3ae
39 files changed
+6151
-243
No files matched your search
@@ -49,8 +49,13 @@ from nanobot.webui.http_utils import (
|
||||
from nanobot.webui.http_utils import (
|
||||
parse_request_path as _parse_request_path,
|
||||
)
|
||||
from nanobot.webui.metadata import WEBSOCKET_TURN_OWNER_METADATA_KEY
|
||||
from nanobot.webui.settings_api import settings_payload, update_provider_settings
|
||||
from nanobot.webui.transcript import append_transcript_object, read_transcript_lines
|
||||
from nanobot.webui.transcript import (
|
||||
append_transcript_object,
|
||||
build_webui_thread_response,
|
||||
read_transcript_lines,
|
||||
)
|
||||
|
||||
from .ws_test_client import http_get as _http_get
|
||||
|
||||
@@ -164,11 +169,20 @@ async def test_start_extends_http_open_timeout_for_slow_settings_routes(
|
||||
|
||||
@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()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -743,6 +757,7 @@ async def test_webui_scope_rejects_running_scope_change(bus: MagicMock, tmp_path
|
||||
"chat_id": "chat-running",
|
||||
"content": "hello",
|
||||
"webui": True,
|
||||
"turn_id": "turn-scope-rejected",
|
||||
"workspace_scope": {
|
||||
"project_path": str(other),
|
||||
"access_mode": "full",
|
||||
@@ -757,6 +772,7 @@ async def test_webui_scope_rejects_running_scope_change(bus: MagicMock, tmp_path
|
||||
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()
|
||||
|
||||
|
||||
@@ -1602,6 +1618,434 @@ async def test_send_turn_end_emits_turn_end_event() -> None:
|
||||
]
|
||||
|
||||
|
||||
@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_fanout_fails(
|
||||
active_owner: str,
|
||||
event_owner: str,
|
||||
expected_cleared: bool,
|
||||
) -> 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 = f"turn-end-failure-{expected_cleared}"
|
||||
channel._attach(mock_ws, chat_id)
|
||||
wth._WEBSOCKET_TURN_WALL_STARTED_AT[chat_id] = 1234.5
|
||||
wth._WEBSOCKET_TURN_OWNERS[chat_id] = active_owner
|
||||
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="fanout failed"):
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="",
|
||||
metadata={WEBSOCKET_TURN_OWNER_METADATA_KEY: event_owner},
|
||||
event=TurnEndEvent(),
|
||||
))
|
||||
|
||||
assert read_transcript_lines(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._WEBSOCKET_TURN_WALL_STARTED_AT.pop(chat_id, None)
|
||||
wth._WEBSOCKET_TURN_IDS.pop(chat_id, None)
|
||||
wth._WEBSOCKET_TURN_OWNERS.pop(chat_id, None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_end_keeps_registry_when_transcript_persistence_fails(
|
||||
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 = "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 = MagicMock(side_effect=OSError("disk full"))
|
||||
monkeypatch.setattr("nanobot.webui.transcript.append_transcript_object", append)
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
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(OutboundMessage(
|
||||
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(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.webui.transcript import build_webui_thread_response
|
||||
|
||||
bus = MagicMock()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
)
|
||||
chat_id = "answer-persistence-failure"
|
||||
key = f"websocket:{chat_id}"
|
||||
owner = "owner-answer"
|
||||
turn_id = "turn-answer"
|
||||
append_transcript_object(
|
||||
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 = append_transcript_object
|
||||
|
||||
def fail_answer(session_key: str, event: dict[str, Any]) -> None:
|
||||
if event.get("event") == "message":
|
||||
raise OSError("transient disk failure")
|
||||
original_append(session_key, event)
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.transcript.append_transcript_object", fail_answer)
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="answer",
|
||||
metadata=dict(inbound.metadata),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="",
|
||||
metadata=dict(inbound.metadata),
|
||||
event=TurnEndEvent(),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="",
|
||||
metadata=dict(inbound.metadata),
|
||||
event=GoalStatusEvent(status="idle"),
|
||||
))
|
||||
|
||||
# Simulate a gateway restart: no process-local owner survives, so the
|
||||
# persisted marker must be sufficient to reject canonical completion.
|
||||
wth._WEBSOCKET_ACTIVE_TURNS.clear()
|
||||
wth._WEBSOCKET_TURN_WALL_STARTED_AT.clear()
|
||||
wth._WEBSOCKET_TURN_IDS.clear()
|
||||
wth._WEBSOCKET_TURN_OWNERS.clear()
|
||||
body = build_webui_thread_response(
|
||||
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 read_transcript_lines(key)[-1]["transcript_incomplete"] is True
|
||||
assert body["completed_turn_ids"] == []
|
||||
assert [(message["role"], message["content"]) for message in body["messages"]] == [
|
||||
("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(
|
||||
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 = tmp_path / "sessions"
|
||||
sessions = SessionManager(sessions_path)
|
||||
session = sessions.get_or_create(key)
|
||||
session.add_message("user", "question")
|
||||
session.add_message("assistant", "durable answer")
|
||||
sessions.save(session)
|
||||
append_transcript_object(
|
||||
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 = append_transcript_object
|
||||
|
||||
def fail_answer(session_key: str, event: dict[str, Any]) -> None:
|
||||
if event.get("event") == "message":
|
||||
raise OSError("transient disk failure")
|
||||
original_append(session_key, event)
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.transcript.append_transcript_object", fail_answer)
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="durable answer",
|
||||
metadata=dict(inbound.metadata),
|
||||
))
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="",
|
||||
metadata=dict(inbound.metadata),
|
||||
event=TurnEndEvent(),
|
||||
))
|
||||
|
||||
persisted_lines = read_transcript_lines(key)
|
||||
assert persisted_lines[-1]["event"] == "turn_end"
|
||||
assert persisted_lines[-1]["transcript_incomplete"] is True
|
||||
|
||||
# Drop all process-local state and construct a fresh HTTP/session layer.
|
||||
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 = restarted_channel.gateway.http._handle_webui_thread_get(
|
||||
request,
|
||||
encoded_key,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = json.loads(response.body.decode())
|
||||
assert [(message["role"], message["content"]) for message in body["messages"]] == [
|
||||
("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_fanout_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)
|
||||
wth._WEBSOCKET_TURN_WALL_STARTED_AT[chat_id] = 1234.5
|
||||
wth._WEBSOCKET_TURN_OWNERS[chat_id] = owner
|
||||
|
||||
with pytest.raises(RuntimeError, match="fanout failed"):
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id=chat_id,
|
||||
content="",
|
||||
metadata={WEBSOCKET_TURN_OWNER_METADATA_KEY: owner},
|
||||
event=GoalStatusEvent(status="idle"),
|
||||
))
|
||||
|
||||
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()
|
||||
@@ -1654,6 +2098,7 @@ async def test_send_goal_status_running_emits_event_with_started_at() -> None:
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"webui_turn_id": "turn-running"},
|
||||
event=GoalStatusEvent(status="running", started_at=1_700_000_000.5),
|
||||
))
|
||||
|
||||
@@ -1664,6 +2109,7 @@ async def test_send_goal_status_running_emits_event_with_started_at() -> None:
|
||||
"chat_id": "chat-1",
|
||||
"status": "running",
|
||||
"started_at": 1_700_000_000.5,
|
||||
"turn_id": "turn-running",
|
||||
}
|
||||
|
||||
|
||||
@@ -1678,12 +2124,18 @@ async def test_send_goal_status_idle_omits_started_at() -> None:
|
||||
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"}
|
||||
assert body == {
|
||||
"event": "goal_status",
|
||||
"chat_id": "chat-1",
|
||||
"status": "idle",
|
||||
"turn_id": "turn-idle",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -2725,6 +3177,147 @@ async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock) -> None
|
||||
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(
|
||||
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-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 = build_webui_thread_response(
|
||||
"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",
|
||||
}
|
||||
|
||||
|
||||
@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",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_client_id_truncation(bus: MagicMock) -> None:
|
||||
port = 29883
|
||||
@@ -3238,6 +3831,255 @@ def test_handle_webui_thread_get_returns_json(tmp_path, monkeypatch) -> None:
|
||||
assert len(body["messages"]) == 1
|
||||
assert body["messages"][0]["role"] == "user"
|
||||
assert body["messages"][0]["content"] == "hi"
|
||||
assert body["has_pending_tool_calls"] is False
|
||||
|
||||
|
||||
def test_handle_webui_thread_get_reports_registered_turn_as_pending(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
from urllib.parse import quote
|
||||
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request
|
||||
|
||||
from nanobot.webui.transcript import append_transcript_object
|
||||
|
||||
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"
|
||||
append_transcript_object(
|
||||
key,
|
||||
{
|
||||
"event": "user",
|
||||
"chat_id": "running",
|
||||
"text": "hi",
|
||||
"turn_id": "turn-running",
|
||||
},
|
||||
)
|
||||
bus = MagicMock()
|
||||
channel = _ch(bus)
|
||||
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 = channel.gateway.http._handle_webui_thread_get(req, enc)
|
||||
|
||||
assert resp.status_code == 200
|
||||
body = json.loads(resp.body.decode())
|
||||
assert body["messages"][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(
|
||||
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
|
||||
from nanobot.webui.transcript import append_transcript_object
|
||||
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
key = "websocket:idle-order"
|
||||
turn_id = "turn-idle-order"
|
||||
append_transcript_object(
|
||||
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)
|
||||
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 = channel.gateway.http._handle_webui_thread_get(request, enc)
|
||||
assert json.loads(before_delivery.body.decode())["has_pending_tool_calls"] is True
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="idle-order",
|
||||
content="",
|
||||
metadata=dict(inbound.metadata),
|
||||
event=TurnEndEvent(),
|
||||
))
|
||||
|
||||
after_delivery = channel.gateway.http._handle_webui_thread_get(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() -> 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}"
|
||||
append_transcript_object(
|
||||
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)
|
||||
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 = channel.gateway.http._handle_webui_thread_get(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.parametrize(
|
||||
("active_turn_id", "expected_pending"),
|
||||
[
|
||||
("turn-complete", False),
|
||||
("turn-next", True),
|
||||
],
|
||||
)
|
||||
def test_handle_webui_thread_get_reconciles_registered_turn_with_turn_end(
|
||||
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
|
||||
|
||||
from nanobot.webui.transcript import append_transcript_object
|
||||
|
||||
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"
|
||||
append_transcript_object(
|
||||
key,
|
||||
{
|
||||
"event": "user",
|
||||
"chat_id": "running",
|
||||
"text": "hi",
|
||||
"turn_id": "turn-complete",
|
||||
},
|
||||
)
|
||||
append_transcript_object(
|
||||
key,
|
||||
{
|
||||
"event": "message",
|
||||
"chat_id": "running",
|
||||
"text": "done",
|
||||
"turn_id": "turn-complete",
|
||||
},
|
||||
)
|
||||
append_transcript_object(
|
||||
key,
|
||||
{
|
||||
"event": "turn_end",
|
||||
"chat_id": "running",
|
||||
"turn_id": "turn-complete",
|
||||
},
|
||||
)
|
||||
bus = MagicMock()
|
||||
channel = _ch(bus)
|
||||
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 = channel.gateway.http._handle_webui_thread_get(req, enc)
|
||||
|
||||
assert resp.status_code == 200
|
||||
body = json.loads(resp.body.decode())
|
||||
assert body["messages"][-1]["content"] == "done"
|
||||
assert body["has_pending_tool_calls"] is expected_pending
|
||||
assert body["active_turn_id"] == active_turn_id
|
||||
|
||||
|
||||
def test_handle_webui_thread_get_accepts_pagination_query(tmp_path, monkeypatch) -> None:
|
||||
|
||||
Reference in new issue
Block a user