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

+12 -12
View File
@@ -1,21 +1,21 @@
# Review guide: independently updated WebUI clients and hosts # Review guide: WebUI clients and hosts
Apply this checklist to changes to WebUI HTTP, WebSocket events/mutations, bootstrap, capabilities, host switching, and persisted browser state. Read this alongside the design and security constraints, not instead of them. Apply this checklist to changes to WebUI HTTP, WebSocket events/mutations, bootstrap, capabilities, host switching, and persisted browser state. Read this alongside the design and security constraints, not instead of them.
## Compatibility is a contract, not a package-version comparison ## Compatibility and deployment
- WebUI/gateway support and test coverage are limited to same-version combinations, including remote hosts. Cross-version combinations may work but have no compatibility guarantee, even when protocol checks pass. Align versions first when troubleshooting; do not reject connections solely because package versions differ.
- The local installation owns executable WebUI assets. A remote host supplies authenticated data, events, and media, never replacement JavaScript or CSS. - The local installation owns executable WebUI assets. A remote host supplies authenticated data, events, and media, never replacement JavaScript or CSS.
- Negotiate the WebUI protocol in `webui/client_contract.py`. The pre-existing terminal `protocolVersion` is a separate contract; do not overload it. - Declare the WebUI protocol in `webui/client_contract.py`. The pre-existing terminal `protocolVersion` is a separate contract; do not overload it.
- Different package versions may use the same protocol. New hosts should keep the previously supported protocol when possible. Extra fields and unknown optional capabilities must not break older clients. - Use named capabilities for optional features and gate their controls and requests at their owning interface. Do not add compatibility fallbacks or negotiation solely to support older gateways.
- Add optional features as named capabilities. Gate their controls and requests at their owning interface; do not require a server upgrade for unrelated features. Raise the core protocol floor only for an intentional breaking change with a documented support window and migration path. - Missing/malformed metadata means **compatibility unconfirmed**, not “old server,” “bad SSH key,” or “network error.” A matching package version alone does not validate the contract. An unconfirmed core contract cannot authorize mutations.
- Missing/malformed metadata means **compatibility unconfirmed**, not “old server,” “bad SSH key,” or “network error.” Do not infer support from matching package versions. An unconfirmed core contract cannot authorize mutations.
- A package update being available is not proof of incompatibility. Optional update notices must use verified release data, be dismissible, and never interrupt an otherwise compatible session. - A package update being available is not proof of incompatibility. Optional update notices must use verified release data, be dismissible, and never interrupt an otherwise compatible session.
## Required proof for a changed contract ## Required proof for a changed contract
- Current client/current host, current client/oldest supported host, and oldest supported client/current host. State the supported protocol range explicitly; never claim every historical nanobot release is supported. - Verify the current client with a same-version host. Cross-version compatibility fixtures or fallback behavior are not required.
- Unknown, missing, malformed and future metadata; overlapping and disjoint protocol ranges; unknown optional capabilities; missing required capability. - For changes to contract validation, test unknown, missing, malformed and future metadata; overlapping and disjoint protocol ranges; unknown optional capabilities; and missing required capability.
- Assert the actual public bootstrap/read/mutation/event behavior, not only a version-comparison helper. Keep an older client/host fixture independent of the implementation under test. Test the affected optional feature's fallback. - Assert the actual public bootstrap/read/mutation/event behavior, not only a version-comparison helper.
- Reconnect after a host restart or upgrade. Previously issued credentials and stale cached compatibility must not bypass a changed host contract. - Reconnect after a host restart or upgrade. Previously issued credentials and stale cached compatibility must not bypass a changed host contract.
- Prove local HTML/JS/CSS are used even when remote static files are missing or different. Missing local assets fail locally, never fall back to remote code. - Prove local HTML/JS/CSS are used even when remote static files are missing or different. Missing local assets fail locally, never fall back to remote code.
- HTTP reads, streamed messages, upload/download, cancellation, multiple tabs, and a response arriving after switching hosts remain scoped to their host. - HTTP reads, streamed messages, upload/download, cancellation, multiple tabs, and a response arriving after switching hosts remain scoped to their host.
@@ -23,8 +23,8 @@ Apply this checklist to changes to WebUI HTTP, WebSocket events/mutations, boots
## Update UX and operator safety ## Update UX and operator safety
- Report the local version, host version (or “not reported”), compatibility, and which machine needs updating. A newer host must not be told to downgrade when the client needs updating. - Report the local version, host version (or “not reported”), compatibility, and which machine needs updating without presenting a passing protocol check as a guarantee of cross-version functionality.
- Keep compatible version differences quiet. Show missing optional capabilities at the affected control. Block only unsupported core sessions or operations. - Show missing optional capabilities at the affected control. Block unsupported core sessions or operations.
- Reuse the application's settings rows, menus and dialogs. Do not introduce a second settings drawer or a persistent global warning for an optional update. - Reuse the application's settings rows, menus and dialogs. Do not introduce a second settings drawer or a persistent global warning for an optional update.
- Explain that updating this computer does not update its hosts. Use the installation environment that owns the running process: installer/uv/pipx/pip, checkout, container, and service-managed deployments are not interchangeable. - Explain that updating this computer does not update its hosts. Use the installation environment that owns the running process: installer/uv/pipx/pip, checkout, container, and service-managed deployments are not interchangeable.
- Never silently install, restart, downgrade, revoke credentials, or reset configuration. Back up configuration/data and consider active tasks before an explicitly requested update. Verify the running process after restart, not merely whichever `nanobot` executable happens to be on PATH. - Never silently install, restart, downgrade, revoke credentials, or reset configuration. Back up configuration/data and consider active tasks before an explicitly requested update. Verify the running process after restart, not merely whichever `nanobot` executable happens to be on PATH.
@@ -32,4 +32,4 @@ Apply this checklist to changes to WebUI HTTP, WebSocket events/mutations, boots
## Current baseline ## Current baseline
WebUI protocol **1** with capability **`webui.core.v1`** is the initial explicit client/host contract. It covers the existing authenticated WebUI read, mutation, event, and media interfaces. Hosts predating this declaration are unconfirmed; the local-client mode requires updating them to a build that declares support. Their independent server WebUI remains a separate way to use that installation. This is an intentional prerequisite for local-client mode, not a blanket claim that legacy nanobot installations no longer function. WebUI protocol **1** with capability **`webui.core.v1`** is the initial explicit client/host contract. It covers the existing authenticated WebUI read, mutation, event, and media interfaces. Hosts predating this declaration are unconfirmed; local-client mode requires a gateway that declares a supported protocol and the required capabilities. Their independent server WebUI remains a separate way to use that installation. This is an intentional prerequisite for local-client mode, not a blanket claim that legacy nanobot installations no longer function.
+2
View File
@@ -2,6 +2,8 @@
The Python gateway owns agent execution, sessions, tools, memory, and security policy. WebUI and TUI share that runtime; keep execution and policy out of the clients. The Python gateway owns agent execution, sessions, tools, memory, and security policy. WebUI and TUI share that runtime; keep execution and policy out of the clients.
WebUI/gateway support and test coverage are limited to same-version combinations, including remote gateways. Cross-version combinations may work but have no compatibility guarantee, even when protocol checks pass; align versions first when troubleshooting. Do not reject connections solely because package versions differ, or add compatibility fallbacks or negotiation solely to support older gateways.
## Task-specific guidance ## Task-specific guidance
| When working on | Read | | When working on | Read |
+1 -1
View File
@@ -44,7 +44,7 @@ Collaborators can open PRs for:
For riskier or larger changes, collaborators are encouraged to open a draft PR early after discussing the scope and approach in an issue. For riskier or larger changes, collaborators are encouraged to open a draft PR early after discussing the scope and approach in an issue.
WebUI and remote-host interface changes must follow the [client/host compatibility review checklist](.agent/review-guide.md), including independent client/server upgrades, host isolation, and actionable update guidance. WebUI and remote-host interface changes must follow the [client/host compatibility review checklist](.agent/review-guide.md), including the same-version support policy, host isolation, and actionable update guidance.
### Starting Work ### Starting Work
+1 -1
View File
@@ -100,7 +100,7 @@ When upgrading from the earlier remote-page mode, the first reconnect reserves a
### Versions and updating the right machine ### Versions and updating the right machine
Open a server's **… → Version & compatibility** in **Manage connections…** to see the local and server versions and the compatibility result. Matching package versions are not required: both sides must support a common WebUI protocol. Compatible version differences do not show an update warning. Open a server's **… → Version & compatibility** in **Manage connections…** to see the local and server versions and the compatibility result. Support and test coverage are limited to same-version WebUI/gateway combinations. Different versions may work together, but cross-version functionality is not guaranteed even when protocol checks pass; align versions first when troubleshooting. The current compatibility check uses protocol metadata, not package-version equality, and does not block connections solely because versions differ.
- **Compatibility not confirmed:** the host has not advertised a supported WebUI contract. This is not evidence of a broken key, VPN issue, or simply an old version. Local-client mode cannot safely proceed until support is confirmed. For older installations, update nanobot on that server and reconnect. - **Compatibility not confirmed:** the host has not advertised a supported WebUI contract. This is not evidence of a broken key, VPN issue, or simply an old version. Local-client mode cannot safely proceed until support is confirmed. For older installations, update nanobot on that server and reconnect.
- **Update this server:** its advertised contract lacks the client's required core features. Update the server, not merely this computer. - **Update this server:** its advertised contract lacks the client's required core features. Update the server, not merely this computer.
+14 -2
View File
@@ -198,7 +198,7 @@ Reasoning frames only flow when the channel's `showReasoning` is `true` (default
The event contains no pairing codes or account data. Read the current state from `GET /api/settings/pairing`; notifications are not replayed, so read a fresh snapshot on initial connection and reconnect. Existing polling continues to discover changes made by another process and expired requests. Approval, denial and authentication checks are unchanged. The event contains no pairing codes or account data. Read the current state from `GET /api/settings/pairing`; notifications are not replayed, so read a fresh snapshot on initial connection and reconnect. Existing polling continues to discover changes made by another process and expired requests. Approval, denial and authentication checks are unchanged.
**`attached`** — confirmation for `new_chat` / `attach` inbound envelopes (see [Multi-chat multiplexing](#multi-chat-multiplexing)): **`attached`** — confirmation for `new_chat`, `new_temporary_chat`, `fork_chat`, or `attach` inbound envelopes (see [Multi-chat multiplexing](#multi-chat-multiplexing)):
```json ```json
{"event": "attached", "chat_id": "uuid-v4"} {"event": "attached", "chat_id": "uuid-v4"}
@@ -228,12 +228,24 @@ Recognized fields: `content`, `text`, `message` (checked in that order). Invalid
| `type` | Fields | Effect | | `type` | Fields | Effect |
|--------|--------|--------| |--------|--------|--------|
| `new_chat` | — | Server mints a new `chat_id`, subscribes this connection, replies with `attached`. | | `new_chat` | Optional `workspace_scope`, `request_id` | Server mints a new `chat_id`, subscribes this connection, replies with `attached`. |
| `new_temporary_chat` | Optional `request_id` | Authenticated WebUI only; creates a connection-owned temporary chat and replies with `attached` and `temporary: true`. |
| `fork_chat` | `source_chat_id`, `before_user_index`; optional `title`, `request_id` | Creates and attaches a non-destructive fork before the selected user message. |
| `attach` | `chat_id` | Subscribe to an existing `chat_id` (e.g. after a page reload). Replies with `attached`. | | `attach` | `chat_id` | Subscribe to an existing `chat_id` (e.g. after a page reload). Replies with `attached`. |
| `message` | `chat_id`, `content` | Send `content` on `chat_id`. First use auto-attaches; no explicit `attach` needed. | | `message` | `chat_id`, `content` | Send `content` on `chat_id`. First use auto-attaches; no explicit `attach` needed. |
See [Multi-chat multiplexing](#multi-chat-multiplexing) for the full flow. See [Multi-chat multiplexing](#multi-chat-multiplexing) for the full flow.
### Chat-request correlation
WebUI sends a `request_id` with every `new_chat`, `new_temporary_chat`, and `fork_chat`; the gateway echoes it on `attached` and expected `error` responses. IDs must match `[A-Za-z0-9._:-]{1,128}`; malformed IDs are rejected before creation. The shared WebSocket API also accepts requests without IDs for callers such as the TUI; those responses have no `request_id`.
Clients must correlate tagged responses by ID, not by arrival order or the temporary-chat flag. Ordinary `attach` replies cannot complete a creation request. IDs provide correlation, not deduplication: a sent request that times out has an unknown outcome and must not be automatically replayed. Expired unsent requests must be removed before reconnecting.
A timeout ends the client's pending request, allowing a new user-initiated request with a different ID. A late response cannot complete that newer request. Late temporary-chat creations are discarded rather than selected.
Support and testing cover same-version WebUI/gateway combinations. Cross-version combinations may work, but a passing protocol check does not guarantee all features work; align versions first when troubleshooting. See [Versions and updating the right machine](guides/remote-instances.md#versions-and-updating-the-right-machine).
### Binary attachments (WebUI and TUI) ### Binary attachments (WebUI and TUI)
The gateway advertises `webui.attachments.binary.v1`. WebUI protocol 1 and the terminal protocol are unchanged. Bundled clients and their gateway use HTTP on the same listener for attachment uploads. After an authorized handshake, `ready` includes an `upload` object with `path: "/api/attachments"` and an opaque `token`. This token is a short-lived capability tied to that live connection, not the one-time handshake token, API token, or client-selected `client_id`. The gateway advertises `webui.attachments.binary.v1`. WebUI protocol 1 and the terminal protocol are unchanged. Bundled clients and their gateway use HTTP on the same listener for attachment uploads. After an authorized handshake, `ready` includes an `upload` object with `path: "/api/attachments"` and an opaque `token`. This token is a short-lived capability tied to that live connection, not the one-time handshake token, API token, or client-selected `client_id`.
+2
View File
@@ -89,6 +89,8 @@ Open **Settings → About** to check for updates automatically. Startup, reconne
The sidebar is the topic switcher. Each topic keeps its own history, title, workspace selection, and linked automations. Use a new topic when you want a separate context; use fork when you want to continue from an existing point without changing the original thread. The sidebar is the topic switcher. Each topic keeps its own history, title, workspace selection, and linked automations. Use a new topic when you want a separate context; use fork when you want to continue from an existing point without changing the original thread.
If creating or forking a topic times out, it may already have succeeded; it is not automatically retried. Reconnecting ends temporary chats.
Drag topics within a sidebar group to reorder them. **Rename** edits a topic title in place; a failed save keeps the draft for retry. Drag topics within a sidebar group to reorder them. **Rename** edits a topic title in place; a failed save keeps the draft for retry.
Use **Select** in a topic's action menu to archive or delete several topics with one confirmation. Click outside the topic rows and toolbar, or press **Esc**, to leave selection mode. Cancelling a confirmation keeps your selection. Archiving removes pins and hides topics from the default list while keeping their conversations. Use **Show archived** to find them again; selecting only archived topics offers **Unarchive**. Use **Select** in a topic's action menu to archive or delete several topics with one confirmation. Click outside the topic rows and toolbar, or press **Esc**, to leave selection mode. Cancelling a confirmation keeps your selection. Archiving removes pins and hides topics from the default list while keeping their conversations. Use **Show archived** to find them again; selecting only archived topics offers **Unarchive**.
@@ -5632,6 +5632,89 @@ async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> N
await server_task 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 @pytest.mark.asyncio
async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None: async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None:
port = 0 port = 0
+12 -5
View File
@@ -24,6 +24,8 @@ class WebUIForkHost(Protocol):
self, self,
connection: ServerConnection, connection: ServerConnection,
detail: str, detail: str,
*,
request_id: str | None = None,
) -> None: ... ) -> None: ...
async def attach_webui_fork( async def attach_webui_fork(
@@ -32,6 +34,7 @@ class WebUIForkHost(Protocol):
*, *,
fork_id: str, fork_id: str,
fork_key: str, fork_key: str,
request_id: str | None = None,
) -> None: ... ) -> None: ...
@@ -59,6 +62,8 @@ async def handle_webui_fork_chat(
channel: WebUIForkHost, channel: WebUIForkHost,
connection: ServerConnection, connection: ServerConnection,
envelope: Mapping[str, Any], envelope: Mapping[str, Any],
*,
request_id: str | None = None,
) -> None: ) -> None:
"""Handle the WebUI ``fork_chat`` websocket command. """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, validate the request, clone session/transcript state, attach the new chat,
and hydrate the client. 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") source_chat_id = envelope.get("source_chat_id")
raw_index = envelope.get("before_user_index") raw_index = envelope.get("before_user_index")
if not is_valid_webui_chat_id(source_chat_id): 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 return
if isinstance(raw_index, bool) or not isinstance(raw_index, int) or raw_index < 0: 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 return
session_manager = channel.gateway.session_manager session_manager = channel.gateway.session_manager
if session_manager is None: 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 return
try: try:
@@ -88,16 +94,17 @@ async def handle_webui_fork_chat(
title=envelope.get("title") if isinstance(envelope.get("title"), str) else None, title=envelope.get("title") if isinstance(envelope.get("title"), str) else None,
) )
if forked is 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 return
fork_id, fork_key = forked fork_id, fork_key = forked
except Exception as exc: except Exception as exc:
logger.warning("fork_chat failed: {}", 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 return
await channel.attach_webui_fork( await channel.attach_webui_fork(
connection, connection,
fork_id=fork_id, fork_id=fork_id,
fork_key=fork_key, 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_TTL_S = 5 * 60.0
_WEBUI_REQUEST_CACHE_MAX = 256 _WEBUI_REQUEST_CACHE_MAX = 256
_WEBUI_REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -168,8 +169,13 @@ class WebUICommandRouter:
self, self,
connection: ServerConnection, connection: ServerConnection,
detail: str, detail: str,
*,
request_id: str | None = 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( async def attach_webui_fork(
self, self,
@@ -177,6 +183,7 @@ class WebUICommandRouter:
*, *,
fork_id: str, fork_id: str,
fork_key: str, fork_key: str,
request_id: str | None = None,
) -> None: ) -> None:
scope = await self._workspaces.async_scope_for_session_key(fork_key) scope = await self._workspaces.async_scope_for_session_key(fork_key)
self._transport.webui_attach(connection, fork_id) self._transport.webui_attach(connection, fork_id)
@@ -184,6 +191,7 @@ class WebUICommandRouter:
connection, connection,
"attached", "attached",
chat_id=fork_id, 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._session_projection.attach_fields(fork_key)),
) )
await self._transport.webui_send_event( await self._transport.webui_send_event(
@@ -271,6 +279,7 @@ class WebUICommandRouter:
*, *,
chat_id: str | None = None, chat_id: str | None = None,
turn_id: str | None = None, turn_id: str | None = None,
request_id: str | None = None,
) -> Any | None: ) -> Any | None:
try: try:
return await resolver() return await resolver()
@@ -280,6 +289,7 @@ class WebUICommandRouter:
"error", "error",
detail="workspace_scope_rejected", detail="workspace_scope_rejected",
reason=exc.message, reason=exc.message,
**({"request_id": request_id} if request_id is not None else {}),
**({"chat_id": chat_id} if chat_id else {}), **({"chat_id": chat_id} if chat_id else {}),
**({"turn_id": turn_id} if turn_id else {}), **({"turn_id": turn_id} if turn_id else {}),
) )
@@ -326,6 +336,14 @@ class WebUICommandRouter:
if command_type == "webui_request": if command_type == "webui_request":
await self.start_webui_request(connection, envelope) await self.start_webui_request(connection, envelope)
return 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": if command_type == "new_chat":
new_id = str(uuid.uuid4()) new_id = str(uuid.uuid4())
scope = await self.workspace_scope_or_error( scope = await self.workspace_scope_or_error(
@@ -334,6 +352,7 @@ class WebUICommandRouter:
envelope, envelope,
can_change_project=self.workspace_project_selection_available(connection), can_change_project=self.workspace_project_selection_available(connection),
), ),
request_id=request_id,
) )
if scope is None: if scope is None:
return return
@@ -343,6 +362,7 @@ class WebUICommandRouter:
connection, connection,
"attached", "attached",
chat_id=new_id, chat_id=new_id,
**request_fields,
**(await self._session_projection.attach_fields(webui_session_key(new_id))), **(await self._session_projection.attach_fields(webui_session_key(new_id))),
) )
await self._transport.webui_send_event( await self._transport.webui_send_event(
@@ -361,7 +381,9 @@ class WebUICommandRouter:
trusted_webui=connection in self._webui_connections, trusted_webui=connection in self._webui_connections,
) )
except TemporaryChatError as exc: 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 return
self._transport.webui_attach(connection, new_id) self._transport.webui_attach(connection, new_id)
await self._transport.webui_send_event( await self._transport.webui_send_event(
@@ -369,10 +391,11 @@ class WebUICommandRouter:
"attached", "attached",
chat_id=new_id, chat_id=new_id,
temporary=True, temporary=True,
**request_fields,
) )
return return
if command_type == "fork_chat": if command_type == "fork_chat":
await handle_webui_fork_chat(self, connection, envelope) await handle_webui_fork_chat(self, connection, envelope, **request_fields)
return return
if command_type == "discard_temporary_chat": if command_type == "discard_temporary_chat":
chat_id = envelope.get("chat_id") chat_id = envelope.get("chat_id")
@@ -888,10 +911,7 @@ class WebUICommandRouter:
envelope: dict[str, Any], envelope: dict[str, Any],
) -> None: ) -> None:
request_id = envelope.get("request_id") request_id = envelope.get("request_id")
if not isinstance(request_id, str) or re.fullmatch( if not isinstance(request_id, str) or _WEBUI_REQUEST_ID_RE.fullmatch(request_id) is None:
r"[A-Za-z0-9._:-]{1,128}",
request_id,
) is None:
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, connection,
"error", "error",
+12 -5
View File
@@ -27,9 +27,11 @@ async def test_fork_handler_rejects_invalid_protocol_input(
gateway=SimpleNamespace(session_manager=MagicMock()), gateway=SimpleNamespace(session_manager=MagicMock()),
) )
await forking.handle_webui_fork_chat(channel, connection, envelope) await forking.handle_webui_fork_chat(channel, connection, envelope, request_id="fork-request")
channel.send_webui_protocol_error.assert_awaited_once_with(connection, detail) channel.send_webui_protocol_error.assert_awaited_once_with(
connection, detail, request_id="fork-request",
)
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -44,11 +46,13 @@ async def test_fork_handler_reports_unavailable_session_manager() -> None:
channel, channel,
connection, connection,
{"source_chat_id": "source", "before_user_index": 0}, {"source_chat_id": "source", "before_user_index": 0},
request_id="fork-request",
) )
channel.send_webui_protocol_error.assert_awaited_once_with( channel.send_webui_protocol_error.assert_awaited_once_with(
connection, connection,
"session_manager_unavailable", "session_manager_unavailable",
request_id="fork-request",
) )
@@ -66,10 +70,11 @@ async def test_fork_handler_maps_invalid_source_and_internal_failure_to_stable_e
envelope = {"source_chat_id": "source", "before_user_index": 0} envelope = {"source_chat_id": "source", "before_user_index": 0}
monkeypatch.setattr(forking, "create_webui_chat_fork", AsyncMock(return_value=None)) monkeypatch.setattr(forking, "create_webui_chat_fork", AsyncMock(return_value=None))
await forking.handle_webui_fork_chat(channel, connection, envelope) await forking.handle_webui_fork_chat(channel, connection, envelope, request_id="fork-request")
channel.send_webui_protocol_error.assert_awaited_once_with( channel.send_webui_protocol_error.assert_awaited_once_with(
connection, connection,
"invalid fork source or index", "invalid fork source or index",
request_id="fork-request",
) )
channel.send_webui_protocol_error.reset_mock() channel.send_webui_protocol_error.reset_mock()
@@ -78,10 +83,12 @@ async def test_fork_handler_maps_invalid_source_and_internal_failure_to_stable_e
"create_webui_chat_fork", "create_webui_chat_fork",
AsyncMock(side_effect=RuntimeError("broken transcript")), AsyncMock(side_effect=RuntimeError("broken transcript")),
) )
await forking.handle_webui_fork_chat(channel, connection, envelope) await forking.handle_webui_fork_chat(channel, connection, envelope, request_id="fork-request")
warning.assert_called_once_with("fork_chat failed: {}", ANY) warning.assert_called_once_with("fork_chat failed: {}", ANY)
channel.send_webui_protocol_error.assert_awaited_once_with(connection, "fork_chat_failed") channel.send_webui_protocol_error.assert_awaited_once_with(
connection, "fork_chat_failed", request_id="fork-request",
)
@pytest.mark.parametrize("with_display", [False, True]) @pytest.mark.parametrize("with_display", [False, True])
+4 -3
View File
@@ -611,8 +611,9 @@ export default function App() {
const bootstrapSecretRef = useRef(""); const bootstrapSecretRef = useRef("");
const refreshReadyClient = useCallback( const refreshReadyClient = useCallback(
async (client: NanobotClient, fallbackSurface: RuntimeSurface) => { async (client: NanobotClient, fallbackSurface: RuntimeSurface, signal?: AbortSignal) => {
const boot = await fetchBootstrap("", bootstrapSecretRef.current); const boot = await fetchBootstrap("", bootstrapSecretRef.current);
signal?.throwIfAborted();
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url); const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface); const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface);
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities); const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
@@ -661,9 +662,9 @@ export default function App() {
url, url,
maxFrameBytes: boot.limits?.transport.max_frame_bytes, maxFrameBytes: boot.limits?.transport.max_frame_bytes,
socketFactory: runtimeHost.socketFactory, socketFactory: runtimeHost.socketFactory,
onReauth: async () => { onReauth: async (signal) => {
try { try {
const refreshed = await refreshReadyClient(client, runtimeSurface); const refreshed = await refreshReadyClient(client, runtimeSurface, signal);
return refreshed.url; return refreshed.url;
} catch { } catch {
return null; return null;
+105 -86
View File
@@ -143,8 +143,11 @@ class WebUIMutationError extends Error {
} }
} }
type ChatRequestFrame = Extract<Outbound, { type: "new_chat" | "new_temporary_chat" | "fork_chat" }>;
interface PendingChatRequest extends PendingRequest<string> { interface PendingChatRequest extends PendingRequest<string> {
temporary: boolean; frame: ChatRequestFrame & { request_id: string };
phase: "queued" | "sent";
} }
const SYSTEM_COMMAND_TURN_PREFIX = "webui-system:"; const SYSTEM_COMMAND_TURN_PREFIX = "webui-system:";
@@ -165,8 +168,8 @@ export interface NanobotClientOptions {
reconnect?: boolean; reconnect?: boolean;
/** Maximum UTF-8 bytes accepted for one websocket message. */ /** Maximum UTF-8 bytes accepted for one websocket message. */
maxFrameBytes?: number; maxFrameBytes?: number;
/** Called when a connection drops so the app can refresh its token. */ /** Refresh authentication; discard side effects when the connection's signal aborts. */
onReauth?: () => Promise<string | null>; onReauth?: (signal: AbortSignal) => Promise<string | null>;
socketFactory?: (url: string) => WebSocket; socketFactory?: (url: string) => WebSocket;
maxBackoffMs?: number; maxBackoffMs?: number;
} }
@@ -250,12 +253,13 @@ export class NanobotClient {
/** Last tracked application frame written, for conservative transport-error attribution. */ /** Last tracked application frame written, for conservative transport-error attribution. */
private lastSocketMessageSend: { chatId: string; turnId: string } | null = null; private lastSocketMessageSend: { chatId: string; turnId: string } | null = null;
private goalStateByChatId = new Map<string, GoalStateWsPayload>(); private goalStateByChatId = new Map<string, GoalStateWsPayload>();
private pendingNewChat: PendingChatRequest | null = null; private pendingChatRequest: PendingChatRequest | null = null;
private pendingTranscriptions = new Map<string, PendingRequest<string>>(); private pendingTranscriptions = new Map<string, PendingRequest<string>>();
private pendingSystemCommands = new Map<string, PendingRequest<void>>(); private pendingSystemCommands = new Map<string, PendingRequest<void>>();
private pendingWebUIRequests = new Map<string, PendingWebUIRequest>(); private pendingWebUIRequests = new Map<string, PendingWebUIRequest>();
private sendQueue: Outbound[] = []; private sendQueue: Outbound[] = [];
private reconnectAttempts = 0; private reconnectAttempts = 0;
private reconnectController: AbortController | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null; private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private readonly shouldReconnect: boolean; private readonly shouldReconnect: boolean;
private readonly maxBackoffMs: number; private readonly maxBackoffMs: number;
@@ -458,7 +462,7 @@ export class NanobotClient {
if ( if (
ev.detail === "workspace_scope_rejected" ev.detail === "workspace_scope_rejected"
&& ev.chat_id === undefined && ev.chat_id === undefined
&& this.pendingNewChat && this.pendingChatRequest
) return null; ) return null;
return this.runs.soleSentTurn(this.lastSocketMessageSend, ev.chat_id); return this.runs.soleSentTurn(this.lastSocketMessageSend, ev.chat_id);
} }
@@ -550,33 +554,27 @@ export class NanobotClient {
connect(): void { connect(): void {
if (this.socket && this.socket.readyState < WS_CLOSING) return; if (this.socket && this.socket.readyState < WS_CLOSING) return;
this.cancelReconnect();
this.intentionallyClosed = false; this.intentionallyClosed = false;
this.setStatus("connecting"); this.setStatus("connecting");
const sock = this.socketFactory(this.currentUrl); const sock = this.socketFactory(this.currentUrl);
this.socket = sock; this.socket = sock;
sock.onopen = () => this.handleOpen(); sock.onopen = () => { if (this.socket === sock) this.handleOpen(); };
sock.onmessage = (ev) => this.handleMessage(ev); sock.onmessage = (ev) => { if (this.socket === sock) this.handleMessage(ev); };
sock.onerror = () => this.setStatus("error"); sock.onerror = () => { if (this.socket === sock) this.setStatus("error"); };
sock.onclose = (ev) => this.handleClose(ev); sock.onclose = (ev) => { if (this.socket === sock) this.handleClose(ev); };
} }
close(): void { close(): void {
this.upload = null;
this.receipts.close();
this.intentionallyClosed = true; this.intentionallyClosed = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
const sock = this.socket; const sock = this.socket;
this.socket = null; // Settle connection-owned work now, not in a possibly delayed close callback.
this.handleClose();
try { try {
sock?.close(); sock?.close();
} catch { } catch {
// ignore // Local cleanup has already completed.
} }
this.clearTemporaryChats();
this.setStatus("closed");
} }
discardTemporaryChat(chatId: string): void { discardTemporaryChat(chatId: string): void {
@@ -589,37 +587,55 @@ export class NanobotClient {
/** Ask the server to provision a new chat_id; resolves with the assigned id. */ /** Ask the server to provision a new chat_id; resolves with the assigned id. */
newChat(timeoutMs: number = 5_000, workspaceScope?: WorkspaceScopePayload | null): Promise<string> { newChat(timeoutMs: number = 5_000, workspaceScope?: WorkspaceScopePayload | null): Promise<string> {
if (this.pendingNewChat) { return this.requestChat({
return Promise.reject(new Error("newChat already in flight")); type: "new_chat",
} ...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
return new Promise<string>((resolve, reject) => { }, timeoutMs, "newChat");
const timer = setTimeout(() => {
this.pendingNewChat = null;
reject(new Error("newChat timed out"));
}, timeoutMs);
this.pendingNewChat = { resolve, reject, timer, temporary: false };
this.queueSend({
type: "new_chat",
...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
});
});
} }
/** Ask the WebUI gateway to create a connection-owned non-persistent chat. */ /** Ask the WebUI gateway to create a connection-owned non-persistent chat. */
newTemporaryChat(timeoutMs: number = 5_000): Promise<string> { newTemporaryChat(timeoutMs: number = 5_000): Promise<string> {
if (this.pendingNewChat) { return this.requestChat({ type: "new_temporary_chat" }, timeoutMs, "newTemporaryChat");
return Promise.reject(new Error("newChat already in flight")); }
}
private requestChat(frame: ChatRequestFrame, timeoutMs: number, name: string): Promise<string> {
if (this.intentionallyClosed) return Promise.reject(new Error("socket closed"));
if (this.pendingChatRequest) return Promise.reject(new Error("newChat already in flight"));
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => { const pending: PendingChatRequest = {
this.pendingNewChat = null; frame: { ...frame, request_id: crypto.randomUUID() },
reject(new Error("newTemporaryChat timed out")); phase: "queued", resolve, reject,
}, timeoutMs); timer: setTimeout(() => {
this.pendingNewChat = { resolve, reject, timer, temporary: true }; const sent = pending.phase === "sent";
this.queueSend({ type: "new_temporary_chat" }); this.pendingChatRequest = null;
reject(new Error(`${name} timed out${sent ? "; creation outcome is unknown" : " before sending"}`));
}, timeoutMs),
};
this.pendingChatRequest = pending;
this.sendPendingChat();
}); });
} }
private sendPendingChat(): void {
const pending = this.pendingChatRequest;
if (!pending || pending.phase !== "queued" || this.socket?.readyState !== WS_OPEN) return;
try {
this.socket.send(JSON.stringify(pending.frame));
pending.phase = "sent";
this.lastSocketMessageSend = null;
} catch {
this.rejectPendingChat("Could not send chat request");
}
}
private rejectPendingChat(detail: string): void {
const pending = this.pendingChatRequest;
if (!pending) return;
this.pendingChatRequest = null;
clearTimeout(pending.timer);
pending.reject(new Error(detail));
}
transcribeAudio( transcribeAudio(
dataUrl: string, dataUrl: string,
options?: { durationMs?: number; timeoutMs?: number }, options?: { durationMs?: number; timeoutMs?: number },
@@ -710,22 +726,12 @@ export class NanobotClient {
title?: string, title?: string,
timeoutMs: number = 5_000, timeoutMs: number = 5_000,
): Promise<string> { ): Promise<string> {
if (this.pendingNewChat) { return this.requestChat({
return Promise.reject(new Error("newChat already in flight")); type: "fork_chat",
} source_chat_id: sourceChatId,
return new Promise<string>((resolve, reject) => { before_user_index: beforeUserIndex,
const timer = setTimeout(() => { ...(title?.trim() ? { title: title.trim() } : {}),
this.pendingNewChat = null; }, timeoutMs, "forkChat");
reject(new Error("forkChat timed out"));
}, timeoutMs);
this.pendingNewChat = { resolve, reject, timer, temporary: false };
this.queueSend({
type: "fork_chat",
source_chat_id: sourceChatId,
before_user_index: beforeUserIndex,
...(title?.trim() ? { title: title.trim() } : {}),
});
});
} }
attach(chatId: string): void { attach(chatId: string): void {
@@ -891,6 +897,7 @@ export class NanobotClient {
} }
const queued = this.sendQueue.splice(0); const queued = this.sendQueue.splice(0);
for (const frame of queued) this.rawSend(frame); for (const frame of queued) this.rawSend(frame);
this.sendPendingChat();
} }
private handleMessage(ev: MessageEvent): void { private handleMessage(ev: MessageEvent): void {
@@ -930,6 +937,17 @@ export class NanobotClient {
return; return;
} }
if (parsed.event === "error" && parsed.request_id !== undefined) {
const pending = this.pendingChatRequest;
if (pending && pending.phase !== "queued" && pending.frame.request_id === parsed.request_id) {
this.rejectPendingChat([parsed.detail, parsed.reason].filter(Boolean).join(":") || "server error");
if (parsed.detail === "workspace_scope_rejected") {
this.emitError({ kind: "workspace_scope_rejected", reason: parsed.reason });
}
}
return;
}
if (parsed.event === "error" && !parsed.turn_id) { if (parsed.event === "error" && !parsed.turn_id) {
const fallback = this.legacyRejectionTarget(parsed); const fallback = this.legacyRejectionTarget(parsed);
if (fallback) { if (fallback) {
@@ -1006,19 +1024,24 @@ export class NanobotClient {
} }
if (parsed.event === "attached") { if (parsed.event === "attached") {
const pending = this.pendingChatRequest;
const known = this.knownChats.has(parsed.chat_id) || this.temporaryChatIds.has(parsed.chat_id);
const matches = pending?.phase === "sent" && parsed.request_id === pending.frame.request_id;
if (matches) {
clearTimeout(pending.timer);
this.pendingChatRequest = null;
pending.resolve(parsed.chat_id);
}
if (!matches && parsed.request_id !== undefined && !known) {
// A late success is not a new user selection; temporary resources need disposal.
if (parsed.temporary) this.rawSend({ type: "discard_temporary_chat", chat_id: parsed.chat_id });
return;
}
if (parsed.temporary === true) { if (parsed.temporary === true) {
this.temporaryChatIds.add(parsed.chat_id); this.temporaryChatIds.add(parsed.chat_id);
} else { } else {
this.knownChats.add(parsed.chat_id); this.knownChats.add(parsed.chat_id);
} }
if (
this.pendingNewChat
&& this.pendingNewChat.temporary === (parsed.temporary === true)
) {
clearTimeout(this.pendingNewChat.timer);
this.pendingNewChat.resolve(parsed.chat_id);
this.pendingNewChat = null;
}
this.dispatch(parsed.chat_id, parsed); this.dispatch(parsed.chat_id, parsed);
return; return;
} }
@@ -1062,19 +1085,6 @@ export class NanobotClient {
chatId: parsed.chat_id, chatId: parsed.chat_id,
turnId: parsed.turn_id, turnId: parsed.turn_id,
}); });
if (this.pendingNewChat) {
clearTimeout(this.pendingNewChat.timer);
this.pendingNewChat.reject(new Error(`workspace_scope_rejected:${parsed.reason || ""}`));
this.pendingNewChat = null;
}
}
if (parsed.event === "error" && this.pendingNewChat) {
clearTimeout(this.pendingNewChat.timer);
const detail = typeof parsed.detail === "string" ? parsed.detail : "server error";
const reason = typeof parsed.reason === "string" && parsed.reason ? `:${parsed.reason}` : "";
this.pendingNewChat.reject(new Error(`${detail}${reason}`));
this.pendingNewChat = null;
} }
if (correlatedChatId) { if (correlatedChatId) {
@@ -1140,16 +1150,13 @@ export class NanobotClient {
} }
private handleClose(event?: { code?: number }): void { private handleClose(event?: { code?: number }): void {
this.cancelReconnect();
this.upload = null; this.upload = null;
this.receipts.close(); this.receipts.close();
this.socket = null; this.socket = null;
this.clearTemporaryChats(); this.clearTemporaryChats();
const willReconnect = !this.intentionallyClosed && this.shouldReconnect; const willReconnect = !this.intentionallyClosed && this.shouldReconnect;
if (this.pendingNewChat) { this.rejectPendingChat("socket closed");
clearTimeout(this.pendingNewChat.timer);
this.pendingNewChat.reject(new Error("socket closed"));
this.pendingNewChat = null;
}
this.rejectAllTranscriptions("socket closed"); this.rejectAllTranscriptions("socket closed");
if (!willReconnect) { if (!willReconnect) {
for (const pending of this.pendingWebUIRequests.values()) { for (const pending of this.pendingWebUIRequests.values()) {
@@ -1252,20 +1259,32 @@ export class NanobotClient {
pending.reject(new Error(detail)); pending.reject(new Error(detail));
} }
private cancelReconnect(): void {
this.reconnectController?.abort();
this.reconnectController = null;
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private scheduleReconnect(): void { private scheduleReconnect(): void {
const controller = new AbortController();
this.reconnectController = controller;
this.setStatus("reconnecting"); this.setStatus("reconnecting");
const attempt = this.reconnectAttempts++; const attempt = this.reconnectAttempts++;
const delay = Math.min(500 * 2 ** attempt, this.maxBackoffMs); const delay = Math.min(500 * 2 ** attempt, this.maxBackoffMs);
this.reconnectTimer = setTimeout(async () => { this.reconnectTimer = setTimeout(async () => {
this.reconnectTimer = null; this.reconnectTimer = null;
if (controller.signal.aborted) return;
let refreshed: string | null = null;
if (this.options.onReauth) { if (this.options.onReauth) {
try { try {
const refreshed = await this.options.onReauth(); refreshed = await this.options.onReauth(controller.signal);
if (refreshed) this.currentUrl = refreshed;
} catch { } catch {
// fall through to retry with current URL // fall through to retry with current URL
} }
} }
if (controller.signal.aborted) return;
if (refreshed) this.currentUrl = refreshed;
this.connect(); this.connect();
}, delay); }, delay);
} }
+5 -3
View File
@@ -1520,6 +1520,7 @@ export type InboundEvent =
| { | {
event: "attached"; event: "attached";
chat_id: string; chat_id: string;
request_id?: string;
temporary?: boolean; temporary?: boolean;
recovery_state?: RecoveryState; recovery_state?: RecoveryState;
usage?: TurnUsage; usage?: TurnUsage;
@@ -1704,6 +1705,7 @@ export type InboundEvent =
} }
| { | {
event: "error"; event: "error";
request_id?: string;
chat_id?: string; chat_id?: string;
detail?: string; detail?: string;
reason?: string; reason?: string;
@@ -1840,15 +1842,15 @@ export type FilePreviewPayload = FilePreviewMetadata & (
); );
export type Outbound = export type Outbound =
| { type: "new_chat"; workspace_scope?: WorkspaceScopePayload } | { type: "new_chat"; workspace_scope?: WorkspaceScopePayload; request_id?: string }
| { type: "new_temporary_chat" } | { type: "new_temporary_chat"; request_id?: string }
| { | {
type: "webui_request"; type: "webui_request";
request_id: string; request_id: string;
action: string; action: string;
payload: Record<string, unknown>; payload: Record<string, unknown>;
} }
| { type: "fork_chat"; source_chat_id: string; before_user_index: number; title?: string } | { type: "fork_chat"; source_chat_id: string; before_user_index: number; title?: string; request_id?: string }
| { type: "attach"; chat_id: string } | { type: "attach"; chat_id: string }
| { type: "set_sidebar_state"; state: SidebarStatePayload } | { type: "set_sidebar_state"; state: SidebarStatePayload }
| { type: "discard_temporary_chat"; chat_id: string } | { type: "discard_temporary_chat"; chat_id: string }
+26 -1
View File
@@ -6,7 +6,7 @@ import type { Window as HappyWindow } from "happy-dom";
import i18n from "@/i18n"; import i18n from "@/i18n";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings"; import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
import { useSessions } from "@/hooks/useSessions"; import { useSessions } from "@/hooks/useSessions";
import type { RunState } from "@/lib/nanobot-client"; import type { NanobotClientOptions, RunState } from "@/lib/nanobot-client";
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache"; import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import type { import type {
ChatSummary, ChatSummary,
@@ -19,6 +19,7 @@ import type {
(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true; (window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
const connectSpy = vi.fn(); const connectSpy = vi.fn();
let clientOptions: NanobotClientOptions | undefined;
const refreshSpy = vi.fn(); const refreshSpy = vi.fn();
const createChatSpy = vi.fn().mockResolvedValue("chat-1"); const createChatSpy = vi.fn().mockResolvedValue("chat-1");
const deleteChatSpy = vi.fn(); const deleteChatSpy = vi.fn();
@@ -254,6 +255,7 @@ vi.mock("@/lib/bootstrap", () => ({
vi.mock("@/lib/nanobot-client", async (importOriginal) => { vi.mock("@/lib/nanobot-client", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/nanobot-client")>(); const actual = await importOriginal<typeof import("@/lib/nanobot-client")>();
class MockClient { class MockClient {
constructor(options: NanobotClientOptions) { clientOptions = options; }
onTaskNotice = () => () => {}; onTaskNotice = () => () => {};
status = "idle" as const; status = "idle" as const;
defaultChatId = mockDefaultChatId; defaultChatId = mockDefaultChatId;
@@ -335,6 +337,7 @@ describe("App layout", () => {
vi.mocked(useSessions).mockImplementation(defaultUseSessions); vi.mocked(useSessions).mockImplementation(defaultUseSessions);
clearReloadCache(); clearReloadCache();
connectSpy.mockClear(); connectSpy.mockClear();
clientOptions = undefined;
updateUrlSpy.mockClear(); updateUrlSpy.mockClear();
refreshSpy.mockReset(); refreshSpy.mockReset();
createChatSpy.mockClear(); createChatSpy.mockClear();
@@ -4475,6 +4478,28 @@ describe("App layout", () => {
expect(within(sidebar).getByText("Existing chat")).toBeInTheDocument(); expect(within(sidebar).getByText("Existing chat")).toBeInTheDocument();
}); });
it("does not apply a bootstrap refresh after its reconnect is cancelled", async () => {
const { unmount } = render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
let complete!: (boot: Awaited<ReturnType<typeof fetchBootstrap>>) => void;
vi.mocked(fetchBootstrap).mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; }));
vi.mocked(deriveWsUrl).mockImplementation((_path, token) => `ws://test?token=${token}`);
const controller = new AbortController();
const refresh = clientOptions!.onReauth!(controller.signal);
controller.abort();
await act(async () => {
complete({ token: "stale", api_token: "stale-api", ws_path: "/" });
await expect(refresh).resolves.toBeNull();
});
expect(updateUrlSpy).not.toHaveBeenCalled();
vi.mocked(fetchBootstrap).mockResolvedValueOnce({ token: "fresh", api_token: "fresh-api", ws_path: "/" });
await act(async () => {
await expect(clientOptions!.onReauth!(new AbortController().signal)).resolves.toBe("ws://test?token=fresh");
});
expect(updateUrlSpy).toHaveBeenCalledWith("ws://test?token=fresh");
unmount();
});
it("refreshes the bootstrap token before REST settings auth expires", async () => { it("refreshes the bootstrap token before REST settings auth expires", async () => {
vi.useFakeTimers(); vi.useFakeTimers();
vi.mocked(fetchBootstrap) vi.mocked(fetchBootstrap)
+171 -11
View File
@@ -53,6 +53,12 @@ function lastSocket(): FakeSocket {
return s; return s;
} }
function lastRequestId(socket: FakeSocket = lastSocket()): string {
const frame = JSON.parse(socket.sent.at(-1) ?? "{}");
if (typeof frame.request_id !== "string") throw new Error("Expected a request ID on the last sent frame");
return frame.request_id;
}
beforeEach(() => { beforeEach(() => {
FakeSocket.instances = []; FakeSocket.instances = [];
vi.useFakeTimers(); vi.useFakeTimers();
@@ -64,6 +70,155 @@ afterEach(() => {
}); });
describe("NanobotClient", () => { describe("NanobotClient", () => {
const chatRequests = [
{ type: "new_chat", start: (client: NanobotClient, timeout: number) => client.newChat(timeout) },
{ type: "new_temporary_chat", start: (client: NanobotClient, timeout: number) => client.newTemporaryChat(timeout) },
{ type: "fork_chat", start: (client: NanobotClient, timeout: number) => client.forkChat("source", 1, undefined, timeout) },
];
it("does not send an expired queued creation after reconnect", async () => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
lastSocket().fakeOpen();
lastSocket().close();
const expired = expect(client.newChat(100)).rejects.toThrow("timed out");
await vi.advanceTimersByTimeAsync(100);
await expired;
await vi.advanceTimersByTimeAsync(400);
const socket = lastSocket();
socket.fakeOpen();
expect(socket.sent.map((frame) => JSON.parse(frame).type)).not.toContain("new_chat");
client.close();
});
it("does not confuse a reconnect attachment with fork creation", async () => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
lastSocket().fakeOpen();
client.attach("existing");
lastSocket().close();
const resolved = vi.fn();
const creation = client.forkChat("source", 1).then(resolved);
await vi.advanceTimersByTimeAsync(500);
const socket = lastSocket();
socket.fakeOpen();
socket.fakeMessage({ event: "attached", chat_id: "existing" });
await Promise.resolve();
expect(resolved).not.toHaveBeenCalled();
socket.fakeMessage({ event: "attached", chat_id: "fresh", request_id: lastRequestId(socket) });
await creation;
expect(resolved).toHaveBeenCalledWith("fresh");
client.close();
});
it.each(chatRequests)("matches $type replies by ID and ignores late successes and errors", async ({ type, start }) => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
const socket = lastSocket();
socket.fakeOpen();
socket.fakeMessage({ event: "ready", chat_id: "default", client_id: "webui" });
const expired = expect(start(client, 100)).rejects.toThrow("outcome is unknown");
const oldFrame = JSON.parse(socket.sent.at(-1)!);
await vi.advanceTimersByTimeAsync(100);
await expired;
const resolved = vi.fn();
const rejected = vi.fn();
const creation = start(client, 1_000).then(resolved, rejected);
const frame = JSON.parse(socket.sent.at(-1)!);
expect(frame.request_id).not.toBe(oldFrame.request_id);
const temporary = type === "new_temporary_chat";
socket.fakeMessage({ event: "attached", chat_id: "old", temporary, request_id: oldFrame.request_id });
socket.fakeMessage({ event: "error", detail: "workspace_scope_rejected", request_id: oldFrame.request_id });
// Ordinary attachment responses do not complete a creation request.
socket.fakeMessage({ event: "attached", chat_id: "unrelated", temporary });
socket.fakeMessage({ event: "error", detail: "fork_chat_failed" });
socket.fakeMessage({ event: "error", detail: "workspace_scope_rejected", chat_id: "another", turn_id: "turn" });
socket.fakeMessage({ event: "error", detail: "invalid_sidebar_state" });
await Promise.resolve();
expect(resolved).not.toHaveBeenCalled();
expect(rejected).not.toHaveBeenCalled();
if (temporary) {
expect(socket.sent.map((value) => JSON.parse(value))).toContainEqual({ type: "discard_temporary_chat", chat_id: "old" });
}
socket.fakeMessage({ event: "attached", chat_id: "fresh", temporary, request_id: frame.request_id });
await creation;
expect(resolved).toHaveBeenCalledWith("fresh");
client.close();
});
it("does not replay a sent chat request after reconnect and correlates the next request", async () => {
const client = new NanobotClient({ url: "ws://test", onReauth: async () => "ws://refreshed",
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
lastSocket().fakeOpen();
lastSocket().fakeMessage({ event: "ready", chat_id: "default", client_id: "webui" });
const interrupted = expect(client.newChat()).rejects.toThrow("socket closed");
const interruptedRequestId = lastRequestId();
lastSocket().close();
await interrupted;
await vi.advanceTimersByTimeAsync(500);
const socket = lastSocket();
expect(socket.url).toBe("ws://refreshed");
socket.fakeOpen();
socket.fakeMessage({ event: "ready", chat_id: "default", client_id: "webui" });
expect(socket.sent.filter((value) => JSON.parse(value).type === "new_chat")).toHaveLength(0);
const creation = client.newChat();
expect(lastRequestId(socket)).not.toBe(interruptedRequestId);
socket.fakeMessage({ event: "attached", chat_id: "fresh", request_id: lastRequestId(socket) });
await expect(creation).resolves.toBe("fresh");
expect(socket.sent.filter((value) => JSON.parse(value).type === "new_chat")).toHaveLength(1);
client.close();
});
it("does not reconnect when closed while reauthentication is pending", async () => {
let finishAuth!: (url: string) => void;
const onReauth = vi.fn(() => new Promise<string>((resolve) => { finishAuth = resolve; }));
const client = new NanobotClient({ url: "ws://test", onReauth,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
lastSocket().fakeOpen();
lastSocket().close();
await vi.advanceTimersByTimeAsync(500);
expect(onReauth).toHaveBeenCalledOnce();
client.close();
client.updateUrl("ws://replacement");
finishAuth("ws://stale-auth");
await Promise.resolve();
expect(client.status).toBe("closed");
expect(FakeSocket.instances).toHaveLength(1);
client.connect();
expect(lastSocket().url).toBe("ws://replacement");
client.close();
});
it("settles queued creation on close and ignores callbacks from the replaced socket", async () => {
const client = new NanobotClient({ url: "ws://test", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
client.connect();
const previous = lastSocket();
// Browser close() returns before its queued close event is delivered.
previous.close = () => { previous.readyState = FakeSocket.CLOSING; };
const closed = expect(client.newChat()).rejects.toThrow("socket closed");
client.close();
await closed;
client.connect();
const current = lastSocket();
current.fakeOpen();
expect(current.sent.map((value) => JSON.parse(value).type)).not.toContain("new_chat");
const resolved = vi.fn();
const creation = client.newChat().then(resolved);
previous.fakeOpen();
previous.fakeMessage({ event: "attached", chat_id: "stale" });
previous.onerror?.();
previous.onclose?.();
await Promise.resolve();
expect(client.status).toBe("open");
expect(resolved).not.toHaveBeenCalled();
current.fakeMessage({ event: "attached", chat_id: "fresh", request_id: lastRequestId(current) });
await creation;
expect(resolved).toHaveBeenCalledWith("fresh");
client.close();
});
it("notifies ready consumers after server ready frames, including reconnects", async () => { it("notifies ready consumers after server ready frames, including reconnects", async () => {
const client = new NanobotClient({ url: "ws://test?token=fixture-token", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); const client = new NanobotClient({ url: "ws://test?token=fixture-token", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
const ready = vi.fn(); const ready = vi.fn();
@@ -128,7 +283,7 @@ describe("NanobotClient", () => {
const socket = lastSocket(); const socket = lastSocket();
socket.fakeOpen(); socket.fakeOpen();
const created = client.newTemporaryChat(); const created = client.newTemporaryChat();
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true }); socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true, request_id: lastRequestId(socket) });
await created; await created;
const notice = vi.fn(); const notice = vi.fn();
client.onTaskNotice(notice); client.onTaskNotice(notice);
@@ -151,7 +306,7 @@ describe("NanobotClient", () => {
const socket = lastSocket(); const socket = lastSocket();
socket.fakeOpen(); socket.fakeOpen();
const created = client.newTemporaryChat(); const created = client.newTemporaryChat();
socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true }); socket.fakeMessage({ event: "attached", chat_id: "temporary", temporary: true, request_id: lastRequestId(socket) });
await created; await created;
for (let index = 0; index < 2_010; index++) { for (let index = 0; index < 2_010; index++) {
for (const chatId of ["regular", "temporary"]) { for (const chatId of ["regular", "temporary"]) {
@@ -465,9 +620,9 @@ describe("NanobotClient", () => {
lastSocket().fakeOpen(); lastSocket().fakeOpen();
const creation = client.newTemporaryChat(); const creation = client.newTemporaryChat();
expect(JSON.parse(lastSocket().sent.at(-1) as string)).toEqual({ expect(JSON.parse(lastSocket().sent.at(-1) as string)).toEqual({
type: "new_temporary_chat", type: "new_temporary_chat", request_id: expect.any(String),
}); });
lastSocket().fakeMessage({ event: "attached", chat_id: chatId, temporary: true }); lastSocket().fakeMessage({ event: "attached", chat_id: chatId, temporary: true, request_id: lastRequestId() });
await expect(creation).resolves.toBe(chatId); await expect(creation).resolves.toBe(chatId);
lastSocket().sent = []; lastSocket().sent = [];
client.onChat(chatId, vi.fn()); client.onChat(chatId, vi.fn());
@@ -510,6 +665,7 @@ describe("NanobotClient", () => {
lastSocket().fakeMessage({ lastSocket().fakeMessage({
event: "attached", event: "attached",
chat_id: "server-temporary-chat", chat_id: "server-temporary-chat",
request_id: lastRequestId(),
temporary: true, temporary: true,
}); });
await expect(creation).resolves.toBe("server-temporary-chat"); await expect(creation).resolves.toBe("server-temporary-chat");
@@ -530,6 +686,7 @@ describe("NanobotClient", () => {
lastSocket().fakeMessage({ lastSocket().fakeMessage({
event: "attached", event: "attached",
chat_id: "temp-drop-a", chat_id: "temp-drop-a",
request_id: lastRequestId(),
temporary: true, temporary: true,
}); });
await firstCreation; await firstCreation;
@@ -537,6 +694,7 @@ describe("NanobotClient", () => {
lastSocket().fakeMessage({ lastSocket().fakeMessage({
event: "attached", event: "attached",
chat_id: "temp-drop-b", chat_id: "temp-drop-b",
request_id: lastRequestId(),
temporary: true, temporary: true,
}); });
await secondCreation; await secondCreation;
@@ -1688,6 +1846,7 @@ describe("NanobotClient", () => {
event: "error", event: "error",
detail: "workspace_scope_rejected", detail: "workspace_scope_rejected",
reason: "project_path must be an existing directory", reason: "project_path must be an existing directory",
request_id: lastRequestId(),
}); });
await expect(pendingChat).rejects.toThrow("workspace_scope_rejected"); await expect(pendingChat).rejects.toThrow("workspace_scope_rejected");
@@ -2184,8 +2343,8 @@ describe("NanobotClient", () => {
client.connect(); client.connect();
lastSocket().fakeOpen(); lastSocket().fakeOpen();
const promise = client.newChat(1_000); const promise = client.newChat(1_000);
expect(lastSocket().sent).toContain(JSON.stringify({ type: "new_chat" })); expect(lastSocket().sent.map((value) => JSON.parse(value))).toContainEqual({ type: "new_chat", request_id: expect.any(String) });
lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id" }); lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id", request_id: lastRequestId() });
await expect(promise).resolves.toBe("fresh-id"); await expect(promise).resolves.toBe("fresh-id");
}); });
@@ -2205,10 +2364,10 @@ describe("NanobotClient", () => {
lastSocket().fakeOpen(); lastSocket().fakeOpen();
const promise = client.newChat(1_000, workspaceScope); const promise = client.newChat(1_000, workspaceScope);
expect(lastSocket().sent).toContain( expect(lastSocket().sent.map((value) => JSON.parse(value))).toContainEqual({
JSON.stringify({ type: "new_chat", workspace_scope: workspaceScope }), type: "new_chat", workspace_scope: workspaceScope, request_id: expect.any(String),
); });
lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id" }); lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id", request_id: lastRequestId() });
await expect(promise).resolves.toBe("fresh-id"); await expect(promise).resolves.toBe("fresh-id");
client.sendMessage("fresh-id", "hello", undefined, { workspaceScope }); client.sendMessage("fresh-id", "hello", undefined, { workspaceScope });
@@ -2675,8 +2834,9 @@ describe("NanobotClient", () => {
event: "error", event: "error",
detail: "workspace_scope_rejected", detail: "workspace_scope_rejected",
reason: "project_path must be an existing directory", reason: "project_path must be an existing directory",
request_id: lastRequestId(),
}); });
await expect(pending).rejects.toThrow("workspace_scope_rejected"); await expect(pending).rejects.toThrow("workspace_scope_rejected:project_path must be an existing directory");
}); });
it("isolates throwing error handlers so reconnect bookkeeping still runs", async () => { it("isolates throwing error handlers so reconnect bookkeeping still runs", async () => {
@@ -53,7 +53,7 @@ class TestSocket {
this.sent.push(frame); this.sent.push(frame);
if (frame.type === "new_temporary_chat") { if (frame.type === "new_temporary_chat") {
const chatId = `00000000-0000-4000-8000-${String(++this.nextChat).padStart(12, "0")}`; const chatId = `00000000-0000-4000-8000-${String(++this.nextChat).padStart(12, "0")}`;
queueMicrotask(() => this.receive({ event: "attached", chat_id: chatId, temporary: true })); queueMicrotask(() => this.receive({ event: "attached", chat_id: chatId, temporary: true, request_id: frame.request_id }));
} else if (frame.type === "set_sidebar_state") { } else if (frame.type === "set_sidebar_state") {
queueMicrotask(() => this.receive({ event: "sidebar_state_updated", state: frame.state })); queueMicrotask(() => this.receive({ event: "sidebar_state_updated", state: frame.state }));
} else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") { } else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") {