Skip to content

fix: Unity no longer pauses on external change dialogs after focus return - #1447

Merged
hatayama merged 8 commits into
v3-betafrom
feature/hatayama/save-editor-state-before-commands
Jul 1, 2026
Merged

hatayama merged 8 commits into
v3-betafrom
feature/hatayama/save-editor-state-before-commands

Conversation

@hatayama

@hatayama hatayama commented Jul 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Unity now preserves open Scene and current Prefab Stage state before asset refresh when returning focus after source-control changes.
  • This prevents external file-change dialogs from blocking workflows after reverting or replacing files outside Unity.

User Impact

  • Before, returning to Unity after Git or other source-control changes could show modal external-change dialogs and stop automated work.
  • Now Unity treats the in-memory Scene and Prefab Stage state as authoritative before refresh, so focus return continues without that interruption.

Changes

  • Hold Unity Auto Refresh while the editor is unfocused and release it only after the focus-return preflight completes.
  • Save dirty open Scenes and the current Prefab Stage, restore missing files, and resolve clean external changes before allowing refresh.
  • Preserve the active Prefab Stage context and mode when reopening externally changed Prefab assets.
  • Persist tracked asset fingerprints across editor domain reloads and validate Prefab reopen inputs before calling Unity APIs that reject invalid context.

Verification

  • cli/dist/darwin-arm64/uloop compile --project-path "$(git rev-parse --show-toplevel)" -> success, 0 errors, 0 warnings
  • cli/dist/darwin-arm64/uloop run-tests --project-path "$(git rev-parse --show-toplevel)" --test-mode EditMode --filter-type regex --filter-value "ExternalSceneChangeResolverTests" -> 16 passed
  • cli/dist/darwin-arm64/uloop run-tests --project-path "$(git rev-parse --show-toplevel)" --test-mode EditMode --filter-type regex --filter-value "TestExecutionStateValidationServiceTests" -> 8 passed
  • autoreview --mode branch --base origin/v3-beta --prompt "<autosave requirement>" -> clean, no accepted/actionable findings
  • Claude Code /review 1447 via cmux -> accepted findings addressed

hatayama added 5 commits June 30, 2026 18:11
Hold Unity Auto Refresh while the editor is unfocused, then save dirty editor state and resolve clean external Scene or Prefab Stage changes before refresh resumes. This keeps common Git restore and checkout workflows from blocking on Unity confirmation dialogs.
Keep active Auto Refresh holds in place during normal command initialization, and avoid reopening a Prefab Stage when dirty prefab state could not be saved.
Domain reload can reinitialize the focus-return guard while the editor is still in the background. Release a persisted Auto Refresh hold only when the editor is focused so later filesystem changes still wait for the focus-return preflight.
Focus-return handling intentionally persists Unity's in-memory editor state before refresh so source-control file replacement cannot trigger external reload dialogs.
Reopen externally changed Prefab Stages with the original opened instance and mode so focus-return refresh keeps in-context editing state intact.
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@hatayama, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2b004e4a-62e8-4062-ad43-8e2365fb0629

📥 Commits

Reviewing files that changed from the base of the PR and between 7f3690a and 0ff763b.

📒 Files selected for processing (2)
  • Assets/Tests/Editor/ExternalSceneChangeResolverTests.cs
  • Packages/src/Editor/FirstPartyTools/Compile/ExternalSceneChangeResolver.cs
📝 Walkthrough

Walkthrough

This PR extends ExternalSceneChangeResolver to track fingerprints for open Scenes and the current Prefab Stage separately, introduces ExternalAssetFocusReturnService to coordinate Auto Refresh suspension across editor focus loss/return, adds focus-return resolution logic including save/restore and prefab reimport/reopen flows, and adds corresponding unit tests.

Changes

Focus-return resolution and Auto Refresh coordination

Layer / File(s) Summary
Snapshot dictionaries, initialization, and trackability
Packages/src/Editor/FirstPartyTools/Compile/ExternalSceneChangeResolver.cs
Adds separate session-keyed snapshot dictionaries for Scenes and Prefab Stages, short-circuits initialization during asset import worker processes, restores prior session snapshots/auto-refresh state, expands editor event wiring to include Prefab Stage lifecycle and focus-changed events, and adds prefab-stage trackability filtering plus a generalized ReadAssetFileFingerprint reader.
Focus-return resolution flow for Scenes and Prefab Stages Implements ResolveForFocusReturn and Prefab Stage open/close/save handlers that re-run Scene change resolution, compare current vs stored Prefab Stage fingerprints, reimport mismatched prefab assets, reopen the Prefab Stage, and record updated fingerprints.
Save/restore persistence helpers and resolver wiring Adds helpers to save dirty/restore missing Scenes and Prefab Stage assets, centralizes prefab saving via TrySavePrefabStage, and introduces CreateSceneChangeResolver wiring plus session-state accessors for the auto-refresh hold flag and snapshot persistence.
ExternalAssetFocusReturnService and auto-refresh coordination Adds ExternalAssetFocusReturnService to hold/disallow Auto Refresh on focus loss and release it after focus-return resolution runs under try/finally, plus ExternalAssetSnapshotSessionStore JSON serialization, fingerprint equality comparison, and centralized failure logging.
Unit tests for focus-return service, snapshot store, and reopen context
Assets/Tests/Editor/ExternalSceneChangeResolverTests.cs
Adds NUnit tests for focus-loss/return behavior, startup recovery, preflight exception handling, snapshot session store round-tripping/clearing, and CreatePrefabStageReopenContext scenarios, plus a test helper for constructing the focus-return service with injectable delegates.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Editor
  participant ExternalAssetFocusReturnService
  participant ExternalSceneChangeTracker
  participant PrefabStage
  participant AssetDatabase

  Editor->>ExternalAssetFocusReturnService: focus lost
  ExternalAssetFocusReturnService->>ExternalAssetFocusReturnService: disallow Auto Refresh, store hold
  Editor->>ExternalAssetFocusReturnService: focus regained
  ExternalAssetFocusReturnService->>ExternalSceneChangeTracker: ResolveForFocusReturn (try)
  ExternalSceneChangeTracker->>ExternalSceneChangeTracker: save dirty/restore missing Scenes and Prefab Stage
  ExternalSceneChangeTracker->>PrefabStage: compare current vs stored fingerprints
  ExternalSceneChangeTracker->>AssetDatabase: reimport mismatched prefab asset
  ExternalSceneChangeTracker->>PrefabStage: reopen Prefab Stage
  ExternalSceneChangeTracker->>ExternalSceneChangeTracker: record updated snapshot
  ExternalAssetFocusReturnService->>ExternalAssetFocusReturnService: release hold, allow Auto Refresh (finally)
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main focus-return fix and matches the changeset.
Description check ✅ Passed The description accurately describes the focus-return, auto-refresh, and Prefab Stage changes in the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/hatayama/save-editor-state-before-commands

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.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 4 files

Re-trigger cubic

hatayama added 2 commits July 1, 2026 17:51
Persist tracked asset fingerprints across editor domain reloads so focus-return preflight can still detect external Scene and Prefab changes. Also validate Prefab Stage reopen inputs before calling Unity APIs that throw for invalid or missing Prefab assets.
Remove the README additions for the focus-return behavior so the PR keeps the documentation unchanged.

@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.

🧹 Nitpick comments (1)
Assets/Tests/Editor/ExternalSceneChangeResolverTests.cs (1)

299-320: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider asserting full fingerprint fields for the missing-scene entry too.

The round-trip test only checks Exists for MissingScenePath; asserting LastWriteTimeUtc/Length as well would give stronger regression coverage for the serialization format.

Suggested addition
             Assert.That(restored[MissingScenePath].Exists, Is.False);
+            Assert.That(restored[MissingScenePath].LastWriteTimeUtc, Is.EqualTo(DateTime.MinValue));
+            Assert.That(restored[MissingScenePath].Length, Is.EqualTo(0));
🤖 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 `@Assets/Tests/Editor/ExternalSceneChangeResolverTests.cs` around lines 299 -
320, The round-trip test in ExternalSceneChangeResolverTests only verifies the
Exists flag for the missing-scene snapshot, so extend
SnapshotSessionStore_WhenSnapshotsRoundTrip_PreservesFingerprints to also assert
the restored LastWriteTimeUtc and Length for MissingScenePath. Use
ExternalAssetSnapshotSessionStore.SerializeSnapshots/RestoreSnapshots and the
MissingScenePath entry to confirm the full fingerprint survives JSON storage.
🤖 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.

Nitpick comments:
In `@Assets/Tests/Editor/ExternalSceneChangeResolverTests.cs`:
- Around line 299-320: The round-trip test in ExternalSceneChangeResolverTests
only verifies the Exists flag for the missing-scene snapshot, so extend
SnapshotSessionStore_WhenSnapshotsRoundTrip_PreservesFingerprints to also assert
the restored LastWriteTimeUtc and Length for MissingScenePath. Use
ExternalAssetSnapshotSessionStore.SerializeSnapshots/RestoreSnapshots and the
MissingScenePath entry to confirm the full fingerprint survives JSON storage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0da70e09-e96e-464f-ae5b-be4d2f597a2d

📥 Commits

Reviewing files that changed from the base of the PR and between ce4f20b and 7f3690a.

📒 Files selected for processing (2)
  • Assets/Tests/Editor/ExternalSceneChangeResolverTests.cs
  • Packages/src/Editor/FirstPartyTools/Compile/ExternalSceneChangeResolver.cs
🚧 Files skipped from review as they are similar to previous changes (1)
  • Packages/src/Editor/FirstPartyTools/Compile/ExternalSceneChangeResolver.cs

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread Packages/src/Editor/FirstPartyTools/Compile/ExternalSceneChangeResolver.cs Outdated
Do not advance Prefab Stage baselines when reopening fails, because the editor can still be showing the previous Prefab contents. Also skip initial snapshot recording after held Auto Refresh recovery has already run preflight, and batch Scene snapshot persistence inside focus-return save loops.
@hatayama
hatayama merged commit 5972b81 into v3-beta Jul 1, 2026
10 checks passed
@hatayama
hatayama deleted the feature/hatayama/save-editor-state-before-commands branch July 1, 2026 09:24
@github-actions github-actions Bot mentioned this pull request Jul 1, 2026
RyanXie123 pushed a commit to RyanXie123/unity-cli-loop that referenced this pull request Sep 22, 2026
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