Skip to content

Commit cb4e2c9

Browse files
dsarnomsanatanScott Jennings
authored
Fix HTTP/Stdio Transport UX and Test Bug (#530)
* refactor: Split ParseColorOrDefault into two overloads and change default to Color.white * Auto-format Python code * Remove unused Python module * Refactored VFX functionality into multiple files Tested everything, works like a charm * Rename ManageVfx folder to just Vfx We know what it's managing * Clean up whitespace on plugin tools and resources * Make ManageGameObject less of a monolith by splitting it out into different files * Remove obsolete FindObjectByInstruction method We also update the namespace for ManageVFX * Add local test harness for fast developer iteration Scripts for running the NL/T/GO test suites locally against a GUI Unity Editor, complementing the CI workflows in .github/workflows/. Benefits: - 10-100x faster than CI (no Docker startup) - Real-time Unity console debugging - Single test execution for rapid iteration - Auto-detects HTTP vs stdio transport Usage: ./scripts/local-test/setup.sh # One-time setup ./scripts/local-test/quick-test.sh NL-0 # Run single test ./scripts/local-test/run-nl-suite-local.sh # Full suite See scripts/local-test/README.md for details. Also updated .gitignore to: - Allow scripts/local-test/ to be tracked - Ignore generated artifacts (reports/*.xml, .claude/local/, .unity-mcp/) * Fix issue #525: Save dirty scenes for all test modes Move SaveDirtyScenesIfNeeded() call outside the PlayMode conditional so EditMode tests don't get blocked by Unity's "Save Scene" modal dialog. This prevents MCP from timing out when running EditMode tests with unsaved scene changes. * refactor: Consolidate editor state resources into single canonical implementation Merged EditorStateV2 into EditorState, making get_editor_state the canonical resource. Updated Unity C# to use EditorStateCache directly. Enhanced Python implementation with advice/staleness enrichment, external changes detection, and instance ID inference. Removed duplicate EditorStateV2 resource and legacy fallback mapping. * Validate editor state with Pydantic models in both C# and Python Added strongly-typed Pydantic models for EditorStateV2 schema in Python and corresponding C# classes with JsonProperty attributes. Updated C# to serialize using typed classes instead of anonymous objects. Python now validates the editor state payload before returning it, catching schema mismatches early. * Consolidate run_tests and run_tests_async into single async implementation Merged run_tests_async into run_tests, making async job-based execution the default behavior. Removed synchronous blocking test execution. Updated RunTests.cs to start test jobs immediately and return job_id for polling. Changed TestJobManager methods to internal visibility. Updated README to reflect single run_tests_async tool. Python implementation now uses async job pattern exclusively. * Validate test job responses with Pydantic models in Python * Change resources URI from unity:// to mcpforunity:// It should reduce conflicts with other Unity MCPs that users try, and to comply with Unity's requests regarding use of their company and product name * Update README with all tools + better listing for resources * Update other references to resources * Updated translated doc - unfortunately I cannot verify * Update the Chinese translation of the dev docks * Change menu item from Setup Window to Local Setup Window We now differentiate whether it's HTTP local or remote * Fix URIs for menu items and tests * Shouldn't have removed it * fix: add missing FAST_FAIL_TIMEOUT constant in PluginHub The FAST_FAIL_TIMEOUT class attribute was referenced on line 149 but never defined, causing AttributeError on every ping attempt. This error was silently caught by the broad 'except Exception' handler, causing all fast-fail commands (read_console, get_editor_state, ping) to fail after 6 seconds of retries with 'ping not answered' error. Added FAST_FAIL_TIMEOUT = 10 to define a 10-second timeout for fast-fail commands, matching the intent of the existing fast-fail infrastructure. * feat(ScriptableObject): enhance dry-run validation for AnimationCurve and Quaternion Dry-run validation now validates value formats, not just property existence: - AnimationCurve: Validates structure ({keys:[...]} or direct array), checks each keyframe is an object, validates numeric fields (time, value, inSlope, outSlope, inWeight, outWeight) and integer fields (weightedMode) - Quaternion: Validates array length (3 for Euler, 4 for raw) or object structure ({x,y,z,w} or {euler:[x,y,z]}), ensures all components are numeric Refactored shared validation helpers into appropriate locations: - ParamCoercion: IsNumericToken, ValidateNumericField, ValidateIntegerField - VectorParsing: ValidateAnimationCurveFormat, ValidateQuaternionFormat Added comprehensive XML documentation clarifying keyframe field defaults (all default to 0 except as noted). Added 5 new dry-run validation tests covering valid and invalid formats for both AnimationCurve and Quaternion properties. * test: fix integration tests after merge - test_refresh_unity_retry_recovery: Mock now handles both refresh_unity and get_editor_state commands (refresh_unity internally calls get_editor_state when wait_for_ready=True) - test_run_tests_async_forwards_params: Mock response now includes required 'mode' field for RunTestsStartResponse Pydantic validation - test_get_test_job_forwards_job_id: Updated to handle GetTestJobResponse as Pydantic model instead of dict (use model_dump() for assertions) * Update warning message to apply to all test modes Follow-up to PR #527: Since SaveDirtyScenesIfNeeded() now runs for all test modes, update the warning message to say 'tests' instead of 'PlayMode tests'. * feat(run_tests): add wait_timeout to get_test_job to avoid client loop detection When polling for test completion, MCP clients like Cursor can detect the repeated get_test_job calls as 'looping' and terminate the agent. Added wait_timeout parameter that makes the server wait internally for tests to complete (polling Unity every 2s) before returning. This dramatically reduces client-side tool calls from 10-20 down to 1-2, avoiding loop detection. Usage: get_test_job(job_id='xxx', wait_timeout=30) - Returns immediately if tests complete within timeout - Returns current status if timeout expires (client can call again) - Recommended: 30-60 seconds * fix: use Pydantic attribute access in test_run_tests_async for merge compatibility * revert: remove local test harness - will be submitted in separate PR * fix: stdio transport survives test runs without UI flicker Root cause: WriteToConfigTests.TearDown() was unconditionally deleting UseHttpTransport EditorPref even when tests were skipped on Windows (NUnit runs TearDown even after Assert.Ignore). Changes: - Fix WriteToConfigTests to save/restore prefs instead of deleting - Add centralized ShouldForceUvxRefresh() for local dev path detection - Clean stale Python build/ artifacts before client configuration - Improve reload handler flag management to prevent stuck Resuming state - Show Resuming status during stdio bridge restart - Initialize client config display on window open - Add DevModeForceServerRefresh to EditorPrefs window known types --------- Co-authored-by: Marcus Sanatan <msanatan@gmail.com> Co-authored-by: Scott Jennings <scott.jennings+CIGINT@cloudimperiumgames.com>
1 parent 34b6a11 commit cb4e2c9

11 files changed

Lines changed: 193 additions & 52 deletions

File tree

MCPForUnity/Editor/Clients/McpClientConfiguratorBase.cs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -467,8 +467,8 @@ private void Register()
467467
else
468468
{
469469
var (uvxPath, gitUrl, packageName) = AssetPathUtility.GetUvxCommandParts();
470-
bool devForceRefresh = GetDevModeForceRefresh();
471-
string devFlags = devForceRefresh ? "--no-cache --refresh " : string.Empty;
470+
// Use central helper that checks both DevModeForceServerRefresh AND local path detection.
471+
string devFlags = AssetPathUtility.ShouldForceUvxRefresh() ? "--no-cache --refresh " : string.Empty;
472472
args = $"mcp add --transport stdio UnityMCP -- \"{uvxPath}\" {devFlags}--from \"{gitUrl}\" {packageName}";
473473
}
474474

@@ -586,8 +586,8 @@ public override string GetManualSnippet()
586586
}
587587

588588
string gitUrl = AssetPathUtility.GetMcpServerGitUrl();
589-
bool devForceRefresh = GetDevModeForceRefresh();
590-
string devFlags = devForceRefresh ? "--no-cache --refresh " : string.Empty;
589+
// Use central helper that checks both DevModeForceServerRefresh AND local path detection.
590+
string devFlags = AssetPathUtility.ShouldForceUvxRefresh() ? "--no-cache --refresh " : string.Empty;
591591

592592
return "# Register the MCP server with Claude Code:\n" +
593593
$"claude mcp add --transport stdio UnityMCP -- \"{uvxPath}\" {devFlags}--from \"{gitUrl}\" mcp-for-unity\n\n" +
@@ -597,12 +597,6 @@ public override string GetManualSnippet()
597597
"claude mcp list # Only works when claude is run in the project's directory";
598598
}
599599

600-
private static bool GetDevModeForceRefresh()
601-
{
602-
try { return EditorPrefs.GetBool(EditorPrefKeys.DevModeForceServerRefresh, false); }
603-
catch { return false; }
604-
}
605-
606600
public override IList<string> GetInstallationSteps() => new List<string>
607601
{
608602
"Ensure Claude CLI is installed",

MCPForUnity/Editor/Helpers/AssetPathUtility.cs

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,88 @@ public static (string uvxPath, string fromUrl, string packageName) GetUvxCommand
186186
return (uvxPath, fromUrl, packageName);
187187
}
188188

189+
/// <summary>
190+
/// Determines whether uvx should use --no-cache --refresh flags.
191+
/// Returns true if DevModeForceServerRefresh is enabled OR if the server URL is a local path.
192+
/// Local paths (file:// or absolute) always need fresh builds to avoid stale uvx cache.
193+
/// </summary>
194+
public static bool ShouldForceUvxRefresh()
195+
{
196+
bool devForceRefresh = false;
197+
try { devForceRefresh = EditorPrefs.GetBool(EditorPrefKeys.DevModeForceServerRefresh, false); } catch { }
198+
199+
if (devForceRefresh)
200+
return true;
201+
202+
// Auto-enable force refresh when using a local path override.
203+
return IsLocalServerPath();
204+
}
205+
206+
/// <summary>
207+
/// Returns true if the server URL is a local path (file:// or absolute path).
208+
/// </summary>
209+
public static bool IsLocalServerPath()
210+
{
211+
string fromUrl = GetMcpServerGitUrl();
212+
if (string.IsNullOrEmpty(fromUrl))
213+
return false;
214+
215+
// Check for file:// protocol or absolute local path
216+
return fromUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase) ||
217+
System.IO.Path.IsPathRooted(fromUrl);
218+
}
219+
220+
/// <summary>
221+
/// Gets the local server path if GitUrlOverride points to a local directory.
222+
/// Returns null if not using a local path.
223+
/// </summary>
224+
public static string GetLocalServerPath()
225+
{
226+
if (!IsLocalServerPath())
227+
return null;
228+
229+
string fromUrl = GetMcpServerGitUrl();
230+
if (fromUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
231+
{
232+
// Strip file:// prefix
233+
fromUrl = fromUrl.Substring(7);
234+
}
235+
236+
return fromUrl;
237+
}
238+
239+
/// <summary>
240+
/// Cleans stale Python build artifacts from the local server path.
241+
/// This is necessary because Python's build system doesn't remove deleted files from build/,
242+
/// and the auto-discovery mechanism will pick up old .py files causing ghost resources/tools.
243+
/// </summary>
244+
/// <returns>True if cleaning was performed, false if not applicable or failed.</returns>
245+
public static bool CleanLocalServerBuildArtifacts()
246+
{
247+
string localPath = GetLocalServerPath();
248+
if (string.IsNullOrEmpty(localPath))
249+
return false;
250+
251+
// Clean the build/ directory which can contain stale .py files
252+
string buildPath = System.IO.Path.Combine(localPath, "build");
253+
if (System.IO.Directory.Exists(buildPath))
254+
{
255+
try
256+
{
257+
System.IO.Directory.Delete(buildPath, recursive: true);
258+
McpLog.Info($"Cleaned stale build artifacts from: {buildPath}");
259+
return true;
260+
}
261+
catch (Exception ex)
262+
{
263+
McpLog.Warn($"Failed to clean build artifacts: {ex.Message}");
264+
return false;
265+
}
266+
}
267+
268+
return false;
269+
}
270+
189271
/// <summary>
190272
/// Gets the package version from package.json
191273
/// </summary>

MCPForUnity/Editor/Helpers/CodexConfigHelper.cs

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,11 @@ namespace MCPForUnity.Editor.Helpers
1717
/// </summary>
1818
public static class CodexConfigHelper
1919
{
20-
private static bool GetDevModeForceRefresh()
21-
{
22-
try
23-
{
24-
return EditorPrefs.GetBool(EditorPrefKeys.DevModeForceServerRefresh, false);
25-
}
26-
catch
27-
{
28-
return false;
29-
}
30-
}
31-
32-
private static void AddDevModeArgs(TomlArray args, bool devForceRefresh)
20+
private static void AddDevModeArgs(TomlArray args)
3321
{
3422
if (args == null) return;
35-
if (!devForceRefresh) return;
23+
// Use central helper that checks both DevModeForceServerRefresh AND local path detection.
24+
if (!AssetPathUtility.ShouldForceUvxRefresh()) return;
3625
args.Add(new TomlString { Value = "--no-cache" });
3726
args.Add(new TomlString { Value = "--refresh" });
3827
}
@@ -59,12 +48,11 @@ public static string BuildCodexServerBlock(string uvPath)
5948
{
6049
// Stdio mode: Use command and args
6150
var (uvxPath, fromUrl, packageName) = AssetPathUtility.GetUvxCommandParts();
62-
bool devForceRefresh = GetDevModeForceRefresh();
6351

6452
unityMCP["command"] = uvxPath;
6553

6654
var args = new TomlArray();
67-
AddDevModeArgs(args, devForceRefresh);
55+
AddDevModeArgs(args);
6856
if (!string.IsNullOrEmpty(fromUrl))
6957
{
7058
args.Add(new TomlString { Value = "--from" });
@@ -209,12 +197,11 @@ private static TomlTable CreateUnityMcpTable(string uvPath)
209197
{
210198
// Stdio mode: Use command and args
211199
var (uvxPath, fromUrl, packageName) = AssetPathUtility.GetUvxCommandParts();
212-
bool devForceRefresh = GetDevModeForceRefresh();
213200

214201
unityMCP["command"] = new TomlString { Value = uvxPath };
215202

216203
var argsArray = new TomlArray();
217-
AddDevModeArgs(argsArray, devForceRefresh);
204+
AddDevModeArgs(argsArray);
218205
if (!string.IsNullOrEmpty(fromUrl))
219206
{
220207
argsArray.Add(new TomlString { Value = "--from" });

MCPForUnity/Editor/Helpers/ConfigJsonBuilder.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ public static JObject ApplyUnityServerToExistingConfig(JObject root, string uvPa
5151
private static void PopulateUnityNode(JObject unity, string uvPath, McpClient client, bool isVSCode)
5252
{
5353
// Get transport preference (default to HTTP)
54-
bool useHttpTransport = client?.SupportsHttpTransport != false && EditorPrefs.GetBool(EditorPrefKeys.UseHttpTransport, true);
54+
bool prefValue = EditorPrefs.GetBool(EditorPrefKeys.UseHttpTransport, true);
55+
bool clientSupportsHttp = client?.SupportsHttpTransport != false;
56+
bool useHttpTransport = clientSupportsHttp && prefValue;
5557
string httpProperty = string.IsNullOrEmpty(client?.HttpUrlProperty) ? "url" : client.HttpUrlProperty;
5658
var urlPropsToRemove = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "url", "serverUrl" };
5759
urlPropsToRemove.Remove(httpProperty);
@@ -81,10 +83,7 @@ private static void PopulateUnityNode(JObject unity, string uvPath, McpClient cl
8183
// Stdio mode: Use uvx command
8284
var (uvxPath, fromUrl, packageName) = AssetPathUtility.GetUvxCommandParts();
8385

84-
bool devForceRefresh = false;
85-
try { devForceRefresh = EditorPrefs.GetBool(EditorPrefKeys.DevModeForceServerRefresh, false); } catch { }
86-
87-
var toolArgs = BuildUvxArgs(fromUrl, packageName, devForceRefresh);
86+
var toolArgs = BuildUvxArgs(fromUrl, packageName);
8887

8988
if (ShouldUseWindowsCmdShim(client))
9089
{
@@ -152,13 +151,15 @@ private static JObject EnsureObject(JObject parent, string name)
152151
return created;
153152
}
154153

155-
private static IList<string> BuildUvxArgs(string fromUrl, string packageName, bool devForceRefresh)
154+
private static IList<string> BuildUvxArgs(string fromUrl, string packageName)
156155
{
157156
// Dev mode: force a fresh install/resolution (avoids stale cached builds while iterating).
158157
// `--no-cache` is the key flag; `--refresh` ensures metadata is revalidated.
159158
// Keep ordering consistent with other uvx builders: dev flags first, then --from <url>, then package name.
160159
var args = new List<string>();
161-
if (devForceRefresh)
160+
161+
// Use central helper that checks both DevModeForceServerRefresh AND local path detection.
162+
if (AssetPathUtility.ShouldForceUvxRefresh())
162163
{
163164
args.Add("--no-cache");
164165
args.Add("--refresh");

MCPForUnity/Editor/Services/ClientConfigurationService.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Collections.Generic;
33
using System.Linq;
44
using MCPForUnity.Editor.Clients;
5+
using MCPForUnity.Editor.Helpers;
56
using MCPForUnity.Editor.Models;
67

78
namespace MCPForUnity.Editor.Services
@@ -22,11 +23,24 @@ public ClientConfigurationService()
2223

2324
public void ConfigureClient(IMcpClientConfigurator configurator)
2425
{
26+
// When using a local server path, clean stale build artifacts first.
27+
// This prevents old deleted .py files from being picked up by Python's auto-discovery.
28+
if (AssetPathUtility.IsLocalServerPath())
29+
{
30+
AssetPathUtility.CleanLocalServerBuildArtifacts();
31+
}
32+
2533
configurator.Configure();
2634
}
2735

2836
public ClientConfigurationSummary ConfigureAllDetectedClients()
2937
{
38+
// When using a local server path, clean stale build artifacts once before configuring all clients.
39+
if (AssetPathUtility.IsLocalServerPath())
40+
{
41+
AssetPathUtility.CleanLocalServerBuildArtifacts();
42+
}
43+
3044
var summary = new ClientConfigurationSummary();
3145
foreach (var configurator in configurators)
3246
{

MCPForUnity/Editor/Services/ServerManagementService.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,9 @@ private string GetPlatformSpecificPathPrepend()
406406
/// </summary>
407407
public bool StartLocalHttpServer()
408408
{
409+
/// Clean stale Python build artifacts when using a local dev server path
410+
AssetPathUtility.CleanLocalServerBuildArtifacts();
411+
409412
if (!TryGetLocalHttpServerCommandParts(out _, out _, out var displayCommand, out var error))
410413
{
411414
EditorUtility.DisplayDialog(
@@ -1236,10 +1239,8 @@ private bool TryGetLocalHttpServerCommandParts(out string fileName, out string a
12361239
return false;
12371240
}
12381241

1239-
bool devForceRefresh = false;
1240-
try { devForceRefresh = EditorPrefs.GetBool(EditorPrefKeys.DevModeForceServerRefresh, false); } catch { }
1241-
1242-
string devFlags = devForceRefresh ? "--no-cache --refresh " : string.Empty;
1242+
// Use central helper that checks both DevModeForceServerRefresh AND local path detection.
1243+
string devFlags = AssetPathUtility.ShouldForceUvxRefresh() ? "--no-cache --refresh " : string.Empty;
12431244
string args = string.IsNullOrEmpty(fromUrl)
12441245
? $"{devFlags}{packageName} --transport http --http-url {httpUrl}"
12451246
: $"{devFlags}--from {fromUrl} {packageName} --transport http --http-url {httpUrl}";

MCPForUnity/Editor/Services/StdioBridgeReloadHandler.cs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ private static void OnBeforeAssemblyReload()
2727
bool useHttp = EditorPrefs.GetBool(EditorPrefKeys.UseHttpTransport, true);
2828
// Check both TransportManager AND StdioBridgeHost directly, because CI starts via StdioBridgeHost
2929
// bypassing TransportManager state.
30-
bool isRunning = MCPServiceLocator.TransportManager.IsRunning(TransportMode.Stdio)
31-
|| StdioBridgeHost.IsRunning;
30+
bool tmRunning = MCPServiceLocator.TransportManager.IsRunning(TransportMode.Stdio);
31+
bool hostRunning = StdioBridgeHost.IsRunning;
32+
bool isRunning = tmRunning || hostRunning;
3233
bool shouldResume = !useHttp && isRunning;
3334

3435
if (shouldResume)
@@ -60,10 +61,12 @@ private static void OnAfterAssemblyReload()
6061
bool resume = false;
6162
try
6263
{
63-
resume = EditorPrefs.GetBool(EditorPrefKeys.ResumeStdioAfterReload, false);
64+
bool resumeFlag = EditorPrefs.GetBool(EditorPrefKeys.ResumeStdioAfterReload, false);
6465
bool useHttp = EditorPrefs.GetBool(EditorPrefKeys.UseHttpTransport, true);
65-
resume = resume && !useHttp;
66-
if (resume)
66+
resume = resumeFlag && !useHttp;
67+
68+
// If we're not going to resume, clear the flag immediately to avoid stuck "Resuming..." state
69+
if (!resume)
6770
{
6871
EditorPrefs.DeleteKey(EditorPrefKeys.ResumeStdioAfterReload);
6972
}
@@ -87,6 +90,13 @@ private static void TryStartBridgeImmediate()
8790
var startTask = MCPServiceLocator.TransportManager.StartAsync(TransportMode.Stdio);
8891
startTask.ContinueWith(t =>
8992
{
93+
// Clear the flag after attempting to start (success or failure).
94+
// This prevents getting stuck in "Resuming..." state.
95+
// We do this synchronously on the continuation thread - it's safe because
96+
// EditorPrefs operations are thread-safe and any new reload will set the flag
97+
// fresh in OnBeforeAssemblyReload before we get here.
98+
try { EditorPrefs.DeleteKey(EditorPrefKeys.ResumeStdioAfterReload); } catch { }
99+
90100
if (t.IsFaulted)
91101
{
92102
var baseEx = t.Exception?.GetBaseException();

MCPForUnity/Editor/Windows/Components/ClientConfig/McpClientConfigSection.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ private void InitializeUI()
8484
}
8585

8686
claudeCliPathRow.style.display = DisplayStyle.None;
87+
88+
// Initialize the configuration display for the first selected client
89+
UpdateClientStatus();
90+
UpdateManualConfiguration();
91+
UpdateClaudeCliPathVisibility();
8792
}
8893

8994
private void RegisterCallbacks()

MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,10 @@ private void RegisterCallbacks()
155155
var selected = (TransportProtocol)evt.newValue;
156156
bool useHttp = selected != TransportProtocol.Stdio;
157157
EditorPrefs.SetBool(EditorPrefKeys.UseHttpTransport, useHttp);
158+
159+
// Clear any stale resume flags when user manually changes transport
160+
try { EditorPrefs.DeleteKey(EditorPrefKeys.ResumeStdioAfterReload); } catch { }
161+
try { EditorPrefs.DeleteKey(EditorPrefKeys.ResumeHttpAfterReload); } catch { }
158162

159163
if (useHttp)
160164
{
@@ -274,7 +278,9 @@ public void UpdateConnectionStatus()
274278
bool isRunning = bridgeService.IsRunning;
275279
bool showLocalServerControls = IsHttpLocalSelected();
276280
bool debugMode = EditorPrefs.GetBool(EditorPrefKeys.DebugLogs, false);
277-
bool stdioSelected = transportDropdown != null && (TransportProtocol)transportDropdown.value == TransportProtocol.Stdio;
281+
// Use EditorPrefs as source of truth for stdio selection - more reliable after domain reload
282+
// than checking the dropdown which may not be initialized yet
283+
bool stdioSelected = !EditorPrefs.GetBool(EditorPrefKeys.UseHttpTransport, true);
278284

279285
// Keep the Start/Stop Server button label in sync even when the session is not running
280286
// (e.g., orphaned server after a domain reload).
@@ -327,19 +333,38 @@ public void UpdateConnectionStatus()
327333
statusIndicator.RemoveFromClassList("disconnected");
328334
statusIndicator.AddToClassList("connected");
329335
connectionToggleButton.text = "End Session";
336+
connectionToggleButton.SetEnabled(true); // Re-enable in case it was disabled during resumption
330337

331338
// Force the UI to reflect the actual port being used
332339
unityPortField.value = bridgeService.CurrentPort.ToString();
333340
unityPortField.SetEnabled(false);
334341
}
335342
else
336343
{
337-
connectionStatusLabel.text = "No Session";
338-
statusIndicator.RemoveFromClassList("connected");
339-
statusIndicator.AddToClassList("disconnected");
340-
connectionToggleButton.text = "Start Session";
344+
// Check if we're resuming the stdio bridge after a domain reload.
345+
// During this brief window, show "Resuming..." instead of "No Session" to avoid UI flicker.
346+
bool isStdioResuming = stdioSelected
347+
&& EditorPrefs.GetBool(EditorPrefKeys.ResumeStdioAfterReload, false);
348+
349+
if (isStdioResuming)
350+
{
351+
connectionStatusLabel.text = "Resuming...";
352+
// Keep the indicator in a neutral/transitional state
353+
statusIndicator.RemoveFromClassList("connected");
354+
statusIndicator.RemoveFromClassList("disconnected");
355+
connectionToggleButton.text = "Start Session";
356+
connectionToggleButton.SetEnabled(false);
357+
}
358+
else
359+
{
360+
connectionStatusLabel.text = "No Session";
361+
statusIndicator.RemoveFromClassList("connected");
362+
statusIndicator.AddToClassList("disconnected");
363+
connectionToggleButton.text = "Start Session";
364+
connectionToggleButton.SetEnabled(true);
365+
}
341366

342-
unityPortField.SetEnabled(true);
367+
unityPortField.SetEnabled(!isStdioResuming);
343368

344369
healthStatusLabel.text = HealthStatusUnknown;
345370
healthIndicator.RemoveFromClassList("healthy");

0 commit comments

Comments
 (0)