import Foundation struct BrowserLaunchBoundary: Codable, Sendable { let bundleID: String let applicationURL: URL let preexistingPIDs: [Int32] let requestedAt: Date } struct BrowserProfileCleanupReceipt: Codable, Sendable { let profiles: [URL] let launches: [BrowserLaunchBoundary] let unclaimedApplications: [RealAppProcessIdentity] } enum BrowserProfileCleanup { static func unclaimedApplications( _ current: [RealAppProcessIdentity], launches: [BrowserLaunchBoundary], claimed: [RealAppLaunchReceipt] ) -> [RealAppProcessIdentity] { current.filter { application in guard application.pid > 0, !application.isTerminated else { return false } let boundaries = launches.filter { application.bundleID == $0.bundleID && (application.bundleURL == nil || samePath(application.bundleURL, $0.applicationURL)) } guard !boundaries.isEmpty else { return false } guard application.bundleURL != nil else { return true } if claimed.contains(where: { receipt in receipt.pid == application.pid && !receipt.isTerminated && !receipt.preexistingPIDs.contains(application.pid) && receipt.bundleID == receipt.app.bundleID && receipt.bundleID == application.bundleID && samePath(application.bundleURL, receipt.applicationURL) && samePath(application.bundleURL, receipt.bundleURL) && receipt.launchDate != nil && receipt.launchDate == application.launchDate }) { return false } return boundaries.contains { boundary in !boundary.preexistingPIDs.contains(application.pid) || application.launchDate.map { $0 > boundary.requestedAt } != false } } } private static func samePath(_ left: URL?, _ right: URL?) -> Bool { guard let left, let right, left.isFileURL, right.isFileURL else { return false } return left.resolvingSymlinksInPath().standardizedFileURL.path == right.resolvingSymlinksInPath().standardizedFileURL.path } }