CmdPal: Cancel page load when superseded by a new page navigation (#42233)

## Summary of the Pull Request

This PR introduces cancellation support for navigation. If a user
navigates to page X and then returns back or navigates elsewhere before
the page X fully loads, this update ensures that page X will not set
itself as the current page and is ignored.

It resolves the issue where returning to the home page left the previous
page's icon and placeholder visible in the search bar, causing the
search functionality to fail.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [x] Closes: #42247
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
This commit is contained in:
Jiří Polášek
2025-10-08 22:25:33 +02:00
committed by GitHub
parent 0472e7dc78
commit ca4e8b2986
10 changed files with 243 additions and 63 deletions

View File

@@ -0,0 +1,12 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.Core.ViewModels;
/// <summary>
/// Encapsulates a navigation request within Command Palette view models.
/// </summary>
/// <param name="TargetViewModel">A view model that should be navigated to.</param>
/// <param name="NavigationToken"> A <see cref="CancellationToken"/> that can be used to cancel the pending navigation.</param>
public record AsyncNavigationRequest(object? TargetViewModel, CancellationToken NavigationToken);

View File

@@ -4,6 +4,4 @@
namespace Microsoft.CmdPal.Core.ViewModels.Messages;
public record NavigateToPageMessage(PageViewModel Page, bool WithAnimation)
{
}
public record NavigateToPageMessage(PageViewModel Page, bool WithAnimation, CancellationToken CancellationToken);

View File

@@ -0,0 +1,8 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CmdPal.Core.ViewModels;
internal sealed partial class NullPageViewModel(TaskScheduler scheduler, AppExtensionHost extensionHost)
: PageViewModel(null, scheduler, extensionHost);

View File

@@ -23,6 +23,9 @@ public partial class ShellViewModel : ObservableObject,
private readonly Lock _invokeLock = new();
private Task? _handleInvokeTask;
// Cancellation token source for page loading/navigation operations
private CancellationTokenSource? _navigationCts;
[ObservableProperty]
public partial bool IsLoaded { get; set; } = false;
@@ -66,6 +69,8 @@ public partial class ShellViewModel : ObservableObject,
public bool IsNested => _isNested;
public PageViewModel NullPage { get; private set; }
public ShellViewModel(
TaskScheduler scheduler,
IRootPageService rootPageService,
@@ -77,6 +82,7 @@ public partial class ShellViewModel : ObservableObject,
_rootPageService = rootPageService;
_appHostService = appHostService;
NullPage = new NullPageViewModel(_scheduler, appHostService.GetDefaultHost());
_currentPage = new LoadingPageViewModel(null, _scheduler, appHostService.GetDefaultHost());
// Register to receive messages
@@ -113,7 +119,7 @@ public partial class ShellViewModel : ObservableObject,
return true;
}
public async Task LoadPageViewModelAsync(PageViewModel viewModel)
private async Task LoadPageViewModelAsync(PageViewModel viewModel, CancellationToken cancellationToken = default)
{
// Note: We removed the general loading state, extensions sometimes use their `IsLoading`, but it's inconsistently implemented it seems.
// IsInitialized is our main indicator of the general overall state of loading props/items from a page we use for the progress bar
@@ -125,44 +131,80 @@ public partial class ShellViewModel : ObservableObject,
if (!viewModel.IsInitialized
&& viewModel.InitializeCommand is not null)
{
var outer = Task.Run(async () =>
{
// You know, this creates the situation where we wait for
// both loading page properties, AND the items, before we
// display anything.
//
// We almost need to do an async await on initialize, then
// just a fire-and-forget on FetchItems.
// RE: We do set the CurrentPage in ShellPage.xaml.cs as well, so, we kind of are doing two different things here.
// Definitely some more clean-up to do, but at least its centralized to one spot now.
viewModel.InitializeCommand.Execute(null);
await viewModel.InitializeCommand.ExecutionTask!;
if (viewModel.InitializeCommand.ExecutionTask.Status != TaskStatus.RanToCompletion)
var outer = Task.Run(
async () =>
{
if (viewModel.InitializeCommand.ExecutionTask.Exception is AggregateException ex)
// You know, this creates the situation where we wait for
// both loading page properties, AND the items, before we
// display anything.
//
// We almost need to do an async await on initialize, then
// just a fire-and-forget on FetchItems.
// RE: We do set the CurrentPage in ShellPage.xaml.cs as well, so, we kind of are doing two different things here.
// Definitely some more clean-up to do, but at least its centralized to one spot now.
viewModel.InitializeCommand.Execute(null);
await viewModel.InitializeCommand.ExecutionTask!;
if (viewModel.InitializeCommand.ExecutionTask.Status != TaskStatus.RanToCompletion)
{
CoreLogger.LogError(ex.ToString());
}
}
else
{
var t = Task.Factory.StartNew(
() =>
if (viewModel.InitializeCommand.ExecutionTask.Exception is AggregateException ex)
{
CurrentPage = viewModel;
},
CancellationToken.None,
TaskCreationOptions.None,
_scheduler);
await t;
}
});
CoreLogger.LogError(ex.ToString());
}
}
else
{
var t = Task.Factory.StartNew(
() =>
{
if (cancellationToken.IsCancellationRequested)
{
if (viewModel is IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch (Exception ex)
{
CoreLogger.LogError(ex.ToString());
}
}
return;
}
CurrentPage = viewModel;
},
cancellationToken,
TaskCreationOptions.None,
_scheduler);
await t;
}
},
cancellationToken);
await outer;
}
else
{
if (cancellationToken.IsCancellationRequested)
{
if (viewModel is IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch (Exception ex)
{
CoreLogger.LogError(ex.ToString());
}
}
return;
}
CurrentPage = viewModel;
}
}
@@ -174,6 +216,28 @@ public partial class ShellViewModel : ObservableObject,
private void PerformCommand(PerformCommandMessage message)
{
// Create/replace the navigation cancellation token.
// If one already exists, cancel and dispose it first.
var newCts = new CancellationTokenSource();
var oldCts = Interlocked.Exchange(ref _navigationCts, newCts);
if (oldCts is not null)
{
try
{
oldCts.Cancel();
}
catch (Exception ex)
{
CoreLogger.LogError(ex.ToString());
}
finally
{
oldCts.Dispose();
}
}
var navigationToken = newCts.Token;
var command = message.Command.Unsafe;
if (command is null)
{
@@ -202,17 +266,25 @@ public partial class ShellViewModel : ObservableObject,
}
// Kick off async loading of our ViewModel
LoadPageViewModelAsync(pageViewModel)
LoadPageViewModelAsync(pageViewModel, navigationToken)
.ContinueWith(
(Task t) =>
{
// clean up the navigation token if it's still ours
if (Interlocked.CompareExchange(ref _navigationCts, null, newCts) == newCts)
{
newCts.Dispose();
}
// When we're done loading the page, then update the command bar to match
OnUIThread(() => { WeakReferenceMessenger.Default.Send<UpdateCommandBarMessage>(new(null)); });
WeakReferenceMessenger.Default.Send<UpdateCommandBarMessage>(new(null));
},
navigationToken,
TaskContinuationOptions.None,
_scheduler);
// While we're loading in the background, immediately move to the next page.
WeakReferenceMessenger.Default.Send<NavigateToPageMessage>(new(pageViewModel, message.WithAnimation));
WeakReferenceMessenger.Default.Send<NavigateToPageMessage>(new(pageViewModel, message.WithAnimation, navigationToken));
// Note: Originally we set our page back in the ViewModel here, but that now happens in response to the Frame navigating triggered from the above
// See RootFrame_Navigated event handler.
@@ -371,4 +443,9 @@ public partial class ShellViewModel : ObservableObject,
TaskCreationOptions.None,
_scheduler);
}
public void CancelNavigation()
{
_navigationCts?.Cancel();
}
}

View File

@@ -46,11 +46,18 @@ public sealed partial class ContentPage : Page,
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter is ContentPageViewModel vm)
if (e.Parameter is not AsyncNavigationRequest navigationRequest)
{
ViewModel = vm;
throw new InvalidOperationException($"Invalid navigation parameter: {nameof(e.Parameter)} must be {nameof(AsyncNavigationRequest)}");
}
if (navigationRequest.TargetViewModel is not ContentPageViewModel contentPageViewModel)
{
throw new InvalidOperationException($"Invalid navigation target: AsyncNavigationRequest.{nameof(AsyncNavigationRequest.TargetViewModel)} must be {nameof(ContentPageViewModel)}");
}
ViewModel = contentPageViewModel;
if (!WeakReferenceMessenger.Default.IsRegistered<ActivateSelectedListItemMessage>(this))
{
WeakReferenceMessenger.Default.Register<ActivateSelectedListItemMessage>(this);

View File

@@ -59,11 +59,18 @@ public sealed partial class ListPage : Page,
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter is ListViewModel lvm)
if (e.Parameter is not AsyncNavigationRequest navigationRequest)
{
ViewModel = lvm;
throw new InvalidOperationException($"Invalid navigation parameter: {nameof(e.Parameter)} must be {nameof(AsyncNavigationRequest)}");
}
if (navigationRequest.TargetViewModel is not ListViewModel listViewModel)
{
throw new InvalidOperationException($"Invalid navigation target: AsyncNavigationRequest.{nameof(AsyncNavigationRequest.TargetViewModel)} must be {nameof(ListViewModel)}");
}
ViewModel = listViewModel;
if (e.NavigationMode == NavigationMode.Back
|| (e.NavigationMode == NavigationMode.New && ItemView.Items.Count > 0))
{

View File

@@ -23,24 +23,30 @@ public sealed partial class LoadingPage : Page
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter is ShellViewModel shellVM
&& shellVM.LoadCommand is not null)
if (e.Parameter is not AsyncNavigationRequest request)
{
// This will load the built-in commands, then navigate to the main page.
// Once the mainpage loads, we'll start loading extensions.
shellVM.LoadCommand.Execute(null);
_ = Task.Run(async () =>
{
await shellVM.LoadCommand.ExecutionTask!;
if (shellVM.LoadCommand.ExecutionTask.Status != TaskStatus.RanToCompletion)
{
// TODO: Handle failure case
}
});
throw new InvalidOperationException($"Invalid navigation parameter: {nameof(e.Parameter)} must be {nameof(AsyncNavigationRequest)}");
}
if (request.TargetViewModel is not ShellViewModel shellVM)
{
throw new InvalidOperationException($"Invalid navigation target: AsyncNavigationRequest.{nameof(AsyncNavigationRequest.TargetViewModel)} must be {nameof(ShellViewModel)}");
}
// This will load the built-in commands, then navigate to the main page.
// Once the mainpage loads, we'll start loading extensions.
shellVM.LoadCommand.Execute(null);
_ = Task.Run(async () =>
{
await shellVM.LoadCommand.ExecutionTask!;
if (shellVM.LoadCommand.ExecutionTask.Status != TaskStatus.RanToCompletion)
{
// TODO: Handle failure case
}
});
base.OnNavigatedTo(e);
}
}

View File

@@ -95,7 +95,7 @@ public sealed partial class ShellPage : Microsoft.UI.Xaml.Controls.Page,
AddHandler(KeyDownEvent, new KeyEventHandler(ShellPage_OnKeyDown), false);
AddHandler(PointerPressedEvent, new PointerEventHandler(ShellPage_OnPointerPressed), true);
RootFrame.Navigate(typeof(LoadingPage), ViewModel);
RootFrame.Navigate(typeof(LoadingPage), new AsyncNavigationRequest(ViewModel, CancellationToken.None));
var pageAnnouncementFormat = ResourceLoaderInstance.GetString("ScreenReader_Announcement_NavigatedToPage0");
_pageNavigatedAnnouncement = CompositeFormat.Parse(pageAnnouncementFormat);
@@ -153,7 +153,7 @@ public sealed partial class ShellPage : Microsoft.UI.Xaml.Controls.Page,
ContentPageViewModel => typeof(ContentPage),
_ => throw new NotSupportedException(),
},
message.Page,
new AsyncNavigationRequest(message.Page, message.CancellationToken),
message.WithAnimation ? DefaultPageAnimation : _noAnimation);
PowerToysTelemetry.Log.WriteEvent(new OpenPage(RootFrame.BackStackDepth));
@@ -403,6 +403,8 @@ public sealed partial class ShellPage : Microsoft.UI.Xaml.Controls.Page,
{
HideDetails();
ViewModel.CancelNavigation();
// Note: That we restore the VM state below in RootFrame_Navigated call back after this occurs.
// In the future, we may want to manage the back stack ourselves vs. relying on Frame
// We could replace Frame with a ContentPresenter, but then have to manage transition animations ourselves.
@@ -456,11 +458,32 @@ public sealed partial class ShellPage : Microsoft.UI.Xaml.Controls.Page,
// This listens to the root frame to ensure that we also track the content's page VM as well that we passed as a parameter.
// This is currently used for both forward and backward navigation.
// As when we go back that we restore ourselves to the proper state within our VM
if (e.Parameter is PageViewModel page)
if (e.Parameter is AsyncNavigationRequest request)
{
// Note, this shortcuts and fights a bit with our LoadPageViewModel above, but we want to better fast display and incrementally load anyway
// We just need to reconcile our loading systems a bit more in the future.
ViewModel.CurrentPage = page;
if (request.NavigationToken.IsCancellationRequested && e.NavigationMode is not (Microsoft.UI.Xaml.Navigation.NavigationMode.Back or Microsoft.UI.Xaml.Navigation.NavigationMode.Forward))
{
return;
}
switch (request.TargetViewModel)
{
case PageViewModel pageViewModel:
ViewModel.CurrentPage = pageViewModel;
break;
case ShellViewModel:
// This one is an exception, for now (LoadingPage is tied to ShellViewModel,
// but ShellViewModel is not PageViewModel.
ViewModel.CurrentPage = ViewModel.NullPage;
break;
default:
ViewModel.CurrentPage = ViewModel.NullPage;
Logger.LogWarning($"Invalid navigation target: AsyncNavigationRequest.{nameof(AsyncNavigationRequest.TargetViewModel)} must be {nameof(PageViewModel)}");
break;
}
}
else
{
Logger.LogWarning("Unrecognized target for shell navigation: " + e.Parameter);
}
if (e.Content is Page element)

View File

@@ -0,0 +1,37 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
namespace SamplePagesExtension;
internal sealed partial class SlowListPage : ListPage
{
public SlowListPage()
{
Icon = new IconInfo("\uEA79");
Name = "Slow List Page";
Title = "This page simulates a slow load";
}
public override IListItem[] GetItems()
{
Thread.Sleep(5000);
return [
new ListItem(new NoOpCommand())
{
Title = "This is a basic item in the list",
Subtitle = "I don't do anything though",
},
new ListItem(new NoOpCommand())
{
Title = "This is another item in the list",
Subtitle = "Still nothing",
},
];
}
}

View File

@@ -48,6 +48,11 @@ public partial class SamplesListPage : ListPage
Title = "Sample Icon Page",
Subtitle = "A demo of using icons in various ways",
},
new ListItem(new SlowListPage())
{
Title = "Slow loading list page",
Subtitle = "A demo of a list page that takes a while to load",
},
// Content pages
new ListItem(new SampleContentPage())