Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

50.1 KB
Raw Blame
//go:build windows

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unsafe"
)

const (
	profileCN       = "workbuddy-cn"
	profileAI       = "workbuddy-ai"
	profileCodeCN   = "codebuddy-cn"
	profileCodeIntl = "codebuddy-intl"

	exitFailure           = 4
	exitElevated          = 5
	exitWorkBuddyRunning  = 10
	exitAccessDenied      = 11
	exitIdentityMismatch  = 12
	exitPreserveLifecycle = 13
	exitUsage             = 20

	processTerminate               = 0x0001
	processQueryLimitedInformation = 0x1000
	synchronize                    = 0x00100000
	tokenAssignPrimary             = 0x0001
	tokenDuplicate                 = 0x0002
	tokenQuery                     = 0x0008
	tokenElevation                 = 20 // TokenElevation
	tokenElevationType             = 18 // TokenElevationType
	tokenSessionID                 = 12 // TokenSessionId
	logonWithProfile               = 0x00000001
	createUnicodeEnvironment       = 0x00000400
	th32csSnapProcess              = 0x00000002
	maxPath                        = 260
	infinite                       = 0xffffffff
	waitObject0                    = 0
	errorAlreadyExists             = 183
	mbOK                           = 0x00000000
	mbIconWarning                  = 0x00000030
	mbIconError                    = 0x00000010
	mbRetryCancel                  = 0x00000005
	idRetry                        = 4
)

var (
	kernel32                      = syscall.NewLazyDLL("kernel32.dll")
	advapi32                      = syscall.NewLazyDLL("advapi32.dll")
	userenv                       = syscall.NewLazyDLL("userenv.dll")
	user32                        = syscall.NewLazyDLL("user32.dll")
	versionDLL                    = syscall.NewLazyDLL("version.dll")
	procCreateMutexW              = kernel32.NewProc("CreateMutexW")
	procGetCurrentProcess         = kernel32.NewProc("GetCurrentProcess")
	procOpenProcessToken          = advapi32.NewProc("OpenProcessToken")
	procGetTokenInformation       = advapi32.NewProc("GetTokenInformation")
	procCreateProcessWithTokenW   = advapi32.NewProc("CreateProcessWithTokenW")
	procCreateEnvironmentBlock    = userenv.NewProc("CreateEnvironmentBlock")
	procDestroyEnvironmentBlock   = userenv.NewProc("DestroyEnvironmentBlock")
	procCreateToolhelp32Snapshot  = kernel32.NewProc("CreateToolhelp32Snapshot")
	procProcess32FirstW           = kernel32.NewProc("Process32FirstW")
	procProcess32NextW            = kernel32.NewProc("Process32NextW")
	procOpenProcess               = kernel32.NewProc("OpenProcess")
	procQueryFullProcessImageName = kernel32.NewProc("QueryFullProcessImageNameW")
	procTerminateProcess          = kernel32.NewProc("TerminateProcess")
	procWaitForSingleObject       = kernel32.NewProc("WaitForSingleObject")
	procMessageBoxW               = user32.NewProc("MessageBoxW")
	procGetShellWindow            = user32.NewProc("GetShellWindow")
	procGetWindowThreadProcessID  = user32.NewProc("GetWindowThreadProcessId")
	procGetFileVersionInfoSizeW   = versionDLL.NewProc("GetFileVersionInfoSizeW")
	procGetFileVersionInfoW       = versionDLL.NewProc("GetFileVersionInfoW")
	procVerQueryValueW            = versionDLL.NewProc("VerQueryValueW")
)

type processEntry32 struct {
	Size              uint32
	Usage             uint32
	ProcessID         uint32
	DefaultHeapID     uintptr
	ModuleID          uint32
	Threads           uint32
	ParentProcessID   uint32
	PriorityClassBase int32
	Flags             uint32
	ExeFile           [maxPath]uint16
}

type processRecord struct {
	PID       uint32 `json:"pid"`
	Name      string `json:"name"`
	Path      string `json:"path,omitempty"`
	ParentPID uint32 `json:"-"`
}

type lockOwner struct {
	PID int `json:"pid"`
}

type workBuddyTarget struct {
	ProfileID    string   `json:"profileId"`
	ClientType   string   `json:"clientType"`
	Binary       string   `json:"binary"`
	Version      string   `json:"version"`
	ProcessName  string   `json:"processName"`
	ProcessNames []string `json:"processNames"`
}

// daemonStatus mirrors the authenticated subset of the daemon /api/status
// payload. Only fields required for capability proof are decoded.
type daemonStatus struct {
	OK        bool   `json:"ok"`
	PID       int    `json:"pid"`
	Privilege string `json:"privilege"`
	DataDir   string `json:"dataDir"`
	AppDir    string `json:"appDir"`
	Profile   struct {
		ID string `json:"id"`
	} `json:"profile"`
}

type vsFixedFileInfo struct {
	Signature        uint32
	StructVersion    uint32
	FileVersionMS    uint32
	FileVersionLS    uint32
	ProductVersionMS uint32
	ProductVersionLS uint32
	FileFlagsMask    uint32
	FileFlags        uint32
	FileOS           uint32
	FileType         uint32
	FileSubtype      uint32
	FileDateMS       uint32
	FileDateLS       uint32
}

func utf16Ptr(value string) *uint16 {
	ptr, err := syscall.UTF16PtrFromString(value)
	if err != nil {
		panic(err)
	}
	return ptr
}

func messageBox(title, message string, flags uintptr) int {
	result, _, _ := procMessageBoxW.Call(0, uintptr(unsafe.Pointer(utf16Ptr(message))), uintptr(unsafe.Pointer(utf16Ptr(title))), flags)
	return int(result)
}

func fileVersion(binary string) string {
	name := utf16Ptr(binary)
	var ignored uint32
	size, _, _ := procGetFileVersionInfoSizeW.Call(uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(&ignored)))
	if size == 0 || size > 16*1024*1024 {
		return ""
	}
	buffer := make([]byte, size)
	ok, _, _ := procGetFileVersionInfoW.Call(
		uintptr(unsafe.Pointer(name)), 0, size, uintptr(unsafe.Pointer(&buffer[0])),
	)
	if ok == 0 {
		return ""
	}
	root := utf16Ptr("\\")
	var fixed *vsFixedFileInfo
	var fixedSize uint32
	ok, _, _ = procVerQueryValueW.Call(
		uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(root)),
		uintptr(unsafe.Pointer(&fixed)), uintptr(unsafe.Pointer(&fixedSize)),
	)
	if ok == 0 || fixed == nil || fixedSize < uint32(unsafe.Sizeof(*fixed)) || fixed.Signature != 0xFEEF04BD {
		return ""
	}
	return fmt.Sprintf("%d.%d.%d.%d",
		fixed.FileVersionMS>>16, fixed.FileVersionMS&0xffff,
		fixed.FileVersionLS>>16, fixed.FileVersionLS&0xffff)
}

func tokenIsElevated(token syscall.Handle) (bool, error) {
	var elevation uint32
	var returned uint32
	result, _, callErr := procGetTokenInformation.Call(
		uintptr(token), tokenElevation, uintptr(unsafe.Pointer(&elevation)), unsafe.Sizeof(elevation), uintptr(unsafe.Pointer(&returned)),
	)
	if result == 0 {
		return false, callErr
	}
	return elevation != 0, nil
}

func isElevated() (bool, error) {
	current, _, _ := procGetCurrentProcess.Call()
	var token syscall.Handle
	result, _, callErr := procOpenProcessToken.Call(current, tokenQuery, uintptr(unsafe.Pointer(&token)))
	if result == 0 {
		return false, callErr
	}
	defer syscall.CloseHandle(token)
	return tokenIsElevated(token)
}

func openDesktopToken(access uint32) (syscall.Handle, error) {
	shellWindow, _, callErr := procGetShellWindow.Call()
	if shellWindow == 0 {
		return 0, fmt.Errorf("cannot find desktop Explorer window: %w", callErr)
	}
	var shellPID uint32
	procGetWindowThreadProcessID.Call(shellWindow, uintptr(unsafe.Pointer(&shellPID)))
	if shellPID == 0 {
		return 0, errors.New("cannot identify desktop Explorer process")
	}
	expectedExplorer := filepath.Join(os.Getenv("SystemRoot"), "explorer.exe")
	if os.Getenv("SystemRoot") == "" || !strings.EqualFold(filepath.Clean(queryProcessPath(shellPID)), filepath.Clean(expectedExplorer)) {
		return 0, errors.New("desktop shell process is not the expected explorer.exe")
	}
	shellProcess, err := openProcess(shellPID, processQueryLimitedInformation)
	if err != nil {
		return 0, fmt.Errorf("cannot open desktop Explorer process: %w", err)
	}
	defer syscall.CloseHandle(shellProcess)
	var shellToken syscall.Handle
	result, _, callErr := procOpenProcessToken.Call(
		uintptr(shellProcess), uintptr(access), uintptr(unsafe.Pointer(&shellToken)),
	)
	if result == 0 {
		return 0, fmt.Errorf("cannot open desktop Explorer token: %w", callErr)
	}
	return shellToken, nil
}

func relaunchWithDesktopToken(appDir string) error {
	shellToken, err := openDesktopToken(tokenAssignPrimary | tokenDuplicate | tokenQuery)
	if err != nil {
		return err
	}
	defer syscall.CloseHandle(shellToken)
	elevated, err := tokenIsElevated(shellToken)
	if err != nil {
		return fmt.Errorf("cannot inspect desktop Explorer token: %w", err)
	}
	if elevated {
		return errDesktopTokenElevated
	}
	executable, err := os.Executable()
	if err != nil {
		return err
	}
	if strings.ContainsAny(executable, "\x00\r\n\"") {
		return errors.New("native launcher path contains invalid characters")
	}
	var environment uintptr
	result, _, callErr := procCreateEnvironmentBlock.Call(
		uintptr(unsafe.Pointer(&environment)), uintptr(shellToken), 0,
	)
	if result == 0 {
		return fmt.Errorf("cannot create desktop user environment: %w", callErr)
	}
	defer procDestroyEnvironmentBlock.Call(environment)
	commandLine := utf16Ptr("\"" + executable + "\" --desktop-shell-relaunch")
	startup := syscall.StartupInfo{Cb: uint32(unsafe.Sizeof(syscall.StartupInfo{}))}
	var processInfo syscall.ProcessInformation
	result, _, callErr = procCreateProcessWithTokenW.Call(
		uintptr(shellToken), logonWithProfile, uintptr(unsafe.Pointer(utf16Ptr(executable))), uintptr(unsafe.Pointer(commandLine)),
		createUnicodeEnvironment, environment, uintptr(unsafe.Pointer(utf16Ptr(appDir))), uintptr(unsafe.Pointer(&startup)), uintptr(unsafe.Pointer(&processInfo)),
	)
	if result == 0 {
		return fmt.Errorf("cannot relaunch with desktop Explorer token: %w", callErr)
	}
	syscall.CloseHandle(processInfo.Thread)
	syscall.CloseHandle(processInfo.Process)
	return nil
}

// Consent is a per-user preference, not a privilege grant. It never creates a
// token: every use rechecks the real desktop and process token before proceeding.
var errDesktopTokenElevated = errors.New("desktop Explorer token is elevated")

type elevatedConsent struct {
	Version int    `json:"version"`
	Profile string `json:"profile"`
	AppDir  string `json:"appDir"`
	UserSID string `json:"userSid"`
}

func tokenDword(token syscall.Handle, kind uint32) (uint32, error) {
	var value, returned uint32
	ok, _, err := procGetTokenInformation.Call(uintptr(token), uintptr(kind),
		uintptr(unsafe.Pointer(&value)), unsafe.Sizeof(value), uintptr(unsafe.Pointer(&returned)))
	if ok == 0 {
		return 0, err
	}
	return value, nil
}

func currentUserSID() (string, error) {
	token, err := syscall.OpenCurrentProcessToken()
	if err != nil {
		return "", err
	}
	defer token.Close()
	user, err := token.GetTokenUser()
	if err != nil {
		return "", err
	}
	return user.User.Sid.String()
}

func verifySameProcessSecurity(handle syscall.Handle) error {
	var target syscall.Token
	if err := syscall.OpenProcessToken(handle, tokenQuery, &target); err != nil {
		return err
	}
	defer target.Close()
	current, err := syscall.OpenCurrentProcessToken()
	if err != nil {
		return err
	}
	defer current.Close()
	targetUser, err := target.GetTokenUser()
	if err != nil {
		return err
	}
	currentUser, err := current.GetTokenUser()
	if err != nil {
		return err
	}
	targetSID, err := targetUser.User.Sid.String()
	if err != nil {
		return err
	}
	currentSID, err := currentUser.User.Sid.String()
	if err != nil {
		return err
	}
	if targetSID != currentSID {
		return errors.New("process belongs to another user")
	}
	for _, kind := range []uint32{tokenElevation, tokenSessionID} {
		left, err := tokenDword(syscall.Handle(target), kind)
		if err != nil {
			return err
		}
		right, err := tokenDword(syscall.Handle(current), kind)
		if err != nil {
			return err
		}
		if left != right {
			return errors.New("process privilege or session differs from launcher")
		}
	}
	return nil
}

func desktopSessionSupportsElevated() bool {
	current, err := isElevated()
	if err != nil || !current {
		return false
	}
	token, err := openDesktopToken(tokenQuery)
	if err != nil {
		return false
	}
	defer syscall.CloseHandle(token)
	elevated, err := tokenIsElevated(token)
	if err != nil || !elevated {
		return false
	}
	// A manually elevated Explorer with a linked standard token is NOT the
	// built-in Administrator/UAC-disabled case. TokenElevationTypeDefault = 1.
	elevationType, err := tokenDword(token, tokenElevationType)
	if err != nil || elevationType != 1 {
		return false
	}
	shellUser, err := syscall.Token(token).GetTokenUser()
	if err != nil {
		return false
	}
	shellSID, err := shellUser.User.Sid.String()
	if err != nil {
		return false
	}
	currentSID, err := currentUserSID()
	return err == nil && shellSID == currentSID
}

func elevatedSessionAllowed(profile, appDir string) bool {
	if !desktopSessionSupportsElevated() {
		return false
	}
	dir, err := dataDir(profile)
	if err != nil {
		return false
	}
	data, err := os.ReadFile(filepath.Join(dir, "windows-elevated-consent.json"))
	if err != nil {
		return false
	}
	var consent elevatedConsent
	if json.Unmarshal(data, &consent) != nil {
		return false
	}
	sid, err := currentUserSID()
	return err == nil && consent.Version == 1 && consent.Profile == profile &&
		filepath.IsAbs(appDir) && samePath(consent.AppDir, appDir) && consent.UserSID == sid
}

func saveElevatedConsent(profile, appDir string) error {
	if !filepath.IsAbs(appDir) || !desktopSessionSupportsElevated() {
		return errors.New("desktop session is not eligible for elevated compatibility")
	}
	dir, err := dataDir(profile)
	if err != nil {
		return err
	}
	sid, err := currentUserSID()
	if err != nil {
		return err
	}
	data, err := json.Marshal(elevatedConsent{1, profile, filepath.Clean(appDir), sid})
	if err != nil {
		return err
	}
	if err := os.MkdirAll(dir, 0700); err != nil {
		return err
	}
	// A partial write cannot grant consent: readers require complete valid JSON.
	return os.WriteFile(filepath.Join(dir, "windows-elevated-consent.json"), data, 0600)
}

func helperAppDir() string {
	if dir := argumentValue("--app-dir"); dir != "" {
		return dir
	}
	dir, _ := executableDir()
	return dir
}

func acquireMutex(profile string) (syscall.Handle, bool, error) {
	name := "Local\\WorkDaddyLauncher-" + profile
	handle, _, callErr := procCreateMutexW.Call(0, 0, uintptr(unsafe.Pointer(utf16Ptr(name))))
	if handle == 0 {
		return 0, false, callErr
	}
	alreadyExists := errors.Is(callErr, syscall.Errno(errorAlreadyExists))
	return syscall.Handle(handle), alreadyExists, nil
}

func executableDir() (string, error) {
	exe, err := os.Executable()
	if err != nil {
		return "", err
	}
	resolved, err := filepath.EvalSymlinks(exe)
	if err == nil {
		exe = resolved
	}
	return filepath.Dir(exe), nil
}

func normalizeProfile(profile string) string {
	switch strings.ToLower(strings.TrimSpace(profile)) {
	case profileAI:
		return profileAI
	case profileCodeCN:
		return profileCodeCN
	case profileCodeIntl:
		return profileCodeIntl
	}
	return profileCN
}

func readProfile(appDir string) string {
	if value := argumentValue("--profile"); value != "" {
		return normalizeProfile(value)
	}
	data, err := os.ReadFile(filepath.Join(appDir, "scripts", "profile-id.txt"))
	if err == nil {
		return normalizeProfile(string(data))
	}
	return profileCN
}

func argumentValue(name string) string {
	for index, arg := range os.Args[1:] {
		if arg == name && index+2 <= len(os.Args[1:]) {
			return os.Args[index+2]
		}
		if strings.HasPrefix(arg, name+"=") {
			return strings.TrimPrefix(arg, name+"=")
		}
	}
	return ""
}

func hasArgument(name string) bool {
	for _, arg := range os.Args[1:] {
		if arg == name {
			return true
		}
	}
	return false
}

func dataDir(profile string) (string, error) {
	root := os.Getenv("APPDATA")
	if root == "" {
		return "", errors.New("APPDATA is not available")
	}
	root = filepath.Join(root, "WorkDaddy")
	if profile != profileCN {
		return filepath.Join(root, "profiles", profile), nil
	}
	return root, nil
}

func productName(profile string) string {
	if profile == profileCodeCN {
		return "CodeDaddy CN"
	}
	if profile == profileCodeIntl {
		return "CodeDaddy"
	}
	if profile == profileAI {
		return "WorkDaddy AI"
	}
	return "WorkDaddy"
}

func configuredTarget(profile string) workBuddyTarget {
	dir, err := dataDir(profile)
	if err != nil {
		return workBuddyTarget{}
	}
	data, err := os.ReadFile(filepath.Join(dir, "workbuddy-target.json"))
	if err != nil {
		return workBuddyTarget{}
	}
	var target workBuddyTarget
	if json.Unmarshal(data, &target) != nil || !strings.EqualFold(target.ProfileID, profile) {
		return workBuddyTarget{}
	}
	configuredBinary := strings.TrimSpace(target.Binary)
	processNames := target.ProcessNames
	if len(processNames) == 0 && strings.TrimSpace(target.ProcessName) != "" {
		processNames = []string{target.ProcessName}
	}
	if !filepath.IsAbs(configuredBinary) || len(processNames) == 0 || len(processNames) > 4 {
		return workBuddyTarget{}
	}
	selectedName := filepath.Base(configuredBinary)
	hasSelectedName := false
	for index, name := range processNames {
		name = strings.TrimSpace(name)
		if name == "" || !strings.EqualFold(name, filepath.Base(name)) || !strings.EqualFold(filepath.Ext(name), ".exe") {
			return workBuddyTarget{}
		}
		processNames[index] = name
		if strings.EqualFold(name, selectedName) {
			hasSelectedName = true
		}
	}
	if !hasSelectedName {
		return workBuddyTarget{}
	}
	target.Binary = filepath.Clean(configuredBinary)
	target.ProcessNames = processNames
	return target
}

func codeBuddyFileNameMatches(profile, binary string) bool {
	name := filepath.Base(binary)
	if profile == profileCodeCN {
		return strings.EqualFold(name, "CodeBuddy CN.exe") || strings.EqualFold(name, "CodeBuddy.exe")
	}
	if profile == profileCodeIntl {
		return strings.EqualFold(name, "CodeBuddy.exe")
	}
	return false
}

func codeBuddyBinaryMatches(profile, binary string) bool {
	if profile != profileCodeCN && profile != profileCodeIntl {
		return true
	}
	if !codeBuddyFileNameMatches(profile, binary) {
		return false
	}
	data, err := os.ReadFile(filepath.Join(filepath.Dir(binary), "resources", "app", "product.json"))
	if err != nil {
		return false
	}
	var product struct {
		ApplicationName string `json:"applicationName"`
	}
	if json.Unmarshal(data, &product) != nil {
		return false
	}
	expected := "buddy"
	if profile == profileCodeCN {
		expected = "buddycn"
	}
	return product.ApplicationName == expected
}

func codeBuddyExplicitBinaryMatches(profile, binary string) bool {
	if profile == profileCodeCN && strings.EqualFold(filepath.Base(binary), "CodeBuddy CN.exe") {
		return true
	}
	return codeBuddyBinaryMatches(profile, binary)
}

func workBuddyImage(profile string) string {
	if profile == profileCodeCN {
		return "CodeBuddy CN.exe"
	}
	if profile == profileCodeIntl {
		return "CodeBuddy.exe"
	}
	if target := configuredTarget(profile); len(target.ProcessNames) > 0 {
		return target.ProcessNames[0]
	}
	if profile == profileAI {
		return "WorkBuddyAI.exe"
	}
	if profile == profileCN {
		return "WorkBuddy.exe"
	}
	return "WorkBuddy.exe"
}

func processNamesForBinary(binary string) []string {
	selected := filepath.Base(binary)
	names := []string{selected}
	stem := strings.TrimSuffix(selected, filepath.Ext(selected))
	lower := strings.ToLower(stem)
	for _, separator := range []string{"-", "_", " "} {
		prefix := "workbuddy" + separator
		if !strings.HasPrefix(lower, prefix) {
			continue
		}
		parts := strings.FieldsFunc(stem[len(prefix):], func(r rune) bool { return r == '-' || r == '_' || r == ' ' })
		suffix := ""
		for _, part := range parts {
			if part != "" {
				suffix += strings.ToUpper(part[:1]) + strings.ToLower(part[1:])
			}
		}
		if suffix != "" {
			names = append(names, "WorkBuddy"+suffix+".exe")
		}
		break
	}
	return names
}

func targetForBinary(profile, binary string) workBuddyTarget {
	binary = strings.TrimSpace(binary)
	if (profile != profileCN && profile != profileAI && profile != profileCodeCN && profile != profileCodeIntl) || !filepath.IsAbs(binary) ||
		!strings.EqualFold(filepath.Ext(binary), ".exe") || strings.ContainsAny(binary, "\r\n") {
		return workBuddyTarget{}
	}
	info, err := os.Stat(binary)
	if err != nil || info.IsDir() {
		return workBuddyTarget{}
	}
	if (profile == profileCodeCN || profile == profileCodeIntl) &&
		!codeBuddyExplicitBinaryMatches(profile, binary) {
		return workBuddyTarget{}
	}
	return workBuddyTarget{ProfileID: profile, Binary: filepath.Clean(binary), ProcessNames: processNamesForBinary(binary)}
}

func enumerateProcesses() ([]processRecord, error) {
	snapshot, _, callErr := procCreateToolhelp32Snapshot.Call(th32csSnapProcess, 0)
	if snapshot == uintptr(syscall.InvalidHandle) {
		return nil, callErr
	}
	defer syscall.CloseHandle(syscall.Handle(snapshot))

	entry := processEntry32{Size: uint32(unsafe.Sizeof(processEntry32{}))}
	result, _, callErr := procProcess32FirstW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
	if result == 0 {
		return nil, callErr
	}
	var records []processRecord
	for {
		name := syscall.UTF16ToString(entry.ExeFile[:])
		records = append(records, processRecord{
			PID: entry.ProcessID, Name: name, Path: queryProcessPath(entry.ProcessID), ParentPID: entry.ParentProcessID,
		})
		entry.Size = uint32(unsafe.Sizeof(processEntry32{}))
		result, _, _ = procProcess32NextW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
		if result == 0 {
			break
		}
	}
	return records, nil
}

func openProcess(pid uint32, access uint32) (syscall.Handle, error) {
	handle, _, callErr := procOpenProcess.Call(uintptr(access), 0, uintptr(pid))
	if handle == 0 {
		return 0, callErr
	}
	return syscall.Handle(handle), nil
}

func queryProcessPath(pid uint32) string {
	handle, err := openProcess(pid, processQueryLimitedInformation)
	if err != nil {
		return ""
	}
	defer syscall.CloseHandle(handle)
	buffer := make([]uint16, 32768)
	size := uint32(len(buffer))
	result, _, _ := procQueryFullProcessImageName.Call(
		uintptr(handle), 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(&size)),
	)
	if result == 0 || size == 0 {
		return ""
	}
	return syscall.UTF16ToString(buffer[:size])
}

func matchingWorkBuddyProcessesForTarget(profile string, target workBuddyTarget) ([]processRecord, error) {
	records, err := enumerateProcesses()
	if err != nil {
		return nil, err
	}
	expectedNames := []string{workBuddyImage(profile)}
	if len(target.ProcessNames) > 0 {
		expectedNames = target.ProcessNames
	}
	matched := make([]processRecord, 0)
	for _, record := range records {
		nameMatches := false
		for _, expected := range expectedNames {
			if strings.EqualFold(record.Name, expected) {
				nameMatches = true
				break
			}
		}
		pathMatches := target.Binary == "" || (record.Path != "" &&
			samePath(filepath.Dir(record.Path), filepath.Dir(target.Binary)) &&
			strings.EqualFold(filepath.Base(record.Path), record.Name))
		identityMatches := target.Binary != "" || codeBuddyBinaryMatches(profile, record.Path)
		if nameMatches && pathMatches && identityMatches {
			matched = append(matched, record)
		}
	}
	return matched, nil
}

func matchingWorkBuddyProcesses(profile string) ([]processRecord, error) {
	return matchingWorkBuddyProcessesForTarget(profile, configuredTarget(profile))
}

func samePath(left, right string) bool {
	return strings.EqualFold(filepath.Clean(left), filepath.Clean(right))
}

func readPID(path string) int {
	data, err := os.ReadFile(path)
	if err != nil {
		return 0
	}
	pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
	return pid
}

func readLockPID(path string) int {
	data, err := os.ReadFile(path)
	if err != nil {
		return 0
	}
	var owner lockOwner
	if json.Unmarshal(data, &owner) != nil {
		return 0
	}
	return owner.PID
}

// A different snapshot name proves a recycled PID is unrelated. A matching or
// unavailable name never authorizes termination or bypasses exact path checks.
func processNameDiffers(actualName, expectedPath string) bool {
	return actualName != "" && expectedPath != "" &&
		!strings.EqualFold(actualName, filepath.Base(expectedPath))
}

func inspectExactProcess(pid int, expectedPath string, label string) (bool, int, error) {
	if pid <= 0 {
		return false, 0, nil
	}
	actual := queryProcessPath(uint32(pid))
	if actual == "" {
		// A process can exit between reading the PID file and querying it.
		handle, err := openProcess(uint32(pid), synchronize)
		if err != nil {
			if errors.Is(err, syscall.Errno(87)) { // ERROR_INVALID_PARAMETER: PID no longer exists.
				return false, 0, nil
			}
			if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
				records, snapshotErr := enumerateProcesses()
				if snapshotErr != nil {
					return false, exitFailure, fmt.Errorf("PID %d process snapshot failed: %w", pid, snapshotErr)
				}
				present := false
				for _, record := range records {
					if record.PID == uint32(pid) {
						if processNameDiffers(record.Name, expectedPath) {
							return false, 0, nil
						}
						present = true
						break
					}
				}
				if !present {
					return false, 0, nil
				}
				return false, exitAccessDenied, fmt.Errorf("PID %d cannot be inspected with the current launcher permissions: %w", pid, err)
			}
			return false, exitFailure, err
		}
		waitResult, _, _ := procWaitForSingleObject.Call(uintptr(handle), 2000)
		syscall.CloseHandle(handle)
		if waitResult == waitObject0 {
			return false, 0, nil
		}
		return false, exitIdentityMismatch, fmt.Errorf("PID %d %s executable path is unavailable", pid, label)
	}
	if !samePath(actual, expectedPath) {
		if processNameDiffers(filepath.Base(actual), expectedPath) {
			return false, 0, nil
		}
		return false, exitIdentityMismatch, fmt.Errorf("PID %d is %s, expected %s", pid, actual, expectedPath)
	}
	return true, 0, nil
}

func terminateExactProcess(pid int, expectedPath string, label string) (bool, int, error) {
	active, code, inspectErr := inspectExactProcess(pid, expectedPath, label)
	if inspectErr != nil {
		return false, code, inspectErr
	}
	if !active {
		return false, 0, nil
	}
	handle, err := openProcess(uint32(pid), processTerminate|synchronize|processQueryLimitedInformation)
	if err != nil {
		if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
			return false, exitAccessDenied, fmt.Errorf("PID %d %s cannot be terminated with the current launcher permissions: %w", pid, label, err)
		}
		return false, exitFailure, err
	}
	defer syscall.CloseHandle(handle)
	if err := verifySameProcessSecurity(handle); err != nil {
		return false, exitAccessDenied, err
	}
	result, _, callErr := procTerminateProcess.Call(uintptr(handle), 0)
	if result == 0 {
		if errors.Is(callErr, syscall.ERROR_ACCESS_DENIED) {
			return false, exitAccessDenied, fmt.Errorf("PID %d %s cannot be terminated with the current launcher permissions: %w", pid, label, callErr)
		}
		return false, exitFailure, callErr
	}
	waitResult, _, callErr := procWaitForSingleObject.Call(uintptr(handle), 15000)
	if waitResult != waitObject0 {
		return false, exitFailure, fmt.Errorf("PID %d did not exit: %v", pid, callErr)
	}
	return true, 0, nil
}

func terminateExactNode(pid int, expectedNode string) (bool, int, error) {
	return terminateExactProcess(pid, expectedNode, "node")
}

func stopInstalledLauncher(profile, appDir string, elevated bool) int {
	expectedLauncher := filepath.Join(appDir, "WorkDaddyLauncher.exe")
	records, err := enumerateProcesses()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return exitFailure
	}
	matches := make([]processRecord, 0, 1)
	for _, record := range records {
		// The --stop-lifecycle helper is itself WorkDaddyLauncher.exe from the
		// target directory. Exclude only this helper; every other match remains
		// subject to the single-process fail-closed boundary below.
		if record.PID == uint32(os.Getpid()) {
			continue
		}
		if strings.EqualFold(record.Name, "WorkDaddyLauncher.exe") && samePath(record.Path, expectedLauncher) {
			matches = append(matches, record)
		}
	}
	if len(matches) > 1 {
		fmt.Fprintln(os.Stderr, "发现多个当前安装目录的 WorkDaddyLauncher 进程,已拒绝批量结束")
		return exitIdentityMismatch
	}
	if len(matches) == 0 {
		return 0
	}
	if elevated && !elevatedSessionAllowed(profile, appDir) {
		fmt.Fprintln(os.Stderr, "installed WorkDaddy launcher is still running; lifecycle stop requires standard user privilege")
		return exitAccessDenied
	}
	_, code, stopErr := terminateExactProcess(int(matches[0].PID), expectedLauncher, "launcher")
	if stopErr != nil {
		fmt.Fprintln(os.Stderr, stopErr)
		return code
	}
	return 0
}

func uniqueRunningWorkBuddyPath(profile string, matches []processRecord) (string, error) {
	paths := make([]string, 0, len(matches))
	for _, match := range matches {
		if strings.TrimSpace(match.Path) == "" {
			return "", fmt.Errorf("PID %d WorkBuddy executable path is unavailable", match.PID)
		}
		found := false
		for _, existing := range paths {
			if samePath(existing, match.Path) {
				found = true
				break
			}
		}
		if !found {
			paths = append(paths, match.Path)
		}
	}
	if len(paths) != 1 {
		return "", fmt.Errorf("发现多个 %s 安装目录中的 WorkBuddy 进程,已拒绝批量结束", productName(profile))
	}
	return paths[0], nil
}

func terminateWorkBuddyTarget(profile string, target workBuddyTarget) int {
	elevated, err := isElevated()
	if err != nil {
		fmt.Fprintln(os.Stderr, "cannot determine helper privilege:", err)
		return exitFailure
	}
	if elevated && !elevatedSessionAllowed(profile, helperAppDir()) {
		fmt.Fprintln(os.Stderr, "WorkBuddy termination requires standard user privilege")
		return exitAccessDenied
	}
	matches, err := matchingWorkBuddyProcessesForTarget(profile, target)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return exitFailure
	}
	if len(matches) == 0 {
		return 0
	}
	expectedPath, err := uniqueRunningWorkBuddyPath(profile, matches)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return exitIdentityMismatch
	}
	for _, match := range matches {
		if !samePath(match.Path, expectedPath) {
			continue
		}
		if _, code, stopErr := terminateExactProcess(int(match.PID), expectedPath, "WorkBuddy"); stopErr != nil {
			fmt.Fprintln(os.Stderr, stopErr)
			return code
		}
	}
	return 0
}

func terminateWorkBuddy(profile string) int {
	return terminateWorkBuddyTarget(profile, configuredTarget(profile))
}

// recoverWatchdogPID uses the process tree only as a recovery proof when the
// user-writable watchdog.pid disappeared during an install/update race. The
// daemon PID comes from the profile lock file and both processes must use the
// exact bundled Node executable. Any ambiguity remains fail-closed.
func recoverWatchdogPID(records []processRecord, expectedNode string, daemonPID int) (int, error) {
	if daemonPID <= 0 {
		return 0, nil
	}
	var daemon *processRecord
	for index := range records {
		record := &records[index]
		if record.PID == uint32(daemonPID) && samePath(record.Path, expectedNode) {
			if daemon != nil {
				return 0, fmt.Errorf("daemon PID %d appears more than once", daemonPID)
			}
			daemon = record
		}
	}
	if daemon == nil || daemon.ParentPID == 0 {
		return 0, nil
	}
	candidates := make([]processRecord, 0, 1)
	for _, record := range records {
		if record.PID == daemon.ParentPID && samePath(record.Path, expectedNode) {
			candidates = append(candidates, record)
		}
	}
	if len(candidates) != 1 {
		if len(candidates) > 1 {
			return 0, fmt.Errorf("daemon PID %d has multiple bundled Node parents", daemonPID)
		}
		return 0, nil
	}
	candidate := candidates[0]
	if strings.TrimSpace(candidate.Path) == "" {
		return 0, nil
	}
	return int(candidate.PID), nil
}

func stopLifecycle(profile, appDir string, elevated bool) int {
	dir, err := dataDir(profile)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return exitFailure
	}
	expectedNode := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")
	watchdogPath := filepath.Join(dir, "watchdog.pid")
	watchdogPID := readPID(watchdogPath)
	watchdogPresent := false
	if _, statErr := os.Stat(watchdogPath); statErr == nil {
		watchdogPresent = true
	} else if !os.IsNotExist(statErr) {
		fmt.Fprintln(os.Stderr, statErr)
		return exitFailure
	}
	if watchdogPresent && watchdogPID <= 0 {
		fmt.Fprintln(os.Stderr, "watchdog.pid 内容无效")
		return exitIdentityMismatch
	}
	daemonPID := readLockPID(filepath.Join(dir, ".daemon.lock"))
	expectedNode = adoptVerifiedLifecycleNode(profile, appDir, daemonPID, watchdogPID)
	if !watchdogPresent && daemonPID > 0 {
		records, enumerateErr := enumerateProcesses()
		if enumerateErr != nil {
			fmt.Fprintln(os.Stderr, enumerateErr)
			return exitFailure
		}
		recovered, recoverErr := recoverWatchdogPID(records, expectedNode, daemonPID)
		if recoverErr != nil {
			fmt.Fprintln(os.Stderr, recoverErr)
			return exitIdentityMismatch
		}
		if recovered > 0 {
			watchdogPID = recovered
			watchdogPresent = true
		} else {
			for _, record := range records {
				if record.PID == uint32(daemonPID) && samePath(record.Path, expectedNode) {
					fmt.Fprintln(os.Stderr, "watchdog.pid 缺失且无法证明当前 daemon 的唯一 watchdog,已拒绝只停止 daemon")
					return exitIdentityMismatch
				}
			}
		}
	}
	pidFiles := []struct {
		path string
		pid  int
	}{
		{watchdogPath, watchdogPID},
		{filepath.Join(dir, ".daemon.lock"), daemonPID},
	}
	seen := map[int]bool{}
	for _, candidate := range pidFiles {
		if candidate.pid <= 0 || seen[candidate.pid] {
			continue
		}
		seen[candidate.pid] = true
		// An elevated helper may clear a stale PID. Active lifecycle work
		// additionally requires saved consent and same-token-security checks.
		active, code, inspectErr := inspectExactProcess(candidate.pid, expectedNode, "node")
		if inspectErr != nil {
			fmt.Fprintln(os.Stderr, inspectErr)
			return code
		}
		if !active {
			continue
		}
		if elevated && !elevatedSessionAllowed(profile, appDir) {
			fmt.Fprintln(os.Stderr, "running WorkDaddy lifecycle requires standard user privilege")
			return exitAccessDenied
		}
		_, code, stopErr := terminateExactNode(candidate.pid, expectedNode)
		if stopErr != nil {
			fmt.Fprintln(os.Stderr, stopErr)
			return code
		}
	}
	for _, candidate := range pidFiles {
		if candidate.path != "" {
			_ = os.Remove(candidate.path)
		}
	}
	if code := stopInstalledLauncher(profile, appDir, elevated); code != 0 {
		return code
	}
	return 0
}

// profileUiPorts returns the fixed UI-port candidates for a profile in
// preference order. They mirror scripts/ui-port.js PROFILE_UI_PORTS.
func profileUiPorts(profile string) []int {
	if profile == profileCodeCN {
		return []int{47834, 17834, 27834, 37834}
	}
	if profile == profileCodeIntl {
		return []int{47835, 17835, 27835, 37835}
	}
	if profile == profileAI {
		return []int{47833, 17833, 27833, 37833}
	}
	return []int{47832, 17832, 27832, 37832}
}

// persistedUiPort reads DATA_DIR/ui-port.json and returns the recorded port
// when it belongs to this profile's candidate list, otherwise 0.
func persistedUiPort(profile, dir string) int {
	data, err := os.ReadFile(filepath.Join(dir, "ui-port.json"))
	if err != nil {
		return 0
	}
	var state struct {
		ProfileID string `json:"profileId"`
		Port      int    `json:"port"`
	}
	if json.Unmarshal(data, &state) != nil || state.ProfileID != profile || state.Port <= 0 {
		return 0
	}
	for _, port := range profileUiPorts(profile) {
		if port == state.Port {
			return port
		}
	}
	return 0
}

// listenerPidOnPort resolves the unique PID listening on a TCP port through
// netstat. It is visible for elevated listeners from a standard process.
func listenerPidOnPort(port int) (int, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	out, err := exec.CommandContext(ctx, "netstat", "-ano").Output()
	if err != nil {
		return 0, fmt.Errorf("netstat failed: %w", err)
	}
	target := fmt.Sprintf(":%d", port)
	pids := map[int]bool{}
	for _, line := range strings.Split(string(out), "\n") {
		if !strings.Contains(line, target) || !strings.Contains(line, "LISTENING") {
			continue
		}
		fields := strings.Fields(line)
		if len(fields) == 0 {
			continue
		}
		pid, parseErr := strconv.Atoi(fields[len(fields)-1])
		if parseErr != nil {
			continue
		}
		pids[pid] = true
	}
	if len(pids) != 1 {
		if len(pids) == 0 {
			return 0, fmt.Errorf("no listener found on port %d", port)
		}
		return 0, fmt.Errorf("multiple listeners found on port %d", port)
	}
	for pid := range pids {
		return pid, nil
	}
	return 0, fmt.Errorf("no listener found on port %d", port)
}

func fetchDaemonStatus(port int, token string) (*daemonStatus, error) {
	client := &http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			Proxy: nil,
		},
	}
	request, err := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/api/status", port), nil)
	if err != nil {
		return nil, err
	}
	request.Header.Set("X-WorkDaddy-Token", token)
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("status endpoint returned %s", response.Status)
	}
	body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
	if err != nil {
		return nil, err
	}
	var status daemonStatus
	if json.Unmarshal(body, &status) != nil {
		return nil, errors.New("status endpoint returned invalid JSON")
	}
	return &status, nil
}

// authenticatedDaemonStatus proves that a listener belongs to this profile's
// daemon. It is used during upgrades when the current lifecycle was started
// from a portable directory different from the installer target directory.
func authenticatedDaemonStatus(profile string) (*daemonStatus, error) {
	dir, err := dataDir(profile)
	if err != nil {
		return nil, err
	}
	tokenData, err := os.ReadFile(filepath.Join(dir, ".api-token"))
	if err != nil {
		return nil, errors.New("当前 profile 缺少本地 API 身份凭证")
	}
	token := strings.TrimSpace(string(tokenData))
	if len(token) != 64 {
		return nil, errors.New("当前 profile 的本地 API 身份凭证无效")
	}
	ports := profileUiPorts(profile)
	if persisted := persistedUiPort(profile, dir); persisted > 0 {
		ports = append([]int{persisted}, ports...)
	}
	expectedDataDir := strings.TrimRight(filepath.Clean(dir), `\/`)
	for _, port := range ports {
		status, fetchErr := fetchDaemonStatus(port, token)
		if fetchErr != nil || !status.OK || status.PID <= 0 ||
			status.Profile.ID != profile || strings.TrimSpace(status.DataDir) == "" ||
			strings.TrimSpace(status.AppDir) == "" {
			continue
		}
		actualDataDir := strings.TrimRight(filepath.Clean(status.DataDir), `\/`)
		if !strings.EqualFold(actualDataDir, expectedDataDir) {
			continue
		}
		listenerPID, listenErr := listenerPidOnPort(port)
		if listenErr != nil || listenerPID != status.PID {
			continue
		}
		return status, nil
	}
	return nil, errors.New("无法通过本地身份凭证确认正在运行的本 profile 生命周期")
}

// adoptVerifiedLifecycleNode allows an installer to stop a same-profile
// portable lifecycle when its app directory differs from the new install
// target. The authenticated daemon status binds the alternate node path to
// the current profile and data directory; without that proof, the original
// target path remains mandatory and the helper fails closed.
func adoptVerifiedLifecycleNode(profile, appDir string, daemonPID, watchdogPID int) string {
	expectedNode := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")
	if daemonPID <= 0 || watchdogPID <= 0 {
		return expectedNode
	}
	actualDaemon := queryProcessPath(uint32(daemonPID))
	actualWatchdog := queryProcessPath(uint32(watchdogPID))
	if actualDaemon == "" || !samePath(actualDaemon, actualWatchdog) || samePath(actualDaemon, expectedNode) {
		return expectedNode
	}
	status, err := authenticatedDaemonStatus(profile)
	if err != nil || status.PID != daemonPID {
		return expectedNode
	}
	statusNode := filepath.Join(status.AppDir, "scripts", "runtime", "node", "node.exe")
	if !samePath(statusNode, actualDaemon) {
		return expectedNode
	}
	return actualDaemon
}

// authenticatedElevatedDaemonStatus proves that the running daemon for this
// profile is the exact current-profile lifecycle using the local API token:
// the per-profile /api/status response must report ok, a positive PID, the
// matching profile id, elevated privilege and the matching data directory,
// and the port listener must be the reported PID itself. This is a
// non-termination capability proof: it never touches the remote process.
func authenticatedElevatedDaemonStatus(profile string) (*daemonStatus, error) {
	dir, err := dataDir(profile)
	if err != nil {
		return nil, err
	}
	tokenData, err := os.ReadFile(filepath.Join(dir, ".api-token"))
	if err != nil {
		return nil, errors.New("当前 profile 缺少本地 API 身份凭证")
	}
	token := strings.TrimSpace(string(tokenData))
	if len(token) != 64 {
		return nil, errors.New("当前 profile 的本地 API 身份凭证无效")
	}
	ports := profileUiPorts(profile)
	if persisted := persistedUiPort(profile, dir); persisted > 0 {
		ports = append([]int{persisted}, ports...)
	}
	expectedDataDir := strings.TrimRight(filepath.Clean(dir), `\/`)
	for _, port := range ports {
		status, fetchErr := fetchDaemonStatus(port, token)
		if fetchErr != nil {
			continue
		}
		if !status.OK || status.PID <= 0 || status.Profile.ID != profile ||
			status.Privilege != "elevated" || strings.TrimSpace(status.DataDir) == "" {
			continue
		}
		actualDataDir := strings.TrimRight(filepath.Clean(status.DataDir), `\/`)
		if !strings.EqualFold(actualDataDir, expectedDataDir) {
			continue
		}
		listenerPid, listenErr := listenerPidOnPort(port)
		if listenErr != nil || listenerPid != status.PID {
			continue
		}
		return status, nil
	}
	return nil, errors.New("无法通过本地身份凭证确认正在运行的本 profile 生命周期")
}

func appendLog(dir string, args ...any) *os.File {
	_ = os.MkdirAll(dir, 0700)
	file, err := os.OpenFile(filepath.Join(dir, "native-launcher.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		return nil
	}
	fmt.Fprintln(file, append([]any{time.Now().Format(time.RFC3339)}, args...)...)
	return file
}

func startupFailureMessage(code int) string {
	var detail string
	switch code {
	case 3:
		detail = "等待 WorkBuddy 调试端口超时。请确认官方更新已完成,并完全退出旧实例后从 WorkDaddy 重试。"
	case exitAccessDenied:
		detail = "无法以当前权限检查或关闭旧 WorkBuddy 实例。请手动退出旧实例,检查 WorkBuddy 的兼容性设置,取消“以管理员身份运行”后重试。"
	case exitIdentityMismatch:
		detail = "无法验证旧进程的路径、账号或会话身份,已停止操作。请手动退出旧实例后重试;若仍失败,请重新选择客户端安装路径。"
	case exitPreserveLifecycle:
		detail = "无法安全确认当前组件的归属,已保留现有进程。请手动退出当前客户端及其 WorkDaddy 后重试。"
	case 14:
		detail = "WorkBuddy 启动进程异常退出。请等待官方更新完成后重试;具体退出码(含十六进制)见日志。"
	case 15:
		detail = "WorkBuddy 安装文件仍在变化或尚不完整。请等待官方更新完成后重试。"
	default:
		detail = "启动失败。请查看日志中的具体原因。"
	}
	return fmt.Sprintf("%s\n\n错误码:%d\n详细信息已写入 native-launcher.log。", detail, code)
}

func runNodeLauncher(appDir, profile string) int {
	dir, err := dataDir(profile)
	if err != nil {
		messageBox(productName(profile), "无法确定 WorkDaddy 数据目录:"+err.Error(), mbOK|mbIconError)
		return exitFailure
	}
	logFile := appendLog(dir, "launch", "profile="+profile, "appDir="+appDir)
	if logFile != nil {
		defer logFile.Close()
	}
	node := filepath.Join(appDir, "scripts", "runtime", "node", "node.exe")
	launcher := filepath.Join(appDir, "scripts", "win-launcher.js")
	if _, err := os.Stat(node); err != nil {
		messageBox(productName(profile), "安装文件不完整:找不到内置 Node.js。请重新安装。", mbOK|mbIconError)
		return exitFailure
	}
	if _, err := os.Stat(launcher); err != nil {
		messageBox(productName(profile), "安装文件不完整:找不到启动脚本。请重新安装。", mbOK|mbIconError)
		return exitFailure
	}

	for {
		cmd := exec.Command(node, launcher)
		cmd.Dir = filepath.Join(appDir, "scripts")
		cmd.Env = append(os.Environ(), "WBSWITCH_NATIVE_LAUNCHER=1", "WBSWITCH_PROFILE="+profile, "WBSWITCH_APP_DIR="+appDir)
		cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
		if logFile != nil {
			cmd.Stdout = io.MultiWriter(logFile)
			cmd.Stderr = io.MultiWriter(logFile)
		}
		err := cmd.Run()
		code := 0
		if err != nil {
			var exitErr *exec.ExitError
			if errors.As(err, &exitErr) {
				code = exitErr.ExitCode()
			} else {
				code = exitFailure
			}
		}
		if code == exitWorkBuddyRunning {
			choice := messageBox(productName(profile), "WorkBuddy 已经打开,但没有启用 WorkDaddy 所需的调试端口。\n\n请完全退出 WorkBuddy,然后点击“重试”。", mbRetryCancel|mbIconWarning)
			if choice == idRetry {
				continue
			}
			return 0
		}
		if code != 0 {
			messageBox(productName(profile), startupFailureMessage(code), mbOK|mbIconError)
		}
		return code
	}
}

func helperMain(appDir, profile string) (bool, int) {
	if hasArgument("--desktop-token-status") {
		token, err := openDesktopToken(tokenQuery)
		if err != nil {
			return true, exitFailure
		}
		defer syscall.CloseHandle(token)
		elevated, err := tokenIsElevated(token)
		if err != nil {
			return true, exitFailure
		}
		if !elevated {
			return true, 0
		}
		if desktopSessionSupportsElevated() {
			return true, exitElevated
		}
		return true, exitAccessDenied
	}
	if hasArgument("--accept-elevated-session") {
		if err := saveElevatedConsent(profile, helperAppDir()); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return true, exitAccessDenied
		}
		return true, 0
	}
	if hasArgument("--check-elevated-session") {
		if elevatedSessionAllowed(profile, helperAppDir()) {
			return true, 0
		}
		return true, exitAccessDenied
	}
	if hasArgument("--launch-context") {
		elevated, err := isElevated()
		if err != nil {
			return true, exitFailure
		}
		if elevated && !elevatedSessionAllowed(profile, helperAppDir()) {
			return true, exitElevated
		}
		privilege := "standard"
		if elevated {
			privilege = "elevated"
		}
		_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"profile": profile, "privilege": privilege})
		return true, 0
	}

	if hasArgument("--target-info") {
		target := configuredTarget(profile)
		output := argumentValue("--output")
		if target.Binary == "" || output == "" || !filepath.IsAbs(output) || strings.ContainsAny(target.Binary, "\r\n") {
			return true, exitFailure
		}
		version := strings.TrimSpace(target.Version)
		if version == "" {
			version = fileVersion(target.Binary)
		}
		clientType := strings.TrimSpace(target.ClientType)
		if strings.ContainsAny(version, "\r\n") || strings.ContainsAny(clientType, "\r\n") {
			return true, exitFailure
		}
		if os.WriteFile(output, []byte(target.Binary+"\r\n"+version+"\r\n"+clientType+"\r\n"), 0600) != nil {
			return true, exitFailure
		}
		return true, 0
	}
	if hasArgument("--file-version") {
		binary := argumentValue("--binary")
		if binary == "" || !filepath.IsAbs(binary) {
			return true, exitUsage
		}
		version := fileVersion(binary)
		if version == "" {
			return true, exitFailure
		}
		fmt.Fprintln(os.Stdout, version)
		return true, 0
	}
	if hasArgument("--check-workbuddy") {
		target := configuredTarget(profile)
		if binary := argumentValue("--binary"); binary != "" {
			target = targetForBinary(profile, binary)
			if target.Binary == "" {
				return true, exitUsage
			}
		}
		matches, err := matchingWorkBuddyProcessesForTarget(profile, target)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return true, exitFailure
		}
		if len(matches) > 0 {
			return true, exitWorkBuddyRunning
		}
		return true, 0
	}
	if hasArgument("--list-workbuddy") {
		matches, err := matchingWorkBuddyProcesses(profile)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return true, exitFailure
		}
		_ = json.NewEncoder(os.Stdout).Encode(matches)
		return true, 0
	}
	if hasArgument("--terminate-workbuddy") {
		if binary := argumentValue("--binary"); binary != "" {
			target := targetForBinary(profile, binary)
			if target.Binary == "" {
				return true, exitUsage
			}
			return true, terminateWorkBuddyTarget(profile, target)
		}
		return true, terminateWorkBuddy(profile)
	}
	if hasArgument("--stop-lifecycle") {
		elevated, err := isElevated()
		if err != nil {
			fmt.Fprintln(os.Stderr, "cannot determine helper privilege:", err)
			return true, exitFailure
		}
		targetApp := argumentValue("--app-dir")
		if targetApp == "" {
			targetApp = appDir
		}
		code := stopLifecycle(profile, targetApp, elevated)
		if code == exitAccessDenied && !elevated {
			// A standard helper cannot terminate an elevated lifecycle. Before
			// failing closed, prove with the per-profile API token that the
			// running daemon is this exact profile's lifecycle; the installer
			// then preserves it and continues instead of blocking upgrades.
			if status, verifyErr := authenticatedElevatedDaemonStatus(profile); verifyErr == nil {
				fmt.Fprintln(os.Stderr, "verified elevated lifecycle preserved pid="+strconv.Itoa(status.PID))
				return true, exitPreserveLifecycle
			} else {
				fmt.Fprintln(os.Stderr, "elevated lifecycle verification failed:", verifyErr)
			}
		}
		return true, code
	}
	if hasArgument("--self-test") {
		elevated, err := isElevated()
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return true, exitFailure
		}
		_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"profile": profile, "appDir": appDir, "elevated": elevated})
		return true, 0
	}
	return false, 0
}

func main() {
	appDir, err := executableDir()
	if err != nil {
		os.Exit(exitFailure)
	}
	profile := readProfile(appDir)
	if handled, code := helperMain(appDir, profile); handled {
		os.Exit(code)
	}

	elevated, err := isElevated()
	if err != nil {
		messageBox(productName(profile), "无法确认当前 Windows 权限,已停止启动。", mbOK|mbIconError)
		os.Exit(exitFailure)
	}
	if elevated {
		var relaunchErr error
		if !hasArgument("--desktop-shell-relaunch") {
			relaunchErr = relaunchWithDesktopToken(appDir)
			if relaunchErr == nil {
				os.Exit(0)
			}
		} else {
			relaunchErr = errDesktopTokenElevated
		}
		allowed := errors.Is(relaunchErr, errDesktopTokenElevated) && elevatedSessionAllowed(profile, appDir)
		if dir, dirErr := dataDir(profile); dirErr == nil {
			if file := appendLog(dir, "desktop relaunch:", relaunchErr, "elevatedConsent="+strconv.FormatBool(allowed)); file != nil {
				file.Close()
			}
		}
		if !allowed {
			messageBox(productName(profile), "无法自动切换到普通用户权限。\n\n请重新运行新版安装程序;若检测到桌面无法降权,可阅读风险提示并选择兼容安装。普通电脑请确认 UAC 已开启,然后直接双击快捷方式。", mbOK|mbIconWarning)
			os.Exit(exitElevated)
		}
	}

	mutex, alreadyRunning, err := acquireMutex(profile)
	if err != nil {
		messageBox(productName(profile), "无法创建启动锁:"+err.Error(), mbOK|mbIconError)
		os.Exit(exitFailure)
	}
	defer syscall.CloseHandle(mutex)
	if alreadyRunning {
		os.Exit(0)
	}
	os.Exit(runNodeLauncher(appDir, profile))
}