diff --git a/.agent/review-guide.md b/.agent/review-guide.md index 8112ffc1c..73922122f 100644 --- a/.agent/review-guide.md +++ b/.agent/review-guide.md @@ -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. -## 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. -- Negotiate 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. -- 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.” Do not infer support from matching package versions. An unconfirmed core contract cannot authorize mutations. +- Declare the WebUI protocol in `webui/client_contract.py`. The pre-existing terminal `protocolVersion` is a separate contract; do not overload it. +- 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. +- 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. - 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 -- 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. -- Unknown, missing, malformed and future metadata; overlapping and disjoint protocol ranges; unknown optional capabilities; 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. +- Verify the current client with a same-version host. Cross-version compatibility fixtures or fallback behavior are not required. +- 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. - 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. - 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 -- 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. -- Keep compatible version differences quiet. Show missing optional capabilities at the affected control. Block only unsupported core sessions or operations. +- 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. +- 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. - 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. @@ -32,4 +32,4 @@ Apply this checklist to changes to WebUI HTTP, WebSocket events/mutations, boots ## 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. diff --git a/AGENTS.md b/AGENTS.md index 9f2cdae9c..3d5cf5a6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. +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 | When working on | Read | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2153d99a2..8fde97c8e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. -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 diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md index 33c64a2a2..8606c1801 100644 --- a/docs/guides/remote-instances.md +++ b/docs/guides/remote-instances.md @@ -100,7 +100,7 @@ When upgrading from the earlier remote-page mode, the first reconnect reserves a ### 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. - **Update this server:** its advertised contract lacks the client's required core features. Update the server, not merely this computer. diff --git a/docs/websocket.md b/docs/websocket.md index 7efd00ea2..8e726db34 100644 --- a/docs/websocket.md +++ b/docs/websocket.md @@ -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. -**`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 {"event": "attached", "chat_id": "uuid-v4"} @@ -228,12 +228,24 @@ Recognized fields: `content`, `text`, `message` (checked in that order). Invalid | `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`. | | `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. +### 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) 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`. diff --git a/docs/webui.md b/docs/webui.md index d4c3c6f7b..ebd8601cf 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -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. +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. 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**. diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index e4b075e9e..2e2401272 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -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 diff --git a/nanobot/webui/forking.py b/nanobot/webui/forking.py index c1a1a1d48..541e8a11c 100644 --- a/nanobot/webui/forking.py +++ b/nanobot/webui/forking.py @@ -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, ) diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index 12dc1948e..6329968d3 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -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", diff --git a/tests/webui/test_forking.py b/tests/webui/test_forking.py index 5c14f43fd..b93d434c5 100644 --- a/tests/webui/test_forking.py +++ b/tests/webui/test_forking.py @@ -27,9 +27,11 @@ async def test_fork_handler_rejects_invalid_protocol_input( 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 @@ -44,11 +46,13 @@ async def test_fork_handler_reports_unavailable_session_manager() -> None: channel, connection, {"source_chat_id": "source", "before_user_index": 0}, + request_id="fork-request", ) channel.send_webui_protocol_error.assert_awaited_once_with( connection, "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} 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( connection, "invalid fork source or index", + request_id="fork-request", ) 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", 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) - 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]) diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 66d9f0a79..1d8617084 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -611,8 +611,9 @@ export default function App() { const bootstrapSecretRef = useRef(""); const refreshReadyClient = useCallback( - async (client: NanobotClient, fallbackSurface: RuntimeSurface) => { + async (client: NanobotClient, fallbackSurface: RuntimeSurface, signal?: AbortSignal) => { const boot = await fetchBootstrap("", bootstrapSecretRef.current); + signal?.throwIfAborted(); const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url); const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface); const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities); @@ -661,9 +662,9 @@ export default function App() { url, maxFrameBytes: boot.limits?.transport.max_frame_bytes, socketFactory: runtimeHost.socketFactory, - onReauth: async () => { + onReauth: async (signal) => { try { - const refreshed = await refreshReadyClient(client, runtimeSurface); + const refreshed = await refreshReadyClient(client, runtimeSurface, signal); return refreshed.url; } catch { return null; diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index bb93b8d9a..1d9b6b6c8 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -143,8 +143,11 @@ class WebUIMutationError extends Error { } } +type ChatRequestFrame = Extract; + interface PendingChatRequest extends PendingRequest { - temporary: boolean; + frame: ChatRequestFrame & { request_id: string }; + phase: "queued" | "sent"; } const SYSTEM_COMMAND_TURN_PREFIX = "webui-system:"; @@ -165,8 +168,8 @@ export interface NanobotClientOptions { reconnect?: boolean; /** Maximum UTF-8 bytes accepted for one websocket message. */ maxFrameBytes?: number; - /** Called when a connection drops so the app can refresh its token. */ - onReauth?: () => Promise; + /** Refresh authentication; discard side effects when the connection's signal aborts. */ + onReauth?: (signal: AbortSignal) => Promise; socketFactory?: (url: string) => WebSocket; maxBackoffMs?: number; } @@ -250,12 +253,13 @@ export class NanobotClient { /** Last tracked application frame written, for conservative transport-error attribution. */ private lastSocketMessageSend: { chatId: string; turnId: string } | null = null; private goalStateByChatId = new Map(); - private pendingNewChat: PendingChatRequest | null = null; + private pendingChatRequest: PendingChatRequest | null = null; private pendingTranscriptions = new Map>(); private pendingSystemCommands = new Map>(); private pendingWebUIRequests = new Map(); private sendQueue: Outbound[] = []; private reconnectAttempts = 0; + private reconnectController: AbortController | null = null; private reconnectTimer: ReturnType | null = null; private readonly shouldReconnect: boolean; private readonly maxBackoffMs: number; @@ -458,7 +462,7 @@ export class NanobotClient { if ( ev.detail === "workspace_scope_rejected" && ev.chat_id === undefined - && this.pendingNewChat + && this.pendingChatRequest ) return null; return this.runs.soleSentTurn(this.lastSocketMessageSend, ev.chat_id); } @@ -550,33 +554,27 @@ export class NanobotClient { connect(): void { if (this.socket && this.socket.readyState < WS_CLOSING) return; + this.cancelReconnect(); this.intentionallyClosed = false; this.setStatus("connecting"); const sock = this.socketFactory(this.currentUrl); this.socket = sock; - sock.onopen = () => this.handleOpen(); - sock.onmessage = (ev) => this.handleMessage(ev); - sock.onerror = () => this.setStatus("error"); - sock.onclose = (ev) => this.handleClose(ev); + sock.onopen = () => { if (this.socket === sock) this.handleOpen(); }; + sock.onmessage = (ev) => { if (this.socket === sock) this.handleMessage(ev); }; + sock.onerror = () => { if (this.socket === sock) this.setStatus("error"); }; + sock.onclose = (ev) => { if (this.socket === sock) this.handleClose(ev); }; } close(): void { - this.upload = null; - this.receipts.close(); this.intentionallyClosed = true; - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } const sock = this.socket; - this.socket = null; + // Settle connection-owned work now, not in a possibly delayed close callback. + this.handleClose(); try { sock?.close(); } catch { - // ignore + // Local cleanup has already completed. } - this.clearTemporaryChats(); - this.setStatus("closed"); } 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. */ newChat(timeoutMs: number = 5_000, workspaceScope?: WorkspaceScopePayload | null): Promise { - if (this.pendingNewChat) { - return Promise.reject(new Error("newChat already in flight")); - } - return new Promise((resolve, reject) => { - 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 } : {}), - }); - }); + return this.requestChat({ + type: "new_chat", + ...(workspaceScope ? { workspace_scope: workspaceScope } : {}), + }, timeoutMs, "newChat"); } /** Ask the WebUI gateway to create a connection-owned non-persistent chat. */ newTemporaryChat(timeoutMs: number = 5_000): Promise { - if (this.pendingNewChat) { - return Promise.reject(new Error("newChat already in flight")); - } + return this.requestChat({ type: "new_temporary_chat" }, timeoutMs, "newTemporaryChat"); + } + + private requestChat(frame: ChatRequestFrame, timeoutMs: number, name: string): Promise { + 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((resolve, reject) => { - const timer = setTimeout(() => { - this.pendingNewChat = null; - reject(new Error("newTemporaryChat timed out")); - }, timeoutMs); - this.pendingNewChat = { resolve, reject, timer, temporary: true }; - this.queueSend({ type: "new_temporary_chat" }); + const pending: PendingChatRequest = { + frame: { ...frame, request_id: crypto.randomUUID() }, + phase: "queued", resolve, reject, + timer: setTimeout(() => { + const sent = pending.phase === "sent"; + 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( dataUrl: string, options?: { durationMs?: number; timeoutMs?: number }, @@ -710,22 +726,12 @@ export class NanobotClient { title?: string, timeoutMs: number = 5_000, ): Promise { - if (this.pendingNewChat) { - return Promise.reject(new Error("newChat already in flight")); - } - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.pendingNewChat = null; - 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() } : {}), - }); - }); + return this.requestChat({ + type: "fork_chat", + source_chat_id: sourceChatId, + before_user_index: beforeUserIndex, + ...(title?.trim() ? { title: title.trim() } : {}), + }, timeoutMs, "forkChat"); } attach(chatId: string): void { @@ -891,6 +897,7 @@ export class NanobotClient { } const queued = this.sendQueue.splice(0); for (const frame of queued) this.rawSend(frame); + this.sendPendingChat(); } private handleMessage(ev: MessageEvent): void { @@ -930,6 +937,17 @@ export class NanobotClient { 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) { const fallback = this.legacyRejectionTarget(parsed); if (fallback) { @@ -1006,19 +1024,24 @@ export class NanobotClient { } 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) { this.temporaryChatIds.add(parsed.chat_id); } else { 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); return; } @@ -1062,19 +1085,6 @@ export class NanobotClient { chatId: parsed.chat_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) { @@ -1140,16 +1150,13 @@ export class NanobotClient { } private handleClose(event?: { code?: number }): void { + this.cancelReconnect(); this.upload = null; this.receipts.close(); this.socket = null; this.clearTemporaryChats(); const willReconnect = !this.intentionallyClosed && this.shouldReconnect; - if (this.pendingNewChat) { - clearTimeout(this.pendingNewChat.timer); - this.pendingNewChat.reject(new Error("socket closed")); - this.pendingNewChat = null; - } + this.rejectPendingChat("socket closed"); this.rejectAllTranscriptions("socket closed"); if (!willReconnect) { for (const pending of this.pendingWebUIRequests.values()) { @@ -1252,20 +1259,32 @@ export class NanobotClient { 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 { + const controller = new AbortController(); + this.reconnectController = controller; this.setStatus("reconnecting"); const attempt = this.reconnectAttempts++; const delay = Math.min(500 * 2 ** attempt, this.maxBackoffMs); this.reconnectTimer = setTimeout(async () => { this.reconnectTimer = null; + if (controller.signal.aborted) return; + let refreshed: string | null = null; if (this.options.onReauth) { try { - const refreshed = await this.options.onReauth(); - if (refreshed) this.currentUrl = refreshed; + refreshed = await this.options.onReauth(controller.signal); } catch { // fall through to retry with current URL } } + if (controller.signal.aborted) return; + if (refreshed) this.currentUrl = refreshed; this.connect(); }, delay); } diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 0361b586b..3160690bd 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1520,6 +1520,7 @@ export type InboundEvent = | { event: "attached"; chat_id: string; + request_id?: string; temporary?: boolean; recovery_state?: RecoveryState; usage?: TurnUsage; @@ -1704,6 +1705,7 @@ export type InboundEvent = } | { event: "error"; + request_id?: string; chat_id?: string; detail?: string; reason?: string; @@ -1840,15 +1842,15 @@ export type FilePreviewPayload = FilePreviewMetadata & ( ); export type Outbound = - | { type: "new_chat"; workspace_scope?: WorkspaceScopePayload } - | { type: "new_temporary_chat" } + | { type: "new_chat"; workspace_scope?: WorkspaceScopePayload; request_id?: string } + | { type: "new_temporary_chat"; request_id?: string } | { type: "webui_request"; request_id: string; action: string; payload: Record; } - | { 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: "set_sidebar_state"; state: SidebarStatePayload } | { type: "discard_temporary_chat"; chat_id: string } diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 8519acdce..c1e4cfed4 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -6,7 +6,7 @@ import type { Window as HappyWindow } from "happy-dom"; import i18n from "@/i18n"; import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings"; 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 type { ChatSummary, @@ -19,6 +19,7 @@ import type { (window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true; const connectSpy = vi.fn(); +let clientOptions: NanobotClientOptions | undefined; const refreshSpy = vi.fn(); const createChatSpy = vi.fn().mockResolvedValue("chat-1"); const deleteChatSpy = vi.fn(); @@ -254,6 +255,7 @@ vi.mock("@/lib/bootstrap", () => ({ vi.mock("@/lib/nanobot-client", async (importOriginal) => { const actual = await importOriginal(); class MockClient { + constructor(options: NanobotClientOptions) { clientOptions = options; } onTaskNotice = () => () => {}; status = "idle" as const; defaultChatId = mockDefaultChatId; @@ -335,6 +337,7 @@ describe("App layout", () => { vi.mocked(useSessions).mockImplementation(defaultUseSessions); clearReloadCache(); connectSpy.mockClear(); + clientOptions = undefined; updateUrlSpy.mockClear(); refreshSpy.mockReset(); createChatSpy.mockClear(); @@ -4475,6 +4478,28 @@ describe("App layout", () => { expect(within(sidebar).getByText("Existing chat")).toBeInTheDocument(); }); + it("does not apply a bootstrap refresh after its reconnect is cancelled", async () => { + const { unmount } = render(); + await waitFor(() => expect(connectSpy).toHaveBeenCalled()); + let complete!: (boot: Awaited>) => 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 () => { vi.useFakeTimers(); vi.mocked(fetchBootstrap) diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index 92710b766..25b62f1cb 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -53,6 +53,12 @@ function lastSocket(): FakeSocket { 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(() => { FakeSocket.instances = []; vi.useFakeTimers(); @@ -64,6 +70,155 @@ afterEach(() => { }); 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((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 () => { const client = new NanobotClient({ url: "ws://test?token=fixture-token", socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); const ready = vi.fn(); @@ -128,7 +283,7 @@ describe("NanobotClient", () => { const socket = lastSocket(); socket.fakeOpen(); 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; const notice = vi.fn(); client.onTaskNotice(notice); @@ -151,7 +306,7 @@ describe("NanobotClient", () => { const socket = lastSocket(); socket.fakeOpen(); 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; for (let index = 0; index < 2_010; index++) { for (const chatId of ["regular", "temporary"]) { @@ -465,9 +620,9 @@ describe("NanobotClient", () => { lastSocket().fakeOpen(); const creation = client.newTemporaryChat(); 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); lastSocket().sent = []; client.onChat(chatId, vi.fn()); @@ -510,6 +665,7 @@ describe("NanobotClient", () => { lastSocket().fakeMessage({ event: "attached", chat_id: "server-temporary-chat", + request_id: lastRequestId(), temporary: true, }); await expect(creation).resolves.toBe("server-temporary-chat"); @@ -530,6 +686,7 @@ describe("NanobotClient", () => { lastSocket().fakeMessage({ event: "attached", chat_id: "temp-drop-a", + request_id: lastRequestId(), temporary: true, }); await firstCreation; @@ -537,6 +694,7 @@ describe("NanobotClient", () => { lastSocket().fakeMessage({ event: "attached", chat_id: "temp-drop-b", + request_id: lastRequestId(), temporary: true, }); await secondCreation; @@ -1688,6 +1846,7 @@ describe("NanobotClient", () => { event: "error", detail: "workspace_scope_rejected", reason: "project_path must be an existing directory", + request_id: lastRequestId(), }); await expect(pendingChat).rejects.toThrow("workspace_scope_rejected"); @@ -2184,8 +2343,8 @@ describe("NanobotClient", () => { client.connect(); lastSocket().fakeOpen(); const promise = client.newChat(1_000); - expect(lastSocket().sent).toContain(JSON.stringify({ type: "new_chat" })); - lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id" }); + 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", request_id: lastRequestId() }); await expect(promise).resolves.toBe("fresh-id"); }); @@ -2205,10 +2364,10 @@ describe("NanobotClient", () => { lastSocket().fakeOpen(); const promise = client.newChat(1_000, workspaceScope); - expect(lastSocket().sent).toContain( - JSON.stringify({ type: "new_chat", workspace_scope: workspaceScope }), - ); - lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id" }); + expect(lastSocket().sent.map((value) => JSON.parse(value))).toContainEqual({ + type: "new_chat", workspace_scope: workspaceScope, request_id: expect.any(String), + }); + lastSocket().fakeMessage({ event: "attached", chat_id: "fresh-id", request_id: lastRequestId() }); await expect(promise).resolves.toBe("fresh-id"); client.sendMessage("fresh-id", "hello", undefined, { workspaceScope }); @@ -2675,8 +2834,9 @@ describe("NanobotClient", () => { event: "error", detail: "workspace_scope_rejected", 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 () => { diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsx index cd0b1bba0..cb9dcf1d2 100644 --- a/webui/src/tests/temporary-chat-navigation.test.tsx +++ b/webui/src/tests/temporary-chat-navigation.test.tsx @@ -53,7 +53,7 @@ class TestSocket { this.sent.push(frame); if (frame.type === "new_temporary_chat") { 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") { queueMicrotask(() => this.receive({ event: "sidebar_state_updated", state: frame.state })); } else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") {