From df88d909b460e5cc3d3c8f505de51aa56bcf8a77 Mon Sep 17 00:00:00 2001 From: Marco Meyer Date: Tue, 11 Aug 2026 00:26:06 +0900 Subject: [PATCH 1/5] fix(transport): refuse sole-survivor auto-select while a bridge is restarting When an MCP client's transport cycled (new session, pin lost) while one editor's bridge was down mid-restart, both auto-select paths silently routed every call to the only editor still connected, and the middleware persisted that guess as the session pin - so calls kept landing in the wrong Unity project even after the intended editor came back (#1023 family). - PluginHub now records recently-disconnected bridges (project hash + name, 600s grace, override via UNITY_MCP_DISCONNECT_GRACE_S), cleared as soon as the same project re-registers. - While any record is fresh, both sole-survivor auto-select sites (middleware _maybe_autoselect_instance and hub _resolve_session_id) refuse to guess; the hub raises InstanceSelectionRequiredError naming the disconnected instance so clients can re-pin deliberately. - Auto-selection no longer persists as the session pin: it routes the current call only. Only an explicit set_active_instance writes the pin, so opening a second editor later surfaces selection instead of silently riding a stale auto-pick. --- Server/src/transport/plugin_hub.py | 70 ++++++++++++++++++- .../transport/unity_instance_middleware.py | 26 +++++-- .../test_domain_reload_resilience.py | 55 +++++++++++++++ .../integration/test_instance_autoselect.py | 54 +++++++++++++- .../tests/test_transport_characterization.py | 5 +- 5 files changed, 197 insertions(+), 13 deletions(-) diff --git a/Server/src/transport/plugin_hub.py b/Server/src/transport/plugin_hub.py index 5ab37a2f5c..2d2780f442 100644 --- a/Server/src/transport/plugin_hub.py +++ b/Server/src/transport/plugin_hub.py @@ -148,6 +148,13 @@ class PluginHub(WebSocketEndpoint): _last_pong: ClassVar[dict[str, float]] = {} # session_id -> ping task _ping_tasks: ClassVar[dict[str, asyncio.Task]] = {} + # project_hash -> (project_name, monotonic disconnect time). A bridge that + # dropped recently is likely an editor mid-restart; while any entry is fresh, + # sole-survivor auto-selection must refuse to guess (#1023 family). + _recent_disconnects: ClassVar[dict[str, tuple[str, float]]] = {} + # How long a disconnect keeps blocking auto-selection. Long editor restarts + # (domain reload + asset import) can take minutes. + DISCONNECT_GRACE_DEFAULT_S = 600.0 @classmethod def configure( @@ -241,6 +248,46 @@ async def on_receive(self, websocket: WebSocket, data: Any) -> None: except Exception as e: logger.error(f"Error handling message type {message_type}: {e}") + @classmethod + async def _record_disconnect(cls, session_id: str) -> None: + """Remember which project just lost its bridge, before it is unregistered.""" + if cls._registry is None: + return + try: + session = await cls._registry.get_session(session_id) + except Exception: + logger.debug("Could not resolve session %s for disconnect tracking", session_id, exc_info=True) + return + project_hash = getattr(session, "project_hash", None) if session else None + if project_hash: + project_name = getattr(session, "project_name", None) or "Unknown" + cls._recent_disconnects[project_hash] = (project_name, time.monotonic()) + + @classmethod + def recently_disconnected_instances(cls) -> list[str]: + """Instance ids (Name@hash) whose bridge dropped within the grace window. + + Prunes expired entries as a side effect. Entries are cleared early when + the same project re-registers. + """ + grace_s = _read_bounded_wait_env( + "UNITY_MCP_DISCONNECT_GRACE_S", + default_s=cls.DISCONNECT_GRACE_DEFAULT_S, + max_s=3600.0, + ) + now = time.monotonic() + expired = [ + project_hash + for project_hash, (_, dropped_at) in cls._recent_disconnects.items() + if now - dropped_at > grace_s + ] + for project_hash in expired: + cls._recent_disconnects.pop(project_hash, None) + return sorted( + f"{name}@{project_hash}" + for project_hash, (name, _) in cls._recent_disconnects.items() + ) + async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None: cls = type(self) lock = cls._lock @@ -276,6 +323,7 @@ async def on_disconnect(self, websocket: WebSocket, close_code: int) -> None: ) ) if cls._registry: + await cls._record_disconnect(session_id) await cls._registry.unregister(session_id) logger.info( f"Plugin session {session_id} disconnected ({close_code})") @@ -459,6 +507,8 @@ async def _handle_register(self, websocket: WebSocket, payload: RegisterMessage) await websocket.send_json(response.model_dump()) session, evicted_session_id = await registry.register(session_id, project_name, project_hash, unity_version, project_path, user_id=user_id) + # This project's bridge is back; stop blocking auto-selection on its account. + cls._recent_disconnects.pop(project_hash, None) evicted_ws = None async with lock: # Clean up the evicted session's connection, ping loop, and pending commands @@ -807,6 +857,7 @@ async def _evict_connection(cls, session_id: str, reason: str) -> None: if cls._registry is not None: try: + await cls._record_disconnect(session_id) await cls._registry.unregister(session_id) except Exception: logger.debug( @@ -927,7 +978,24 @@ async def _try_once() -> tuple[str | None, int, bool]: if explicit_required: return None, count, explicit_required if count == 1: - return next(iter(sessions.keys())), count, explicit_required + sole_id, sole = next(iter(sessions.items())) + ghosts = [ + ghost for ghost in cls.recently_disconnected_instances() + if ghost.rpartition("@")[2] != sole.project_hash + ] + if ghosts: + # Another editor's bridge dropped moments ago (likely a domain + # reload or editor restart). The sole survivor may be the wrong + # target, so refuse to guess instead of silently rerouting. + raise InstanceSelectionRequiredError( + "A Unity bridge disconnected recently and may be restarting: " + f"{', '.join(ghosts)}. Refusing to auto-route to the only " + "connected instance; pass unity_instance or call " + "set_active_instance to choose one.", + available_instances=sorted( + f"{s.project_name}@{s.project_hash}" for s in sessions.values()), + ) + return sole_id, count, explicit_required # Multiple sessions but no explicit target is ambiguous return None, count, explicit_required diff --git a/Server/src/transport/unity_instance_middleware.py b/Server/src/transport/unity_instance_middleware.py index 82ba47fd73..197bfe6d3d 100644 --- a/Server/src/transport/unity_instance_middleware.py +++ b/Server/src/transport/unity_instance_middleware.py @@ -216,9 +216,11 @@ async def _maybe_autoselect_instance(self, ctx) -> str | None: """ Auto-select the sole Unity instance when no active instance is set. - Note: This method both *discovers* and *persists* the selection via - `set_active_instance` as a side-effect, since callers expect the selection - to stick for subsequent tool/resource calls in the same session. + The selection applies to the current call only and is deliberately NOT + persisted as the session pin: a transient sole-survivor guess (e.g. while + another editor's bridge restarts) must never stick and silently reroute + later calls (#1023 family). Re-discovery on subsequent calls is cheap. + It also declines to guess while another bridge disconnected recently. """ try: transport = (config.transport_mode or "stdio").lower() @@ -238,9 +240,20 @@ async def _maybe_autoselect_instance(self, ctx) -> str | None: ids.append(f"{project}@{hash_value}") if len(ids) == 1: chosen = ids[0] - await self.set_active_instance(ctx, chosen) + ghosts = [ + ghost for ghost in PluginHub.recently_disconnected_instances() + if ghost != chosen + ] + if ghosts: + logger.info( + "Not auto-selecting sole Unity instance %s: recently " + "disconnected instance(s) %s may be restarting. " + "Pass unity_instance or call set_active_instance.", + chosen, ", ".join(ghosts), + ) + return None logger.info( - "Auto-selected sole Unity instance via PluginHub: %s", + "Auto-selected sole Unity instance via PluginHub (this call only): %s", chosen, ) return chosen @@ -276,9 +289,8 @@ async def _maybe_autoselect_instance(self, ctx) -> str | None: ids = [inst_id for inst_id in ids if inst_id] if len(ids) == 1: chosen = ids[0] - await self.set_active_instance(ctx, chosen) logger.info( - "Auto-selected sole Unity instance via stdio discovery: %s", + "Auto-selected sole Unity instance via stdio discovery (this call only): %s", chosen, ) return chosen diff --git a/Server/tests/integration/test_domain_reload_resilience.py b/Server/tests/integration/test_domain_reload_resilience.py index 803eec7b0f..83b368b23e 100644 --- a/Server/tests/integration/test_domain_reload_resilience.py +++ b/Server/tests/integration/test_domain_reload_resilience.py @@ -68,6 +68,61 @@ async def mock_list_sessions(**kwargs): PluginHub._lock = original_lock +@pytest.mark.asyncio +async def test_plugin_hub_refuses_sole_survivor_after_recent_disconnect(): + """A recently-disconnected bridge blocks auto-routing to the sole remaining session.""" + import time as time_module + + from transport.plugin_hub import PluginHub, InstanceSelectionRequiredError + from transport.plugin_registry import PluginRegistry, PluginSession + + mock_registry = AsyncMock(spec=PluginRegistry) + now = datetime.now() + survivor = PluginSession( + session_id="sess-playground", + project_name="Playground", + project_hash="aaa111", + unity_version="6000.0.0f1", + registered_at=now, + connected_at=now, + ) + + async def mock_list_sessions(**kwargs): + return {"sess-playground": survivor} + + mock_registry.list_sessions = mock_list_sessions + mock_registry.get_session_id_by_hash = AsyncMock(return_value="sess-playground") + + original_registry = PluginHub._registry + original_lock = PluginHub._lock + original_recent = dict(PluginHub._recent_disconnects) + PluginHub._registry = mock_registry + PluginHub._lock = asyncio.Lock() + PluginHub._recent_disconnects["bbb222"] = ("Sandbox", time_module.monotonic()) + + try: + # Unpinned call: refuse to guess while Sandbox may be restarting. + with pytest.raises(InstanceSelectionRequiredError) as excinfo: + await PluginHub._resolve_session_id(unity_instance=None) + assert "Sandbox@bbb222" in str(excinfo.value) + assert excinfo.value.available_instances == ["Playground@aaa111"] + + # Explicit targeting is unaffected. + session_id = await PluginHub._resolve_session_id(unity_instance="aaa111") + assert session_id == "sess-playground" + + # Once the disconnect record clears (re-register or grace expiry), + # sole-instance auto-routing resumes. + PluginHub._recent_disconnects.clear() + session_id = await PluginHub._resolve_session_id(unity_instance=None) + assert session_id == "sess-playground" + finally: + PluginHub._registry = original_registry + PluginHub._lock = original_lock + PluginHub._recent_disconnects.clear() + PluginHub._recent_disconnects.update(original_recent) + + @pytest.mark.asyncio async def test_plugin_hub_fails_after_timeout(): """Test that PluginHub._resolve_session_id eventually times out if plugin never reconnects.""" diff --git a/Server/tests/integration/test_instance_autoselect.py b/Server/tests/integration/test_instance_autoselect.py index b974cb11c3..3af0952cd9 100644 --- a/Server/tests/integration/test_instance_autoselect.py +++ b/Server/tests/integration/test_instance_autoselect.py @@ -25,6 +25,10 @@ def is_configured(cls) -> bool: async def get_sessions(cls): raise AssertionError("get_sessions should be stubbed in test") + @classmethod + def recently_disconnected_instances(cls): + return [] + plugin_hub.PluginHub = PluginHub monkeypatch.setitem(sys.modules, "transport.plugin_hub", plugin_hub) monkeypatch.delitem(sys.modules, "transport.unity_instance_middleware", raising=False) @@ -54,13 +58,15 @@ async def fake_get_sessions(): selected = await middleware._maybe_autoselect_instance(ctx) assert selected == "Ramble@deadbeef" - assert await middleware.get_active_instance(ctx) == "Ramble@deadbeef" + # Auto-selection is per-call only; it must not stick as the session pin. + assert await middleware.get_active_instance(ctx) is None assert call_count["sessions"] == 1 await middleware._inject_unity_instance(middleware_context) assert await ctx.get_state("unity_instance") == "Ramble@deadbeef" - assert call_count["sessions"] == 1 + # Injection re-discovered rather than reading a persisted pin. + assert call_count["sessions"] == 2 @pytest.mark.asyncio @@ -98,13 +104,55 @@ def discover_all_instances(self, force_refresh=False): selected = await middleware._maybe_autoselect_instance(ctx) assert selected == "UnityMCPTests@cc8756d4" - assert await middleware.get_active_instance(ctx) == "UnityMCPTests@cc8756d4" + # Auto-selection is per-call only; it must not stick as the session pin. + assert await middleware.get_active_instance(ctx) is None await middleware._inject_unity_instance(middleware_context) assert await ctx.get_state("unity_instance") == "UnityMCPTests@cc8756d4" +@pytest.mark.asyncio +async def test_no_autoselect_while_another_bridge_recently_disconnected(monkeypatch): + plugin_hub = types.ModuleType("transport.plugin_hub") + + class PluginHub: + @classmethod + def is_configured(cls) -> bool: + return True + + @classmethod + async def get_sessions(cls): + return SimpleNamespace( + sessions={ + "session-1": SimpleNamespace(project="Playground", hash="aaaa1111"), + } + ) + + @classmethod + def recently_disconnected_instances(cls): + return ["Sandbox@bbbb2222"] + + plugin_hub.PluginHub = PluginHub + monkeypatch.setitem(sys.modules, "transport.plugin_hub", plugin_hub) + monkeypatch.delitem(sys.modules, "transport.unity_instance_middleware", raising=False) + + from transport.unity_instance_middleware import UnityInstanceMiddleware, PluginHub as ImportedPluginHub + assert ImportedPluginHub is plugin_hub.PluginHub + + monkeypatch.setattr(config, "transport_mode", "http") + + middleware = UnityInstanceMiddleware() + ctx = DummyContext() + ctx.client_id = "client-1" + + selected = await middleware._maybe_autoselect_instance(ctx) + + # The sole survivor may be the wrong editor while another bridge restarts. + assert selected is None + assert await middleware.get_active_instance(ctx) is None + + @pytest.mark.asyncio async def test_auto_select_handles_stdio_errors(monkeypatch): plugin_hub = types.ModuleType("transport.plugin_hub") diff --git a/Server/tests/test_transport_characterization.py b/Server/tests/test_transport_characterization.py index 11fef31f97..e39da2d6b5 100644 --- a/Server/tests/test_transport_characterization.py +++ b/Server/tests/test_transport_characterization.py @@ -702,7 +702,8 @@ class TestAutoSelectInstance: async def test_autoselect_via_plugin_hub_single_instance(self, mock_context): """ Current behavior: When single instance is available via PluginHub, - auto-select it and store in middleware state. + auto-select it for the current call WITHOUT persisting it as the + session pin (a transient sole-survivor guess must never stick). """ middleware = UnityInstanceMiddleware() @@ -725,7 +726,7 @@ async def test_autoselect_via_plugin_hub_single_instance(self, mock_context): instance = await middleware._maybe_autoselect_instance(mock_context) assert instance == "TestProject@abc123" - assert await middleware.get_active_instance(mock_context) == "TestProject@abc123" + assert await middleware.get_active_instance(mock_context) is None @pytest.mark.asyncio async def test_autoselect_fails_with_multiple_instances(self, mock_context): From 24d4f3228d3d7c0067f97468b3750facc33ad4cf Mon Sep 17 00:00:00 2001 From: Marco Meyer Date: Tue, 11 Aug 2026 00:35:37 +0900 Subject: [PATCH 2/5] fix(transport): persist recent-disconnect records across server restarts The disconnect-grace guard only lived in memory, so a server restart forgot that a bridge had just dropped and the sole-survivor window briefly reopened. Records are now mirrored to /recent-disconnects.json (state dir defaults to ~/.unity-mcp, override via UNITY_MCP_STATE_DIR) with wall-clock timestamps, converted to monotonic ages on lazy load. In-memory entries win over persisted ones; re-registration clears disk too; save failures only log at debug and never affect routing. Tests redirect the state dir to tmp_path via an autouse fixture so suites never touch the real ~/.unity-mcp. --- Server/src/transport/plugin_hub.py | 78 ++++++++++++++++++- Server/tests/conftest.py | 16 ++++ .../test_domain_reload_resilience.py | 26 +++++++ 3 files changed, 119 insertions(+), 1 deletion(-) diff --git a/Server/src/transport/plugin_hub.py b/Server/src/transport/plugin_hub.py index 2d2780f442..4c6b7a70bb 100644 --- a/Server/src/transport/plugin_hub.py +++ b/Server/src/transport/plugin_hub.py @@ -3,11 +3,13 @@ from __future__ import annotations import asyncio +import json import logging import os import time import uuid import weakref +from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar from starlette.endpoints import WebSocketEndpoint @@ -155,6 +157,10 @@ class PluginHub(WebSocketEndpoint): # How long a disconnect keeps blocking auto-selection. Long editor restarts # (domain reload + asset import) can take minutes. DISCONNECT_GRACE_DEFAULT_S = 600.0 + # Disconnect records are mirrored to disk (wall-clock timestamps) so a + # server restart doesn't forget a bridge that dropped moments earlier. + RECENT_DISCONNECTS_FILENAME = "recent-disconnects.json" + _recent_disconnects_loaded: ClassVar[bool] = False @classmethod def configure( @@ -248,6 +254,71 @@ async def on_receive(self, websocket: WebSocket, data: Any) -> None: except Exception as e: logger.error(f"Error handling message type {message_type}: {e}") + @staticmethod + def _state_dir() -> Path: + override = os.environ.get("UNITY_MCP_STATE_DIR") + return Path(override) if override else Path.home() / ".unity-mcp" + + @classmethod + def _recent_disconnects_file(cls) -> Path: + return cls._state_dir() / cls.RECENT_DISCONNECTS_FILENAME + + @classmethod + def _load_recent_disconnects(cls) -> None: + """Merge disconnect records persisted by a previous server process. + + The file stores wall-clock timestamps; in-memory records use monotonic + time, so ages are converted at the boundary. In-memory entries win over + persisted ones. + """ + if cls._recent_disconnects_loaded: + return + cls._recent_disconnects_loaded = True + try: + raw = json.loads(cls._recent_disconnects_file().read_text()) + except (FileNotFoundError, json.JSONDecodeError, OSError): + return + if not isinstance(raw, dict): + return + now_wall = time.time() + now_mono = time.monotonic() + for project_hash, entry in raw.items(): + if project_hash in cls._recent_disconnects or not isinstance(entry, dict): + continue + try: + age_s = max(0.0, now_wall - float(entry.get("dropped_at", 0.0))) + except (TypeError, ValueError): + continue + name = entry.get("name") or "Unknown" + cls._recent_disconnects[project_hash] = (name, now_mono - age_s) + + @classmethod + def _save_recent_disconnects(cls) -> None: + try: + now_wall = time.time() + now_mono = time.monotonic() + payload = { + project_hash: { + "name": name, + "dropped_at": now_wall - (now_mono - dropped_mono), + } + for project_hash, (name, dropped_mono) in cls._recent_disconnects.items() + } + target = cls._recent_disconnects_file() + target.parent.mkdir(parents=True, exist_ok=True) + tmp = target.with_name(f"{target.name}.{os.getpid()}.tmp") + tmp.write_text(json.dumps(payload)) + tmp.replace(target) + except Exception: + logger.debug("Failed to persist recent-disconnect records", exc_info=True) + + @classmethod + def _clear_recent_disconnect(cls, project_hash: str) -> None: + """Forget a disconnect record once the same project re-registers.""" + cls._load_recent_disconnects() + if cls._recent_disconnects.pop(project_hash, None) is not None: + cls._save_recent_disconnects() + @classmethod async def _record_disconnect(cls, session_id: str) -> None: """Remember which project just lost its bridge, before it is unregistered.""" @@ -261,7 +332,9 @@ async def _record_disconnect(cls, session_id: str) -> None: project_hash = getattr(session, "project_hash", None) if session else None if project_hash: project_name = getattr(session, "project_name", None) or "Unknown" + cls._load_recent_disconnects() cls._recent_disconnects[project_hash] = (project_name, time.monotonic()) + cls._save_recent_disconnects() @classmethod def recently_disconnected_instances(cls) -> list[str]: @@ -270,6 +343,7 @@ def recently_disconnected_instances(cls) -> list[str]: Prunes expired entries as a side effect. Entries are cleared early when the same project re-registers. """ + cls._load_recent_disconnects() grace_s = _read_bounded_wait_env( "UNITY_MCP_DISCONNECT_GRACE_S", default_s=cls.DISCONNECT_GRACE_DEFAULT_S, @@ -283,6 +357,8 @@ def recently_disconnected_instances(cls) -> list[str]: ] for project_hash in expired: cls._recent_disconnects.pop(project_hash, None) + if expired: + cls._save_recent_disconnects() return sorted( f"{name}@{project_hash}" for project_hash, (name, _) in cls._recent_disconnects.items() @@ -508,7 +584,7 @@ async def _handle_register(self, websocket: WebSocket, payload: RegisterMessage) session, evicted_session_id = await registry.register(session_id, project_name, project_hash, unity_version, project_path, user_id=user_id) # This project's bridge is back; stop blocking auto-selection on its account. - cls._recent_disconnects.pop(project_hash, None) + cls._clear_recent_disconnect(project_hash) evicted_ws = None async with lock: # Clean up the evicted session's connection, ping loop, and pending commands diff --git a/Server/tests/conftest.py b/Server/tests/conftest.py index b3408ed27d..dccc994973 100644 --- a/Server/tests/conftest.py +++ b/Server/tests/conftest.py @@ -61,6 +61,22 @@ def pytest_collection_modifyitems(session, config, items): # noqa: ARG001 items[:] = other_tests + integration_tests +@pytest.fixture(autouse=True) +def isolate_plugin_hub_disconnect_state(tmp_path, monkeypatch): + """Keep PluginHub disconnect tracking off the real ~/.unity-mcp and between tests.""" + monkeypatch.setenv("UNITY_MCP_STATE_DIR", str(tmp_path / "unity-mcp-state")) + try: + from transport.plugin_hub import PluginHub + except Exception: + yield + return + PluginHub._recent_disconnects.clear() + PluginHub._recent_disconnects_loaded = False + yield + PluginHub._recent_disconnects.clear() + PluginHub._recent_disconnects_loaded = False + + @pytest.fixture(autouse=True) def restore_global_config(): """Restore global config/env mutations between tests.""" diff --git a/Server/tests/integration/test_domain_reload_resilience.py b/Server/tests/integration/test_domain_reload_resilience.py index 83b368b23e..56e206ec9e 100644 --- a/Server/tests/integration/test_domain_reload_resilience.py +++ b/Server/tests/integration/test_domain_reload_resilience.py @@ -123,6 +123,32 @@ async def mock_list_sessions(**kwargs): PluginHub._recent_disconnects.update(original_recent) +@pytest.mark.asyncio +async def test_recent_disconnects_survive_server_restart(): + """Disconnect records persist to disk and are reloaded by a fresh server process.""" + import time as time_module + + from transport.plugin_hub import PluginHub + + # "Old" server process records a drop and mirrors it to disk. + PluginHub._recent_disconnects_loaded = True + PluginHub._recent_disconnects["bbb222"] = ("Sandbox", time_module.monotonic()) + PluginHub._save_recent_disconnects() + + # Simulate a server restart: in-memory state gone, lazy load re-arms. + PluginHub._recent_disconnects.clear() + PluginHub._recent_disconnects_loaded = False + + assert PluginHub.recently_disconnected_instances() == ["Sandbox@bbb222"] + + # Re-registration clears the record on disk too. + PluginHub._clear_recent_disconnect("bbb222") + PluginHub._recent_disconnects.clear() + PluginHub._recent_disconnects_loaded = False + + assert PluginHub.recently_disconnected_instances() == [] + + @pytest.mark.asyncio async def test_plugin_hub_fails_after_timeout(): """Test that PluginHub._resolve_session_id eventually times out if plugin never reconnects.""" From 34369ff1674e4e0694815e7298f326d52867bf11 Mon Sep 17 00:00:00 2001 From: Marco Meyer-Conde Date: Tue, 27 Oct 2026 15:04:39 +0900 Subject: [PATCH 3/5] fix(transport): clear the per-call instance when auto-select declines; harden the disconnect file Review follow-up. - The middleware wrote the routed instance to "unity_instance" in FastMCP's state store, which is session-scoped. When a later call's auto-selection declined (another bridge recently dropped), nothing overwrote it, so the earlier call's sole survivor still routed the new call - the wrong- project routing this change exists to prevent. Each call now stores None when no instance is selected, so a per-call choice never outlives its call. - UNITY_MCP_STATE_DIR expands "~". - The disconnect file is read and written as UTF-8, and any ValueError (invalid JSON or invalid bytes) is ignored: a damaged file must never escape into on_disconnect or registration. Tests: a second injection on the same context after a declined auto-select leaves unity_instance None; damaged state files are ignored; "~" is expanded. The no-instance characterization test now expects the cleared value. --- Server/src/transport/plugin_hub.py | 10 ++-- .../transport/unity_instance_middleware.py | 5 ++ .../test_domain_reload_resilience.py | 21 ++++++++ .../integration/test_instance_autoselect.py | 51 +++++++++++++++++++ .../tests/test_transport_characterization.py | 7 +-- 5 files changed, 87 insertions(+), 7 deletions(-) diff --git a/Server/src/transport/plugin_hub.py b/Server/src/transport/plugin_hub.py index 4c6b7a70bb..1cc15d5ece 100644 --- a/Server/src/transport/plugin_hub.py +++ b/Server/src/transport/plugin_hub.py @@ -257,7 +257,7 @@ async def on_receive(self, websocket: WebSocket, data: Any) -> None: @staticmethod def _state_dir() -> Path: override = os.environ.get("UNITY_MCP_STATE_DIR") - return Path(override) if override else Path.home() / ".unity-mcp" + return Path(override).expanduser() if override else Path.home() / ".unity-mcp" @classmethod def _recent_disconnects_file(cls) -> Path: @@ -275,8 +275,10 @@ def _load_recent_disconnects(cls) -> None: return cls._recent_disconnects_loaded = True try: - raw = json.loads(cls._recent_disconnects_file().read_text()) - except (FileNotFoundError, json.JSONDecodeError, OSError): + raw = json.loads(cls._recent_disconnects_file().read_text(encoding="utf-8")) + except (OSError, ValueError): + # ValueError covers a JSONDecodeError and a UnicodeDecodeError: a damaged file must never + # escape into on_disconnect or registration, where it would skip unregister/register. return if not isinstance(raw, dict): return @@ -307,7 +309,7 @@ def _save_recent_disconnects(cls) -> None: target = cls._recent_disconnects_file() target.parent.mkdir(parents=True, exist_ok=True) tmp = target.with_name(f"{target.name}.{os.getpid()}.tmp") - tmp.write_text(json.dumps(payload)) + tmp.write_text(json.dumps(payload), encoding="utf-8") tmp.replace(target) except Exception: logger.debug("Failed to persist recent-disconnect records", exc_info=True) diff --git a/Server/src/transport/unity_instance_middleware.py b/Server/src/transport/unity_instance_middleware.py index 197bfe6d3d..1f385de12d 100644 --- a/Server/src/transport/unity_instance_middleware.py +++ b/Server/src/transport/unity_instance_middleware.py @@ -408,6 +408,11 @@ async def _inject_unity_instance(self, context: MiddlewareContext) -> None: await ctx.set_state("unity_instance", active_instance) if session_id is not None: await ctx.set_state("unity_session_id", session_id) + else: + # The state store is session-scoped: without this, a previous call's instance (an + # auto-selected sole survivor, say) would still route this call after auto-selection + # declined. Every call overwrites it, so a per-call choice never outlives its call. + await ctx.set_state("unity_instance", None) async def on_call_tool(self, context: MiddlewareContext, call_next): """Inject active Unity instance into tool context if available.""" diff --git a/Server/tests/integration/test_domain_reload_resilience.py b/Server/tests/integration/test_domain_reload_resilience.py index 56e206ec9e..33b3cda2af 100644 --- a/Server/tests/integration/test_domain_reload_resilience.py +++ b/Server/tests/integration/test_domain_reload_resilience.py @@ -149,6 +149,27 @@ async def test_recent_disconnects_survive_server_restart(): assert PluginHub.recently_disconnected_instances() == [] +@pytest.mark.parametrize("content", [b"\xff\xfe not utf-8", b"{not json", b"[1, 2]"]) +def test_damaged_recent_disconnects_file_is_ignored(content): + """A damaged state file is skipped: the persistence layer never affects routing.""" + from transport.plugin_hub import PluginHub + + target = PluginHub._recent_disconnects_file() + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + + assert PluginHub.recently_disconnected_instances() == [] + + +def test_state_dir_override_expands_home(monkeypatch, tmp_path): + from transport.plugin_hub import PluginHub + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("UNITY_MCP_STATE_DIR", "~/unity-mcp-state") + + assert PluginHub._state_dir() == tmp_path / "unity-mcp-state" + + @pytest.mark.asyncio async def test_plugin_hub_fails_after_timeout(): """Test that PluginHub._resolve_session_id eventually times out if plugin never reconnects.""" diff --git a/Server/tests/integration/test_instance_autoselect.py b/Server/tests/integration/test_instance_autoselect.py index 3af0952cd9..8214b28b3b 100644 --- a/Server/tests/integration/test_instance_autoselect.py +++ b/Server/tests/integration/test_instance_autoselect.py @@ -153,6 +153,57 @@ def recently_disconnected_instances(cls): assert await middleware.get_active_instance(ctx) is None +@pytest.mark.asyncio +async def test_declined_autoselect_clears_the_previous_calls_instance(monkeypatch): + plugin_hub = types.ModuleType("transport.plugin_hub") + + class PluginHub: + ghosts: list[str] = [] + + @classmethod + def is_configured(cls) -> bool: + return True + + @classmethod + async def get_sessions(cls): + return SimpleNamespace( + sessions={ + "session-1": SimpleNamespace(project="Playground", hash="aaaa1111"), + } + ) + + @classmethod + def recently_disconnected_instances(cls): + return list(cls.ghosts) + + @classmethod + async def _resolve_session_id(cls, unity_instance, user_id=None): + return "session-1" + + plugin_hub.PluginHub = PluginHub + monkeypatch.setitem(sys.modules, "transport.plugin_hub", plugin_hub) + monkeypatch.delitem(sys.modules, "transport.unity_instance_middleware", raising=False) + + from transport.unity_instance_middleware import UnityInstanceMiddleware + + monkeypatch.setattr(config, "transport_mode", "http") + + middleware = UnityInstanceMiddleware() + ctx = DummyContext() + ctx.client_id = "client-1" + middleware_context = DummyMiddlewareContext(ctx) + + # First call: the sole instance is auto-selected for this call. + await middleware._inject_unity_instance(middleware_context) + assert await ctx.get_state("unity_instance") == "Playground@aaaa1111" + + # Next call on the same session: another bridge just dropped, so auto-selection declines. + # The state store is session-scoped; the first call's instance must not route this one. + PluginHub.ghosts = ["Sandbox@bbbb2222"] + await middleware._inject_unity_instance(middleware_context) + assert await ctx.get_state("unity_instance") is None + + @pytest.mark.asyncio async def test_auto_select_handles_stdio_errors(monkeypatch): plugin_hub = types.ModuleType("transport.plugin_hub") diff --git a/Server/tests/test_transport_characterization.py b/Server/tests/test_transport_characterization.py index e39da2d6b5..a6f87d9332 100644 --- a/Server/tests/test_transport_characterization.py +++ b/Server/tests/test_transport_characterization.py @@ -245,7 +245,8 @@ async def mock_call_next(_ctx): async def test_middleware_does_not_inject_when_no_instance(self, mock_context): """ Current behavior: When no active instance is set and auto-select fails, - middleware does not inject anything (None instance not stored). + middleware stores None, so an instance left in the session-scoped state by + an earlier call cannot route this one. """ middleware = UnityInstanceMiddleware() @@ -261,10 +262,10 @@ async def mock_call_next(_ctx): with patch("transport.legacy.unity_connection.get_unity_connection_pool", return_value=None): await middleware.on_call_tool(middleware_ctx, mock_call_next) - # set_state should not be called for unity_instance if no instance found + # unity_instance is cleared (None), never left at an earlier call's value calls = [c for c in mock_context.set_state.call_args_list if len(c[0]) > 0 and c[0][0] == "unity_instance"] - assert len(calls) == 0 + assert [c[0][1] for c in calls] == [None] @pytest.mark.asyncio async def test_list_tools_filters_disabled_unity_tools_and_aliases(self, mock_context, monkeypatch): From ffcdbebf48874e8a1e79cc3ae930ce84c0e69136 Mon Sep 17 00:00:00 2001 From: Marco Meyer-Conde Date: Thu, 29 Oct 2026 22:28:04 +0900 Subject: [PATCH 4/5] test(autoselect): load unity_transport before any test stubs plugin_hub The middleware imports transport.unity_transport lazily. Run on its own, a test here made that first import resolve against its stub plugin_hub, which has no InstanceSelectionRequiredError, and failed with ImportError (three of the five tests, two of them already on beta). Importing the real module at load time fixes them all. --- Server/tests/integration/test_instance_autoselect.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Server/tests/integration/test_instance_autoselect.py b/Server/tests/integration/test_instance_autoselect.py index 8214b28b3b..3b19a76162 100644 --- a/Server/tests/integration/test_instance_autoselect.py +++ b/Server/tests/integration/test_instance_autoselect.py @@ -5,6 +5,10 @@ from .test_helpers import DummyContext from core.config import config +# The middleware imports transport.unity_transport lazily; load it now, against the real +# plugin_hub, so that import never resolves against a test's stub (which lacks +# InstanceSelectionRequiredError) when a test here runs on its own. +import transport.unity_transport # noqa: F401 class DummyMiddlewareContext: From 33ce6f7e3a6b6d8598ed7ce98b176852a107dae6 Mon Sep 17 00:00:00 2001 From: Marco Meyer-Conde Date: Tue, 10 Nov 2026 15:16:51 +0900 Subject: [PATCH 5/5] test(transport): cover disconnect recording and the state file's edge cases The recording itself had no test: on_disconnect and the stale-session eviction now run against a real registry and are checked in memory and on disk. Also covered: no registry, an unknown session or a failing lookup records nothing; records past the grace window are pruned from the file; malformed entries in the file are skipped without hiding the valid ones; a state directory that cannot be written leaves the record in memory. --- .../test_domain_reload_resilience.py | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/Server/tests/integration/test_domain_reload_resilience.py b/Server/tests/integration/test_domain_reload_resilience.py index 33b3cda2af..1ce43eabfc 100644 --- a/Server/tests/integration/test_domain_reload_resilience.py +++ b/Server/tests/integration/test_domain_reload_resilience.py @@ -382,3 +382,130 @@ async def mock_get_session_id_by_hash(project_hash, user_id=None): # Clean up: restore original PluginHub state PluginHub._registry = original_registry PluginHub._lock = original_lock + + +@pytest.fixture +def hub_with_registry(): + """PluginHub on a real registry, restored afterwards.""" + from transport.plugin_hub import PluginHub + from transport.plugin_registry import PluginRegistry + + saved = (PluginHub._registry, PluginHub._lock, dict(PluginHub._connections)) + registry = PluginRegistry() + PluginHub._registry = registry + PluginHub._lock = asyncio.Lock() + PluginHub._connections.clear() + try: + yield PluginHub, registry + finally: + PluginHub._registry, PluginHub._lock = saved[0], saved[1] + PluginHub._connections.clear() + PluginHub._connections.update(saved[2]) + + +@pytest.mark.asyncio +async def test_bridge_disconnect_is_recorded_and_persisted(hub_with_registry): + """A dropped socket leaves a record, in memory and on disk, before the session is unregistered.""" + import json + + PluginHub, registry = hub_with_registry + await registry.register("sess-sandbox", "Sandbox", "bbb222", "6000.0.0f1") + websocket = object() + PluginHub._connections["sess-sandbox"] = websocket + + hub = PluginHub({"type": "websocket"}, receive=AsyncMock(), send=AsyncMock()) + await hub.on_disconnect(websocket, 1006) + + assert await registry.get_session("sess-sandbox") is None + assert PluginHub.recently_disconnected_instances() == ["Sandbox@bbb222"] + persisted = json.loads(PluginHub._recent_disconnects_file().read_text(encoding="utf-8")) + assert persisted["bbb222"]["name"] == "Sandbox" + + +@pytest.mark.asyncio +async def test_evicted_stale_session_is_recorded(hub_with_registry): + """Evicting a stale session counts as a disconnect too.""" + PluginHub, registry = hub_with_registry + await registry.register("sess-sandbox", "Sandbox", "bbb222", "6000.0.0f1") + PluginHub._connections["sess-sandbox"] = AsyncMock() + + await PluginHub._evict_connection("sess-sandbox", "stale_websocket_state") + + assert await registry.get_session("sess-sandbox") is None + assert PluginHub.recently_disconnected_instances() == ["Sandbox@bbb222"] + + +@pytest.mark.asyncio +async def test_record_disconnect_without_a_known_session_records_nothing(hub_with_registry): + """No registry, an unknown session or a failing lookup: nothing is recorded, nothing is raised.""" + from transport.plugin_registry import PluginRegistry + + PluginHub, _ = hub_with_registry + + await PluginHub._record_disconnect("sess-unknown") + + failing = AsyncMock(spec=PluginRegistry) + failing.get_session.side_effect = RuntimeError("registry unavailable") + PluginHub._registry = failing + await PluginHub._record_disconnect("sess-sandbox") + + PluginHub._registry = None + await PluginHub._record_disconnect("sess-sandbox") + + assert PluginHub._recent_disconnects == {} + assert not PluginHub._recent_disconnects_file().exists() + + +def test_expired_disconnect_records_are_pruned_from_disk(monkeypatch): + """A record older than the grace window is dropped, on disk as well.""" + import json + import time as time_module + + from transport.plugin_hub import PluginHub + + monkeypatch.setenv("UNITY_MCP_DISCONNECT_GRACE_S", "60") + now = time_module.monotonic() + PluginHub._recent_disconnects_loaded = True + PluginHub._recent_disconnects["old111"] = ("Old", now - 120.0) + PluginHub._recent_disconnects["bbb222"] = ("Sandbox", now) + PluginHub._save_recent_disconnects() + + assert PluginHub.recently_disconnected_instances() == ["Sandbox@bbb222"] + persisted = json.loads(PluginHub._recent_disconnects_file().read_text(encoding="utf-8")) + assert list(persisted) == ["bbb222"] + + +def test_malformed_persisted_entries_are_skipped(): + """One bad entry in the state file does not hide the valid ones.""" + import json + import time as time_module + + from transport.plugin_hub import PluginHub + + target = PluginHub._recent_disconnects_file() + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps({ + "not-a-record": "Sandbox", + "bad-time": {"name": "Broken", "dropped_at": "yesterday"}, + "null-time": {"name": "Broken", "dropped_at": None}, + "bbb222": {"name": "Sandbox", "dropped_at": time_module.time()}, + }), encoding="utf-8") + + assert PluginHub.recently_disconnected_instances() == ["Sandbox@bbb222"] + + +def test_unwritable_state_dir_keeps_the_record_in_memory(monkeypatch, tmp_path): + """Persistence is best effort: a state directory that cannot be written is not an error.""" + import time as time_module + + from transport.plugin_hub import PluginHub + + blocker = tmp_path / "not-a-directory" + blocker.write_text("", encoding="utf-8") + monkeypatch.setenv("UNITY_MCP_STATE_DIR", str(blocker / "state")) + PluginHub._recent_disconnects_loaded = True + PluginHub._recent_disconnects["bbb222"] = ("Sandbox", time_module.monotonic()) + + PluginHub._save_recent_disconnects() + + assert PluginHub.recently_disconnected_instances() == ["Sandbox@bbb222"]