Skip to content

Use new model to clear results & Fix clear existing results when using IResultUpdate #3588

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jun 2, 2025

Conversation

Jack251970
Copy link
Member

@Jack251970 Jack251970 commented May 26, 2025

Follow on with #3524.

CHANGE

  • Add new property in Query class IsHomeQuery to indicate home query state
  • Handle ShouldClearExistingResultsForQuery in UpdateActionAsync
    • We will skip if token is cancelled there
    • We will also check clear existing results in IResultUpdate event to fix the issue that one query consumes much time, the results will be cleared once the results updated (as below)
  • Remove token cancellation check between var newResults = NewResults(resultsForUpdates); & if (Count != 0) RemoveAll(newItems.Count); or Clear();
    • All clear actions will be executed.
  • Check token cancellation before AddAll(newItems, token); & BulkAddAll(newItems, token);
    • We will not add new items from the cancelled queries. It can make sure we only need to clear existing results for one time.
  • Use local cancellation in ResultCollection for code quality.
  • Pass shouldClearExistingResults flag when overriding results in queue.

Issue Example

image

The first item is from new query while others are from old one. If we do not add clear existing results when using IResultUpdate and this query happens to consume long time, the list will display old items for a long time until the query is completed and updated.

TEST

  • Testing

This comment has been minimized.

@Jack251970 Jack251970 requested a review from Copilot May 26, 2025 12:20
Copy link

gitstream-cm bot commented May 26, 2025

🥷 Code experts: jjw24

Jack251970, jjw24 have most 👩‍💻 activity in the files.
Jack251970 has most 🧠 knowledge in the files.

See details

Flow.Launcher/ViewModel/MainViewModel.cs

Activity based on git-commit:

Jack251970 jjw24
MAY 529 additions & 316 deletions 39 additions & 27 deletions
APR 35 additions & 28 deletions
MAR 695 additions & 628 deletions
FEB 63 additions & 21 deletions
JAN 17 additions & 21 deletions
DEC 59 additions & 63 deletions

Knowledge based on git-blame:
Jack251970: 40%

Flow.Launcher/ViewModel/ResultsForUpdate.cs

Activity based on git-commit:

Jack251970 jjw24
MAY 2 additions & 1 deletions
APR
MAR
FEB
JAN
DEC

Knowledge based on git-blame:

Flow.Launcher/ViewModel/ResultsViewModel.cs

Activity based on git-commit:

Jack251970 jjw24
MAY 17 additions & 7 deletions 8 additions & 3 deletions
APR 4 additions & 5 deletions
MAR 8 additions & 6 deletions
FEB
JAN
DEC

Knowledge based on git-blame:
Jack251970: 7%

To learn more about /:\ gitStream - Visit our Docs

Copy link

gitstream-cm bot commented May 26, 2025

Be a legend 🏆 by adding a before and after screenshot of the changes you made, especially if they are around UI/UX.

Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR updates the results updating mechanism by removing the per-update flag for clearing existing results and instead using a centralized model flag from the main view model. Key changes include:

  • In ResultsViewModel.cs, modifying the logic to check a centralized flag (ShouldClearExistingResults) instead of a per-update parameter.
  • In ResultsForUpdate.cs, removing the redundant shouldClearExistingResults parameter from the record.
  • In MainViewModel.cs, introducing the ShouldClearExistingResults property and updating query flows to set this flag as needed.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
Flow.Launcher/ViewModel/ResultsViewModel.cs Updates to result handling logic and token checks with added clarifications.
Flow.Launcher/ViewModel/ResultsForUpdate.cs Removal of the now-unneeded shouldClearExistingResults parameter.
Flow.Launcher/ViewModel/MainViewModel.cs Addition of the ShouldClearExistingResults flag and updating its usage.

Copy link
Contributor

coderabbitai bot commented May 26, 2025

📝 Walkthrough

"""

Walkthrough

The changes refactor how the ShouldClearExistingResults flag is computed and applied within MainViewModel, moving its calculation into the results update processing loop. The ResultsForUpdate struct is updated to rename the flag parameter. The ResultsViewModel and its nested ResultCollection class adjust cancellation token handling to always clear existing results before checking for cancellation when adding new results. A new IsHomeQuery property is added to Query and set in QueryBuilder. Minor logging and formatting improvements are also included.

Changes

File(s) Change Summary
Flow.Launcher/ViewModel/MainViewModel.cs Moved computation of ShouldClearExistingResults flag into UpdateActionAsync loop; removed explicit passing of the flag in query methods; added debug logging before writing to results update channel; minor formatting tweak; use query.IsHomeQuery instead of checking raw query string.
Flow.Launcher/ViewModel/ResultsForUpdate.cs Renamed constructor parameter shouldClearExistingResults to ShouldClearExistingResults with PascalCase.
Flow.Launcher/ViewModel/ResultsViewModel.cs Adjusted cancellation token handling to defer cancellation checks until after clearing existing results; updated method signatures in nested ResultCollection to accept optional cancellation tokens; ensured clearing always occurs regardless of cancellation; added logging context field.
Flow.Launcher.Core/Plugin/QueryBuilder.cs Modified Build method to set new IsHomeQuery property on returned Query object based on whether input text is empty.
Flow.Launcher.Plugin/Query.cs Added new boolean property IsHomeQuery to Query class with internal init-only setter, defaulting to false.
Flow.Launcher/MainWindow.xaml.cs Made explicit discard of returned Task from async call _theme.RefreshFrameAsync() in theme change event handler.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant MainVM as MainViewModel
    participant UpdateLoop as UpdateActionAsync
    participant ResultsVM as ResultsViewModel

    MainVM->>UpdateLoop: Enqueue ResultsForUpdate (without clear flag)
    UpdateLoop->>UpdateLoop: Compute ShouldClearExistingResults for each item
    UpdateLoop->>ResultsVM: Add results with updated clear flag
    ResultsVM->>ResultsVM: Clear existing results (ignoring cancellation)
    ResultsVM->>ResultsVM: Add new results (check cancellation before adding)

Possibly related PRs

Suggested reviewers

  • jjw24

Poem

🐇 I hop through code with gentle paws,
Flags and queries, clearing laws.
Results refreshed without a pause,
Cancellation waits its cause,
Smooth updates without a flaw! ✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d972e6 and 8ef3a8f.

📒 Files selected for processing (2)
  • Flow.Launcher/MainWindow.xaml.cs (1 hunks)
  • Flow.Launcher/ViewModel/MainViewModel.cs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • Flow.Launcher/MainWindow.xaml.cs
  • Flow.Launcher/ViewModel/MainViewModel.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
Flow.Launcher/ViewModel/ResultsViewModel.cs (3)

248-248: Fix typo in comment.

-            // If mainVM has flag to clear existing results, hanlde it here
+            // If mainVM has flag to clear existing results, handle it here

193-197: Document the implications of skipping cancellation token checks.

The comment explains that token checks are skipped after NewResults, but it doesn't explain why clearing results takes precedence over cancellation. This design decision should be documented more clearly to help future maintainers understand the trade-offs.

Consider adding a more detailed comment:

-            // Since NewResults may need to clear existing results, do not check token cancellation after this point
+            // Since NewResults may need to clear existing results based on MainViewModel flag,
+            // we must complete the clearing operation even if cancellation is requested.
+            // This ensures UI consistency by preventing partial result sets from being displayed.

350-372: Consider the impact of ignoring cancellation tokens during collection updates.

Multiple comments indicate that cancellation tokens are not checked during RemoveAll, Clear, and other operations. While this ensures results are properly cleared, it could lead to performance issues if large result sets continue processing after the user has cancelled the operation.

Consider adding a mechanism to track whether clearing was initiated and allow cancellation after the critical clearing phase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6333cd3 and 35a544a.

📒 Files selected for processing (3)
  • Flow.Launcher/ViewModel/MainViewModel.cs (3 hunks)
  • Flow.Launcher/ViewModel/ResultsForUpdate.cs (1 hunks)
  • Flow.Launcher/ViewModel/ResultsViewModel.cs (3 hunks)
🧰 Additional context used
🪛 GitHub Actions: Check Spelling
Flow.Launcher/ViewModel/MainViewModel.cs

[warning] 1857-1857: Unrecognized spelling warning for 'VSTHRD'.

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: gitStream.cm
  • GitHub Check: gitStream workflow automation
  • GitHub Check: gitStream.cm
  • GitHub Check: build
🔇 Additional comments (2)
Flow.Launcher/ViewModel/ResultsForUpdate.cs (1)

7-12:

✅ Verification successful

Verify all callers of ResultsForUpdate have been updated.

The removal of the shouldClearExistingResults parameter is a breaking change. Ensure all instantiations of ResultsForUpdate throughout the codebase have been updated accordingly.


🏁 Script executed:

#!/bin/bash
# Description: Find all instantiations of ResultsForUpdate to verify they've been updated

# Search for all uses of ResultsForUpdate constructor
ast-grep --pattern 'new ResultsForUpdate($$$)'

# Also search for any direct references to ResultsForUpdate
rg -A 3 'ResultsForUpdate\s*\(' --type cs

Length of output: 2443


All ResultsForUpdate call sites updated

Verified all three instantiations in MainViewModel.cs (lines 268–269, 1447–1448, 1475–1476) now match the new constructor signature (4 args or 5 with the optional ReSelectFirstResult). No further changes needed.

Flow.Launcher/ViewModel/MainViewModel.cs (1)

1082-1082:

✅ Verification successful

Where is ShouldClearExistingResults consumed and reset?

The flag is being set but I cannot find where it's consumed or reset to false. This could lead to incorrect behavior where results are cleared when they shouldn't be.

Run the following script to find where this flag is used:


🏁 Script executed:

#!/bin/bash
# Description: Search for usage of ShouldClearExistingResults property
# Expected: Find where the flag is read and reset

# Search for any reference to ShouldClearExistingResults
rg -A 5 -B 5 "ShouldClearExistingResults"

# Search in ResultsViewModel for potential consumption
fd -e cs ResultsViewModel | xargs rg -A 10 "ShouldClearExistingResults|AddResults|NewResults"

Length of output: 12823


ShouldClearExistingResults is consumed and reset in ResultsViewModel.NewResults

  • In Flow.Launcher/ViewModel/ResultsViewModel.cs, method NewResults(ICollection<ResultsForUpdate>) (the overload at the bottom of the class) you’ll find:

    if (_mainVM != null && _mainVM.ShouldClearExistingResults)
    {
        _mainVM.ShouldClearExistingResults = false;
        App.API.LogDebug("NewResults", $"Existing results are cleared for query");
        return newResults.OrderByDescending(rv => rv.Result.Score).ToList();
    }

    This both reads and immediately resets the flag to false.

  • Writing to a bool is atomic in .NET, and the channel-based handoff to the UI thread provides the necessary memory-fencing. There’s no additional thread-safety risk here.

No changes required.

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

This comment has been minimized.

@Jack251970 Jack251970 requested a review from Copilot May 26, 2025 12:31
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

A PR to refactor how existing results are cleared by replacing the local flag with a global flag and removing token cancellation checks to ensure all clear actions execute.

  • Remove the local shouldClearExistingResults flag and update references accordingly.
  • Introduce a global flag in MainViewModel with proper locking to manage clearing behavior.
  • Remove token cancellation checks in the critical sections to guarantee that clear actions are executed.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
Flow.Launcher/ViewModel/ResultsViewModel.cs Adjusted behavior in NewResults and removal methods to rely on the global flag and removed token cancellation checks.
Flow.Launcher/ViewModel/ResultsForUpdate.cs Removed the shouldClearExistingResults parameter from the record struct.
Flow.Launcher/ViewModel/MainViewModel.cs Added a global flag with locking and updated ResultForUpdate constructor calls accordingly.
Comments suppressed due to low confidence (2)

Flow.Launcher/ViewModel/MainViewModel.cs:1452

  • Verify that removing the shouldClearExistingResults parameter from the ResultsForUpdate record does not affect components still expecting that flag, as the clearing behavior is now managed globally.
_resultsUpdateChannelWriter.TryWrite(new ResultsForUpdate(resultsCopy, plugin.Metadata, query, token, reSelect)))

Flow.Launcher/ViewModel/ResultsViewModel.cs:249

  • Ensure that the null check on _mainVM is intentional; if _mainVM is null, confirm that skipping the clear action is the desired behavior.
if (_mainVM != null && _mainVM.CheckShouldClearExistingResultsAndReset())

This comment has been minimized.

@Jack251970 Jack251970 added the Dev branch only An issue or fix for the Dev branch build label May 26, 2025
@Jack251970 Jack251970 added this to the 1.20.0 milestone May 26, 2025
@Jack251970 Jack251970 linked an issue May 26, 2025 that may be closed by this pull request

This comment has been minimized.

@Jack251970 Jack251970 requested a review from Copilot May 26, 2025 14:53
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR updates the results clearing mechanism to use a global flag instead of a local one and adjusts where cancellation checks occur to ensure clear actions are fully executed. Key changes include:

  • Removing the local shouldClearExistingResults flag and related parameter from ResultsForUpdate.
  • Updating the AddResults and Update methods in ResultsViewModel to reposition token cancellation checks.
  • Adding a global flag with locking in MainViewModel to control clearing of existing results.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
Flow.Launcher/ViewModel/ResultsViewModel.cs Adjusts execution order and adds cancellation token parameters to results update
Flow.Launcher/ViewModel/ResultsForUpdate.cs Removes the local shouldClearExistingResults parameter
Flow.Launcher/ViewModel/MainViewModel.cs Introduces a global flag and locking mechanism for clearing results
Comments suppressed due to low confidence (1)

Flow.Launcher/ViewModel/ResultsViewModel.cs:318

  • Consider renaming the parameter 'Items' to 'items' to follow standard naming conventions for parameters.
private void AddAll(List<ResultViewModel> Items, CancellationToken token = default)

@prlabeler prlabeler bot added the enhancement New feature or request label May 26, 2025

This comment has been minimized.

@prlabeler prlabeler bot added the enhancement New feature or request label May 30, 2025

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

This comment has been minimized.

@Jack251970
Copy link
Member Author

Jack251970 commented May 31, 2025

@jjw24 I targeted the problem. We need to pass shouldClearExistingResults flag when overriding results. More information in Pass shouldClearExistingResults flag when overriding results.

And please use the new package for test.

This comment has been minimized.

@jjw24
Copy link
Member

jjw24 commented Jun 1, 2025

Yeah ok. Seems good so far, I will test drive it one more day to make sure.

@jjw24
Copy link
Member

jjw24 commented Jun 1, 2025

This iteration of the change has the code really clear now, I am happy with this change. Thank you for taking the time to do this.

@Jack251970
Copy link
Member Author

Yeah, good

Copy link

github-actions bot commented Jun 1, 2025

@check-spelling-bot Report

🔴 Please review

See the 📂 files view, the 📜action log, or 📝 job summary for details.

❌ Errors and Warnings Count
❌ forbidden-pattern 24
⚠️ non-alpha-in-dictionary 13

See ❌ Event descriptions for more information.

Forbidden patterns 🙅 (1)

In order to address this, you could change the content to not match the forbidden patterns (comments before forbidden patterns may help explain why they're forbidden), add patterns for acceptable instances, or adjust the forbidden patterns themselves.

These forbidden patterns matched content:

s.b. workaround(s)

\bwork[- ]arounds?\b
If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

@jjw24 jjw24 requested a review from Copilot June 2, 2025 02:51
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR improves query result handling by introducing a new property for home query detection and refining the cancellation handling logic during updates.

  • Introduces a new IsHomeQuery property in the Query class and updates related logic.
  • Refines cancellation checks and logging in result update methods to ensure proper clearing of results.
  • Adjusts the ResultsForUpdate record and updates the MainViewModel logic to correctly handle the clear existing results flag.

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
Flow.Launcher/ViewModel/ResultsViewModel.cs Updates cancellation check style and logging for result updates.
Flow.Launcher/ViewModel/ResultsForUpdate.cs Renames the clear existing results flag to use PascalCase.
Flow.Launcher/ViewModel/MainViewModel.cs Refactors home query checking and updates the clear results flag.
Flow.Launcher/MainWindow.xaml.cs Adjusts async call to RefreshFrameAsync to await completion.
Flow.Launcher.Plugin/Query.cs Adds new IsHomeQuery property with internal init support.
Flow.Launcher.Core/Plugin/QueryBuilder.cs Sets IsHomeQuery appropriately for default vs. normal queries.

// If the queue already has the item, we need to pass the shouldClearExistingResults flag
if (queue.TryGetValue(item.ID, out var existingItem))
{
item.ShouldClearExistingResults = shouldClearExistingResults || existingItem.ShouldClearExistingResults;
Copy link
Preview

Copilot AI Jun 2, 2025

Choose a reason for hiding this comment

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

ResultsForUpdate is defined as a record struct with an init-only property for ShouldClearExistingResults. Reassigning this property later in MainViewModel may cause compilation issues. Consider changing the property to allow mutation (e.g., using a mutable property with get; set;) if it needs to be updated after initialization.

Copilot uses AI. Check for mistakes.

@jjw24
Copy link
Member

jjw24 commented Jun 2, 2025

@coderabbitai review

@jjw24 jjw24 enabled auto-merge (squash) June 2, 2025 03:15
@jjw24 jjw24 removed bug Something isn't working enhancement New feature or request review in progress Indicates that a review is in progress for this PR 1 min review labels Jun 2, 2025
@jjw24 jjw24 merged commit a06cb43 into dev Jun 2, 2025
6 checks passed
@jjw24 jjw24 deleted the late_clear branch June 2, 2025 03:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Dev branch only An issue or fix for the Dev branch build
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Dev Branch: Results Clear Issue
2 participants