Skip to content

fix: Avoid false "Unity not running" errors when the editor is still open#919

Merged
hatayama merged 6 commits into
mainfrom
codex/improve-unity-connection-diagnostics
Apr 10, 2026
Merged

fix: Avoid false "Unity not running" errors when the editor is still open#919
hatayama merged 6 commits into
mainfrom
codex/improve-unity-connection-diagnostics

Conversation

@hatayama
Copy link
Copy Markdown
Owner

@hatayama hatayama commented Apr 10, 2026

Summary

  • diagnose Unity connection failures after an actual connection attempt instead of trusting the stale isServerRunning flag up front
  • add OS-level Unity process detection with parser-focused unit tests for macOS, Linux, and Windows
  • clarify in AGENTS.md that commit messages, PR titles, and PR descriptions must all be written in English

Why

The previous CLI flow could report Unity not running too early because UserSettings/UnityMcpSettings.json may still say isServerRunning: true or false after crashes, force-kills, or other unclean shutdowns. That made it harder to distinguish between a closed Unity Editor and a still-open editor whose C# server was unavailable.

What changed

  • keep port resolution focused on reading customPort from settings
  • when a retryable connection failure happens for a known project, inspect the OS process list and convert the result into either UnityNotRunningError or UnityServerNotRunningError
  • surface a dedicated CLI message for the editor-running/server-stopped case
  • make the Unity process inspection logic unit-testable and add Windows coverage for command generation, parsing, and project-path matching
  • update the repository guidance sentence in AGENTS.md so the English-writing rule is harder to misread

Testing

  • npx jest src/__tests__/cli-project-error.test.ts src/__tests__/execute-tool.test.ts src/__tests__/port-resolver.test.ts src/__tests__/unity-process.test.ts --runInBand --testTimeout=60000
  • npm run build
  • npm run lint (existing warnings only)
  • manual check: node Packages/src/Cli~/dist/cli.bundle.cjs get-logs --project-path . while Unity is not running to confirm the CLI reports the not-running guidance

Summary by cubic

Prevents false “Unity not running” errors by diagnosing after real connection failures and matching the running Unity Editor per project across macOS/Linux/Windows. Detection now tolerates flattened POSIX paths with spaces and trailing slashes, and shows clear guidance when the Editor is closed vs. when the Unity CLI Loop server is stopped.

  • Bug Fixes

    • Diagnose after an actual connection attempt; map retryable failures to UnityNotRunningError or UnityServerNotRunningError with dedicated CLI guidance.
    • POSIX matcher accepts flattened ps output and ignores trailing “/” in -projectPath while guarding against prefix-only matches.
    • Verify the Unity editor executable; treat Unity.exe case‑insensitively on Windows; ignore non‑Unity tools that use -projectPath.
    • Centralize final error handling via throwFinalToolError; keep port resolution on customPort and ignore stale isServerRunning.
  • New Features

    • Cross‑platform process detection (ps/PowerShell) plus isUnityEditorProcess; diagnoseRetryableProjectConnectionError checks OS processes per project.
    • Tests cover flattened POSIX paths, trailing slashes, and Windows casing. Updated CLI messages and AGENTS.md to require English commit/PR text.

Written for commit 46cee42. Summary will update on new commits.

This PR improves Unity connection diagnostics by performing OS-level process inspection after retryable connection failures and moving the final diagnosis to after an actual connection attempt instead of trusting the potentially stale isServerRunning flag.

Key changes

  • New module: Packages/src/Cli~/src/unity-process.ts

    • Cross-platform process inspection (ps on macOS/Linux; PowerShell on Windows)
    • Exports: buildUnityProcessCommand, parseUnityProcesses, tokenizeCommandLine, extractUnityProjectPath, normalizeUnityProjectPath, isUnityProcessForProject, isUnityEditorProcess, findRunningUnityProcessForProject
    • Robust parsing, tokenization, and project-path matching with Windows case-insensitive normalization; injectable runCommand dependency for unit testing
  • Error classification & port resolution

    • Added exported class UnityServerNotRunningError(projectRoot) with code 'UNITY_SERVER_NOT_RUNNING'
    • Removed blocking behavior that threw UnityNotRunningError when UnityMcpSettings.isServerRunning === false; readPortFromSettingsOrThrow now proceeds to resolve customPort even if isServerRunning is false
  • Connection failure diagnosis & control flow

    • Added exported diagnoseRetryableProjectConnectionError(error, projectRoot, shouldDiagnoseProjectState, dependencies?) which:
      • For retryable connection failures (e.g., ECONNREFUSED, EADDRNOTAVAIL, UNITY_NO_RESPONSE) inspects OS processes and maps to:
        • UnityNotRunningError when no matching Unity editor process found
        • UnityServerNotRunningError when a Unity editor process exists but the Unity CLI Loop server is unreachable
      • Preserves the original error for non-retryable cases, when diagnosis is disabled, or when the finder throws
    • Added throwFinalToolError(...) to centralize final post-retry error diagnosis and throwing
    • executeToolCommand, listAvailableTools, syncTools updated to use throwFinalToolError for consistent final error behavior
  • CLI UX & messages

    • getProjectResolutionErrorLines extended to accept UnityServerNotRunningError and return dedicated guidance including projectRoot and an instruction to start the server (Window > Unity CLI Loop > Server)
    • cli.ts runWithErrorHandling now handles both UnityNotRunningError and UnityServerNotRunningError and prints project-resolution lines with exit code 1
  • Tests & verification

    • Added unity-process.test.ts covering command construction, tokenization, project-path extraction, normalization, parsing (ps and PowerShell), matching logic, and findRunningUnityProcessForProject with mocked runCommand
    • Extended execute-tool.test.ts to cover diagnoseRetryableProjectConnectionError behavior
    • Updated cli-project-error.test.ts to validate UnityServerNotRunningError guidance lines
    • Updated port-resolver.test.ts to reflect removed isServerRunning blocking behavior
    • Test guidance: run Jest with --runInBand --testTimeout=60000, npm run build, npm run lint (existing warnings only), and a manual CLI check for not-running guidance
  • Documentation & minor policy change

    • AGENTS.md: tightened language to require that comments, commit messages, PR titles, and PR descriptions must be written in English

API / surface changes

  • Added exports:
    • UnityServerNotRunningError (class) in port-resolver.ts
    • unity-process module exports listed above
    • diagnoseRetryableProjectConnectionError (exported) in execute-tool.ts
  • No other public APIs removed; implementation surfaced to avoid unused-export build issues

Architecture Impact

classDiagram
class UnityNotRunningError {
+projectRoot: string
}
class UnityServerNotRunningError {
+projectRoot: string
}
class ConnectionFailureDiagnosisDependencies {
+findRunningUnityProcessForProjectFn
}
class UnityProcessModule {
+buildUnityProcessCommand()
+parseUnityProcesses()
+tokenizeCommandLine()
+extractUnityProjectPath()
+normalizeUnityProjectPath()
+isUnityProcessForProject()
+isUnityEditorProcess()
+findRunningUnityProcessForProject()
}
class ExecuteToolModule {
+diagnoseRetryableProjectConnectionError()
+throwFinalToolError()
+executeToolCommand()
+listAvailableTools()
+syncTools()
}
ExecuteToolModule --> UnityProcessModule: uses
ExecuteToolModule --> UnityNotRunningError: throws
ExecuteToolModule --> UnityServerNotRunningError: throws
ExecuteToolModule --> ConnectionFailureDiagnosisDependencies: depends on
UnityProcessModule --> RunningUnityProcess: returns

Behavior changes

  • Before: Final connection diagnosis could rely on isServerRunning in UnityMcpSettings and report incorrect causes when that flag was stale.
  • After: On retryable connection failures the CLI inspects OS processes to determine:
    • Unity Editor not running → UnityNotRunningError
    • Unity Editor running but C# server unavailable → UnityServerNotRunningError with CLI hint to start the server
    • Otherwise, preserve the original error

Notes for reviewers

  • Focus review on unity-process parsing/tokenization, path normalization, platform-specific command generation, and dependency injection for runCommand.
  • Verify UnityServerNotRunningError messaging and getProjectResolutionErrorLines content match UX expectations.

The CLI previously trusted isServerRunning before attempting a connection, which made stale settings after crashes or forced termination look like a clean Unity-not-running state. That hid the difference between an editor that is closed and an editor that is still open while the Unity CLI Loop server is unavailable.

This change keeps port resolution focused on reading customPort from project settings and moves the final diagnosis to the point where a real connection attempt fails. When a retryable connection error happens for a known project, the CLI now checks the OS process list for that project and reports either UnityNotRunningError or UnityServerNotRunningError with dedicated user-facing guidance.

It also adds a standalone unity-process module with macOS, Linux, and Windows process queries plus parser-focused unit tests, so the OS-level detection can be verified without launching Unity. The affected surface is limited to CLI connection diagnostics, project error messaging, and the related unit tests.
The repository already expected code comments, commit messages, and pull request text to be written in English, but the previous sentence bundled those rules together in a way that was easy to skim past.

This updates AGENTS.md to say the same policy more explicitly by calling out commit messages, PR titles, and PR descriptions individually. The goal is to reduce future conflicts between repository-specific conventions and local automation prompts.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 10, 2026

📝 Walkthrough

Walkthrough

Introduces UnityServerNotRunningError and diagnostics that inspect running Unity editor processes; adds a new unity-process module; integrates diagnosis into execute-tool and CLI error handling; adjusts port-resolver to not fail when settings report the server as not running; updates tests and docs accordingly.

Changes

Cohort / File(s) Summary
Documentation
AGENTS.md
Tightened language requirement: "should" → "must" and changed "bodies" to "PR descriptions".
Process discovery & tests
Packages/src/Cli~/src/unity-process.ts, Packages/src/Cli~/src/__tests__/unity-process.test.ts
New module to build platform-specific process-listing commands, parse outputs, tokenize/extract project paths, normalize/compare paths, detect Unity editor processes, and find running Unity processes for a project; comprehensive cross-platform tests added.
Port resolver & error type
Packages/src/Cli~/src/port-resolver.ts, Packages/src/Cli~/src/__tests__/port-resolver.test.ts
Added exported UnityServerNotRunningError class; removed logic that previously rejected when isServerRunning === false so port resolution proceeds; tests adjusted to expect successful resolution.
CLI project error messages & tests
Packages/src/Cli~/src/cli-project-error.ts, Packages/src/Cli~/src/__tests__/cli-project-error.test.ts
Extended getProjectResolutionErrorLines signature to include UnityServerNotRunningError and added branch returning server-specific guidance lines; test added for the new error case.
CLI entrypoint error handling
Packages/src/Cli~/src/cli.ts
Import updated to include UnityServerNotRunningError; runWithErrorHandling catch treats UnityNotRunningError and UnityServerNotRunningError uniformly (prints resolution lines and exits with status 1).
Tool execution, diagnostics & tests
Packages/src/Cli~/src/execute-tool.ts, Packages/src/Cli~/src/__tests__/execute-tool.test.ts
Added exported diagnoseRetryableProjectConnectionError to inspect running Unity processes and map retryable connection errors to UnityNotRunningError or UnityServerNotRunningError; introduced throwFinalToolError to centralize final error throwing; updated execution flows and tests to use these diagnostics.

Sequence Diagram

sequenceDiagram
    actor CLI as CLI Client
    participant Exec as executeToolCommand
    participant Diag as diagnoseRetryableProjectConnectionError
    participant ProcFinder as findRunningUnityProcessForProject
    participant Reporter as getProjectResolutionErrorLines
    participant Exit as CLI Exit

    CLI->>Exec: run tool for project
    Exec->>Exec: attempt/connect/retry
    Exec->>Diag: diagnoseRetryableProjectConnectionError(error, projectRoot, shouldDiagnose)
    Diag->>ProcFinder: findRunningUnityProcessForProject(projectRoot)
    alt process found
        ProcFinder-->>Diag: { pid }
        Diag-->>Exec: UnityServerNotRunningError
    else no process
        ProcFinder-->>Diag: null
        Diag-->>Exec: UnityNotRunningError
    end
    Exec->>Reporter: getProjectResolutionErrorLines(error)
    Reporter-->>Exec: lines[]
    Exec->>CLI: print lines
    CLI->>Exit: exit(1)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • PR #898: Modifies port-resolver and tests around settings/port-resolution; closely related to the port-resolution behavior changes here.
  • PR #911: Refactors CLI error reporting and execution flows across cli-project-error, cli.ts, and execute-tool; overlaps with this PR's error-handling changes.
  • PR #875: Addresses server-state detection and isServerRunning handling; related to the adjusted logic preventing premature rejection when the server flag is false.
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% 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: avoiding false 'Unity not running' errors by implementing better connection diagnostics when the editor is still open.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/improve-unity-connection-diagnostics

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

@cubic-dev-ai cubic-dev-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.

No issues found across 10 files

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: 2

🧹 Nitpick comments (2)
Packages/src/Cli~/src/cli-project-error.ts (1)

7-14: Reuse the existing product/menu constants here.

This introduces another hard-coded copy of the server guidance, while Packages/src/Cli~/src/cli.ts already prints the same concept via shared constants. Pulling PRODUCT_DISPLAY_NAME / MENU_PATH_SERVER into this branch would keep the wording consistent if the menu path or branding changes again.

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

In `@Packages/src/Cli`~/src/cli-project-error.ts around lines 7 - 14, The branch
handling UnityServerNotRunningError in the function that returns the message
array currently hard-codes the product/menu text; update this branch to use the
shared constants PRODUCT_DISPLAY_NAME and MENU_PATH_SERVER (same symbols used in
cli.ts) instead of literal strings, add the necessary import for those
constants, and interpolate them into the returned lines (e.g., replace "Unity
Editor" and the "Window > Unity CLI Loop > Server" line with
PRODUCT_DISPLAY_NAME and MENU_PATH_SERVER) so wording stays consistent across
the codebase.
Packages/src/Cli~/src/__tests__/unity-process.test.ts (1)

19-29: Add test coverage for Windows single-process JSON output; consider simplifying with array-wrapping.

The production parser already handles both JSON array and single-object output (via the conditional on line 199 of unity-process.ts). However, the test suite should verify this single-object case, as PowerShell ConvertTo-Json outputs a plain object {...} rather than an array [...] when exactly one Win32_Process matches. Optionally, wrapping the pipeline in @(...) would force consistent array output and eliminate the conditional check:

Suggested improvement
- 'Get-CimInstance Win32_Process -Filter "name = \'Unity.exe\'" | Select-Object ProcessId, CommandLine | ConvertTo-Json -Compress',
+ '@(Get-CimInstance Win32_Process -Filter "name = \'Unity.exe\'" | Select-Object ProcessId, CommandLine) | ConvertTo-Json -Compress',

Add a test case for single-object JSON output (e.g., {"ProcessId":101,"CommandLine":"..."}) to verify it parses correctly alongside the existing array test.

Also applies to: 85–103

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

In `@Packages/src/Cli`~/src/__tests__/unity-process.test.ts around lines 19 - 29,
Add a unit test in unity-process.test.ts that exercises the parser in
unity-process.ts with a single-object PowerShell JSON string (e.g.
'{"ProcessId":101,"CommandLine":"..."}') to ensure parseUnityProcessOutput (or
the exported parser function in unity-process.ts) correctly returns the same
normalized result as the array case; construct the single-object JSON string,
call the parser, and assert the parsed output matches the expected process entry
(you can mirror the existing array test assertions), or alternatively update the
PowerShell command to force array output via @(...) if you prefer consistent
command output.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Packages/src/Cli`~/src/unity-process.ts:
- Around line 9-11: The exported interface RunningUnityProcess is flagged as
unused; remove the export to make it internal (change "export interface
RunningUnityProcess" to "interface RunningUnityProcess") or eliminate the
interface and inline its shape ({ pid: number }) where it’s used/returned so no
exported type is unused; update any function or return signatures that
referenced RunningUnityProcess to use the inline type if you remove the
interface.
- Around line 201-207: Remove the redundant case-sensitive CommandLine check
that filters for UNITY_WINDOWS_PROCESS_NAME and rely on the existing
isWindowsUnityProcessWithCommandLine predicate returned from the PowerShell
query; specifically delete the .filter((processInfo) =>
processInfo.CommandLine.includes(UNITY_WINDOWS_PROCESS_NAME)) call so the
pipeline becomes
processArray.filter(isWindowsUnityProcessWithCommandLine).map(...) — this
prevents false negatives caused by path casing and avoids incorrectly producing
UnityNotRunningError while leaving the mapping to pid/commandLine intact.

---

Nitpick comments:
In `@Packages/src/Cli`~/src/__tests__/unity-process.test.ts:
- Around line 19-29: Add a unit test in unity-process.test.ts that exercises the
parser in unity-process.ts with a single-object PowerShell JSON string (e.g.
'{"ProcessId":101,"CommandLine":"..."}') to ensure parseUnityProcessOutput (or
the exported parser function in unity-process.ts) correctly returns the same
normalized result as the array case; construct the single-object JSON string,
call the parser, and assert the parsed output matches the expected process entry
(you can mirror the existing array test assertions), or alternatively update the
PowerShell command to force array output via @(...) if you prefer consistent
command output.

In `@Packages/src/Cli`~/src/cli-project-error.ts:
- Around line 7-14: The branch handling UnityServerNotRunningError in the
function that returns the message array currently hard-codes the product/menu
text; update this branch to use the shared constants PRODUCT_DISPLAY_NAME and
MENU_PATH_SERVER (same symbols used in cli.ts) instead of literal strings, add
the necessary import for those constants, and interpolate them into the returned
lines (e.g., replace "Unity Editor" and the "Window > Unity CLI Loop > Server"
line with PRODUCT_DISPLAY_NAME and MENU_PATH_SERVER) so wording stays consistent
across the codebase.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 04cb44d6-912f-4b6a-beb5-7611d5242846

📥 Commits

Reviewing files that changed from the base of the PR and between 2e5b383 and ce6f7d2.

📒 Files selected for processing (10)
  • AGENTS.md
  • Packages/src/Cli~/src/__tests__/cli-project-error.test.ts
  • Packages/src/Cli~/src/__tests__/execute-tool.test.ts
  • Packages/src/Cli~/src/__tests__/port-resolver.test.ts
  • Packages/src/Cli~/src/__tests__/unity-process.test.ts
  • Packages/src/Cli~/src/cli-project-error.ts
  • Packages/src/Cli~/src/cli.ts
  • Packages/src/Cli~/src/execute-tool.ts
  • Packages/src/Cli~/src/port-resolver.ts
  • Packages/src/Cli~/src/unity-process.ts

Comment thread Packages/src/Cli~/src/unity-process.ts Outdated
Comment thread Packages/src/Cli~/src/unity-process.ts Outdated
The build-typescript-server GitHub Actions job failed in the CLI knip step because RunningUnityProcess was exported from src/unity-process.ts but never imported anywhere else.

This change keeps the type internal to the module while preserving the public helper functions used by the CLI and the unit tests. The goal is to satisfy the unused-export check without changing the runtime behavior of the Unity process detection code.

Verification:
- npx knip
- npx tsc --noEmit
- npm run build
- npx jest src/__tests__/unity-process.test.ts --runInBand --testTimeout=60000
@hatayama hatayama changed the title fix: Improve Unity connection diagnostics after abrupt shutdowns fix: Show clearer uloop errors when Unity is starting or unavailable Apr 10, 2026
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

♻️ Duplicate comments (1)
Packages/src/Cli~/src/unity-process.ts (1)

201-203: ⚠️ Potential issue | 🟠 Major

Remove the extra case-sensitive Unity.exe filter.

The PowerShell query already limits rows to name = 'Unity.exe'; this second filter drops real processes when the executable path casing differs and can incorrectly downgrade the diagnosis to “Unity not running”.

Suggested fix
   return processArray
     .filter(isWindowsUnityProcessWithCommandLine)
-    .filter((processInfo) => processInfo.CommandLine.includes(UNITY_WINDOWS_PROCESS_NAME))
     .map((processInfo) => ({
       pid: processInfo.ProcessId,
       commandLine: processInfo.CommandLine,
     }));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Packages/src/Cli`~/src/unity-process.ts around lines 201 - 203, The second,
case-sensitive filter that checks
processInfo.CommandLine.includes(UNITY_WINDOWS_PROCESS_NAME) is redundant and
can drop matching Unity processes due to path casing; remove that filter and
return only processArray.filter(isWindowsUnityProcessWithCommandLine) so the
PowerShell name restriction is relied upon instead—update any downstream
assumptions if they depended on the extra include check and keep references to
isWindowsUnityProcessWithCommandLine and UNITY_WINDOWS_PROCESS_NAME for clarity.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Packages/src/Cli`~/src/unity-process.ts:
- Around line 151-154: parseUnityProcesses returns every ps row so the current
lookup can false-positive match any process with the same -projectPath value;
update the search to first assert the row is actually a Unity editor process
before checking project path. Add or reuse a predicate (e.g.,
isUnityEditorProcess or isUnityBinary) that inspects
processInfo.commandLine/executable for Unity editor signatures (case-insensitive
"unity", "Unity.app/Contents/MacOS/Unity", or platform-specific Unity binary
names) and on macOS/Linux check for an .app or expected binary path; then change
the find call to require this predicate AND
isUnityProcessForProject(processInfo.commandLine, projectRoot,
dependencies.platform) so only true Unity editor processes are matched.

---

Duplicate comments:
In `@Packages/src/Cli`~/src/unity-process.ts:
- Around line 201-203: The second, case-sensitive filter that checks
processInfo.CommandLine.includes(UNITY_WINDOWS_PROCESS_NAME) is redundant and
can drop matching Unity processes due to path casing; remove that filter and
return only processArray.filter(isWindowsUnityProcessWithCommandLine) so the
PowerShell name restriction is relied upon instead—update any downstream
assumptions if they depended on the extra include check and keep references to
isWindowsUnityProcessWithCommandLine and UNITY_WINDOWS_PROCESS_NAME for clarity.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2d2c0898-400e-4718-bbb6-468b808dc306

📥 Commits

Reviewing files that changed from the base of the PR and between ce6f7d2 and a3515d9.

📒 Files selected for processing (1)
  • Packages/src/Cli~/src/unity-process.ts

Comment thread Packages/src/Cli~/src/unity-process.ts
@hatayama hatayama changed the title fix: Show clearer uloop errors when Unity is starting or unavailable fix: Avoid false "Unity not running" errors when the editor is still open Apr 10, 2026
Address the PR review feedback around OS-level Unity detection so the CLI can distinguish real Unity editor processes from unrelated commands more reliably. The previous implementation could reject valid Windows processes when the executable casing differed from 'Unity.exe', and it could also accept non-Unity macOS/Linux processes as long as they reused the same -projectPath argument.

Key changes:
- removed the redundant Windows command-line filter that re-checked for 'Unity.exe' after the PowerShell query had already limited results to Unity.exe processes
- added an isUnityEditorProcess predicate and required findRunningUnityProcessForProject to validate both the executable identity and the project path before returning a match
- covered the new behavior with unit tests for uppercase Windows executable names and for non-Unity processes that happen to share the same projectPath

Impact:
- reduces false negatives on Windows when CommandLine casing differs from the expected literal
- reduces false positives on macOS/Linux by avoiding matches against arbitrary tools that expose a -projectPath flag
- keeps the detection logic small and local to unity-process.ts instead of spreading platform-specific checks across callers
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

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

Inline comments:
In `@Packages/src/Cli`~/src/unity-process.ts:
- Around line 65-109: tokenizeCommandLine and extractUnityProjectPath fail on
POSIX ps output because quoting is lost; update extractUnityProjectPath (and
stop relying on tokenizeCommandLine for POSIX) to match the known projectRoot
directly against the raw commandLine string instead of tokenizing it: detect a
substring equal to projectRoot (with path separators or boundaries to avoid
false matches) and return that when found; adjust
findRunningUnityProcessForProject to pass the expected projectRoot into
extractUnityProjectPath (or call the new raw-match helper) and remove/limit
usage of tokenizeCommandLine for POSIX-only code paths so we reliably detect
running Unity instances even when ps has flattened quotes.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e312e0e5-e4e0-4a51-9c22-5b7195daacd6

📥 Commits

Reviewing files that changed from the base of the PR and between a3515d9 and 58f714e.

📒 Files selected for processing (2)
  • Packages/src/Cli~/src/__tests__/unity-process.test.ts
  • Packages/src/Cli~/src/unity-process.ts

Comment thread Packages/src/Cli~/src/unity-process.ts
Fix the remaining PR review issue around OS-level Unity detection on macOS and Linux. POSIX `ps` output does not reliably preserve shell quoting, so a Unity command like `-projectPath /Users/me/My Project` could be flattened into a plain string that the existing token-based parser split at the first space. When that happened, `findRunningUnityProcessForProject` could return `null` even though the editor was running, which reintroduced the false `Unity not running` diagnosis this branch is meant to remove.

Key changes:
- changed `isUnityProcessForProject` to use a POSIX-specific raw command-line matcher instead of relying on `extractUnityProjectPath` tokenization
- added `commandLineContainsProjectRoot` and a terminator check so the matcher accepts flattened paths with spaces but rejects prefix-only matches such as `/Users/me/My Project Backup`
- kept the Windows path extraction flow unchanged so the existing `-projectPath` parsing behavior still applies there
- added regression tests for flattened macOS `ps` output and for the prefix false-positive case, including the end-to-end `findRunningUnityProcessForProject` path

Impact:
- reduces false `Unity not running` errors when the Unity project path contains spaces on macOS or Linux
- avoids expanding the detection to unrelated neighboring paths that merely share the same prefix
- keeps the platform-specific behavior localized to `unity-process.ts`, which makes later changes to process detection easier to reason about
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-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.

1 issue found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="Packages/src/Cli~/src/unity-process.ts">

<violation number="1" location="Packages/src/Cli~/src/unity-process.ts:126">
P2: Non-Windows project matching can fail when `-projectPath` has a trailing slash, causing running Unity editors to be misclassified as not matching the target project.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread Packages/src/Cli~/src/unity-process.ts
Fix the latest PR review issue around the POSIX project matcher in `unity-process.ts`. After the previous raw command-line matching change, macOS and Linux could still misclassify a running Unity editor when the `-projectPath` value ended with one or more trailing `/` characters. That left a gap where normalized project roots such as `/Users/me/My Project` no longer matched raw process output like `/Users/me/My Project/`, which could surface as another false `Unity not running` diagnosis.

Key changes:
- added `skipTrailingProjectPathSeparators` so the POSIX matcher ignores trailing `/` characters before evaluating the end of the project path
- kept the existing prefix guard intact so neighboring paths such as `/Users/me/My Project Backup` still do not match the target project
- added regression tests for single and repeated trailing slash variants in both `isUnityProcessForProject` and `findRunningUnityProcessForProject`

Impact:
- reduces false negative Unity process detection when POSIX process output preserves trailing slashes on `-projectPath`
- preserves the earlier fix for flattened paths with spaces without reopening the prefix-only false positive case
- keeps the path-normalization behavior localized to the POSIX-specific matcher, so Windows detection remains unchanged
@hatayama hatayama merged commit 5376279 into main Apr 10, 2026
13 checks passed
@hatayama hatayama deleted the codex/improve-unity-connection-diagnostics branch April 10, 2026 16: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