Repository navigation
[iOS/MacCatalyst] Arm CollectionView anchor animations before reentrant UIKit callbacks - #40828
Merged
Merged
Conversation
Arm the edge and target before UIKit can synchronously raise Scrolled or an animation end, so an older call cannot overwrite the marker of a newer request. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Contributor
Author
|
@dalexsoto stamp |
This comment has been minimized.
This comment has been minimized.
kubaflo
temporarily deployed
to
copilot-pat-pool
November 29, 2026 21:41 — with
GitHub Actions
Inactive
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
kubaflo
temporarily deployed
to
copilot-pat-pool
November 29, 2026 21:42 — with
GitHub Actions
Inactive
kubaflo
temporarily deployed
to
copilot-pat-pool
November 29, 2026 21:43 — with
GitHub Actions
Inactive
kubaflo
temporarily deployed
to
copilot-pat-pool
November 29, 2026 21:44 — with
GitHub Actions
Inactive
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Contributor
There was a problem hiding this comment.
🔵 Needs a closer look
The UIKit callback-ordering fix still needs native iOS and configured macOS 27 CI validation, since reported testing covers only local Catalyst.
No open issues 🎉
What changed in this PR
This PR fixes scroll-anchor animation ownership in the iOS/Mac Catalyst CollectionView handler. It complements #40817 by recording animation state before UIKit callbacks can synchronously start or complete another request.
Changes:
- Set start/end animation markers before calling UIKit, preserving newer requests made during callbacks.
- Publish the tracker’s current anchored state instead of an unconditional value.
- Add a deterministic native regression test covering a reentrant End request followed by disabling anchoring and growing the last row.
| File | Description |
|---|---|
src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.ScrollAnchor.cs |
Adds the regression test and private native helpers that trigger synchronous callbacks. |
src/Controls/src/Core/Handlers/Items2/iOS/CollectionViewScrollAnchor.cs |
Records animation ownership before native scrolling and publishes current anchor state. |
Review effort: Balanced
kubaflo
temporarily deployed
to
copilot-pat-pool
November 29, 2026 21:46 — with
GitHub Actions
Inactive
kubaflo
temporarily deployed
to
copilot-pat-pool
November 29, 2026 21:46 — with
GitHub Actions
Inactive
This was referenced Nov 30, 2026
1 of 2 tasks
kubaflo
added a commit
that referenced
this pull request
Nov 30, 2026
…nimates the view back as it lays it out (#40854) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `06dd7c47b0c2d9b0c41cb5aafc4e57fc09571b75` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ The new test fails without the fix in every local run (Mac Catalyst 40/40, iOS 27 simulator 42/42) and passes with it (iOS 27 42/42, Mac Catalyst 39/40; the one miss timed out in the harness window setup before the test body ran).<br>↑ Whole CollectionView device-test family with the fix: Mac Catalyst 422 passed, 0 failed, 8 skipped in two runs; iOS 27 418 passed, 0 failed, 8 skipped.<br>↑ Acts only on a scroll animation UIKit starts inside a layout pass while the view follows an edge; animations the app or the anchor started, drags and decelerations are excluded. No public API change. Merges cleanly with #40828.<br>↓ No PR CI: the device-test pipelines are disabled. The local host runs macOS 26.7.3; CI runs macOS 27.2. | | Diagnosis confidence | 8.5/10 | ↑ Native stack of the animation start: -[UICollectionView layoutSubviews] → _setContentSize:skipContentOffsetAdjustment: → performWhileAnimatingAutomaticContentOffsetAdjustments: → _adjustContentOffsetIfNecessary → setContentOffset:animated:YES (850 → 760).<br>↑ Anchor trace: ScrollAnimating turns true in that layout pass, the anchor counts it as user scrolling, and it switches from End to None once the re-targeted animation is 10 points above the end.<br>↓ When UIKit animates this adjustment rather than applying it at once is inferred from private method names. | | Evidence fit | 4/10 | ↑ Same signature as the Mac Catalyst CI failures in builds 1704369 and 1704494: the list stops following its end and stays a fixed distance above it (370 in both).<br>↓ The flaky test's own shrink step doesn't start this animation on macOS 26.7.3 or the iOS 27 simulator (100+ local runs pass before and after the fix), so it isn't confirmed that macOS 27 takes this path; CI is disabled. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!NOTE] > Are you waiting for the changes in this PR to be merged? > It would be very helpful if you could [test the resulting artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> This investigates the intermittent Mac Catalyst device-test failure `[CollectionView] Back at the end after a ScrollTo away, the list keeps the end in view as the last item shrinks` on `main` ("Following the end, the list should keep the end in view as the last item shrinks. Distance to the end: 370."). It fixes a deterministic `ScrollAnchorMode` (#40211) defect on iOS and Mac Catalyst that leaves the list in the same failed state. **Root cause.** When the content of a `UICollectionView` shrinks under its content offset during a layout pass, UIKit animates the view back within the content. Native stack captured locally on Mac Catalyst: ``` -[UICollectionView setContentOffset:animated:] animated: YES, 850 → 760 -[UICollectionView _applyAutomaticAdjustedContentOffset:] -[UIScrollView _adjustContentOffsetIfNecessary] -[UIScrollView setContentSize:] -[UICollectionView setContentSize:] -[UIScrollView performWhileAnimatingAutomaticContentOffsetAdjustments:] -[UICollectionView _setContentSize:skipContentOffsetAdjustment:] -[UICollectionView _updateVisibleCellsNow:] -[UICollectionView layoutSubviews] ``` `CollectionViewScrollAnchor` treats every scroll animation it didn't start as a fling (`ScrollAnimating`), and stops correcting until it ends. On its way, UIKit measures the rows the animation brings into view and re-targets it, so the view ends up above where the end settles. The anchor sees the view move more than its threshold away from the end and stops following it (`End → None`), and the view stays there. This happens whenever rows are shorter than UIKit's 30-point estimate (`LayoutFactory2` uses `NSCollectionLayoutDimension.CreateEstimated(30)`). The anchor goes to the end as estimated, UIKit measures the rows there shorter, the content shrinks under the view, and UIKit animates back. **Fix.** `CollectionViewScrollAnchor.LayoutStarting` now notes whether a scroll animation is running when an outermost layout pass starts. In `LayoutFinished`, if one is running that wasn't before, and neither the anchor nor the app started one (no edge animation, no animated request, no drag or deceleration), UIKit started it while laying the view out. A view that follows an edge stops it where it starts with `SetContentOffset(ContentOffset, false)`, the idiom the controller already uses to stop animations. The usual post-layout look then scrolls to the edge. Views that don't follow an edge keep UIKit's animation. The three `LayoutStarting` call sites in `ItemsViewController2` now pass the collection view. **Regression test.** `AnchorMode End shows and follows the end of rows shorter than UIKit estimates them` (iOS and Mac Catalyst): 40 rows of 20 points must open at their end, and the list must keep following its end when 20 more arrive. | Local run | Without the fix | With the fix | |---|---|---| | Mac Catalyst (macOS 26.7.3), new test ×20 per navigation variant | 40/40 failed: 32 didn't open at the end (45 to 89.5 above it), 8 lost it after the batch (up to 486 above) | 39/40 passed; the other timed out in the harness window setup (`OnLoadedAsync`) before the test body ran | | iOS 27.0 simulator, new test ×21 per navigation variant | 42/42 failed: 40 didn't open at the end (40 above it), 2 lost it after the batch | 42/42 passed | | Mac Catalyst, whole CollectionView family (both variants) | — | 422 passed, 0 failed, 8 skipped (two runs) | | iOS 27.0 simulator, whole CollectionView family | — | 418 passed, 0 failed, 8 skipped | The repeated runs used a temporary local theory that called the new test; it isn't part of this PR. The flaky test also passed 40/40 locally with the fix, and its assertions are unchanged. **Relationship to the Mac Catalyst CI failure.** Both observed failures end with the list no longer following its end and a stable 370 points above it: build 1704369 on main `9c4919b856` (`[NavigationViewHandler]`) and build 1704494 (`[NavigationRenderer]`). That's the state this defect leaves the view in. Locally, though, the flaky test's shrink step doesn't take this path. On macOS 26.7.3 and on the iOS 27 simulator, UIKit re-estimates the rows above and moves the offset in that layout pass before it shrinks the content, so it never animates. More than 100 local runs of that test passed, with and without this change, including in the full family. CI runs macOS 27.2, which I couldn't run locally. So this PR fixes a real, deterministic anchor defect with the same failure signature, and it's the most likely explanation I found, but it doesn't prove that the macOS 27 run took this path. Other findings, not changed here: - With macOS keyboard navigation enabled, the focus engine asks the collection view for `preferredFocusedView`. UIKit then sizes that cell outside a layout pass (`_endReusableViewCreationAndSelfSizingOutsideVisibleCellsUpdate`), and applies the compositional layout's content-offset adjustment at once. It reports the move to `scrollViewDidScroll` before it updates the content size, and the anchor judges it as a scroll. With rows taller than the estimate, as in the flaky test, the move is toward the end and harmless. With shorter rows it briefly un-anchors the list. A possible follow-up is to treat offset changes made inside `CustomUICollectionViewCompositionalLayout.InvalidateLayout(context)` as layout. - #40828 changes the animated `ScrollToStart`/`ScrollToEnd` branches; this PR changes `LayoutStarting`/`LayoutFinished`. Their hunks don't overlap, and a trial merge is clean. #40817 is unaffected. **CI.** `maui-pr`, `maui-pr-uitests` and `maui-pr-devicetests` have been disabled since 2026-11-29 23:22 UTC, so CI hasn't run on this PR. It's pending until the pipelines are re-enabled; the validation above is local. Validation, with the pinned SDK `12.0.100-alpha.1.26523.103` and Xcode 27.2 (hence `-SkipXcodeVersionCheck`): ```bash pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst \ -DotnetPath "$PWD/.dotnet/dotnet" -SkipXcodeVersionCheck \ -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests # passed: 422 passed, 0 failed, 8 skipped (430 total), in two runs pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -iOSVersion 27 \ -DotnetPath "$PWD/.dotnet/dotnet" -SkipXcodeVersionCheck \ -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests # passed: 418 passed, 0 failed, 8 skipped (426 total) pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst \ -DotnetPath "$PWD/.dotnet/dotnet" -SkipXcodeVersionCheck \ -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CollectionViewNavigationHandlerTests \ -IncludeMethods AnchorModeEndShowsAndFollowsTheEndOfRowsShorterThanEstimated # without the product change: 0 passed, 2 failed (distances 67.5 and 490); with it: 2 passed dotnet format whitespace Microsoft.Maui.sln --no-restore --exclude Templates/src --include <the three changed files> # passed, no changes ``` ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No standalone issue. Related to #40211 (ScrollAnchorMode), the intermittent Mac Catalyst failure above, #40828 and #40817. ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
34743c3d66cdd5a00ce98ef5166238e6c13c5a48↓ Other platform results have not been exhaustively reviewed.
↓ The exact CI Position 1090 case was not reproduced naturally locally; other family failures may have additional causes.
↓ The exact intermittent 1090 symptom was not naturally reproduced locally; local OS differs from CI.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewFor .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
Fix shared CollectionView scroll-anchor animation ownership, not individual test delays or assertion tolerances. This is a new branch from
6e6416eece627b26e7ac45a92a3c64427c3ded4b, after #40817 merged; its request-scoped completion fix is retained unchanged.Root cause:
CollectionViewScrollAnchor.ScrollToStartandScrollToEndassigned_edgeAnimationafter calling UIKit. UIKit can synchronously raiseScrolledor an animation end before returning. IfScrolledstarts a newer End request, the older Start call resumes and overwrites the newer marker with(Start, 0). Turning anchoring off then transfers the wrong completion correction. Diagnostic output on merged main showedrequestedEnd=True marker=(Start, -0) offset=0, followed by failure to reach the measured end.Fix: Arm the edge/target before calling
SetContentOffset, and do not write it again afterward. A newer reentrant request—or synchronous completion clearing the marker—therefore survives. Publish the current tracker state rather than an unconditional anchored value.Regression test: A private native test view detaches immediately before the native
SetContentOffset, after the anchor has selected its animated branch. UIKit really jumps and reports callbacks synchronously; no delegate completion is fabricated. The app reattaches and requests End fromScrolled, then disables anchoring and grows the last row. The test waits for a real window and the grown native cell before checking the measured end. Both navigation variants run it. The helper exists only to make the window/callback interleaving deterministic; production code gains no test hook.Baseline comparison
The exact reported case is:
An animated ScrollToStart or ScrollToEnd right after one to the other edge that doesn't animate wins(anchorMode: Start | End, edge: End, headerAndFooter: False).Raw Catalyst logs show it ran without failure in both navigation variants in all five baseline builds:
9c4919b856a16185b807cea39ee6e3Logs inspected: 835, 849, 769, 783, and 849 respectively. #40806 changes iOS simulator provisioning; #40802's change is Windows-only. Neither changes the Catalyst scroll-anchor implementation.
1704445, #40817 merge
78e680c543, is the first observed failure of this exact case in the inspected set: log 784,Position: 1090.Attribution boundary: The exact 1090 failure did not reproduce naturally locally. Repeated full-fixture runs and width probes (320/800/1200/6650) did reproduce a related native reentrant End failure. The controlled window interleaving then proved this shared marker bug on both pre-#40817 and merged-main code. This establishes a pre-existing ownership defect, not a proven introduction of the exact CI symptom by #40817. No per-test assertion was weakened.
Causal local validation
macOS 26.7.3, Xcode 27.2, pinned SDK
12.0.100-alpha.1.26523.103from the existing fallback SDK directory. The installed Xcode is newer than the workload's requested 27.1, so-SkipXcodeVersionCheckwas used. All execution was in-process Mac Catalyst; no physical devices or host XCTest UI automation.The following exact command was used with the fix and again with only
CollectionViewScrollAnchor.csrestored to merged main:ItemsViewController2.csandGroupableItemsViewController2.csfromcea39ee6e3, the same repro also failed twice, at offset 1080 and distance 340. Both files were restored to merged main afterward.artifacts/scroll-anchor/prearmed-reverted: 34 passed, 2 failed. Only the new regression variants failed, with end distances 210 and 340.422 passed, 0 failed, 8 existing skips (430 total), verified from genuine
testResults.trx.Additional checks:
dotnet build Microsoft.Maui.BuildTasks.slnf --nologo -v:q: passed, 0 warnings/errors.dotnet format whitespace Microsoft.Maui.sln --no-restore --exclude Templates/src --include src/Controls/src/Core/Handlers/Items2/iOS/CollectionViewScrollAnchor.cs src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.ScrollAnchor.cs: passed; workspace-loading warnings.git diff --check: passed.Ten further complete-family repetitions passed on committed revision
34743c3d66cdd5a00ce98ef5166238e6c13c5a48: 211 passed, 0 failed, 4 existing skips per run; aggregate 2110 passed, 0 failed, 40 skips. Each run includes the entire scroll-anchor family inCollectionViewNavigationHandlerTests, not just the newly added test. All ten fresh TRX files were checked.PR CI Catalyst controls is green: build 1704506, job
Catalyst controls CoreCLR macos27, completed/succeeded. Raw test-task log 778 reports 2190 passed, 0 failed, 42 skipped (2232 total). Both new regression variants appear in that log. The required real-TRX validation step also succeeded.CI tested merge
1f4954e3e5896dfc92b2e2c3380d123ea98a4d4b, whose parents are main3507ea53b79eee7d2452c2ba4609b05a98e6b0f4and this PR head34743c3d66cdd5a00ce98ef5166238e6c13c5a48. The newer main changes do not touch the scroll-anchor implementation.Post-#40817 main comparison: 1704496 at
6e6416eececompleted Catalyst tests with 2186 passed, 1 failed, 42 skipped (raw task log 813). The entire scroll-anchor family, including the exact 1090 variant, passed. Its only failure was the unrelated PageTransitions testA root replacement started from the assignment's PropertyChanging animates once its own page lands (UIKit)(“The queued replacement swapped the root without animating”). That main Catalyst job is therefore not called green; no unrelated product code was changed here.Issues Fixed
No standalone GitHub issue was supplied. Investigates the Catalyst scroll-anchor failures linked above; fixes the reproduced pre-existing marker-ownership race. Related to #40211 and merged #40817.
Let AI finish this PR