Skip to content
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

Support Logon Task for Faster Startup Experience #3218

Open
wants to merge 8 commits into
base: dev
Choose a base branch
from

Conversation

Jack251970
Copy link
Contributor

@Jack251970 Jack251970 commented Jan 31, 2025

Add support for FL to use logon task instead of startup entry for faster startup experience.

As described.

Related issue: #3212.

Test

Latest screenshot:

image

After using logon task for startup, FL launches as fast as PowerToys (the center app in the tray) which uses logon task for startup as well.

Also, it launchers faster than other apps using startup entry, like Microsoft Security Center (You cannot see it here because it has not launched yet.)
Screenshot 2025-01-31 215138

As for precise performance: This PR improves startup time by about 80%. (from chrisl8 in #3212)

This comment has been minimized.

Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new boolean property, UseLogonTaskForStartup, in the application settings to control whether a logon task is used for startup. This property is added in the settings class and is exposed through the settings view model and UI. The auto-startup functionality is updated to call methods with a boolean parameter that directs the use of registry-based or scheduled task-based startup. Additional methods for task scheduling and verification have been added to the AutoStartup class. A new package dependency for TaskScheduler and localization strings for the new feature have also been incorporated.

Changes

File(s) Change Summary
Flow.Launcher.Infrastructure/.../Settings.cs
Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs
Flow.Launcher/SettingPages/Views/SettingsPaneGeneral.xaml
Flow.Launcher/Languages/en.xaml
Added the new UseLogonTaskForStartup property in settings and view model, introduced a corresponding UI toggle (with card and binding) for user configuration, and added localization strings for the new startup option.
Flow.Launcher/App.xaml.cs
Flow.Launcher/Helper/AutoStartup.cs
Modified the AutoStartup flow to accept a boolean parameter for logon task handling. Updated method signatures and added new private methods to check, schedule, and unschedule logon tasks, with the App class now passing the new setting value.
Flow.Launcher/Flow.Launcher.csproj Added a new package reference for TaskScheduler version 2.11.0.

Suggested labels

bug

Suggested reviewers

  • JohnTheGr8
  • jjw24
  • taooceros

Poem

Hop along the lines of code,
In startup tasks a story's told.
A logon task for faster start,
New properties play their part.
I nibble through this change with glee,
Coding adventures just for me! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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: 1

🧹 Nitpick comments (2)
Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs (1)

64-85: Switching startup method is done effectively.
Toggling UseLogonTaskForStartup triggers a quick disable-enable routine to transition smoothly between registry and task-based startup. As a good-to-have, consider refactoring into a single switch function if multiple toggles become too frequent.

Flow.Launcher/SettingPages/Views/SettingsPaneGeneral.xaml (1)

39-44: Consider adding an icon for consistency.

The new card for logon task setting is missing an icon attribute, while other cards in this file use icons. Consider adding an icon for visual consistency.

Apply this diff to add an icon:

-            <cc:Card Title="{DynamicResource useLogonTaskForStartup}">
+            <cc:Card Title="{DynamicResource useLogonTaskForStartup}" Icon="&#xe8fc;">
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6cf7674 and 3f93d18.

📒 Files selected for processing (9)
  • Flow.Launcher.Infrastructure/UserSettings/Settings.cs (1 hunks)
  • Flow.Launcher/App.xaml.cs (1 hunks)
  • Flow.Launcher/Flow.Launcher.csproj (1 hunks)
  • Flow.Launcher/Helper/AutoStartup.cs (3 hunks)
  • Flow.Launcher/Languages/en.xaml (1 hunks)
  • Flow.Launcher/Languages/zh-cn.xaml (2 hunks)
  • Flow.Launcher/Languages/zh-tw.xaml (2 hunks)
  • Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs (2 hunks)
  • Flow.Launcher/SettingPages/Views/SettingsPaneGeneral.xaml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: gitStream.cm
🔇 Additional comments (16)
Flow.Launcher/Helper/AutoStartup.cs (8)

2-4: Imports look correct for newly introduced functionalities.
No concerns found with these added using statements.

Also applies to: 8-8


15-16: Consider clarifying task naming.
The constants for task name and description look fine. However, ensure that the naming remains consistent across logs and user-facing messages so users can identify the task more easily.


22-27: Centralized check is valid but consider text clarifications.
Comment indicates checking the logon task first, which aligns with the new logic. No immediate issues are found here.


70-85: Disable logic is straightforward and consistent.
The updated signature adds flexibility for disabling either the registry entry or the scheduled task. Looks good.


91-103: Enable logic is well structured.
Similar to the disable method, enabling either logon task or registry-based startup is properly separated by parameter.


111-138: Check administrative privileges for correct run level execution.
The scheduling logic is robust. The conditional for setting RunLevel.Highest is appropriate.


140-153: Unscheduling approach is appropriate.
This routine correctly removes existing tasks by name and handles exceptions gracefully.


155-160: Role check for administrative context is correct.
Implementation using WindowsPrincipal is standard practice. No changes necessary.

Flow.Launcher/App.xaml.cs (1)

122-122: Method call respects user preference for logon task startup.
Passing _settings.UseLogonTaskForStartup into Enable() aligns with the new approach. The existing exception handling ensures graceful fallback if enabling fails.

Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs (2)

45-48: Selective enable logic is correct.
The property setter checks if startup is toggled on and correctly calls AutoStartup.Enable(UseLogonTaskForStartup).


50-54: Disabling multiple startup methods ensures consistency.
Calling Disable(true) followed by Disable(false) is thorough, preventing leftover startup entries.

Flow.Launcher.Infrastructure/UserSettings/Settings.cs (1)

241-241: LGTM!

The new property is well-placed near other startup-related settings and follows the existing code style.

Flow.Launcher/Languages/zh-cn.xaml (1)

50-50: LGTM!

The translation is accurate and appropriately placed in the startup settings section.

Flow.Launcher/Languages/zh-tw.xaml (1)

50-50: LGTM!

The translation is accurate and appropriately placed in the startup settings section.

Flow.Launcher/Languages/en.xaml (1)

49-49: LGTM!

The string resource is well-written, follows naming conventions, and clearly explains the benefit of using a logon task for startup.

Flow.Launcher/Flow.Launcher.csproj (1)

103-103: Verify the TaskScheduler package version.

The package version is fixed at 2.11.0. Let's verify if this is the latest stable version and check for any security advisories.

✅ Verification successful

TaskScheduler package version 2.11.0 is current and secure

The project is using the latest stable version available on NuGet, and no security vulnerabilities were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for latest version and security advisories of the TaskScheduler package.

# Check NuGet for latest versions
curl -s https://api.nuget.org/v3/registration5-gz-semver2/taskscheduler/index.json | jq -r '.items[0].upper'

# Check for security advisories
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NUGET, package: "TaskScheduler") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 517


Script:

#!/bin/bash
# Description: Check latest version of TaskScheduler package using alternative NuGet API endpoint
curl -s "https://api.nuget.org/v3-flatcontainer/taskscheduler/index.json" | jq -r '.versions[]' | sort -V | tail -n 1

Length of output: 124

This comment has been minimized.

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: 0

♻️ Duplicate comments (1)
Flow.Launcher/Helper/AutoStartup.cs (1)

44-69: ⚠️ Potential issue

Logic error: returns true even when the task doesn't exist.

If task is null, the method proceeds to return true, which incorrectly signals that the logon task is enabled.

Apply a fix to return false when the task is not found:

 private static bool CheckLogonTask()
 {
     using var taskService = new TaskService();
     var task = taskService.RootFolder.AllTasks.FirstOrDefault(t => t.Name == LogonTaskName);
-    if (task != null)
+    if (task == null)
+    {
+        return false;
+    }
     {
         try
         {
🧹 Nitpick comments (3)
Flow.Launcher/Helper/AutoStartup.cs (3)

22-27: Add error handling for logon task check.

The logon task check should be wrapped in a try-catch block similar to the registry check to ensure robustness.

 // Check if logon task is enabled
-if (CheckLogonTask())
+try
 {
-    return true;
+    if (CheckLogonTask())
+    {
+        return true;
+    }
+}
+catch (Exception e)
+{
+    Log.Error("AutoStartup", $"Ignoring non-critical logon task error (querying if enabled): {e}");
 }

Line range hint 71-111: Add parameter validation.

The methods should validate the state before making changes to avoid potential race conditions.

 public static void Enable(bool logonTask)
 {
+    // Avoid enabling if already enabled with the same method
+    if (IsEnabled && CheckLogonTask() == logonTask)
+    {
+        return;
+    }
+
     try
     {

113-161: Enhance security settings for the scheduled task.

Consider adding these security-related improvements:

  1. Set AllowHardTerminate to false to prevent force-stopping
  2. Enable RunOnlyIfNetworkAvailable if network connectivity is required
  3. Add SecurityDescriptor to restrict task access
 td.Settings.StopIfGoingOnBatteries = false;
 td.Settings.DisallowStartIfOnBatteries = false;
 td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
+td.Settings.AllowHardTerminate = false;
+td.Settings.RunOnlyIfNetworkAvailable = true;
+
+// Restrict access to SYSTEM and Administrators
+td.SecurityDescriptor = "D:(A;;FRFX;;;SY)(A;;FRFX;;;BA)";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f93d18 and 3d9a6b2.

📒 Files selected for processing (1)
  • Flow.Launcher/Helper/AutoStartup.cs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: gitStream.cm
  • GitHub Check: gitStream.cm
🔇 Additional comments (1)
Flow.Launcher/Helper/AutoStartup.cs (1)

8-8: LGTM!

The new imports and constants are well-defined and appropriate for the task scheduler functionality.

Also applies to: 15-16

This comment has been minimized.

@Jack251970 Jack251970 added the enhancement New feature or request label Feb 9, 2025
@Jack251970 Jack251970 linked an issue Feb 9, 2025 that may be closed by this pull request
@jjw24
Copy link
Member

jjw24 commented Feb 10, 2025

@Jack251970 I noticed PT had issues removing schedule logon task when uninstalling. Could you test this part please- how does the schedule task gets handled by installed flow version?

If it is a manual process to remove the task when uninstalling flow, especially for portable version, I think we need to have this explained under the option so user is aware that manual removal is needed.

@Jack251970
Copy link
Contributor Author

@jjw24 Yeah, when I uninstall the FL, I find the logon task will not be deleted. I need to add tooltip for this.

This comment has been minimized.

@Jack251970
Copy link
Contributor Author

@Jack251970 I noticed PT had issues removing schedule logon task when uninstalling. Could you test this part please- how does the schedule task gets handled by installed flow version?

If it is a manual process to remove the task when uninstalling flow, especially for portable version, I think we need to have this explained under the option so user is aware that manual removal is needed.

@jjw24 Please check.

This comment has been minimized.

Copy link

gitstream-cm bot commented Feb 15, 2025

🥷 Code experts: Yusyuriv, onesounds

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

See details

Flow.Launcher.Infrastructure/UserSettings/Settings.cs

Activity based on git-commit:

Jack251970
FEB 10 additions & 4 deletions
JAN 16 additions & 4 deletions
DEC 1 additions & 1 deletions
NOV
OCT
SEP

Knowledge based on git-blame:
onesounds: 24%
Yusyuriv: 14%

Flow.Launcher/App.xaml.cs

Activity based on git-commit:

Jack251970
FEB 11 additions & 12 deletions
JAN 85 additions & 65 deletions
DEC
NOV
OCT
SEP

Knowledge based on git-blame:
Yusyuriv: 2%

Flow.Launcher/Flow.Launcher.csproj

Activity based on git-commit:

Jack251970
FEB
JAN 3 additions & 2 deletions
DEC 4 additions & 0 deletions
NOV
OCT
SEP

Knowledge based on git-blame:
onesounds: 17%

Flow.Launcher/Helper/AutoStartup.cs

Activity based on git-commit:

Jack251970
FEB
JAN
DEC
NOV
OCT
SEP

Knowledge based on git-blame:
Yusyuriv: 64%

Flow.Launcher/Languages/en.xaml

Activity based on git-commit:

Jack251970
FEB 2 additions & 4 deletions
JAN
DEC
NOV
OCT
SEP

Knowledge based on git-blame:
onesounds: 44%
Yusyuriv: 6%

Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs

Activity based on git-commit:

Jack251970
FEB
JAN 1 additions & 1 deletions
DEC
NOV
OCT
SEP

Knowledge based on git-blame:
Yusyuriv: 99%

Flow.Launcher/SettingPages/Views/SettingsPaneGeneral.xaml

Activity based on git-commit:

Jack251970
FEB
JAN
DEC
NOV
OCT
SEP

Knowledge based on git-blame:
onesounds: 63%
Yusyuriv: 37%

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

@rottakore
Copy link

rottakore commented Feb 15, 2025

Creating a string key on HKLM\...\Run to launch FL is a tiny tiny bit faster than task scheduler, and I think it's easier to delete it.

@Jack251970
Copy link
Contributor Author

@rottakore Thanks for your idea! I have decided to use this way.

@Jack251970
Copy link
Contributor Author

@jjw24 I attempted to use the HKLM...\Run registry key, but it requires significant adjustments since FL is not designed to run with administrator privileges. For now, I’ll continue using the logon task to avoid complications.

@jjw24 jjw24 added this to the 1.20.0 milestone Feb 24, 2025
AutoStartup.Disable();
{
// Disable both registry and task scheduler
AutoStartup.Disable(true);
Copy link
Member

Choose a reason for hiding this comment

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

One nitpick, could we change this to DisableViaLogonTask & EnableViaLogonTask and same type of naming for registry.

Copy link
Member

Choose a reason for hiding this comment

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

Keep these original methods as private and just add the additional wrapper functions for easier understanding.

Copy link
Contributor Author

@Jack251970 Jack251970 Feb 24, 2025

Choose a reason for hiding this comment

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

Well, that is fine. Please check the latest commit.

This comment has been minimized.

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/Helper/AutoStartup.cs (3)

99-139: Consider more specific error handling.

The catch blocks could be more specific about the types of exceptions they handle to provide better error messages and recovery options.

Consider this pattern:

-        catch (Exception e)
+        catch (UnauthorizedAccessException e)
+        {
+            Log.Error("AutoStartup", $"Access denied while managing auto-startup: {e}");
+            throw;
+        }
+        catch (Exception e)

141-167: Document task configuration choices.

The task configuration includes specific choices (2-second delay, battery settings disabled) that should be documented to explain the rationale.

Add comments explaining these choices:

+        // Add a small delay to ensure system services are ready
         td.Triggers.Add(new LogonTrigger { UserId = WindowsIdentity.GetCurrent().Name, Delay = TimeSpan.FromSeconds(2) });
         td.Actions.Add(Constant.ExecutablePath);

+        // Ensure the application runs regardless of power source
         td.Settings.StopIfGoingOnBatteries = false;
         td.Settings.DisallowStartIfOnBatteries = false;

184-189: Consider caching admin status check.

The IsCurrentUserIsAdmin check might be called frequently. Consider caching the result since admin status rarely changes during runtime.

+    private static bool? _isAdmin;
     private static bool IsCurrentUserIsAdmin()
     {
+        if (_isAdmin.HasValue)
+            return _isAdmin.Value;
         var identity = WindowsIdentity.GetCurrent();
         var principal = new WindowsPrincipal(identity);
-        return principal.IsInRole(WindowsBuiltInRole.Administrator);
+        return _isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a445e3 and 9630516.

📒 Files selected for processing (3)
  • Flow.Launcher/App.xaml.cs (1 hunks)
  • Flow.Launcher/Helper/AutoStartup.cs (3 hunks)
  • Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • Flow.Launcher/App.xaml.cs
  • Flow.Launcher/SettingPages/ViewModels/SettingsPaneGeneralViewModel.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: gitStream.cm
🔇 Additional comments (2)
Flow.Launcher/Helper/AutoStartup.cs (2)

14-42: LGTM! Well-structured property implementation.

The IsEnabled property cleanly handles both logon task and registry checks with proper error handling and logging.


71-97: LGTM! Well-designed public API.

The public methods are well-named and follow the Single Responsibility Principle, making the API intuitive to use.

@Jack251970 Jack251970 requested a review from jjw24 February 24, 2025 12:02
Copy link
Member

@jjw24 jjw24 left a comment

Choose a reason for hiding this comment

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

Let's log exception for easier troubleshooting later if needed.

@Jack251970 Jack251970 requested a review from jjw24 February 25, 2025 07:08
Copy link

@check-spelling-bot Report

🔴 Please review

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

❌ Errors Count
❌ forbidden-pattern 22
⚠️ ignored-expect-variant 1
⚠️ non-alpha-in-dictionary 19

See ❌ Event descriptions for more information.

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.

@Jack251970
Copy link
Contributor Author

Let's log exception for easier troubleshooting later if needed.

Please check

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: 1

♻️ Duplicate comments (1)
Flow.Launcher/Helper/AutoStartup.cs (1)

53-53: ⚠️ Potential issue

Add null check for task action.

The null-forgiving operator (!) on line 53 could cause a NullReferenceException if the task has no actions defined. This was identified in a previous review but has not been addressed.

Apply this fix to properly handle potential null references:

-                var action = task.Definition.Actions.FirstOrDefault()!.ToString().Trim();
+                var action = task.Definition.Actions.FirstOrDefault()?.ToString()?.Trim();
+                if (action == null)
+                {
+                    UnscheduleLogonTask();
+                    ScheduleLogonTask();
+                    return true;
+                }
🧹 Nitpick comments (5)
Flow.Launcher/Helper/AutoStartup.cs (5)

184-189: Fix method name with redundant "is".

The method name IsCurrentUserIsAdmin() contains a redundant "is" which affects readability.

-    private static bool IsCurrentUserIsAdmin()
+    private static bool IsCurrentUserAdmin()

Update all references to this method accordingly.


145-145: Consider making the delay configurable.

The current implementation uses a fixed 2-second delay after logon before starting the application. Consider making this delay configurable through the settings to accommodate different system performance characteristics.

-        td.Triggers.Add(new LogonTrigger { UserId = WindowsIdentity.GetCurrent().Name, Delay = TimeSpan.FromSeconds(2) });
+        td.Triggers.Add(new LogonTrigger { UserId = WindowsIdentity.GetCurrent().Name, Delay = TimeSpan.FromSeconds(Settings.StartupDelay) });

This would require adding a new StartupDelay setting with a reasonable default of 2 seconds.


159-166: Enhance error handling and logging.

The current error handling captures and logs exceptions but doesn't provide specific guidance for users or administrators when task registration fails.

Consider enhancing the error message to include more specific information about the failure reason and potential remediation steps:

         catch (Exception e)
         {
-            Log.Error("AutoStartup", $"Failed to schedule logon task: {e}");
+            string errorDetails = e is UnauthorizedAccessException 
+                ? "Access denied. Try running Flow Launcher as administrator."
+                : e.Message;
+            Log.Error("AutoStartup", $"Failed to schedule logon task: {errorDetails}", e);
             return false;
         }

This would provide more actionable information to users experiencing issues.


153-156: Consider adding additional task settings for power management.

The current implementation disables stopping if going on batteries and starting if on batteries, but there are other power-related settings that might be worth configuring.

Consider adding these additional settings to ensure the task behaves correctly under all power conditions:

         td.Settings.StopIfGoingOnBatteries = false;
         td.Settings.DisallowStartIfOnBatteries = false;
+        td.Settings.AllowHardTerminate = true;
+        td.Settings.StartWhenAvailable = true;
+        td.Settings.RestartOnFailure = new RestartSettings(new TimeSpan(0, 1, 0), 3);
         td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

These settings would ensure the task can start when the system becomes available, can be forcefully terminated if needed, and can restart on failure.


22-28: Improve comment clarity for better code readability.

The current comments are functional but could be more descriptive to better explain the priority order of startup methods.

-            // Check if logon task is enabled
+            // First check if logon task is enabled (preferred method for faster startup)
             if (CheckLogonTask())
             {
                 return true;
             }

-            // Check if registry is enabled
+            // Fall back to registry method if logon task is not enabled
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9630516 and fe48427.

📒 Files selected for processing (1)
  • Flow.Launcher/Helper/AutoStartup.cs (3 hunks)
🔇 Additional comments (1)
Flow.Launcher/Helper/AutoStartup.cs (1)

171-182: Verify task cleanup during uninstallation.

Per PR comments, the logon task is not automatically removed during uninstallation. Consider integrating the UnscheduleLogonTask() method with the application's uninstallation process.

This would prevent orphaned tasks from remaining on the system after the application is uninstalled, improving user experience.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
20 min review enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Option to change priority at startup, so it launches sooner
4 participants