wails icon indicating copy to clipboard operation
wails copied to clipboard

[v3] Start At Login

Open ansxuman opened this issue 1 year ago • 8 comments

Description

Added

Support for Start At Login #1789

Type of change

Please select the option that is relevant.

  • [ ] Bug fix (non-breaking change which fixes an issue)
  • [x] New feature (non-breaking change which adds functionality)
  • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • [ ] This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration using wails3 doctor.

  • [x] Windows
  • [x] macOS
  • [ ] Linux

If you checked Linux, please specify the distro and version.

Test Configuration

Please paste the output of wails3 doctor. If you are unable to run this command, please describe your environment in as much detail as possible.


                                
          Wails Doctor          
                                

                                                                                                                                                        
# System
┌────────────────────────────┐
| Name          | MacOS      |
| Version       | 15.1       |
| ID            | 24B83      |
| Branding      | MacOS 15.1 |
| Platform      | darwin     |
| Architecture  | arm64      |
| Apple Silicon | true       |
| CPU           | Apple M1   |
| CPU           | Unknown    |
| GPU           | Unknown    |
| Memory        | Unknown    |
└────────────────────────────┘

# Build Environment
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
| Wails CLI      | v3.0.0-alpha.69                                                                                                           |
| Go Version     | go1.23.2                                                                                                                  |
| Revision       | d27e75c57f6cb481334f207c86666ad3419b7da1                                                                                  |
| Modified       | true                                                                                                                      |
| -buildmode     | exe                                                                                                                       |
| -compiler      | gc                                                                                                                        |
| CGO_CFLAGS     |                                                                                                                           |
| CGO_CPPFLAGS   |                                                                                                                           |
| CGO_CXXFLAGS   |                                                                                                                           |
| CGO_ENABLED    | 1                                                                                                                         |
| CGO_LDFLAGS    |                                                                                                                           |
| DefaultGODEBUG | asynctimerchan=1,gotypesalias=0,httpservecontentkeepheaders=1,tls3des=1,tlskyber=0,x509keypairleaf=0,x509negativeserial=1 |
| GOARCH         | arm64                                                                                                                     |
| GOARM64        | v8.0                                                                                                                      |
| GOOS           | darwin                                                                                                                    |
| vcs            | git                                                                                                                       |
| vcs.modified   | true                                                                                                                      |
| vcs.revision   | d27e75c57f6cb481334f207c86666ad3419b7da1                                                                                  |
| vcs.time       | 2024-11-23T20:46:14Z                                                                                                      |
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

# Dependencies
┌───────────────────────────┐
| Xcode cli tools | 2409    |
| npm             | 10.8.1  |
| *NSIS           | v3.10   |
└─ * - Optional Dependency ─┘

Checklist:

  • [x] I have updated website/src/pages/changelog.mdx with details of this PR
  • [x] My code follows the general coding style of this project
  • [x] I have performed a self-review of my own code
  • [ ] I have commented my code, particularly in hard-to-understand areas
  • [ ] I have made corresponding changes to the documentation
  • [ ] My changes generate no new warnings
  • [ ] I have added tests that prove my fix is effective or that my feature works
  • [ ] New and existing unit tests pass locally with my changes

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for automatic application startup on login across Windows, macOS, and Linux.
    • Introduced new commands for updating build assets and generating runtime for SvelteKit.
    • Enhanced documentation for events and added new templates.
  • Bug Fixes

    • Resolved issues with app image compilation and improved systray functionality on Linux and macOS.
  • Improvements

    • Refactored systray click messaging for better user interaction.
    • Enhanced error handling for application startup settings.
    • Improved cross-platform compatibility and user experience through various adjustments.

ansxuman avatar Nov 24 '24 12:11 ansxuman

Walkthrough

The pull request introduces multiple enhancements and fixes across various platform-specific application files. Key updates include the addition of methods to manage application startup behavior on login for macOS, Linux, and Windows, alongside new options in the application configuration. The changelog has been updated to reflect these changes, including support for new features like StartAtLogin, improved error handling, and various bug fixes. Overall, the changes aim to improve cross-platform compatibility and user experience.

Changes

File Path Change Summary
mkdocs-website/docs/en/changelog.md Updated changelog to include new features, changes, and fixes, including StartAtLogin support.
v3/pkg/application/application.go Added startAtLoginOnRun field, modified Run method, and added setStartAtLogin methods.
v3/pkg/application/application_darwin.go Added setStartAtLogin and canStartAtLogin methods for macOS application startup behavior.
v3/pkg/application/application_linux.go Added setStartAtLogin and canStartAtLogin methods for Linux application startup behavior.
v3/pkg/application/application_options.go Added StartAtLogin field to Options struct.
v3/pkg/application/application_windows.go Added setStartAtLogin and canStartAtLogin methods for Windows application startup behavior.

Possibly related PRs

  • #3823: Introduces a new Path method in the application package, related to this PR's addition of similar methods.
  • #3902: Introduces support for Darwin universal builds, a key focus of this PR.
  • #3920: Reworks service.OnStartup to close the application on error, enhancing error handling.
  • #3886: Addresses systray click implementations, enhancing user interaction.
  • #3907: Fixes systray click behavior, contributing to improved user interaction.
  • #3924: Cleans up .syso files during Windows builds, relevant to overall enhancements.

Suggested reviewers

  • leaanthony

🐰 "In the code we hop and play,
New features brighten up the day!
With options for login, oh what fun,
Cross-platform joy for everyone!
Let’s celebrate with a happy cheer,
For all the changes that bring us near!" 🐇


📜 Recent review details

Configuration used: .coderabbit.yaml Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7157952e6950a959e008e65d78eb0fbadb57da08 and 11fdcc1996a8f9794adafbdc1ca54918d983d0ea.

📒 Files selected for processing (1)
  • mkdocs-website/docs/en/changelog.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • mkdocs-website/docs/en/changelog.md

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

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.

coderabbitai[bot] avatar Nov 24 '24 12:11 coderabbitai[bot]

Hey, I'm pretty interested in having this functionality. Is there anything that can be done to help test or move this across the line?

IanVS avatar Mar 26 '25 18:03 IanVS

If I'm understanding this correctly, this is an option that must be set when creating the application, right? So would there be no way for the user to toggle this on and off, for example from a menu item?

Also, I wonder if this approach will only work without sandboxing (apps that are not delivered via the app store), that's the impression I get from https://eclecticlight.co/2018/05/23/a-simpler-way-to-control-an-apps-login-item/ at least.

Other idea/question: would it be possible to use SMAppService for more recent versions of macOS (13+) to manage login items? https://developer.apple.com/documentation/servicemanagement/smappservice

IanVS avatar Mar 26 '25 20:03 IanVS

Yeah, this has sat here for a bit as I'm looking for feedback, just like yours! I had questions myself about whether it would work in other environments other than that tested. Also this: https://github.com/wailsapp/wails/pull/3910#discussion_r1855437926. I do think this isn't quite there yet and needs more love.

leaanthony avatar Mar 31 '25 10:03 leaanthony

Yeah, this has sat here for a bit as I'm looking for feedback, just like yours! I had questions myself about whether it would work in other environments other than that tested. Also this: #3910 (comment). I do think this isn't quite there yet and needs more love.

If you dont mind, can you give this a try on your mac, it has Start At Login using the same code https://clave.rocks/

ansxuman avatar Apr 03 '25 14:04 ansxuman

It looks like Clave is not distributed through the app store. It would be great to find an open source project which is, and verify how they do it, since I think that's where trouble might come up.

IanVS avatar Apr 07 '25 12:04 IanVS

@ansxuman - Are you ok to address all the comments above or will you not have time? Thanks

leaanthony avatar Apr 09 '25 08:04 leaanthony

@ansxuman - Are you ok to address all the comments above or will you not have time? Thanks

Sure, i will spend sometime in the weekend.

ansxuman avatar Apr 09 '25 19:04 ansxuman

@ansxuman - Hi 👋 Did you want to keep this PR open? Thanks 🙏

leaanthony avatar Aug 02 '25 04:08 leaanthony

@ansxuman - Hi 👋 Did you want to keep this PR open? Thanks 🙏

I changed my company in April, and with increased responsibilities, I haven't had time to contribute here. Can we merge this MR as Phase 1 for now? We can add additional enhancements later for @IanVS.

ansxuman avatar Aug 02 '25 17:08 ansxuman

Thanks for getting back to me 🙏 I think there's some improvements to be made before we merge but I'm happy to take that on if you don't have the time 👍

leaanthony avatar Aug 02 '25 23:08 leaanthony

Thanks for getting back to me 🙏 I think there's some improvements to be made before we merge but I'm happy to take that on if you don't have the time 👍

Sure, Thanks 🙏

ansxuman avatar Aug 03 '25 06:08 ansxuman

It would be really useful to be able to specify the registryKey on windows, I have an application which this will register as simply 'watchdog', which is a very vague name and probably prone to collisions.

And being able to query the current state would be useful too, to allow for making a better UX. Some snippets I am using which achieve this, feel free to include and use them:

func isStartAtLoginEnabled() (bool, error) {
	key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Run`, registry.READ)
	if err != nil {
		return false, fmt.Errorf("failed to open registry key: %s", err)
	}
	defer key.Close()

	_, _, err = key.GetStringValue(registryKey)
	if err == registry.ErrNotExist {
		return false, nil
	} else if err != nil {
		return false, fmt.Errorf("failed to read registry value: %s", err)
	}
	return true, nil
}
func isStartAtLoginEnabled() (bool, error) {
	// If we're not running from an app bundle, treat as disabled
	bundleID := GetBundleID()
	if bundleID == "" {
		return false, nil
	}

	exe, err := os.Executable()
	if err != nil {
		return false, fmt.Errorf("error running os.Executable: %v", err)
	}

	binName := filepath.Base(exe)
	// If not running as a packaged .app, we can't manage login items the way we do
	if !strings.HasSuffix(exe, "/Contents/MacOS/"+binName) {
		return false, nil
	}

	// Query System Events for the names of all login items
	cmd := exec.Command("osascript", "-e", `tell application "System Events" to get the name of every login item`)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return false, fmt.Errorf("osascript failed: %v: %s", err, strings.TrimSpace(string(out)))
	}

	s := strings.TrimSpace(string(out))
	if s == "" || s == "missing value" {
		return false, nil
	}

	// AppleScript returns a comma-separated list when there are multiple items
	items := strings.Split(s, ", ")
	for _, it := range items {
		if strings.TrimSpace(it) == itemName {
			return true, nil
		}
	}

	return false, nil
}

Julusian avatar Sep 05 '25 15:09 Julusian

On some further testing, the macos logic doesn't quite work right.

If I run osascript -e 'tell application "System Events" to make login item at end with properties {name: "test123",path:"/Applications/My App.app", hidden:false}' it says login item test123 But running osascript -e 'tell application "System Events" to get the properties of every login item' gives:

name:My App, path:/Applications/My App.app, class:login item, kind:Application, hidden:false

And trying to delete it osascript -e 'tell application \"System Events\" to delete login item "test123"' fails with 36execution error: System Events got an error: Can’t get login item "test123". (-1728)

So it looks like this has to be use the same name as the .app

My reworked version of this is:

func getAppNameAndPath() (string, string, error) {
	exe, err := os.Executable()
	if err != nil {
		return "", "", fmt.Errorf("error running os.Executable: %v", err)
	}

	binName := filepath.Base(exe)
	// Escape special characters in binName to prevent AppleScript injection
	binName = strings.ReplaceAll(binName, "\"", "\\\"")
	if !strings.HasSuffix(exe, "/Contents/MacOS/"+binName) {
		return "", "", fmt.Errorf("app does not appear to be packaged")
	}

	appPath := strings.TrimSuffix(exe, "/Contents/MacOS/"+binName)
	appName := filepath.Base(appPath)

	// trim extension if present
	appName = strings.TrimSuffix(appName, ".app")
	return appName, appPath, nil
}

func setStartAtLogin(enabled bool) error {
	appName, appPath, err := getAppNameAndPath()
	if err != nil {
		return fmt.Errorf("error getting app name and path: %v", err)
	}

	var command string
	if enabled {
		// the "name" field appears to be ignored, with the name of the entry being the .app name
		command = fmt.Sprintf("tell application \"System Events\" to make login item at end with properties {name: \"%s\",path:\"%s\", hidden:false}", appName, appPath)
	} else {
		command = fmt.Sprintf("tell application \"System Events\" to delete login item \"%s\"", appName)
	}

	cmd := exec.Command("osascript", "-e", command)
	_, err = cmd.CombinedOutput()
	return err
}

func isStartAtLoginEnabled() (bool, error) {
	// If we're not running from an app bundle, treat as disabled
	bundleID := GetBundleID()
	if bundleID == "" {
		return false, nil
	}

	appName, _, err := getAppNameAndPath()
	if err != nil {
		return false, fmt.Errorf("error getting app name and path: %v", err)
	}

	// Query System Events for the names of all login items
	cmd := exec.Command("osascript", "-e", `tell application "System Events" to get the name of every login item`)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return false, fmt.Errorf("osascript failed: %v: %s", err, strings.TrimSpace(string(out)))
	}

	s := strings.TrimSpace(string(out))
	if s == "" || s == "missing value" {
		return false, nil
	}

	// AppleScript returns a comma-separated list when there are multiple items
	items := strings.Split(s, ", ")
	for _, it := range items {
		if strings.TrimSpace(it) == appName {
			return true, nil
		}
	}

	return false, nil
}

Julusian avatar Sep 05 '25 15:09 Julusian

Yeah, I think this PR needs reworking. Is there anyone willing to take it on?

leaanthony avatar Sep 07 '25 09:09 leaanthony