Skip to content

perf: avoid blocking update checks in editor window#954

Open
jiajunfeng wants to merge 1 commit intoCoplayDev:betafrom
jiajunfeng:fix/editor-window-initial-open-lag
Open

perf: avoid blocking update checks in editor window#954
jiajunfeng wants to merge 1 commit intoCoplayDev:betafrom
jiajunfeng:fix/editor-window-initial-open-lag

Conversation

@jiajunfeng
Copy link

@jiajunfeng jiajunfeng commented Mar 19, 2026

Summary

  • move the editor window package update check off the Unity main thread
  • add explicit network timeouts for GitHub/Asset Store version fetches
  • prevent repeated update-check queueing while a background check is already running

Changes

  • run CheckForUpdate(...) on a background task and marshal UI updates back with EditorApplication.delayCall
  • add a timeout-configured WebClient wrapper to cap remote version fetch latency at 3 seconds
  • keep the visible update banner behavior unchanged when results are available

Validation

  • rebuilt MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs
  • rebuilt MCPForUnity/Editor/Services/PackageUpdateService.cs

Summary by Sourcery

Run Unity editor package update checks asynchronously with bounded network latency while preserving existing update banner behavior.

Bug Fixes:

  • Prevent repeated queuing of editor package update checks while a previous check is still in flight.
  • Avoid UI updates from background update checks when the editor window or its UI elements have been disposed.

Enhancements:

  • Move package update checks off the Unity main thread and marshal results back via delayed UI callbacks.
  • Introduce a timeout-configured WebClient wrapper to cap GitHub and Asset Store version fetches to a short, configurable duration.

Summary by CodeRabbit

  • Bug Fixes
    • Improved package update checking with enhanced timeout handling and centralized HTTP request management
    • Update checks now execute asynchronously, preventing editor UI freezing and eliminating overlapping concurrent checks

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Mar 19, 2026

Reviewer's Guide

Runs package update checks for the Unity editor window on a background task instead of the main thread, adds a timeout-configured WebClient for GitHub/Asset Store version fetches, and guards against re-queuing update checks while one is already in flight, without changing visible update banner behavior when results are available.

Sequence diagram for asynchronous package update check in editor window

sequenceDiagram
    actor User
    participant MCPForUnityEditorWindow
    participant EditorApplication
    participant TaskScheduler
    participant PackageUpdateService

    User->>MCPForUnityEditorWindow: Trigger QueueUpdateCheck
    MCPForUnityEditorWindow->>MCPForUnityEditorWindow: QueueUpdateCheck()
    alt updateCheckQueued or updateCheckInFlight is true
        MCPForUnityEditorWindow-->>User: Return (no new check queued)
    else
        MCPForUnityEditorWindow->>EditorApplication: delayCall += CheckForPackageUpdates
    end

    EditorApplication->>MCPForUnityEditorWindow: Invoke CheckForPackageUpdates
    MCPForUnityEditorWindow->>MCPForUnityEditorWindow: updateCheckQueued = false
    MCPForUnityEditorWindow->>MCPForUnityEditorWindow: Get currentVersion
    alt currentVersion invalid
        MCPForUnityEditorWindow->>MCPForUnityEditorWindow: Hide updateNotification
        MCPForUnityEditorWindow-->>User: No update check
    else
        MCPForUnityEditorWindow->>MCPForUnityEditorWindow: updateCheckInFlight = true
        MCPForUnityEditorWindow->>TaskScheduler: Task.Run(CheckForUpdate)
        TaskScheduler->>PackageUpdateService: CheckForUpdate(currentVersion)
        PackageUpdateService-->>TaskScheduler: UpdateCheckResult or null
        TaskScheduler->>EditorApplication: ContinueWith -> delayCall callback

        EditorApplication->>MCPForUnityEditorWindow: Invoke UI update callback
        MCPForUnityEditorWindow->>MCPForUnityEditorWindow: updateCheckInFlight = false
        alt window or UI elements destroyed
            MCPForUnityEditorWindow-->>User: Return (no UI update)
        else
            alt result indicates update available
                MCPForUnityEditorWindow->>MCPForUnityEditorWindow: Set updateNotificationText
                MCPForUnityEditorWindow->>MCPForUnityEditorWindow: Show updateNotification
            else
                MCPForUnityEditorWindow->>MCPForUnityEditorWindow: Hide updateNotification
            end
        end
    end
Loading

Class diagram for PackageUpdateService and TimeoutWebClient changes

classDiagram
    class MCPForUnityEditorWindow {
        -bool toolsLoaded
        -bool resourcesLoaded
        -double lastRefreshTime
        -const double RefreshDebounceSeconds
        -bool updateCheckQueued
        -bool updateCheckInFlight
        +void QueueUpdateCheck()
        +void CheckForPackageUpdates()
    }

    class PackageUpdateService {
        -const int DefaultRequestTimeoutMs
        -string LastCheckDateKey
        -string CachedVersionKey
        -string LastBetaCheckDateKey
        +string FetchLatestVersionFromGitHub(string branch)
        +string FetchLatestVersionFromAssetStoreJson()
        +WebClient CreateWebClient()
        +int GetRequestTimeoutMs()
    }

    class TimeoutWebClient {
        -int _timeoutMs
        +TimeoutWebClient(int timeoutMs)
        +WebRequest GetWebRequest(Uri address)
    }

    MCPForUnityEditorWindow --> PackageUpdateService : uses
    PackageUpdateService o-- TimeoutWebClient : creates
    TimeoutWebClient --|> WebClient
Loading

Flow diagram for update check queuing and in-flight guard

flowchart TD
    A[QueueUpdateCheck called] --> B{updateCheckQueued<br/>or updateCheckInFlight}

    B -- yes --> C[Return without queuing]
    B -- no --> D[Set updateCheckQueued = true]
    D --> E[EditorApplication.delayCall += CheckForPackageUpdates]

    E --> F[CheckForPackageUpdates invoked]
    F --> G[Set updateCheckQueued = false]
    G --> H{currentVersion is null<br/>empty or unknown}

    H -- yes --> I[Hide updateNotification]
    I --> J[Return]

    H -- no --> K[Set updateCheckInFlight = true]
    K --> L["Task.Run(CheckForUpdate)"]
    L --> M[Background CheckForUpdate completes]
    M --> N[EditorApplication.delayCall UI callback]

    N --> O[Set updateCheckInFlight = false]
    O --> P{window or UI destroyed}

    P -- yes --> Q[Return]
    P -- no --> R{Update available<br/>and check succeeded}

    R -- yes --> S[Set updateNotificationText<br/>and tooltip]
    S --> T[Show updateNotification]
    R -- no --> U[Hide updateNotification]

    T --> V[End]
    U --> V[End]
Loading

File-Level Changes

Change Details Files
Move editor window package update check off the Unity main thread and prevent concurrent/duplicate checks while preserving UI behavior.
  • Add updateCheckInFlight flag to track active background update checks and extend QueueUpdateCheck guard to skip when a check is already running.
  • Refactor CheckForPackageUpdates to start MCPServiceLocator.Updates.CheckForUpdate in a Task.Run with try/catch, logging and treating failures as no-update cases.
  • Use ContinueWith plus EditorApplication.delayCall to marshal completion back to the main thread, clear updateCheckInFlight, validate window/UI elements are still valid, and then update or hide the notification banner based on the result.
MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs
Introduce a timeout-configured WebClient for remote version fetches to bound network latency for GitHub and Asset Store update checks.
  • Add DefaultRequestTimeoutMs constant and a GetRequestTimeoutMs virtual method to centralize timeout configuration.
  • Replace direct WebClient instantiations in FetchLatestVersionFromGitHub and FetchLatestVersionFromAssetStoreJson with a new CreateWebClient factory method.
  • Implement TimeoutWebClient subclass that sets Timeout and ReadWriteTimeout on the underlying WebRequest/HttpWebRequest to enforce the configured request timeout.
MCPForUnity/Editor/Services/PackageUpdateService.cs

Possibly linked issues

  • #(none provided): PR makes CheckForPackageUpdates non-blocking with timeouts and in-flight guards, directly mitigating the frequent-freeze issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

📝 Walkthrough

Walkthrough

The pull request refactors HTTP client creation in PackageUpdateService by introducing a centralized factory method with configurable request timeout handling, and updates MCPForUnityEditorWindow to execute update checks asynchronously while preventing concurrent executions through gating logic, deferring UI mutations back to the editor thread.

Changes

Cohort / File(s) Summary
HTTP Client Timeout Management
MCPForUnity/Editor/Services/PackageUpdateService.cs
Centralizes WebClient creation via CreateWebClient() factory method; introduces DefaultRequestTimeoutMs constant (3000ms) and TimeoutWebClient subclass that overrides GetWebRequest to enforce request/read-write timeouts; adds overridable GetRequestTimeoutMs() hook.
Asynchronous Update Check Execution
MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs
Converts synchronous CheckForPackageUpdates() to async via Task.Run; adds updateCheckInFlight flag to prevent overlapping executions; defers UI mutations (updateNotification/updateNotificationText) to editor thread via EditorApplication.delayCall; handles task failures gracefully by returning null instead of throwing.

Sequence Diagram

sequenceDiagram
    participant UI as EditorWindow UI
    participant Gate as Update Check Gate
    participant Task as Task Executor
    participant Service as PackageUpdateService
    participant Web as TimeoutWebClient

    UI->>Gate: QueueUpdateCheck()
    alt updateCheckQueued or updateCheckInFlight?
        Gate-->>UI: Return (blocked)
    else Proceed
        Gate->>Gate: Set updateCheckQueued/inFlight = true
        Gate->>Task: Task.Run(CheckForPackageUpdates)
        Task->>Service: CheckForUpdate()
        Service->>Service: FetchLatestVersionFromGitHub/AssetStore
        Service->>Web: CreateWebClient() + Execute Request
        Web->>Web: Override GetWebRequest (set Timeout)
        Web-->>Service: Response
        Service-->>Task: Update result
        Task->>UI: EditorApplication.delayCall
        UI->>UI: Update UI (updateNotification)
        UI->>Gate: Clear updateCheckInFlight
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Async hops where blocks once stood,
Timeouts tick as they should,
No overlapping queues—just grace,
UI waits in its safe place,
Factory builds clients with care—
Updates fly through the air!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change—moving editor window update checks off the blocking main thread, which is the primary performance objective.
Description check ✅ Passed The description covers the key changes (async execution, network timeouts, deduplication), validation steps, and bug fixes, but lacks explicit sections matching the template structure (Type of Change, Changes Made format, etc.).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

Migrating from UI to YAML configuration.

Use the @coderabbitai configuration command in a PR comment to get a dump of all your UI settings in YAML format. You can then edit this YAML file and upload it to the root of your repository to configure CodeRabbit programmatically.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • In CheckForPackageUpdates, updateCheckInFlight is only reset inside the delayed UI callback and after the this/updateNotification null checks, so if the window is closed or the notification elements are null, the method returns early and leaves updateCheckInFlight stuck true, preventing future update checks; move the reset before those early returns (or ensure it's done in a finally-style path) so the flag is always cleared.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `CheckForPackageUpdates`, `updateCheckInFlight` is only reset inside the delayed UI callback and after the `this/updateNotification` null checks, so if the window is closed or the notification elements are null, the method returns early and leaves `updateCheckInFlight` stuck `true`, preventing future update checks; move the reset before those early returns (or ensure it's done in a `finally`-style path) so the flag is always cleared.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs`:
- Around line 382-387: The CheckForUpdate call currently runs on a worker thread
and therefore performs unsafe EditorPrefs access and lazy initialization of
MCPServiceLocator.Updates off the main thread; instead, ensure
MCPServiceLocator.Updates is accessed on the editor thread and read any
EditorPrefs cache (EditorPrefs.GetString/SetString) on the main thread before
starting background work, then call Task.Run only to execute the network methods
(FetchLatestVersionFromGitHub / FetchLatestVersionFromAssetStoreJson) using the
cached values as parameters; finally, marshal the result back with
EditorApplication.delayCall and perform any EditorPrefs writes or
MCPServiceLocator.Updates lazy initialization there.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 446a5176-1e3f-446d-885d-6673965b9e4a

📥 Commits

Reviewing files that changed from the base of the PR and between ec25df8 and b050907.

📒 Files selected for processing (2)
  • MCPForUnity/Editor/Services/PackageUpdateService.cs
  • MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs

Comment on lines +382 to +387
Task.Run(() =>
{
try
{
return MCPServiceLocator.Updates.CheckForUpdate(currentVersion);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the background-thread call path and UnityEditor API usage.
rg -n "Task.Run|CheckForPackageUpdates|CheckForUpdate\\(" MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs -C 3
rg -n "EditorPrefs\\.(GetString|SetString|DeleteKey)" MCPForUnity/Editor/Services/PackageUpdateService.cs -C 2
rg -n "public static IPackageUpdateService Updates =>" MCPForUnity/Editor/Services/MCPServiceLocator.cs -C 2

Repository: CoplayDev/unity-mcp

Length of output: 2267


🏁 Script executed:

# Get the full implementation of CheckForUpdate to see all code paths
rg -n "public.*CheckForUpdate" MCPForUnity/Editor/Services/PackageUpdateService.cs -A 50

Repository: CoplayDev/unity-mcp

Length of output: 2529


🏁 Script executed:

# Check if there's any thread-safety or main-thread queuing already in place
rg -n "EditorApplication\.(delayCall|update)" MCPForUnity/Editor/Services/PackageUpdateService.cs

Repository: CoplayDev/unity-mcp

Length of output: 45


🏁 Script executed:

# Verify the full context of the Task.Run usage in the editor window
cat -n MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs | sed -n '365,400p'

Repository: CoplayDev/unity-mcp

Length of output: 1525


Move EditorPrefs access to the editor thread; only run network I/O on background threads.

Task.Run at line 382 executes MCPServiceLocator.Updates.CheckForUpdate(...) on a worker thread. That method calls EditorPrefs.GetString(...) unconditionally at lines 42–43 (before any network I/O), which is not thread-safe. Additionally, the lazy initialization of MCPServiceLocator.Updates at line 29 happens on the worker thread on first access.

While the result processing correctly uses EditorApplication.delayCall to queue back to the main thread (line 395), the EditorPrefs calls have already executed unsafely. Refactor to read/write the editor cache on the main thread and move only the network fetch (FetchLatestVersionFromGitHub / FetchLatestVersionFromAssetStoreJson) to the background thread.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@MCPForUnity/Editor/Windows/MCPForUnityEditorWindow.cs` around lines 382 -
387, The CheckForUpdate call currently runs on a worker thread and therefore
performs unsafe EditorPrefs access and lazy initialization of
MCPServiceLocator.Updates off the main thread; instead, ensure
MCPServiceLocator.Updates is accessed on the editor thread and read any
EditorPrefs cache (EditorPrefs.GetString/SetString) on the main thread before
starting background work, then call Task.Run only to execute the network methods
(FetchLatestVersionFromGitHub / FetchLatestVersionFromAssetStoreJson) using the
cached values as parameters; finally, marshal the result back with
EditorApplication.delayCall and perform any EditorPrefs writes or
MCPServiceLocator.Updates lazy initialization there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant