Skip to content

fix(read_console): force console severity flags ON to bypass UI filter (silent 0 entries)#1252

Open
beast-ofcourse wants to merge 1 commit into
CoplayDev:betafrom
beast-ofcourse:fix/readconsole-console-filter-flags
Open

fix(read_console): force console severity flags ON to bypass UI filter (silent 0 entries)#1252
beast-ofcourse wants to merge 1 commit into
CoplayDev:betafrom
beast-ofcourse:fix/readconsole-console-filter-flags

Conversation

@beast-ofcourse

@beast-ofcourse beast-ofcourse commented Jul 7, 2026

Copy link
Copy Markdown

Problem

read_console silently returns success: true with zero entries whenever the Unity Console window's severity toggle buttons (Log / Warning / Error counters in the Console toolbar) are switched off — even for freshly logged messages, and even though logs are plainly in Editor.log. The tool succeeds, so an agent concludes the console is clean — worst case right after a compile, where it happily proceeds on broken state.

Fixes #1239

Root Cause

GetConsoleEntries calls LogEntries.StartGettingEntries(), which respects the Console window's consoleFlags bits:

  • LogLevelLog = 1 << 7 (128)
  • LogLevelWarning = 1 << 8 (256)
  • LogLevelError = 1 << 9 (512)

With any toggle off, StartGettingEntries() returns 0 entries. The tool has no way to distinguish "console is clean" from "UI is hiding everything."

Solution

Before calling StartGettingEntries, save the current consoleFlags, OR in all three log level bits (forcing them on), and clear the console search filter. After EndGettingEntries (in the finally block), restore the saved flags.

Changes:

  1. Reflect LogEntries.consoleFlags — get/set property to save and restore the severity toggles.
  2. Reflect LogEntries.SetFilteringText — optional method to clear the console search filter (gracefully skipped if absent on older Unity versions).
  3. GetConsoleEntries: Before the try block, save flags and force bits on; in the finally block, restore flags.
  4. Null guard_consoleFlagsProperty added to the static constructor failure check since all log reading depends on it.

Verification

  • The OR operation is idempotent: if flags are already correct, forcedFlags == savedConsoleFlags and the set is a no-op.
  • The restore always runs in the finally block — even if the iteration throws.
  • SetFilteringText is optional; the core fix only requires consoleFlags.
  • No behavioral change when Console toggles are already on (normal case).

Notes

  • The console search filter is cleared without saving because GetFilteringText is not guaranteed to exist across Unity versions. The tool applies its own filterText parameter client-side, so this is a minor UX trade-off — the console search box is cleared after a read_console call.

Summary by CodeRabbit

  • Bug Fixes
    • Console reads now return all log, warning, and error entries more reliably, even when Unity’s console filters are enabled.
    • Search/filter state is cleared during console capture so hidden entries are less likely to be missed.
    • Console severity settings are restored after reading, reducing the chance of leaving the editor in an altered state.

…ntries to bypass UI filter

Unity's internal LogEntries.StartGettingEntries() respects the Console
window's severity toggle buttons (Log/Warning/Error). When a toggle is
off, StartGettingEntries returns 0 entries — even when logs exist in
Editor.log. The read_console tool then silently returns '0 entries',
and the agent cannot distinguish 'console is clean' from 'UI is hiding
everything'.

Fix:
- Reflect LogEntries.consoleFlags property to get/set the severity bits.
- Before StartGettingEntries: save consoleFlags, OR in all three log level
  bits (LogLevelLog=1<<7, LogLevelWarning=1<<8, LogLevelError=1<<9), and
  clear the console search filter via SetFilteringText.
- After EndGettingEntries (in finally): restore the saved consoleFlags.
- SetFilteringText reflection is optional (gracefully skipped if absent);
  consoleFlags is required and added to the null guard.

The override is transparent — the UI toggle position doesn't change and
flags are always restored.

Fixes CoplayDev#1239
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

ReadConsole.cs adds reflection access to Unity's internal console severity flags (consoleFlags) and search filter clearing (SetFilteringText). GetConsoleEntries now saves, overrides, and restores console severity toggles and clears the search filter around entry iteration so all requested entries are returned regardless of Console UI toggle state.

Changes

ReadConsole Severity Filter Fix

Layer / File(s) Summary
Reflection setup for console state
MCPForUnity/Editor/Tools/ReadConsole.cs
New reflection fields for consoleFlags and SetFilteringText are declared, populated in the static initializer, and required by HandleCommand's reflection-completeness guard.
Override and restore severity flags during entry retrieval
MCPForUnity/Editor/Tools/ReadConsole.cs
GetConsoleEntries saves current severity toggles, forces log/warning/error flags and clears the internal search filter before iterating entries, then restores the original flags in a finally block with error logging on failure.

Estimated code review effort: 2 (Simple) | ~12 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ReadConsole
  participant LogEntries

  Client->>ReadConsole: GetConsoleEntries(filterText)
  ReadConsole->>LogEntries: read consoleFlags (save original)
  ReadConsole->>LogEntries: set flags (Log, Warning, Error = true)
  ReadConsole->>LogEntries: SetFilteringText("")
  ReadConsole->>LogEntries: StartGettingEntries / GetEntryInternal
  LogEntries-->>ReadConsole: all entries
  ReadConsole->>LogEntries: EndGettingEntries
  ReadConsole->>LogEntries: restore original consoleFlags
  ReadConsole-->>Client: filtered/paged entries
Loading

Possibly related PRs

  • CoplayDev/unity-mcp#202: Both PRs modify ReadConsole.cs's GetConsoleEntries retrieval flow using StartGettingEntries/EndGettingEntries and reflection-based console state.
  • CoplayDev/unity-mcp#762: Both PRs modify reflection setup/guards around HandleCommand/GetConsoleEntries in the same file.

Suggested labels: `bug`

Suggested reviewers: `jordandunmire97-ai`

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits several required template sections like Type of Change, Testing, and Compatibility. Add the missing template sections, especially Type of Change, Changes Made, Compatibility/Package Source, Testing, and Related Issues.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: forcing console severity flags on to avoid empty read_console results.
Linked Issues check ✅ Passed The PR implements the issue's suggested fix by forcing severity flags on, clearing the filter, and restoring the original flags.
Out of Scope Changes check ✅ Passed The change set stays confined to ReadConsole.cs and directly supports the linked console-filter bug fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@MCPForUnity/Editor/Tools/ReadConsole.cs`:
- Line 149: HandleCommand is rejecting all commands when _consoleFlagsProperty
is null, but clear only depends on _clearMethod. Update the guard logic in
ReadConsole.HandleCommand so the consoleFlagsProperty check is only applied for
the get path, and keep clear available whenever _clearMethod exists, even on
Unity versions without consoleFlags.
- Line 34: The console state mutations in ReadConsole should be scoped together
so cleanup always restores the original state. In the ReadConsole flow, capture
the current filtering text via GetFilteringText before calling
SetFilteringText(""), then move both the filter-text change and the consoleFlags
change into the same try/finally path so any throw still restores both values.
Use the existing helper members around _setFilteringTextMethod,
_getFilteringTextMethod, and the console flag fields to locate and update the
affected logic.
🪄 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: aaba7959-e942-461e-95cb-847a6930ce4e

📥 Commits

Reviewing files that changed from the base of the PR and between 484937c and fa1646d.

📒 Files selected for processing (1)
  • MCPForUnity/Editor/Tools/ReadConsole.cs

private static FieldInfo _fileField;
private static FieldInfo _lineField;
private static PropertyInfo _consoleFlagsProperty;
private static MethodInfo _setFilteringTextMethod;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the target file and related symbols first.
git ls-files 'MCPForUnity/Editor/Tools/ReadConsole.cs' 'MCPForUnity/Editor/Tools/*.cs' 'MCPForUnity/Runtime/Helpers/*.cs' | sed 's#^`#FILE` #'

echo
echo "== AST outline for ReadConsole.cs =="
ast-grep outline MCPForUnity/Editor/Tools/ReadConsole.cs --view expanded || true

echo
echo "== Relevant symbol search =="
rg -n "_consoleFlagsProperty|_setFilteringTextMethod|GetFilteringText|SetFilteringText|finally|FilteringText|consoleFlags" MCPForUnity/Editor/Tools/ReadConsole.cs MCPForUnity/Editor/Tools -S || true

Repository: CoplayDev/unity-mcp

Length of output: 12739


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the exact method body around the read path.
nl -ba MCPForUnity/Editor/Tools/ReadConsole.cs | sed -n '1,260p'

Repository: CoplayDev/unity-mcp

Length of output: 197


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check whether console filter text can be read/restored elsewhere in the codebase.
rg -n "GetFilteringText|SetFilteringText|FilteringText" MCPForUnity -S

Repository: CoplayDev/unity-mcp

Length of output: 927


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# If ReadConsole.cs is large, inspect the relevant middle section only.
wc -l MCPForUnity/Editor/Tools/ReadConsole.cs
nl -ba MCPForUnity/Editor/Tools/ReadConsole.cs | sed -n '260,520p'

Repository: CoplayDev/unity-mcp

Length of output: 241


🏁 Script executed:

#!/bin/bash
set -euo pipefail
nl -ba MCPForUnity/Editor/Tools/ReadConsole.cs | sed -n '1,520p'

Repository: CoplayDev/unity-mcp

Length of output: 197


🌐 Web query:

Unity Editor LogEntries GetFilteringText SetFilteringText API

💡 Result:

The GetFilteringText and SetFilteringText methods are internal API methods belonging to the UnityEditor.LogEntries class [1][2]. Because these methods are internal and not part of the public Unity Scripting API, they are not intended for use in production code and their signatures or functionality can change without warning [1][3]. These methods are primarily used by Unity's own Editor code—specifically the Console Window—to manage the text filter string currently applied to the console's log entries [2][4]. Key characteristics include: - Purpose: They control the search filter string used to narrow down which log entries are displayed in the Unity Editor Console [2]. - Access: As internal methods, they cannot be accessed directly via standard code references. Developers who require this functionality often use C# reflection to access the UnityEditor.LogEntries class at runtime [5][6]. - Usage in Unity's Source: The Unity ConsoleWindow class invokes GetFilteringText to retrieve the current filter state and SetFilteringText to update the filter when a user types into the Console's search field [2]. Because they are not documented public APIs, using them via reflection is considered an unstable practice for Unity development [7][5]. Developers looking to interact with the Console should be aware that these internal calls may fail if Unity changes its internal architecture in future versions [8].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path("MCPForUnity/Editor/Tools/ReadConsole.cs")
lines = p.read_text().splitlines()
for start, end in [(250, 450)]:
    for i in range(start, min(end, len(lines)) + 1):
        print(f"{i:4d}: {lines[i-1]}")
PY

Repository: CoplayDev/unity-mcp

Length of output: 10298


Keep the Console mutations in cleanup.

SetFilteringText("") runs before the try, so a throw there skips restoring consoleFlags; when it succeeds, the search text also stays cleared. Save/restore the filter text when GetFilteringText is available, and move both mutations under the same finally.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@MCPForUnity/Editor/Tools/ReadConsole.cs` at line 34, The console state
mutations in ReadConsole should be scoped together so cleanup always restores
the original state. In the ReadConsole flow, capture the current filtering text
via GetFilteringText before calling SetFilteringText(""), then move both the
filter-text change and the consoleFlags change into the same try/finally path so
any throw still restores both values. Use the existing helper members around
_setFilteringTextMethod, _getFilteringTextMethod, and the console flag fields to
locate and update the affected logic.

|| _messageField == null
|| _fileField == null
|| _lineField == null
|| _consoleFlagsProperty == null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the file structure first, then inspect the relevant region.
ast-grep outline MCPForUnity/Editor/Tools/ReadConsole.cs --view expanded || true

echo
echo "---- relevant lines ----"
sed -n '120,190p' MCPForUnity/Editor/Tools/ReadConsole.cs

Repository: CoplayDev/unity-mcp

Length of output: 5025


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '190,330p' MCPForUnity/Editor/Tools/ReadConsole.cs

Repository: CoplayDev/unity-mcp

Length of output: 6822


Don’t gate clear on consoleFlags. HandleCommand rejects every action when _consoleFlagsProperty is missing, but clear only needs _clearMethod. Move that guard into the get path so clear still works on Unity versions without consoleFlags.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@MCPForUnity/Editor/Tools/ReadConsole.cs` at line 149, HandleCommand is
rejecting all commands when _consoleFlagsProperty is null, but clear only
depends on _clearMethod. Update the guard logic in ReadConsole.HandleCommand so
the consoleFlagsProperty check is only applied for the get path, and keep clear
available whenever _clearMethod exists, even on Unity versions without
consoleFlags.

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.

[Bug] read_console silently returns 0 entries when Console window severity toggles are off (filter inheritance)

1 participant