fix(webui): correlate chat requests and cancel stale reconnects (#6617)

* fix(webui): correlate chat requests and cancel stale reconnects

* refactor(webui): remove chat request capability negotiation

* docs(webui): clarify version pairing and cover HTTP startup

* test(webui): focus lifecycle coverage and clarify support policy
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-12 14:44:38 +08:00
1 parent 9f7ae6fb7b
commit 1046a37be1
16 files changed
+478 -138

No files matched your search

@@ -5632,6 +5632,89 @@ async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> N
await server_task
@pytest.mark.parametrize("command_type", ["new_chat", "new_temporary_chat", "fork_chat"])
@pytest.mark.asyncio
async def test_chat_requests_correlate_only_creation_responses(
bus, tmp_path, start_listener, command_type,
) -> None:
sessions = SessionManager(tmp_path)
source = sessions.get_or_create("websocket:source")
source.add_message("user", "first question")
source.add_message("assistant", "first answer")
sessions.save(source)
channel = _ch(bus, session_manager=sessions)
port, _ = await start_listener(channel)
token = channel.gateway.tokens.issue_token(300, audience="webui")
request_id = "Chat._:-" + "x" * 120
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?token={token}") as client:
async with asyncio.timeout(5):
ready = json.loads(await client.recv())
assert ready["event"] == "ready"
envelope = {"type": command_type, "request_id": request_id}
if command_type == "fork_chat":
envelope.update(source_chat_id="source", before_user_index=1)
await client.send(json.dumps(envelope))
attached = await _recv_ws_event(client, "attached")
assert attached["chat_id"] not in {"source", ready["chat_id"]}
assert attached["request_id"] == request_id
if command_type == "new_temporary_chat":
assert attached["temporary"] is True
await client.send(json.dumps({
"type": "attach", "chat_id": "source", "request_id": "not-a-creation",
}))
attached = await _recv_ws_event(client, "attached")
assert attached["chat_id"] == "source"
assert "request_id" not in attached
@pytest.mark.parametrize(("envelope", "trusted_webui", "detail"), [
({"type": "new_chat", "workspace_scope": {"access_mode": "invalid"}}, True,
"workspace_scope_rejected"),
({"type": "new_temporary_chat"}, False, "access_denied"),
({"type": "fork_chat", "source_chat_id": "missing", "before_user_index": 0}, True,
"invalid fork source or index"),
])
@pytest.mark.asyncio
async def test_chat_request_errors_preserve_correlation(
bus, tmp_path, envelope, trusted_webui, detail,
) -> None:
channel = _ch(bus, session_manager=SessionManager(tmp_path))
connection = AsyncMock()
if trusted_webui:
channel._webui_connections.add(connection)
await channel._dispatch_envelope(connection, "client", {**envelope, "request_id": "create-request"})
[error] = _sent_ws_payloads(connection)
assert error["event"] == "error"
assert error["detail"] == detail
assert error["request_id"] == "create-request"
assert channel._conn_chats == {}
@pytest.mark.parametrize(("command_type", "request_id"), [
("new_chat", "bad/id"),
("new_temporary_chat", "x" * 129),
("fork_chat", None),
])
@pytest.mark.asyncio
async def test_chat_request_rejects_invalid_id_before_execution(
bus, command_type, request_id,
) -> None:
channel = _ch(bus)
connection = AsyncMock()
channel._webui_connections.add(connection)
await channel._dispatch_envelope(connection, "client", {
"type": command_type, "request_id": request_id,
"source_chat_id": "source", "before_user_index": 0,
})
assert _sent_ws_payloads(connection) == [{"event": "error", "detail": "invalid chat request_id"}]
assert channel._conn_chats == {}
@pytest.mark.asyncio
async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None:
port = 0
+12 -5
View File
@@ -24,6 +24,8 @@ class WebUIForkHost(Protocol):
self,
connection: ServerConnection,
detail: str,
*,
request_id: str | None = None,
) -> None: ...
async def attach_webui_fork(
@@ -32,6 +34,7 @@ class WebUIForkHost(Protocol):
*,
fork_id: str,
fork_key: str,
request_id: str | None = None,
) -> None: ...
@@ -59,6 +62,8 @@ async def handle_webui_fork_chat(
channel: WebUIForkHost,
connection: ServerConnection,
envelope: Mapping[str, Any],
*,
request_id: str | None = None,
) -> None:
"""Handle the WebUI ``fork_chat`` websocket command.
@@ -66,18 +71,19 @@ async def handle_webui_fork_chat(
validate the request, clone session/transcript state, attach the new chat,
and hydrate the client.
"""
request_fields = {"request_id": request_id} if request_id is not None else {}
source_chat_id = envelope.get("source_chat_id")
raw_index = envelope.get("before_user_index")
if not is_valid_webui_chat_id(source_chat_id):
await channel.send_webui_protocol_error(connection, "invalid source_chat_id")
await channel.send_webui_protocol_error(connection, "invalid source_chat_id", **request_fields)
return
if isinstance(raw_index, bool) or not isinstance(raw_index, int) or raw_index < 0:
await channel.send_webui_protocol_error(connection, "invalid before_user_index")
await channel.send_webui_protocol_error(connection, "invalid before_user_index", **request_fields)
return
session_manager = channel.gateway.session_manager
if session_manager is None:
await channel.send_webui_protocol_error(connection, "session_manager_unavailable")
await channel.send_webui_protocol_error(connection, "session_manager_unavailable", **request_fields)
return
try:
@@ -88,16 +94,17 @@ async def handle_webui_fork_chat(
title=envelope.get("title") if isinstance(envelope.get("title"), str) else None,
)
if forked is None:
await channel.send_webui_protocol_error(connection, "invalid fork source or index")
await channel.send_webui_protocol_error(connection, "invalid fork source or index", **request_fields)
return
fork_id, fork_key = forked
except Exception as exc:
logger.warning("fork_chat failed: {}", exc)
await channel.send_webui_protocol_error(connection, "fork_chat_failed")
await channel.send_webui_protocol_error(connection, "fork_chat_failed", **request_fields)
return
await channel.attach_webui_fork(
connection,
fork_id=fork_id,
fork_key=fork_key,
**request_fields,
)
+27 -7
View File
@@ -68,6 +68,7 @@ if TYPE_CHECKING:
_WEBUI_REQUEST_CACHE_TTL_S = 5 * 60.0
_WEBUI_REQUEST_CACHE_MAX = 256
_WEBUI_REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
@dataclass(frozen=True)
@@ -168,8 +169,13 @@ class WebUICommandRouter:
self,
connection: ServerConnection,
detail: str,
*,
request_id: str | None = None,
) -> None:
await self._transport.webui_send_event(connection, "error", detail=detail)
await self._transport.webui_send_event(
connection, "error", detail=detail,
**({"request_id": request_id} if request_id is not None else {}),
)
async def attach_webui_fork(
self,
@@ -177,6 +183,7 @@ class WebUICommandRouter:
*,
fork_id: str,
fork_key: str,
request_id: str | None = None,
) -> None:
scope = await self._workspaces.async_scope_for_session_key(fork_key)
self._transport.webui_attach(connection, fork_id)
@@ -184,6 +191,7 @@ class WebUICommandRouter:
connection,
"attached",
chat_id=fork_id,
**({"request_id": request_id} if request_id is not None else {}),
**(await self._session_projection.attach_fields(fork_key)),
)
await self._transport.webui_send_event(
@@ -271,6 +279,7 @@ class WebUICommandRouter:
*,
chat_id: str | None = None,
turn_id: str | None = None,
request_id: str | None = None,
) -> Any | None:
try:
return await resolver()
@@ -280,6 +289,7 @@ class WebUICommandRouter:
"error",
detail="workspace_scope_rejected",
reason=exc.message,
**({"request_id": request_id} if request_id is not None else {}),
**({"chat_id": chat_id} if chat_id else {}),
**({"turn_id": turn_id} if turn_id else {}),
)
@@ -326,6 +336,14 @@ class WebUICommandRouter:
if command_type == "webui_request":
await self.start_webui_request(connection, envelope)
return
request_id: str | None = None
if command_type in ("new_chat", "new_temporary_chat", "fork_chat") and "request_id" in envelope:
raw_request_id = envelope["request_id"]
if not isinstance(raw_request_id, str) or _WEBUI_REQUEST_ID_RE.fullmatch(raw_request_id) is None:
await self.send_webui_protocol_error(connection, "invalid chat request_id")
return
request_id = raw_request_id
request_fields = {"request_id": request_id} if request_id is not None else {}
if command_type == "new_chat":
new_id = str(uuid.uuid4())
scope = await self.workspace_scope_or_error(
@@ -334,6 +352,7 @@ class WebUICommandRouter:
envelope,
can_change_project=self.workspace_project_selection_available(connection),
),
request_id=request_id,
)
if scope is None:
return
@@ -343,6 +362,7 @@ class WebUICommandRouter:
connection,
"attached",
chat_id=new_id,
**request_fields,
**(await self._session_projection.attach_fields(webui_session_key(new_id))),
)
await self._transport.webui_send_event(
@@ -361,7 +381,9 @@ class WebUICommandRouter:
trusted_webui=connection in self._webui_connections,
)
except TemporaryChatError as exc:
await self._transport.webui_send_event(connection, "error", detail=exc.detail)
await self._transport.webui_send_event(
connection, "error", detail=exc.detail, **request_fields,
)
return
self._transport.webui_attach(connection, new_id)
await self._transport.webui_send_event(
@@ -369,10 +391,11 @@ class WebUICommandRouter:
"attached",
chat_id=new_id,
temporary=True,
**request_fields,
)
return
if command_type == "fork_chat":
await handle_webui_fork_chat(self, connection, envelope)
await handle_webui_fork_chat(self, connection, envelope, **request_fields)
return
if command_type == "discard_temporary_chat":
chat_id = envelope.get("chat_id")
@@ -888,10 +911,7 @@ class WebUICommandRouter:
envelope: dict[str, Any],
) -> None:
request_id = envelope.get("request_id")
if not isinstance(request_id, str) or re.fullmatch(
r"[A-Za-z0-9._:-]{1,128}",
request_id,
) is None:
if not isinstance(request_id, str) or _WEBUI_REQUEST_ID_RE.fullmatch(request_id) is None:
await self._transport.webui_send_event(
connection,
"error",