importAppKitimportFoundationimportServiceManagement/// 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.enumLoginItem {staticlet agentLabel = "com.decemberfm.cotton.mac.agent"staticlet agentPlist = "\(agentLabel).plist"/// Whether this copy of the app is installed where it may register itself.staticvar installed: Bool {let bundle = Bundle.mainreturn bundle.bundleIdentifier?.isEmpty == false && bundle.bundlePath.hasSuffix(".app") && bundle.bundlePath.hasPrefix("/Applications/") }/// Whether launchd started this process as the agent.staticvar 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. @MainActorstaticfunc registerIfInstalled() -> Bool {guard installed else { returnfalse }let mainApp = SMAppService.mainAppif mainApp.status == .enabled {try? mainApp.unregister() }let agent = SMAppService.agent(plistName: agentPlist)if agent.status != .enabled {do {try agent.register() } catch {returnfalse } }guard agent.status == .enabled, !startedByAgent else { returnfalse }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.privatestaticfunc handOver() -> Bool {let process = Process() process.executableURL = URL(fileURLWithPath: "/bin/launchctl") process.arguments = ["kickstart", "gui/\(getuid())/\(agentLabel)"] process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevicedo {try process.run() } catch {returnfalse } process.waitUntilExit()return process.terminationStatus == 0 }}