Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(show-runtime): invalidate stale WebSocket target (#1664)
Call White20dc008e69f3
diff --git a/core/show_runtime.py b/core/show_runtime.pyindex cc437030a..53e176816 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -170,6 +170,8 @@ class ShowRuntimeProtocolEnvelope:class ShowRuntimeWebSocketTarget:url: strheaders: dict[str, str]+ _base_url: str | None = None+ _process: subprocess.Popen[str] | None = None@dataclass(frozen=True)@@ -823,10 +825,7 @@ class ShowRuntimeManager:f"Show Runtime request exceeded {total_timeout_seconds:g} seconds") from excexcept (ShowRuntimeRequestTimeoutError, httpx.RequestError) as exc:- async with self._lock:- if self._base_url == base_url and self._process is process:- self._base_url = None- self._clear_capability_state()+ await self._invalidate_runtime_snapshot(base_url, process)if isinstance(exc, ShowRuntimeRequestTimeoutError):raiseevidence = ShowRuntimeFailureEvidence(@@ -919,9 +918,31 @@ class ShowRuntimeManager:ready = await self.ensure()if not ready.available or not ready.base_url:raise self._unavailable_error(ready)- await self._negotiate_context_key_capability(ready.base_url)- url = f"{ready.base_url.replace('http://', 'ws://', 1).replace('https://', 'wss://', 1)}{path}"- return ShowRuntimeWebSocketTarget(url=url, headers=envelope.headers())+ base_url = ready.base_url+ process = self._process+ await self._negotiate_context_key_capability(base_url)+ url = f"{base_url.replace('http://', 'ws://', 1).replace('https://', 'wss://', 1)}{path}"+ return ShowRuntimeWebSocketTarget(+ url=url,+ headers=envelope.headers(),+ _base_url=base_url,+ _process=process,+ )++ async def invalidate_websocket_target(self, target: ShowRuntimeWebSocketTarget) -> None:+ if target._base_url is None:+ return+ await self._invalidate_runtime_snapshot(target._base_url, target._process)++ async def _invalidate_runtime_snapshot(+ self,+ base_url: str,+ process: subprocess.Popen[str] | None,+ ) -> None:+ async with self._lock:+ if self._base_url == base_url and self._process is process:+ self._base_url = None+ self._clear_capability_state()def _unavailable_error(self, availability: ShowRuntimeAvailability) -> ShowRuntimeUnavailableError:reason = availability.reasondiff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 3c017f03e..4c208473f 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -29,6 +29,7 @@ import pytestimport core.dependency_network as dependency_networkimport core.show_runtime as show_runtimeimport core.show_runtime_failures as show_runtime_failures_module+from aiohttp import ClientConnectionError, WSServerHandshakeErrorfrom starlette.websockets import WebSocketDisconnectfrom config import paths@@ -7417,6 +7418,123 @@ def test_delayed_transport_failure_does_not_invalidate_replacement_process(monkeassert manager._base_url == base_url+class _FailingWebSocketHandshake:+ def __init__(self, error, *, before_failure=None):+ self.error = error+ self.before_failure = before_failure++ async def _fail(self):+ if self.before_failure is not None:+ self.before_failure()+ raise self.error++ def __await__(self):+ return self._fail().__await__()++ async def __aenter__(self):+ return await self++ async def __aexit__(self, _exc_type, _exc, _traceback):+ return False+++class _FailingWebSocketSession:+ def __init__(self, handshake):+ self.handshake = handshake++ async def __aenter__(self):+ return self++ async def __aexit__(self, _exc_type, _exc, _traceback):+ return False++ def ws_connect(self, *_args, **_kwargs):+ return self.handshake+++def test_websocket_transport_failure_invalidates_runtime_and_readmits(monkeypatch, tmp_path):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ set_show_runtime_manager_for_tests(manager)+ handshake = _FailingWebSocketHandshake(ClientConnectionError("runtime connection refused"))+ monkeypatch.setattr(ui_server, "ClientSession", lambda: _FailingWebSocketSession(handshake))+ websocket = SimpleNamespace(url=SimpleNamespace(query=""))++ with pytest.raises(ClientConnectionError):+ asyncio.run(ui_server._proxy_show_runtime_websocket(websocket, "ses123"))++ assert manager._base_url is None++ admissions = []+ replacement_process = SimpleNamespace(pid=654, poll=lambda: None)++ async def admit(*, automatic=True):+ admissions.append((automatic, manager._base_url))+ manager._process = replacement_process+ manager._base_url = "http://127.0.0.1:49322"+ return manager._publish_runtime_availability(+ ShowRuntimeServingState.SERVING,+ manager._base_url,+ )++ monkeypatch.setattr(manager, "ensure", admit)++ target = asyncio.run(+ manager.websocket_target(+ "/show/ses123/__vite_hmr",+ envelope=ShowRuntimeProtocolEnvelope(ShowRuntimeContext.PRIVATE),+ )+ )++ assert admissions == [(True, None)]+ assert target.url == "ws://127.0.0.1:49322/show/ses123/__vite_hmr"+++def test_delayed_websocket_failure_does_not_invalidate_replacement_process(monkeypatch, tmp_path):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ set_show_runtime_manager_for_tests(manager)+ base_url = manager._base_url+ replacement_process = SimpleNamespace(pid=654, poll=lambda: None)++ def replace_runtime():+ manager._process = replacement_process+ manager._base_url = base_url++ handshake = _FailingWebSocketHandshake(+ ClientConnectionError("old runtime failed late"),+ before_failure=replace_runtime,+ )+ monkeypatch.setattr(ui_server, "ClientSession", lambda: _FailingWebSocketSession(handshake))+ websocket = SimpleNamespace(url=SimpleNamespace(query=""))++ with pytest.raises(ClientConnectionError):+ asyncio.run(ui_server._proxy_show_runtime_websocket(websocket, "ses123"))++ assert manager._process is replacement_process+ assert manager._base_url == base_url+++def test_websocket_handshake_response_does_not_invalidate_runtime(monkeypatch, tmp_path):+ manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)+ set_show_runtime_manager_for_tests(manager)+ base_url = manager._base_url+ handshake = _FailingWebSocketHandshake(+ WSServerHandshakeError(+ request_info=None,+ history=(),+ status=503,+ message="runtime rejected websocket upgrade",+ headers=None,+ )+ )+ monkeypatch.setattr(ui_server, "ClientSession", lambda: _FailingWebSocketSession(handshake))+ websocket = SimpleNamespace(url=SimpleNamespace(query=""))++ with pytest.raises(WSServerHandshakeError):+ asyncio.run(ui_server._proxy_show_runtime_websocket(websocket, "ses123"))++ assert manager._base_url == base_url++def test_runtime_transport_programming_error_stays_loud(monkeypatch, tmp_path):manager = _runtime_manager_with_failing_transport(monkeypatch, tmp_path)base_url = manager._base_urldiff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 5e6895fba..b6f41efc9 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -27,7 +27,7 @@ from typing import TYPE_CHECKING, Any, Callable, Mappingfrom urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplitimport psutil-from aiohttp import ClientSession, WSMsgType+from aiohttp import ClientConnectionError, ClientSession, WSMsgTypefrom fastapi import Request as FastAPIRequest, WebSocket, WebSocketDisconnectfrom fastapi.responses import Response as FastAPIResponsefrom starlette.datastructures import UploadFile as StarletteUploadFile@@ -4390,17 +4390,23 @@ async def _proxy_show_runtime_websocket(runtime_path = f"{external_prefix.rstrip('/')}/__vite_hmr"if websocket.url.query:runtime_path = f"{runtime_path}?{websocket.url.query}"- upstream = await get_show_runtime_manager().websocket_target(+ manager = get_show_runtime_manager()+ target = await manager.websocket_target(runtime_path,envelope=ShowRuntimeProtocolEnvelope(context),)async with ClientSession() as session:- async with session.ws_connect(- upstream.url,- headers=upstream.headers,- protocols=["vite-hmr"],- autoping=True,- ) as upstream:+ try:+ upstream = await session.ws_connect(+ target.url,+ headers=target.headers,+ protocols=["vite-hmr"],+ autoping=True,+ )+ except (asyncio.TimeoutError, ClientConnectionError):+ await manager.invalidate_websocket_target(target)+ raise+ async with upstream:async def client_to_upstream():try:while True: