Skip to content

fix: Unity 2021.3 compat — compile errors, Mono crash, 19 test failures#1036

Merged
dsarno merged 4 commits intoCoplayDev:betafrom
dsarno:fix/profiler-unity-version-compat
Apr 6, 2026
Merged

fix: Unity 2021.3 compat — compile errors, Mono crash, 19 test failures#1036
dsarno merged 4 commits intoCoplayDev:betafrom
dsarno:fix/profiler-unity-version-compat

Conversation

@dsarno
Copy link
Copy Markdown
Collaborator

@dsarno dsarno commented Apr 4, 2026

Context: CI has been red for 39 days

Unity Tests CI has not passed since February 24, 2026 — over 5 weeks and 36 feature/fix PRs ago (107 total merges including automated version bumps). Python Tests last passed on March 27. During this period, compile errors, a runtime crash, and test regressions accumulated undetected.

Going forward, it would help the project to confirm that both Python and Unity tests pass (including any new coverage the PR introduces) before merging. When CI is red, regressions compound silently — this PR fixes 19 test failures and a Unity-crashing segfault that were all introduced incrementally across many PRs.

What this PR fixes

Compile errors on Unity 2021.3 (7 errors)

The profiler tools (FrameTimingOps.cs, CounterOps.cs) used APIs added in Unity 2022.2 without version guards, while package.json declares minimum version 2021.3.

API Fix
FrameTimingManager.IsFeatureEnabled() #if UNITY_2022_2_OR_NEWER
FrameTiming.cpuMainThreadFrameTime (+ 4 related fields) #if UNITY_2022_2_OR_NEWER
ProfilerCategory.Physics2D #if UNITY_2022_2_OR_NEWER

Mono segfault crashing Unity (fatal)

UnityReflect.GetTypeInfo() called GetGenericArguments(), GetInterfaces(), and member reflection on open generic type definitions (List<T>, Dictionary<TKey,TValue>). This triggers a segfault in mono_metadata_generic_param_equal_internal on Unity 2021.3 Mono — crashing the editor on every full test run.

Fix: Early return with minimal type info (name, namespace, assembly) for IsGenericTypeDefinition types, avoiding all Mono metadata operations that trigger the crash.

Test failures (19 fixed)

Category Count Root cause Fix
ErrorResponse field mismatch 8 Tests read result["message"] but ErrorResponse serializes as "error" Changed to result["error"] in ManageGraphics, Screenshot, MultiScene tests
UXML attribute injection 7 EnsureEditorExtensionMode() injects editor-extension-mode="False" into UXML; tests expected exact match Relaxed assertions to Does.Contain; added LogAssert.ignoreFailingMessages for expected UXML importer errors; used proper xmlns declarations
UnityReflect ambiguity 2 Transform ambiguous with log4net.Util.Transform Use fully qualified UnityEngine.Transform
GUID shorthand resolution 1 ComponentOps.SetObjectReference handled instance IDs, paths, and scene names but not 32-char hex GUIDs Added GUID resolution via AssetDatabase.GUIDToAssetPath before scene name fallback
CLI test 1 test_prefab_workflow_open_modify_save passed --force to prefab save which has no such flag Removed --force
Physics raycast 1 Leftover scene object at origin intercepted the test raycast Offset raycast origin to (500,500,0)
ProBuilder guard 1 ProBuilder not-installed check runs before action dispatch Accept either "Unknown action" or "not installed"
Pipeline settings 1 PipelineGetSettings expects success but built-in pipeline has no asset Skip with Assume.That when no URP/HDRP

Bug fix: GUID shorthand in object references

ComponentOps.SetObjectReference now resolves plain 32-character hex GUID strings to assets via AssetDatabase.GUIDToAssetPath. This was a missing code path — the JSON deserializer (UnityTypeConverters) already handled GUIDs, but the SerializedProperty patch handler did not.

Test results after this PR

  • Python: 1210/1210 passed
  • Unity: 900/900 — 835 passed, 0 failed, 47 skipped, 18 inconclusive (missing optional packages like URP/ProBuilder)
  • Crashes: 0

Test plan

  • cd Server && uv run pytest tests/ -v — 1210 passed
  • Run full EditMode test suite via MCP on Unity 2021.3.45f2 — 900/900, 0 failures, 0 crashes
  • Verify no compile errors on Unity 2021.3
  • Verify UnityReflect generic type resolution does not crash
  • Verify GUID shorthand resolves in ScriptableObject patches

🤖 Generated with Claude Code

Summary by Sourcery

Restore compatibility and stability on Unity 2021.3 by guarding newer profiler APIs, preventing Mono crashes in reflection utilities, and aligning tests and helpers with current engine and tooling behavior.

Bug Fixes:

  • Prevent Mono crashes in Unity 2021.3 by returning minimal type info for open generic types in UnityReflect.
  • Fix object reference patching to support 32-character GUID strings when resolving assets in ComponentOps.
  • Guard Unity profiler counters and frame timing fields that only exist in Unity 2022.2+ to avoid compilation errors on Unity 2021.3.
  • Adjust physics raycast tests to avoid unintended collisions with existing scene objects.
  • Make ProBuilder command tests accept both 'unknown action' and 'not installed' error messages depending on environment.
  • Skip pipeline settings tests when running with the built-in render pipeline that has no settings asset.

Enhancements:

  • Relax UXML-related ManageUI tests to tolerate Unity injecting editor-extension attributes while still validating key content.
  • Use fully qualified UnityEngine.Transform type names in reflection tests to avoid ambiguity with other libraries.
  • Add a helper to detect hex strings when interpreting potential GUIDs for object reference resolution.

Tests:

  • Update graphics, screenshot, multiscene, and other tool tests to assert against the standard 'error' field instead of the deprecated 'message' field in error responses.
  • Adjust ManageUI tests to use proper UXML namespace declarations and to ignore expected importer log errors that would otherwise fail tests.
  • Update CLI prefab workflow tests to match the current prefab save command-line interface without unsupported flags.

Summary by CodeRabbit

  • New Features

    • Resolve string asset GUIDs when assigning object references.
  • Bug Fixes

    • Safer handling for open generic types in reflection responses.
    • Avoided errors when member/type queries target generic type definitions.
  • Improvements

    • Additional profiler timing fields and conditional Physics2D category on Unity 2022.2+.
  • Tests

    • Standardized error field checks, relaxed several UXML assertions, HDRP capability flag added, and adjusted prefab/test inputs and positions.

dsarno and others added 3 commits April 4, 2026 14:58
…st fixes

- Add #if UNITY_2022_2_OR_NEWER guards for FrameTimingManager.IsFeatureEnabled,
  FrameTiming detailed fields, and ProfilerCategory.Physics2D
- Skip member reflection on open generic types (List<T>, Dictionary<TKey,TValue>)
  to avoid Mono segfault in mono_metadata_generic_param_equal_internal on 2021.3
- Fix UnityReflectTests to use FQN for Transform (ambiguous with log4net)
- Fix CLI characterization test passing non-existent --force flag to prefab save

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix ErrorResponse field mismatch: tests reading "message" on ErrorResponse
  which serializes as "error" (ManageGraphics, Screenshot, MultiScene tests)
- Fix ManageUITests: account for EnsureEditorExtensionMode injecting
  editor-extension-mode attribute; expect UXML importer errors with LogAssert
- Fix ManageGraphicsTests: skip PipelineGetSettings on built-in pipeline
- Fix ManageProBuilderTests: accept "not installed" when ProBuilder absent
- Fix ManagePhysicsTests: offset raycast to avoid hitting unrelated scene objects
- Use proper UXML content with xmlns declarations in UI tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
ComponentOps.SetObjectReference handled instance IDs, asset paths, and scene
names but not plain 32-char hex GUID strings. Add GUID resolution via
AssetDatabase.GUIDToAssetPath before falling back to scene object lookup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Apr 4, 2026

Reviewer's Guide

Restores green CI on Unity 2021.3 by adding missing Unity-version guards around newer profiler APIs, preventing a Mono crash in UnityReflect’s type inspection for open generic types, fixing 19 test failures (mainly error-field expectations and UXML assertions), and adding GUID shorthand resolution when setting SerializedProperty object references.

Sequence diagram for GUID shorthand resolution in SetObjectReference

sequenceDiagram
    actor User
    participant Server
    participant ComponentOps
    participant AssetDatabase

    User->>Server: Submit_patch_with_object_reference_value
    Server->>ComponentOps: SetObjectReference(prop, value, context, out_error)

    alt value_is_string
        alt resolved_by_existing_instance_id_or_path
            ComponentOps->>ComponentOps: AssignObjectReference(prop, resolved, context, out_error)
            ComponentOps-->>Server: return_true
        else not_resolved_yet
            alt length_32_and_IsHexString
                ComponentOps->>AssetDatabase: GUIDToAssetPath(strVal)
                alt asset_path_found
                    ComponentOps->>AssetDatabase: LoadAssetAtPath(assetPath)
                    alt resolved_not_null
                        ComponentOps->>ComponentOps: AssignObjectReference(prop, resolved, context, out_error)
                        ComponentOps-->>Server: return_true
                    else resolved_null
                        ComponentOps->>ComponentOps: ResolveSceneObjectByName(prop, strVal, context, out_error)
                        ComponentOps-->>Server: return_result
                    end
                else no_asset_path
                    ComponentOps->>ComponentOps: ResolveSceneObjectByName(prop, strVal, context, out_error)
                    ComponentOps-->>Server: return_result
                end
            else not_guid_like
                ComponentOps->>ComponentOps: ResolveSceneObjectByName(prop, strVal, context, out_error)
                ComponentOps-->>Server: return_result
            end
        end
    else value_not_string
        ComponentOps-->>Server: handle_non_string_value_unmodified
    end

    Server-->>User: Patch_result
Loading

Updated class diagram for ComponentOps and UnityReflect changes

classDiagram
    class ComponentOps {
        +bool SetObjectReference(SerializedProperty prop, JToken value, object context, out string error)
        +bool AssignObjectReference(SerializedProperty prop, UnityEngine_Object resolved, object context, out string error)
        +bool ResolveSceneObjectByName(SerializedProperty prop, string name, object context, out string error)
        -long GetSpriteFileId(Sprite sprite)
        -bool IsHexString(string str)
    }

    class UnityReflect {
        +object GetTypeInfo(ToolParams p)
    }

    class SuccessResponse {
        +SuccessResponse(string message, object data)
    }

    class AssetDatabase {
        +string GUIDToAssetPath(string guid)
        +UnityEngine_Object LoadAssetAtPath~UnityEngine_Object~(string assetPath)
    }

    class System_Type {
        +bool IsGenericTypeDefinition
        +string Name
        +string FullName
        +string Namespace
        +System_Reflection_Assembly Assembly
    }

    class System_Reflection_Assembly {
        +System_Reflection_AssemblyName GetName()
    }

    class System_Reflection_AssemblyName {
        +string Name
    }

    ComponentOps ..> AssetDatabase : uses
    UnityReflect ..> SuccessResponse : returns
    UnityReflect ..> System_Type : inspects
    System_Type ..> System_Reflection_Assembly : uses
    System_Reflection_Assembly ..> System_Reflection_AssemblyName : returns
Loading

Flow diagram for FrameTimingOps.GetFrameTiming with Unity version guards

flowchart TD
    Start([GetFrameTiming_called]) --> CheckFeature{UNITY_2022_2_OR_NEWER_and_feature_check}
    CheckFeature -- feature_disabled_on_2022_2_or_newer --> Error[Return_ErrorResponse_about_enabling_Frame_Timing_Stats]
    CheckFeature -- feature_enabled_or_pre_2022_2 --> Capture[FrameTimingManager.CaptureFrameTimings]

    Capture --> Alloc[Allocate_single_element_FrameTiming_array]
    Alloc --> Query[FrameTimingManager.GetLatestTimings]
    Query --> HasData{timings_length_greater_than_zero}

    HasData -- no --> NoData[Return_response_with_available_false]
    HasData -- yes --> Read[Read_first_FrameTiming_t]

    Read --> BaseFields[Set_base_fields:
    cpu_frame_time_ms,
    gpu_frame_time_ms,
    cpu_time_present_called,
    cpu_time_frame_complete,
    height_scale,
    width_scale]

    BaseFields --> NewerFields{UNITY_2022_2_OR_NEWER}

    NewerFields -- yes --> ExtraFields[Also_set_fields:
    cpu_main_thread_frame_time_ms,
    cpu_main_thread_present_wait_time_ms,
    cpu_render_thread_frame_time_ms,
    frame_start_timestamp,
    first_submit_timestamp]
    NewerFields -- no --> SkipExtra[Skip_additional_timing_fields]

    ExtraFields --> ReturnSuccess[Return_SuccessResponse_with_timing_data]
    SkipExtra --> ReturnSuccess
    NoData --> ReturnSuccess
Loading

File-Level Changes

Change Details Files
Relax UXML content assertions and handle expected importer warnings in ManageUI tests to be robust to editor-extension-mode attribute injection.
  • Replace exact string equality checks on generated UXML files with substring containment assertions for key elements and namespaces.
  • Use proper xmlns declarations in UXML test content to reflect real UIElements usage.
  • Wrap tests that intentionally trigger UXML importer errors with LogAssert.ignoreFailingMessages on/off to ignore expected Unity error logs.
  • Adjust malformed-XML test to assert preservation via key content presence/absence rather than full file equality.
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs
Support 32-character GUID shorthand when setting object reference SerializedProperties so JSON patches can refer to assets by GUID string.
  • Detect 32-character hex-only strings when interpreting string object-reference values.
  • Resolve such GUIDs to asset paths via AssetDatabase.GUIDToAssetPath.
  • Load the asset at the resolved path and assign it via existing AssignObjectReference helper if found.
  • Introduce a small IsHexString utility to validate candidate GUID strings.
MCPForUnity/Editor/Helpers/ComponentOps.cs
Avoid Unity 2021.3 Mono segfaults when reflecting over open generic types in UnityReflect by short-circuiting with minimal type info.
  • Detect type.IsGenericTypeDefinition in GetTypeInfo.
  • Return a SuccessResponse with basic metadata (name, namespace, assembly, full_name) and a flag indicating generic type definitions.
  • Avoid calling GetGenericArguments or enumerating members for open generic types to prevent Mono crashes on 2021.3.
  • Add a hint field explaining that open generic types omit member details.
MCPForUnity/Editor/Tools/UnityReflect.cs
Align tests with ErrorResponse serialization ("error" field) and make tests more resilient to environment-specific graphics/pipeline configuration.
  • Update tests that previously asserted against result["message"] to check result["error"] instead for various tools (ManageGraphics, Screenshot, MultiScene).
  • Introduce HDRP presence tracking in ManageGraphicsTests setup and use Assume.That to skip PipelineGetSettings when neither URP nor HDRP is present.
  • Broaden ProBuilder unknown-action test to accept either an "Unknown action" error or a "not installed" error depending on environment.
  • Adjust UnityReflect tests to reference UnityEngine.Transform explicitly to avoid ambiguity with log4net.Transform.
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageGraphicsTests.cs
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageSceneHierarchyPagingTests.cs
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageSceneMultiSceneTests.cs
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageProBuilderTests.cs
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityReflectTests.cs
Add Unity 2021.3 compatibility guards around newer profiler APIs used by CounterOps and FrameTimingOps.
  • Wrap usage of ProfilerCategory.Physics2D and its category name in UNITY_2022_2_OR_NEWER defines to avoid compile errors on 2021.3.
  • Guard FrameTimingManager.IsFeatureEnabled and newer FrameTiming fields (main-thread times and timestamps) with UNITY_2022_2_OR_NEWER while still exposing compatible fields on older versions.
  • Keep overall API shape and response object stable while conditionally omitting fields that don’t exist on older Unity versions.
MCPForUnity/Editor/Tools/Profiler/Operations/CounterOps.cs
MCPForUnity/Editor/Tools/Profiler/Operations/FrameTimingOps.cs
Stabilize physics and CLI characterization tests to avoid environment-related flakiness and invalid flag usage.
  • Move physics raycast test objects to an offset position and adjust ray origin accordingly to avoid collisions with unrelated scene objects at the origin.
  • Remove unsupported --force flag from prefab save CLI test step so it matches the actual command-line interface.
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManagePhysicsTests.cs
Server/tests/test_cli_commands_characterization.py

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
Copy Markdown
Contributor

coderabbitai bot commented Apr 4, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 895548bc-ea1f-4548-a109-442e8f02d487

📥 Commits

Reviewing files that changed from the base of the PR and between 2d08ded and 17dd7fb.

📒 Files selected for processing (2)
  • MCPForUnity/Editor/Tools/UnityReflect.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs
✅ Files skipped from review due to trivial changes (1)
  • MCPForUnity/Editor/Tools/UnityReflect.cs
🚧 Files skipped from review as they are similar to previous changes (1)
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs

📝 Walkthrough

Walkthrough

Adds GUID-string → asset resolution to object-reference deserialization, gates Physics2D and additional frame-timing fields behind UNITY_2022_2_OR_NEWER, returns early for open generic type definitions in reflection helpers, and standardizes/relaxes multiple test assertions (error field usage and UXML resilience).

Changes

Cohort / File(s) Summary
Component reference resolution
MCPForUnity/Editor/Helpers/ComponentOps.cs
SetObjectReference now accepts 32‑char hex GUID strings, validates via IsHexString, converts with AssetDatabase.GUIDToAssetPath, attempts to load the asset, and assigns if found.
Profiler operations (Unity 2022.2+ guards)
MCPForUnity/Editor/Tools/Profiler/Operations/CounterOps.cs, MCPForUnity/Editor/Tools/Profiler/Operations/FrameTimingOps.cs
Moved Physics2D category and several frame-timing fields / feature checks behind #if UNITY_2022_2_OR_NEWER.
Reflection safety for open generics
MCPForUnity/Editor/Tools/UnityReflect.cs
Early-return when type.IsGenericTypeDefinition in GetTypeInfo and GetMemberInfo, returning basic metadata / not-found without enumerating members.
UXML & UI tests — resilience and logging
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs
Loosened exact-content assertions to substring checks, added namespace-qualified UXML inputs, and suppressed failing Unity logs during validation checks.
Standardize error-field reads across tests
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/...
Multiple tests now read failure text from result["error"] (with fallback) instead of result["message"]; updated assertions accordingly (ManageGraphicsTests, ManageProBuilderTests, ManageSceneHierarchyPagingTests, ManageSceneMultiSceneTests).
Graphics test updates
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageGraphicsTests.cs
Added _hasHDRP capability flag and gated pipeline settings test to run only when URP or HDRP present.
Physics test coordinate change
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManagePhysicsTests.cs
Shifted test object and raycast origin to (500,500,*) to avoid scene interference.
CLI test tweak
Server/tests/test_cli_commands_characterization.py
Removed --force from prefab save command invocation; test expects success without forcing.
Reflection tests — type qualification
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityReflectTests.cs
Switched test inputs from Transform to fully qualified UnityEngine.Transform.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

bug

Poem

🐰 I nibbled GUIDs in moonlit code,
Found lost assets down the node,
Tests grew kinder, warnings tame,
Generics wear a safety name,
Hopping home with one small ode. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.95% 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 'fix: Unity 2021.3 compat — compile errors, Mono crash, 19 test failures' directly and concisely summarizes the main changes in the PR: addressing Unity 2021.3 compatibility issues including compile errors, a critical Mono crash, and test failures.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering context, detailed fixes across multiple categories, test results, and a clear test plan. It aligns with and exceeds the template requirements by providing specific information about what was broken and how it was fixed.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown
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 found 1 issue, and left some high level feedback:

  • In the UXML tests where you toggle LogAssert.ignoreFailingMessages, consider wrapping the command invocation in a try/finally block to ensure the flag is always restored to its previous value even if an assertion fails or an exception is thrown.
  • The updated UXML content assertions in ManageUITests now only check for a couple of substrings; to keep these tests effective at catching unintended changes, you might want to normalize out the injected editor-extension-mode attribute (e.g., via a small helper) and still perform a stronger comparison on the full content.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the UXML tests where you toggle `LogAssert.ignoreFailingMessages`, consider wrapping the command invocation in a `try/finally` block to ensure the flag is always restored to its previous value even if an assertion fails or an exception is thrown.
- The updated UXML content assertions in `ManageUITests` now only check for a couple of substrings; to keep these tests effective at catching unintended changes, you might want to normalize out the injected `editor-extension-mode` attribute (e.g., via a small helper) and still perform a stronger comparison on the full content.

## Individual Comments

### Comment 1
<location path="TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs" line_range="686-691" />
<code_context>
             string path = $"{TempRoot}/NoNs_{Guid.NewGuid():N}.uxml";
             string content = "<ui:UXML><ui:Label text=\"hi\" /></ui:UXML>";

+            // Unity's UXML importer logs an error for undeclared 'ui' prefix
+            LogAssert.ignoreFailingMessages = true;
+
</code_context>
<issue_to_address>
**issue (testing):** Avoid globally flipping LogAssert.ignoreFailingMessages without a try/finally to prevent leaking state across tests

In this and the `Create_WrongRootElement_WritesWithWarning` test, `LogAssert.ignoreFailingMessages` is set to `true` and later reset without `try/finally`. If the test throws before the reset, the flag remains `true` and may hide real failures in other tests. Wrap the change in a `try`/`finally`, or preferably use `LogAssert.Expect` for the specific expected errors instead of globally ignoring failing messages.
</issue_to_address>

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
Copy Markdown
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

🧹 Nitpick comments (2)
MCPForUnity/Editor/Tools/Profiler/Operations/CounterOps.cs (1)

123-151: Consider unifying category-resolution behavior across profiler tools.

CounterOps.ResolveCategory fails unknown categories explicitly, while MCPForUnity/Editor/Tools/Graphics/RenderingStatsOps.cs currently falls back to ProfilerCategory.Render (Lines 147-169 in that file). A shared resolver (or consistent error policy) would reduce drift and surprising behavior.

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

In `@MCPForUnity/Editor/Tools/Profiler/Operations/CounterOps.cs` around lines 123
- 151, Extract the category-resolution logic into a single shared helper (e.g.,
a new static ProfilerCategoryResolver.Resolve(string name, out string error)
that contains the mapping now in CounterOps.ResolveCategory and exposes
ValidCategories), then change both CounterOps.ResolveCategory to delegate to
that helper and update RenderingStatsOps to call the same helper (remove its
hard fallback to ProfilerCategory.Render) so both tools use the same resolution
and error policy; ensure you preserve the existing error string format using
ValidCategories and keep the same conditional compilation entries like
Physics2D.
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs (1)

3-3: Remove unused import.

System.Text.RegularExpressions is imported but never used in this file.

Proposed cleanup
-using System.Text.RegularExpressions;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs` at
line 3, Remove the unused using directive "using
System.Text.RegularExpressions;" from ManageUITests.cs in the
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools namespace (the file
containing the ManageUITests class) so there are no unused imports; simply
delete that using line and save the file to eliminate the unused reference.
🤖 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/Tools/UnityReflect.cs`:
- Around line 173-191: GetMemberInfo currently performs member reflection even
for open generic types and can trigger the Mono segfault; add the same
IsGenericTypeDefinition guard used in GetTypeInfo at the start of GetMemberInfo
so that if type.IsGenericTypeDefinition is true it returns a minimal
SuccessResponse (include found=true, name, full_name, `@namespace`, assembly,
is_generic_type_definition=true and a hint) without calling GetGenericArguments
or enumerating members; reference the GetMemberInfo method and mirror the
guard/response structure used in GetTypeInfo to keep behavior consistent.

---

Nitpick comments:
In `@MCPForUnity/Editor/Tools/Profiler/Operations/CounterOps.cs`:
- Around line 123-151: Extract the category-resolution logic into a single
shared helper (e.g., a new static ProfilerCategoryResolver.Resolve(string name,
out string error) that contains the mapping now in CounterOps.ResolveCategory
and exposes ValidCategories), then change both CounterOps.ResolveCategory to
delegate to that helper and update RenderingStatsOps to call the same helper
(remove its hard fallback to ProfilerCategory.Render) so both tools use the same
resolution and error policy; ensure you preserve the existing error string
format using ValidCategories and keep the same conditional compilation entries
like Physics2D.

In `@TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs`:
- Line 3: Remove the unused using directive "using
System.Text.RegularExpressions;" from ManageUITests.cs in the
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools namespace (the file
containing the ManageUITests class) so there are no unused imports; simply
delete that using line and save the file to eliminate the unused reference.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ce6b3c9f-fa93-4ca1-b452-1c6946dc9227

📥 Commits

Reviewing files that changed from the base of the PR and between 1f0ef2c and 016045f.

📒 Files selected for processing (12)
  • MCPForUnity/Editor/Helpers/ComponentOps.cs
  • MCPForUnity/Editor/Tools/Profiler/Operations/CounterOps.cs
  • MCPForUnity/Editor/Tools/Profiler/Operations/FrameTimingOps.cs
  • MCPForUnity/Editor/Tools/UnityReflect.cs
  • Server/tests/test_cli_commands_characterization.py
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageGraphicsTests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManagePhysicsTests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageProBuilderTests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageSceneHierarchyPagingTests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageSceneMultiSceneTests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageUITests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/UnityReflectTests.cs

- Add IsGenericTypeDefinition guard in GetMemberInfo (CodeRabbit) — same
  Mono crash path as GetTypeInfo, just not hit by current tests
- Wrap LogAssert.ignoreFailingMessages in try/finally (Sourcery) — prevents
  state leak if test throws before reset
- Remove unused System.Text.RegularExpressions import (CodeRabbit)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@dsarno dsarno force-pushed the fix/profiler-unity-version-compat branch from 2d08ded to 17dd7fb Compare April 5, 2026 02:25
@dsarno dsarno merged commit a346558 into CoplayDev:beta Apr 6, 2026
2 checks passed
@dsarno dsarno deleted the fix/profiler-unity-version-compat branch April 6, 2026 02:42
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