import AppKit import Foundation import ServiceManagement /// Cotton opens at login and again after a crash: a launch agent /// (`Contents/Library/LaunchAgents/com.decemberfm.cotton.mac.agent.plist`, /// `KeepAlive.SuccessfulExit = false`) registered through `SMAppService.agent`. /// A person's own Quit ends with status 0 and launchd leaves it quit until the /// next login or until the person opens Cotton again. /// /// Registered only from a packaged app installed in /Applications, so a build /// directory never becomes the person's login item. /// /// On 22 Nov 2026 the installed app was quit from its panel and nothing brought /// it back for an hour (the Mac import report): the agent is the way back /// after a crash or kill, and the panel says once what Quit does. enum LoginItem { static let agentLabel = "com.decemberfm.cotton.mac.agent" static let agentPlist = "\(agentLabel).plist" /// Whether this copy of the app is installed where it may register itself. static var installed: Bool { let bundle = Bundle.main return bundle.bundleIdentifier?.isEmpty == false && bundle.bundlePath.hasSuffix(".app") && bundle.bundlePath.hasPrefix("/Applications/") } /// Whether launchd started this process as the agent. static var startedByAgent: Bool { ProcessInfo.processInfo.environment["XPC_SERVICE_NAME"] == agentLabel } /// Registers the agent (and retires the plain login item of builds before /// it). Answers `true` when this process should end because launchd now runs /// Cotton as the agent: opened by hand from Finder or Spotlight, or relaunched /// by an update, the app hands itself to the agent so a crash later brings it /// back. @MainActor static func registerIfInstalled() -> Bool { guard installed else { return false } let mainApp = SMAppService.mainApp if mainApp.status == .enabled { try? mainApp.unregister() } let agent = SMAppService.agent(plistName: agentPlist) if agent.status != .enabled { do { try agent.register() } catch { return false } } guard agent.status == .enabled, !startedByAgent else { return false } return handOver() } /// `launchctl kickstart` the agent; `true` once launchd runs it, so this /// copy may end. A failure keeps this copy running: never no Cotton. private static func handOver() -> Bool { let process = Process() process.executableURL = URL(fileURLWithPath: "/bin/launchctl") process.arguments = ["kickstart", "gui/\(getuid())/\(agentLabel)"] process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice do { try process.run() } catch { return false } process.waitUntilExit() return process.terminationStatus == 0 } }