Skip to content

[iOS] ScrollView: Complete element scroll requests inside collapsed branches - #37409

Merged
kubaflo merged 15 commits into
dotnet:inflight/currentfrom
albyrock87:fix-36801-followup-collapsed-element-requests
Aug 19, 2026
Merged

kubaflo merged 15 commits into
dotnet:inflight/currentfrom
albyrock87:fix-36801-followup-collapsed-element-requests

Conversation

@albyrock87

@albyrock87 albyrock87 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

1. The final review-round commit that missed the merge. #37060 was merged at e3f386a811 a few hours before its last round landed, so the two findings adopted from the final AI review (and referenced in the inline replies there) never shipped:

  • A parked element scroll request has one contract: it lives exactly as long as the task the caller is awaiting. An element-mode request parked for arranged geometry (issued before the first layout, e.g. from OnAppearing) leaves the park in exactly two ways and no other: the arrange arrives and the request is replayed against real geometry (the task completes with the scroll), or the view's lifecycle ends — its handler goes away or it is removed from the tree — and the request is dropped (the task completes without a scroll). Nothing releases the task while a request is still parked, so a completed await can never scroll later; and nothing but a lifecycle end drops the request, so a view that is merely hidden (a collapsed branch, an unselected Shell tab) still scrolls to the element when it is eventually shown and arranged. A view that stays attached and is never arranged keeps the task pending — that is the contract, not a leak: the task completes when the scroll happens or the view is torn down. Removal from the tree is the newly-covered lifecycle end: LayoutHandler.Remove detaches only the platform view and does not disconnect the child's handler, so without it a removed ScrollView held a parked request nobody would ever retry.
  • A dropped request completes its task inline, at the moment it is dropped, binding the release to that request by construction — there is no window in which a newer ScrollToAsync could swap the completion source and be released in its place. This is the convention already in place (the shipped handler-detach drop and Core's DisconnectHandler both complete inline from their lifecycle hooks); the completion source construction is unchanged from before this PR, so ordinary await ScrollToAsync(...) timing is untouched on every platform.
  • The geometry gate is per-target. The ScrollView itself is a valid target (ScrollToAsync(scrollView, …)) and resolves to the origin needing only its own geometry; any other target sits inside the content and needs the content arranged too. A descendant target can be orphaned while parked (the content it hung off is removed, or replaced with content that no longer contains it): no arrange of this ScrollView can ever give it a position, so that is a terminal condition — the request is dropped and completed at the moment of orphaning, from the Content setter. Content replaced with a layout that still contains the target keeps waiting for that content's arrange.
  • A request made from inside the replayed ScrollToRequested event wins over the replay. A subscriber (as a compatibility renderer would be) that issues a new ScrollToAsync from inside the event previously had its request sent and then the stale replay sent on top of it, landing on the old target. The replay now yields when a request was made during the event, detected by the completion source having changed (every request creates a fresh one). The mechanism is UI-thread-affine, so re-entrant callbacks are its only race surface; every mutation site clears state before invoking any callback and re-checks after, and both re-entrant orderings (from the drop's inline completion, and from the replayed event) are pinned by tests that fail without the fix.
  • Reparenting cancels a pending element scroll. Removal from the tree includes the transient removal of a reparent: a request made against a tree position that no longer exists completes at the removal and is not carried into the new parent (a caller that moves a ScrollView with a pending scroll re-requests it there). The drop is deliberately not deferred to watch for a re-add, since a window between drop and completion is exactly what allows a newer request to be released in the old one's place.
  • SafeAreaBakedIntoContent is captured at arrange time, alongside the arranged rect, instead of being re-derived live from UIKit state: under Automatic the arrange that bakes the padding can push the content size past the bounds, at which point UIKit turns the adjusted inset non-zero while the content still carries the padding — a live read got that window wrong. The arrange branch and the _safeArea source selection share one predicate (UIKitCompensatesForSafeArea) where live evaluation is the correct semantics.

2. Repair of the Issue36801 inset-mode expectations crossed by the landscape-notch revert. The fixtures merged with #37060 asserted SafeAreaEdges.Default resolves to Never, matching the landscape-notch fix (#35533) present in inflight/current at the time. That fix has since been reverted (#36580), so Default resolves to Automatic again and the shipped resolved-mode sentinel currently fails the suite on this base. This restores the Automatic expectations in the shared tests and the HostApp oracle — the sentinel failing loudly on both transitions is it doing exactly what it was designed for (never silently testing a different clamp branch).

No new public API; WillArrange and UIKitCompensatesForSafeArea are private.

Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the collapsed-branch finding and the shared-predicate finding.

Tests

Verified on the current inflight/current base on the iOS simulator:

  • ScrollViewUnitTests: 39/39 — including tests pinning each edge of the contract: a hidden view waits and scrolls once shown; a view leaving the tree drops the request, completes the task, and does not resurrect the request if re-attached; drop-then-new-request on both lifecycle ends completes only the dropped task and leaves the new one to scroll (reproduced failing on the deferred design); consecutive and doubled lifecycle ends; pre-handler parks in both modes leaving the tree; supersede while geometry-parked; content replacement with and without the target; content removal; the self-target on a content-less ScrollView; reparent cancellation; re-entrant requests from the drop continuation and from the replayed event
  • Issue36801 + Issue36801DeferredElement + ShellFlyoutHeaderScrollViewContent UI suites: 12/12 — note these fail on the base without the expectation repair in this PR.

🤖 Generated with Claude Code

albyrock87 and others added 2 commits August 13, 2026 18:52
…the baked-safe-area predicate

Two adopted findings from the latest review round:

An element-mode request parked for arranged geometry is retried only by
OnSizeAllocated/ContentSizeChanged, and a view anywhere inside a
collapsed (IsVisible=false) branch is skipped by layout entirely — so
parking there left the caller's ScrollToAsync task pending forever.
Both park sites now check WillArrange() (the IsVisible chain) and
dispatch immediately when no arrange is coming: the target clamps and
the task completes, matching the other platforms' behavior for a
collapsed scroll view.

SafeAreaBakedIntoContent restated the arrange branch's predicate, so an
edit to one could silently desynchronize the other by a full safe-area
thickness. Both now share UIKitCompensatesForSafeArea, and the doc spells
out the one deliberate asymmetry: the horizontal safe-area origin the
landscape-notch arrange keeps for vertical Automatic is not reported,
because that axis cannot scroll and the arranged-rect origin already
carries it for the extent.

Verified: ScrollViewUnitTests 25/25 (two new regression tests), and the
Issue36801 + Issue36801DeferredElement + ShellFlyoutHeaderScrollViewContent
iOS UI suites 12/12 on the simulator.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…ndscape-notch revert

The Issue36801 fixtures merged with PR dotnet#37060 asserted the resolved
ContentInsetAdjustmentBehavior for SafeAreaEdges.Default as Never,
matching the landscape-notch fix (dotnet#35533) that was in inflight/current
at the time. That fix has since been reverted (dotnet#36580), so Default
resolves to Automatic again and the shipped resolved-mode sentinel now
fails the suite on the current base. Restore the Automatic expectations
in the shared tests and the HostApp oracle; the sentinel is doing its
job both times, failing loudly instead of silently testing a different
clamp branch.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Aug 13, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@albyrock87! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @albyrock87! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 13, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 3 findings

See inline comments for details.

_replayPendingScrollToRequestedEvent = true;
}
else if (e.Mode == ScrollToMode.Element && !IsElementTargetGeometryReady())
else if (e.Mode == ScrollToMode.Element && !IsElementTargetGeometryReady() && WillArrange())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness / Regression Prevention — WillArrange() is evaluated only at the two entry points that park or re-dispatch a request (here, and DispatchPendingScrollToRequest on handler attach). It is a point-in-time snapshot: nothing re-evaluates it when visibility changes later. Concrete scenario that still hangs: ScrollToAsync(item, ScrollToPosition.End, false) is called from OnAppearing while the branch is visible and geometry is not ready, so WillArrange() returns true and the request parks; the same code path then sets container.IsVisible = false (a loading/empty-state toggle) before the first arrange. The collapsed branch is skipped by layout, so neither OnSizeAllocated nor ContentSizeChanged ever fires, the handler stays non-null (so the OnHandlerChangedCore release path at line 55 does not run), and the caller's task stays pending forever — the exact failure mode this PR set out to remove, only with the collapse happening after the park instead of before. Reparenting a ScrollView with a parked request into a collapsed branch is the same class. A re-check of the parked request when IsVisible changes (or on the propagated visibility change) would close it; as written neither added test (ElementRequestOnCollapsedScrollViewCompletesInsteadOfHanging collapses before the request, DeferredElementRequestOnCollapsedAncestorDispatchesOnAttach collapses before attach) exercises the collapse-after-park ordering, so the gap is untested as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not adopted — the collapse-after-park window is real but bounded, and every fix shape for it costs more than the residual it closes. The bounds: a request parked while visible self-heals on both exits — if the branch is ever shown again, the arrange fires and the request drains correctly (the desired outcome, not a hang), and if the view goes away, the handler detach drains and completes the task. A permanent hang therefore requires the app to keep an invisible, handler-attached ScrollView alive indefinitely while awaiting its scroll. Closing that window would mean PropertyChanged subscriptions across the entire ancestor chain with re-walks on reparenting — a mutable subscription web whose own failure modes (leaks, stale handlers, re-entrancy during layout) have a larger expected cost than the marginal case it removes; a partial guard (self-only IsVisible watch) would cover a slice while conceding the class, which is worse than a clear boundary. The boundary as shipped: visibility is evaluated at park time and at every retry (now across all visual ancestors, per the sibling thread); transitions during the parked window heal on re-show or detach. Worth noting this point-in-time semantics is also what the previous round's winning candidate validated.

// completes it, which is also what the other platforms do with a collapsed scroll view.
bool WillArrange()
{
for (Element element = this; element is VisualElement visual; element = element.RealParent)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness — the ancestor walk terminates at the first non-VisualElement in the chain (element is VisualElement visual is the loop condition), so it never sees visibility state carried by non-visual ancestors. A ScrollView hosted in a Shell tab stops the walk at ShellContent/ShellSection (BaseShellItem : NavigableElement : Element, not a VisualElement) even though BaseShellItem exposes its own IsVisible; a hidden or not-yet-realized ShellContent therefore yields WillArrange() == true, the request parks, and if that branch is never arranged the caller's task never completes. Same for any custom non-visual container in the chain. The helper's comment claims the check covers "a view anywhere inside a collapsed branch", which is only true for chains that are VisualElement all the way up — worth either handling the BaseShellItem.IsVisible hop or narrowing the comment to the guarantee actually provided. No test covers a non-VisualElement boundary in the chain.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adopted in 7306000, taking the narrowing option for the non-visual half: the walk now traverses the whole RealParent chain and checks IsVisible on every VisualElement it crosses, skipping over non-visual links instead of stopping — so a collapsed Shell (or any visual ancestor beyond a non-visual container) is seen. A new unit test (CollapsedShellAncestorBeyondNonVisualLinksIsDetected) exercises exactly the ShellContent/ShellSection boundary and fails under the old walk. BaseShellItem.IsVisible is deliberately not consulted, per the comment now stating the precise guarantee: for a hidden tab, parking keeps the scroll correct if the tab is ever shown, while early-completing would execute a garbage scroll — and a handler detach still completes the task either way.

/// coordinate space instead. Shared by the arrange branch and
/// <see cref="SafeAreaBakedIntoContent"/> so the two can never desynchronize.
/// </summary>
bool UIKitCompensatesForSafeArea =>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[minor] Complexity Reduction — the new property's summary states it is "shared by the arrange branch and SafeAreaBakedIntoContent so the two can never desynchronize", but a third occurrence of the identical predicate remains inline at line 395 (if (SystemAdjustedContentInset == UIEdgeInsets.Zero || ContentInsetAdjustmentBehavior == ...Never)), and that one selects the source of _safeArea — the very value SafeAreaBakedIntoContent returns. Leaving it duplicated means a future change to UIKitCompensatesForSafeArea silently diverges from the _safeArea computation it feeds, which is the desynchronization the refactor is meant to prevent. Converting line 395 to !UIKitCompensatesForSafeArea is behavior-preserving (the De Morgan negation matches exactly, as it does for the two sites already converted).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adopted in 9f439ed — the _safeArea source selection in ValidateSafeArea now uses !UIKitCompensatesForSafeArea too, and the property doc lists all three sites. You're right that leaving it inline kept alive exactly the desynchronization the refactor exists to prevent.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Aug 13, 2026
albyrock87 and others added 2 commits August 14, 2026 10:37
ValidateSafeArea still selected the _safeArea source with the inline
condition that UIKitCompensatesForSafeArea now names — and that value is
exactly what SafeAreaBakedIntoContent returns, so leaving it duplicated
kept alive the desynchronization the refactor exists to prevent. The De
Morgan negation is exact; no behavior change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…n the chain

WillArrange() terminated its walk at the first non-VisualElement parent,
so a collapsed VisualElement above a non-visual link — Shell itself
above ShellContent/ShellSection, or any custom non-visual container —
was never seen and the request parked for an arrange that cannot come.
The walk now traverses the whole RealParent chain and checks IsVisible
on the visual nodes it crosses. Non-visual containers' own visibility
semantics (a hidden tab, say) are deliberately not consulted: parking
keeps the scroll correct if that container is ever shown, and a handler
detach still completes the task; the comment now states that guarantee
precisely.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Aug 14, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Expert Review — 1 findings

See inline comments for details.

if (pending.Mode == ScrollToMode.Element && !IsElementTargetGeometryReady())
{
if (!IsElementTargetGeometryReady())
if (WillArrange())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[moderate] Logic and Correctness / Regression Prevention — WillArrange() treats "currently collapsed" as "will never arrange", but a collapsed branch that is later made visible does arrange. Concrete scenario: scrollView.IsVisible = false (or a collapsed ancestor layout), caller does await ScrollToAsync(item, ScrollToPosition.End, false), then the branch is set visible. Before this change the request parked and was replayed from OnSizeAllocated/ContentSizeChanged on the first real arrange, so it landed on item. Now it is dispatched immediately against the never-arranged sentinels (Width/Height == -1 → GetScrollPositionForElement yields ~(-1,-1), clamped to the origin), so when the branch is shown the scroll position is wrong and the request is gone (_pendingScrollToRequested = null). The same decision is made at line 559 in OnScrollToRequested. The three new unit tests all cover the never-shown case only; there is no test for collapsed-then-shown, so this behavior change is untested. Consider parking and completing the caller's task (or re-parking on the IsVisible false→true transition) so the hang is fixed without losing the correct target.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adopted in 7f625b3, with your park-and-complete shape: both sites now release the caller's task immediately when the branch is collapsed (no hang) while leaving the request parked — the first arrange after the branch is shown replays it against real geometry, so the scroll lands on the element exactly like a visible pre-arrange park. Latest-request-wins supersedes it as usual and a handler detach still drains it. The three collapsed-branch unit tests now assert the full sequence (caller released → no premature dispatch → shown-and-arranged replay landing on the element's computed position), closing the collapsed-then-shown coverage gap you noted.

One deliberate distinction, to head off a symmetry question with the drain-on-detach thread on #37060: showing a hidden view is the same living view continuing its lifecycle, so honoring the last requested target is the expected outcome — whereas replaying across a handler detach/reattach would resurrect a request from a completed lifecycle. The two behaviors are intentionally different for that reason.

MauiBot

This comment was marked as outdated.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Aug 14, 2026
@kubaflo
kubaflo merged commit a2935e6 into dotnet:inflight/current Aug 19, 2026
34 of 38 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Aug 19, 2026
@albyrock87

Copy link
Copy Markdown
Contributor Author

For anyone following the last review round here: the two findings from it (the superseded-replay strand and the inline completion inside SetParent) were confirmed, and — together with a third hole the fix audit surfaced (a parked request displaced by any newer ScrollToAsync orphaned the first caller's task, reachable by two ordinary calls in a row) — are fixed in follow-up #37666, which landed after this PR merged. All three share one primitive: a captured-by-value, dispatcher-posted completion applied at every point a request ends without its scroll.

kubaflo pushed a commit that referenced this pull request Aug 20, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Aug 26, 2026
…ranches (#37837)

<!-- 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!
 
### Description of Change
 
Ported the changes from PR #37409 to the inflight/Candidate branch.
kubaflo added a commit that referenced this pull request Aug 27, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Aug 27, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo added a commit that referenced this pull request Sep 2, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 2, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 3, 2026
…ranches (#37837)

<!-- 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!
 
### Description of Change
 
Ported the changes from PR #37409 to the inflight/Candidate branch.
kubaflo added a commit that referenced this pull request Sep 3, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 3, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 4, 2026
…ranches (#37837)

<!-- 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!
 
### Description of Change
 
Ported the changes from PR #37409 to the inflight/Candidate branch.
kubaflo added a commit that referenced this pull request Sep 6, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 6, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo added a commit that referenced this pull request Sep 7, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 7, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 7, 2026
…ranches (#37837)

<!-- 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!
 
### Description of Change
 
Ported the changes from PR #37409 to the inflight/Candidate branch.
kubaflo added a commit that referenced this pull request Sep 8, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 8, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 8, 2026
…ranches (#37837)

<!-- 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!

Ported the changes from PR #37409 to the inflight/Candidate branch.
kubaflo added a commit that referenced this pull request Sep 9, 2026
…ranches (#37409)

### Description of Change

Follow-up to #37060, carrying two pieces the merged PR is missing:

**1. The final review-round commit that missed the merge.** #37060 was
merged at `e3f386a811` a few hours before its last round landed, so the
two findings adopted from the final AI review (and referenced in the
inline replies there) never shipped:

- **A parked element scroll request has one contract: it lives exactly
as long as the task the caller is awaiting.** An element-mode request
parked for arranged geometry (issued before the first layout, e.g. from
`OnAppearing`) leaves the park in exactly two ways and no other: the
arrange arrives and the request is replayed against real geometry (the
task completes *with* the scroll), or the view's lifecycle ends — its
handler goes away or it is removed from the tree — and the request is
dropped (the task completes *without* a scroll). Nothing releases the
task while a request is still parked, so a completed `await` can never
scroll later; and nothing but a lifecycle end drops the request, so a
view that is merely hidden (a collapsed branch, an unselected Shell tab)
still scrolls to the element when it is eventually shown and arranged. A
view that stays attached and is never arranged keeps the task pending —
that is the contract, not a leak: *the task completes when the scroll
happens or the view is torn down*. Removal from the tree is the
newly-covered lifecycle end: `LayoutHandler.Remove` detaches only the
platform view and does not disconnect the child's handler, so without it
a removed ScrollView held a parked request nobody would ever retry.
- **A dropped request completes its task inline, at the moment it is
dropped**, binding the release to that request by construction — there
is no window in which a newer `ScrollToAsync` could swap the completion
source and be released in its place. This is the convention already in
place (the shipped handler-detach drop and Core's `DisconnectHandler`
both complete inline from their lifecycle hooks); the completion source
construction is unchanged from before this PR, so ordinary `await
ScrollToAsync(...)` timing is untouched on every platform.
- **The geometry gate is per-target.** The ScrollView itself is a valid
target (`ScrollToAsync(scrollView, …)`) and resolves to the origin
needing only its own geometry; any other target sits inside the content
and needs the content arranged too. A descendant target can be
*orphaned* while parked (the content it hung off is removed, or replaced
with content that no longer contains it): no arrange of this ScrollView
can ever give it a position, so that is a terminal condition — the
request is dropped and completed at the moment of orphaning, from the
`Content` setter. Content replaced with a layout that still contains the
target keeps waiting for that content's arrange.
- **A request made from inside the replayed `ScrollToRequested` event
wins over the replay.** A subscriber (as a compatibility renderer would
be) that issues a new `ScrollToAsync` from inside the event previously
had its request sent and then the stale replay sent on top of it,
landing on the old target. The replay now yields when a request was made
during the event, detected by the completion source having changed
(every request creates a fresh one). The mechanism is UI-thread-affine,
so re-entrant callbacks are its only race surface; every mutation site
clears state before invoking any callback and re-checks after, and both
re-entrant orderings (from the drop's inline completion, and from the
replayed event) are pinned by tests that fail without the fix.
- **Reparenting cancels a pending element scroll.** Removal from the
tree includes the transient removal of a reparent: a request made
against a tree position that no longer exists completes at the removal
and is not carried into the new parent (a caller that moves a ScrollView
with a pending scroll re-requests it there). The drop is deliberately
not deferred to watch for a re-add, since a window between drop and
completion is exactly what allows a newer request to be released in the
old one's place.
- **`SafeAreaBakedIntoContent` is captured at arrange time**, alongside
the arranged rect, instead of being re-derived live from UIKit state:
under `Automatic` the arrange that bakes the padding can push the
content size past the bounds, at which point UIKit turns the adjusted
inset non-zero while the content still carries the padding — a live read
got that window wrong. The arrange branch and the `_safeArea` source
selection share one predicate (`UIKitCompensatesForSafeArea`) where live
evaluation is the correct semantics.

**2. Repair of the `Issue36801` inset-mode expectations crossed by the
landscape-notch revert.** The fixtures merged with #37060 asserted
`SafeAreaEdges.Default` resolves to `Never`, matching the
landscape-notch fix (#35533) present in `inflight/current` at the time.
That fix has since been reverted (#36580), so `Default` resolves to
`Automatic` again and the shipped resolved-mode sentinel currently fails
the suite on this base. This restores the `Automatic` expectations in
the shared tests and the HostApp oracle — the sentinel failing loudly on
both transitions is it doing exactly what it was designed for (never
silently testing a different clamp branch).

No new public API; `WillArrange` and `UIKitCompensatesForSafeArea` are
private.

### Issues Fixed

Follow-up to #37060 (fixes for #36801). Review threads addressed: the
[collapsed-branch
finding](#37060 (comment))
and the [shared-predicate
finding](#37060 (comment)).

### Tests

Verified on the current `inflight/current` base on the iOS simulator:

- `ScrollViewUnitTests`: 39/39 — including tests pinning each edge of
the contract: a hidden view waits and scrolls once shown; a view leaving
the tree drops the request, completes the task, and does not resurrect
the request if re-attached; drop-then-new-request on both lifecycle ends
completes only the dropped task and leaves the new one to scroll
(reproduced failing on the deferred design); consecutive and doubled
lifecycle ends; pre-handler parks in both modes leaving the tree;
supersede while geometry-parked; content replacement with and without
the target; content removal; the self-target on a content-less
ScrollView; reparent cancellation; re-entrant requests from the drop
continuation and from the replayed event
- `Issue36801` + `Issue36801DeferredElement` +
`ShellFlyoutHeaderScrollViewContent` UI suites: 12/12 — note these fail
on the base without the expectation repair in this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
…ranches (#37837)

<!-- 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!

Ported the changes from PR #37409 to the inflight/Candidate branch.
kubaflo pushed a commit that referenced this pull request Sep 11, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 15, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
kubaflo pushed a commit that referenced this pull request Sep 18, 2026
…'s task (#37666)

### Description of Change

Follow-up to #37409 (itself a follow-up to #37060), closing three holes
of the same species in the deferred element-scroll machinery: **a
request that ends without its task completing, or whose completion runs
on the wrong stack.** Two are permanent hangs of `await
ScrollToAsync(...)`; one is reachable by entirely ordinary code.

1. **A parked request displaced by any newer `ScrollToAsync` orphaned
the first caller's task** — two calls in a row (say, both from
`OnAppearing` before the first layout) and the first `await` never
returns. Nothing else ever completes it: the superseding request creates
a fresh completion source, and the `TaskStatus.Running` check in
`CheckTaskCompletionSource` is dead code (a TCS-backed task reports
`WaitingForActivation`, never `Running`, so the `TrySetCanceled` there
is unreachable). This is the headline fix.
2. **Yielding the replay to a re-entrant `ScrollToRequested` subscriber
abandoned the superseded caller's task** — same mechanism, narrower
trigger (a legacy renderer issuing its own `ScrollToAsync` from inside
the replayed event): permanent hang.
3. **The lifecycle-drop completion ran the caller's continuation from
inside `Element.SetParent`**, before `OnPropertyChanged(nameof(Parent))`
fires — caller code observing/mutating a half-propagated parent change.

**One primitive fixes all three.** `CompleteWithoutScroll(completion)`
captures the completion source **as a value** and posts
`TrySetResult(true)` through the dispatcher:

- **off the mutation stack** (fixes 3) — the continuation never runs
inside `SetParent`/handler-change;
- **bound by identity** (preserves the invariant from #37409's review
rounds) — the post cannot read the field at fire time, so a newer
request swapping `_scrollCompletionSource` in the window can never be
released in the old request's place;
- **applied at every point a request ends without its scroll** — the
drop paths (detach, tree-removal, orphaned target), the yielded replay
(fixes 2), and the supersede in `OnScrollToRequested` (fixes 1).

The ordinary platform-callback completion (`SendScrollFinished` when a
scroll actually happens) is untouched, so `await ScrollToAsync(...)`
timing on the normal path is unchanged. Completing (rather than
cancelling) a superseded task matches the existing drop semantics — no
`await` in this API's history has thrown on supersede, and introducing
`TaskCanceledException` would be a new public behavior.

The contract comment now names all three exits from the park — replayed,
superseded, dropped — so the stated contract and the code have no gap.

No new public API.

### Issues Fixed

Follow-up to #37409 / #37060 (fixes for #36801).

### Tests

Every fix is pinned by a test **proven to fail with that fix reverted**:

- `SupersedingAParkedRequestCompletesTheSupersededCallersTask` — both
supersede shapes (direct send, and park-in-place)
- `ReentrantRequestFromTheReplayedEventSupersedesTheReplay` — extended
to assert the superseded caller is released
- `DropCompletionIsPostedNotRunOnTheMutationStack` — dispatcher-capture
harness: task pending after `Remove` returns, exactly one post queued,
completes when it runs
-
`PostedDropCompletionReleasesOnlyTheDroppedTaskEvenIfANewRequestArrivesFirst`
— the identity property: a new request arriving before the post runs is
untouched; the dropped task completes (this test fails against a
field-reading post, the bug shape from #37409's review)

Verified on the merged `inflight/current` base: `ScrollViewUnitTests`
42/42 (10 consecutive runs), `Issue36801` + `Issue36801DeferredElement`
+ `ShellFlyoutHeaderScrollViewContent` iOS UI suites 12/12 on the
simulator.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 19, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

community ✨ Community Contribution s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants