Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 147 additions & 1 deletion Server/src/transport/plugin_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -148,6 +150,17 @@ 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
# 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(
Expand Down Expand Up @@ -241,6 +254,118 @@ 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).expanduser() 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(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
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), encoding="utf-8")
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."""
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._load_recent_disconnects()
cls._recent_disconnects[project_hash] = (project_name, time.monotonic())
cls._save_recent_disconnects()

@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.
"""
cls._load_recent_disconnects()
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)
if expired:
cls._save_recent_disconnects()
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
Expand Down Expand Up @@ -276,6 +401,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})")
Expand Down Expand Up @@ -459,6 +585,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._clear_recent_disconnect(project_hash)
evicted_ws = None
async with lock:
# Clean up the evicted session's connection, ping loop, and pending commands
Expand Down Expand Up @@ -807,6 +935,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(
Expand Down Expand Up @@ -927,7 +1056,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

Expand Down
31 changes: 24 additions & 7 deletions Server/src/transport/unity_instance_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
logger.info(
"Auto-selected sole Unity instance via PluginHub: %s",
"Auto-selected sole Unity instance via PluginHub (this call only): %s",
chosen,
)
return chosen
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -396,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."""
Expand Down
16 changes: 16 additions & 0 deletions Server/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
Loading