Skip to content

fix(CmdPal): prevent memory leak when activating extension via global hotkey#47413

Draft
Copilot wants to merge 3 commits into
mainfrom
copilot/fix-memory-leak-hotkey-activation
Draft

fix(CmdPal): prevent memory leak when activating extension via global hotkey#47413
Copilot wants to merge 3 commits into
mainfrom
copilot/fix-memory-leak-hotkey-activation

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 29, 2026

Summary of the Pull Request

Each global-hotkey activation of a CmdPal extension creates a new ListViewModel and starts a background _initializeItemsTask to fully initialize item properties. A race between that task and UnsafeCleanup() left orphaned cross-process COM PropChanged event registrations — the extension process held the delegate alive, keeping CommandItemViewModel objects (and eventually the entire ListViewModel) in memory indefinitely.

PR Checklist

  • 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
  • Documentation updated: If checked, please file a pull request on our docs repo and link it here: #xxx

Detailed Description of the Pull Request / Additional comments

Race condition (primary bug)

_initializeItemsTask checks ct.IsCancellationRequested before calling SafeInitializeProperties(). UnsafeCleanup() (UI thread) cancels the token and iterates Items to call item.SafeCleanup()model.PropChanged -= handler. If the background task passes the cancellation check just before the token is marked, it then subscribes model.PropChanged += handler with no cleanup path. The extension process holds that delegate via COM, preventing GC.

Fixes

  • ExtensionObjectViewModel — Added volatile bool _isCleanedUp / IsCleanedUp property. SafeCleanup() sets it before calling UnsafeCleanup() so background threads observe it immediately.

  • CommandItemViewModel.InitializeProperties() — Double-check guard: bail at entry if IsCleanedUp; and again after the model.PropChanged += / Command.PropertyChanged += subscriptions to handle the narrow window between the two:

    model.PropChanged += Model_PropChanged;
    Command.PropertyChanged += Command_PropertyChanged;
    // Undo if cleanup raced between the guard above and here
    if (IsCleanedUp)
    {
        model.PropChanged -= Model_PropChanged;
        Command.PropertyChanged -= Command_PropertyChanged;
        return;
    }
  • PageViewModel.InitializeProperties() — Same double-check pattern for the page-level PropChanged subscription.

  • ListViewModel.UnsafeCleanup() — Explicitly unsubscribes _lastSelectedItem.PropertyChanged to break the ListItemViewModel → SelectedItemPropertyChanged → ListViewModel delegate chain.

  • ShellViewModel.LoadPageViewModelAsync() — When navigation is cancelled (rapid back-to-back hotkey presses can cancel an in-flight navigation before it sets CurrentPage), call viewModel.SafeCleanup() instead of only Dispose(). Also changed the UI-thread cleanup task from cancellationTokenCancellationToken.None so the lambda always executes — if an already-cancelled token is passed to Task.Factory.StartNew, the task is placed in Cancelled state immediately and the action never runs.

Validation Steps Performed

  • Code review and static analysis of the race window in _initializeItemsTask vs UnsafeCleanup across all affected paths.
  • Verified IsCleanedUp is set atomically (volatile write) before any subscription-removal in UnsafeCleanup, ensuring background threads always see the flag before they can subscribe.
  • Confirmed double-cleanup is safe: CancelAndDisposeTokenSource uses Interlocked.Exchange and guards on null; iterating an empty Items is a no-op.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • o3svsblobprodcus318.vsblob.vsassets.io
    • Triggering command: /usr/bin/dotnet dotnet build -p:Platform=x64 --no-restore --uid-owner 0 -j ACCEPT (dns block)
    • Triggering command: /usr/bin/dotnet dotnet build src/modules/cmdpal/Microsoft.CmdPal.UI.ViewModels/Microsoft.CmdPal.UI.ViewModels.csproj -p:Platform=x64 --no-restore -p:UseSharedCompilation=false (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Copilot AI and others added 2 commits April 29, 2026 11:13
…tkey

Fixes a race condition where _initializeItemsTask subscribes to COM events
on IListItem/IPage objects after SafeCleanup has already run, leaving those
subscriptions permanently alive (held by the cross-process COM event
registration in the extension process).

Changes:
- ExtensionObjectViewModel: add IsCleanedUp volatile property, set before
  UnsafeCleanup() so background threads see it immediately
- CommandItemViewModel.InitializeProperties: guard against IsCleanedUp
  at entry and after subscribing (double-check to close the race window)
- PageViewModel.InitializeProperties: same guard pattern for page PropChanged
- ListViewModel.UnsafeCleanup: unsubscribe _lastSelectedItem.PropertyChanged
  to sever the delegate chain that keeps ListViewModel alive
- ShellViewModel.LoadPageViewModelAsync: call SafeCleanup() (not just Dispose)
  when navigation is cancelled; use CancellationToken.None for the UI-thread
  task so the cleanup lambda always runs even if the token is already cancelled

Agent-Logs-Url: https://github.com/microsoft/PowerToys/sessions/0bf9ec35-b19d-4ea4-971d-803a1d4f305e

Co-authored-by: MuyuanMS <116717757+MuyuanMS@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix memory leak when activating extension via global hotkey fix(CmdPal): prevent memory leak when activating extension via global hotkey Apr 29, 2026
Copilot AI requested a review from MuyuanMS April 29, 2026 11:17
@niels9001 niels9001 added the Product-Command Palette Refers to the Command Palette utility label Apr 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Product-Command Palette Refers to the Command Palette utility

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Memory leak when activating extension via global hotkey

3 participants