import AppKit import Darwin import Foundation import RealityDriverSupport enum RealApp: String, CaseIterable, Codable, Sendable { case textEdit, finder, safari, firefox, chromium, vscode, terminal, notes, calculator, systemSettings, quickTime, fixture var bundleID: String { switch self { case .textEdit: "com.apple.TextEdit" case .finder: "com.apple.finder" case .safari: "com.apple.Safari" case .firefox: "org.mozilla.firefox" case .chromium: "org.chromium.Chromium" case .vscode: "com.microsoft.VSCode" case .terminal: "com.apple.Terminal" case .notes: "com.apple.Notes" case .calculator: "com.apple.calculator" case .systemSettings: "com.apple.systempreferences" case .quickTime: "com.apple.QuickTimePlayerX" case .fixture: "dev.vinnymac.parcel.reality-fixture" } } var tokenMatched: Bool { [.textEdit, .finder, .safari, .firefox, .chromium, .vscode, .terminal, .fixture].contains(self) } var requiresExclusiveProcess: Bool { self == .safari || !tokenMatched } } struct OwnedWindow: Codable, Sendable { let app: RealApp let pid: Int32 let id: UInt32 } struct RealAppLaunchReceipt: Codable, Sendable { let app: RealApp let applicationURL: URL let preexistingPIDs: [Int32] let pid: Int32 let bundleID: String? let bundleURL: URL? let isTerminated: Bool let launchDate: Date? let discardStrategy: RealAppDiscardStrategy init( app: RealApp, applicationURL: URL, preexistingPIDs: [Int32], pid: Int32, bundleID: String?, bundleURL: URL?, isTerminated: Bool, launchDate: Date? = nil ) { self.app = app self.applicationURL = applicationURL self.preexistingPIDs = preexistingPIDs self.pid = pid self.bundleID = bundleID self.bundleURL = bundleURL self.isTerminated = isTerminated self.launchDate = launchDate discardStrategy = app == .finder ? .closeOwnedFinderWindow : .forceTerminateWithoutSaving } func validateDiscardIdentity( pid: Int32, bundleID: String?, bundleURL: URL?, launchDate: Date?, isTerminated: Bool ) throws { guard app != .finder, discardStrategy == .forceTerminateWithoutSaving, !isTerminated else { throw RealityError("Refusing to discard a terminated launch or a shared application") } try validateIdentity(pid: pid, bundleID: bundleID, bundleURL: bundleURL, launchDate: launchDate) } func validateIdentity(pid: Int32, bundleID: String?, bundleURL: URL?, launchDate: Date?) throws { _ = try validatedPID() guard pid == self.pid, let launchDate, launchDate == self.launchDate, launchDate.timeIntervalSinceReferenceDate.isFinite, bundleID == self.bundleID, let bundleURL, bundleURL.isFileURL, bundleURL.resolvingSymlinksInPath().standardizedFileURL == applicationURL.resolvingSymlinksInPath().standardizedFileURL else { throw RealityError("Live process identity differs from its owned launch receipt") } } func validatedPID() throws -> Int32 { guard pid > 0, !isTerminated, !preexistingPIDs.contains(pid) else { throw RealityError("\(app.rawValue) launch returned no live fresh process; no unowned process was claimed") } guard bundleID == app.bundleID, let bundleURL, applicationURL.isFileURL, bundleURL.isFileURL, bundleURL.resolvingSymlinksInPath().standardizedFileURL == applicationURL.resolvingSymlinksInPath().standardizedFileURL else { throw RealityError( "\(app.rawValue) launch returned a different application; no unowned process was claimed") } return pid } } enum RealAppDiscardStrategy: String, Codable, Sendable { case forceTerminateWithoutSaving case closeOwnedFinderWindow } struct RealAppProcessIdentity: Codable, Sendable { let pid: Int32 let bundleID: String? let bundleURL: URL? let launchDate: Date? let isTerminated: Bool @MainActor init(_ application: NSRunningApplication) { pid = application.processIdentifier bundleID = application.bundleIdentifier bundleURL = application.bundleURL launchDate = application.launchDate isTerminated = application.isTerminated } init(pid: Int32, bundleID: String?, bundleURL: URL?, launchDate: Date?, isTerminated: Bool) { self.pid = pid self.bundleID = bundleID self.bundleURL = bundleURL self.launchDate = launchDate self.isTerminated = isTerminated } func validate(against launch: RealAppLaunchReceipt) throws { do { try launch.validateIdentity(pid: pid, bundleID: bundleID, bundleURL: bundleURL, launchDate: launchDate) } catch { throw RealityError("Safety stop: refusing changed owned launch identity: \(error)") } } func validateAvailableExitMetadata(against launch: RealAppLaunchReceipt) throws { var changed: [String] = [] if pid != launch.pid { changed.append("pid") } if let bundleID, bundleID != launch.bundleID { changed.append("bundleID") } if let launchDate, launchDate != launch.launchDate || !launchDate.timeIntervalSinceReferenceDate.isFinite { changed.append("launchDate") } if let bundleURL, !bundleURL.isFileURL || bundleURL.resolvingSymlinksInPath().standardizedFileURL != launch.applicationURL.resolvingSymlinksInPath().standardizedFileURL { changed.append("bundleURL") } guard changed.isEmpty else { throw RealityError("Safety stop: owned exit metadata changed: \(changed.joined(separator: ", "))") } } } enum RealAppProcessPresence: Codable, Equatable, Sendable { case present, absent, unavailable(Int32) static func read(pid: Int32) -> Self { let status = kill(pid, 0) let code = errno if status == 0 || code == EPERM { return .present } return code == ESRCH ? .absent : .unavailable(code) } } enum RealAppLaunchReadback { enum FocusResult: Equatable { case verified, retryLookup } static func focus( window: OwnedWindow, launch: RealAppLaunchReceipt, retained: RealAppProcessIdentity, current: RealAppProcessIdentity?, presence: RealAppProcessPresence, windows: [RealWindow], elapsed: Duration = .zero ) throws -> FocusResult { guard window.pid == launch.pid, window.app == launch.app else { throw RealityError("Safety stop: focus target differs from its owned launch receipt") } try retained.validate(against: launch) if let current { try current.validate(against: launch) } guard !retained.isTerminated, current?.isTerminated != true else { throw RealityError("Safety stop: owned focus launch terminated before input") } switch presence { case .present: break case .absent: throw RealityError("Safety stop: owned focus PID disappeared before input") case .unavailable(let code): throw RealityError("Safety stop: owned focus PID liveness is unavailable: errno \(code)") } let matchingID = windows.filter { $0.id == window.id } guard matchingID.count == 1, matchingID[0].pid == window.pid else { throw RealityError("Safety stop: owned focus CG identity disappeared or changed before input") } if current != nil { return .verified } guard elapsed < .milliseconds(500) else { throw RealityError("Safety stop: owned launch identity lookup did not revalidate within 500 ms") } // Corroboration permits waiting, never using the retained handle in place of a fresh identity. return .retryLookup } static func expectedExit( launch: RealAppLaunchReceipt, closeRequested: Bool, retained: RealAppProcessIdentity, current: RealAppProcessIdentity?, presence: RealAppProcessPresence, windows: [RealWindow], cleanup: Bool = false ) throws -> Bool { _ = try launch.validatedPID() guard retained.pid == launch.pid, launch.app != .finder, launch.discardStrategy == .forceTerminateWithoutSaving, let launchDate = launch.launchDate, launchDate.timeIntervalSinceReferenceDate.isFinite else { throw RealityError("Safety stop: process exit lacks its exact isolated launch identity") } switch presence { case .present: if closeRequested || cleanup { // Exit metadata can disappear before the termination flag updates; this path only waits. try retained.validateAvailableExitMetadata(against: launch) if let current { try current.validateAvailableExitMetadata(against: launch) } return false } try retained.validate(against: launch) if let current { try current.validate(against: launch) } return false case .absent: guard closeRequested || cleanup else { throw RealityError("Safety stop: owned process disappearance lacks an explicit isolated close request") } // Terminated application handles can lose metadata. No live PID remains to validate or act on. return retained.isTerminated && current == nil && !windows.contains { $0.pid == launch.pid } case .unavailable(let code): throw RealityError("Safety stop: owned close PID liveness is unavailable: errno \(code)") } } static func ownedChildExit( launch: RealAppLaunchReceipt, childPID: Int32, childRunning: Bool, presence: RealAppProcessPresence, windows: [RealWindow] ) throws -> Bool { _ = try launch.validatedPID() guard launch.app == .fixture, launch.pid == childPID, launch.discardStrategy == .forceTerminateWithoutSaving else { throw RealityError("Safety stop: fixture exit lacks its exact owned child process") } switch presence { case .present: guard childRunning else { throw RealityError("Safety stop: exited fixture child PID is still present or reused") } return false case .absent: return !childRunning && !windows.contains { $0.pid == childPID } case .unavailable(let code): throw RealityError("Safety stop: fixture child liveness is unavailable: errno \(code)") } } } struct RealAppNativeCloseRequest: Codable, Sendable { let launch: RealAppLaunchReceipt let window: OwnedWindow let input: DriverInputState let lastOwnedWindow: Bool private(set) var acknowledged = false init(launch: RealAppLaunchReceipt, window: OwnedWindow, owned: [OwnedWindow], input: DriverInputState) throws { try launch.validateIdentity( pid: window.pid, bundleID: launch.bundleID, bundleURL: launch.bundleURL, launchDate: launch.launchDate) guard launch.app != .finder, launch.app == window.app, launch.pid == window.pid, owned.filter({ $0.id == window.id }).count == 1, owned.contains(where: { $0.id == window.id && $0.pid == window.pid && $0.app == window.app }) else { throw RealityError("Safety stop: native close lacks an exact isolated owned launch/window") } try input.requireNeutralBaseline() self.launch = launch self.window = window self.input = input lastOwnedWindow = owned.filter { $0.pid == window.pid }.count == 1 } mutating func acknowledge() { acknowledged = true } var authorizesProcessExit: Bool { acknowledged && lastOwnedWindow } } private struct RealAppFocusIdentityObservation: Codable { let elapsedSeconds: Double let retained: RealAppProcessIdentity let current: RealAppProcessIdentity? let presence: RealAppProcessPresence let windows: [RealWindow] } private struct RealAppFocusIdentityReceipt: Codable { let launch: RealAppLaunchReceipt let window: OwnedWindow var observations: [RealAppFocusIdentityObservation] = [] var failure: String? } private struct RealAppFocusActivationObservation: Codable { let activationAccepted: Bool let foregroundPID: Int32? let windows: [RealWindow] } struct RealAppOwnedArtifact: Codable, Equatable, Sendable { enum Kind: String, Codable, Sendable { case document, finderFolder, browserProfile, editorProfile, editorExtensions, fixtureBundle } let url: URL let kind: Kind func cleanupURL(in directory: URL) throws -> URL { guard url.isFileURL, directory.isFileURL else { throw RealityError("Owned artifact cleanup requires local file paths") } let root = directory.resolvingSymlinksInPath().standardizedFileURL.path let path = url.standardizedFileURL guard path.path != root, path.deletingLastPathComponent().resolvingSymlinksInPath().standardizedFileURL.path == root, path.resolvingSymlinksInPath().standardizedFileURL.deletingLastPathComponent().path == root else { throw RealityError("Refusing to remove an owned artifact outside its exact scenario directory: \(url.path)") } if kind == .document, !["txt", "html", "command", "mov"].contains(path.pathExtension) { throw RealityError("Refusing to remove a non-document artifact as a document: \(url.path)") } if kind == .fixtureBundle, path.pathExtension != "app" { throw RealityError("Refusing to remove a fixture artifact without its bundle extension") } if [.browserProfile, .editorProfile, .editorExtensions, .fixtureBundle].contains(kind) { let name = kind == .fixtureBundle ? path.deletingPathExtension().lastPathComponent : path.lastPathComponent let prefix: String switch kind { case .fixtureBundle: prefix = "fixture-" case .editorProfile: prefix = "editor-profile-" case .editorExtensions: prefix = "editor-extensions-" default: prefix = "browser-profile-" } guard name.hasPrefix(prefix), UUID(uuidString: String(name.dropFirst(prefix.count))) != nil else { throw RealityError("Refusing to remove a directory without its isolated artifact identity") } } return path } static func cleanupURLs(_ artifacts: [Self], in directory: URL) throws -> [URL] { var seen: Set = [] return try artifacts.compactMap { artifact in let url = try artifact.cleanupURL(in: directory) return seen.insert(url).inserted ? url : nil } } } enum RealAppCleanupSelection { static func remainingWindows( _ rows: [RealWindow], processIDs: Set, finderWindows: [OwnedWindow] ) -> [RealWindow] { rows.filter { row in processIDs.contains(row.pid) || finderWindows.contains { $0.app == .finder && $0.pid == row.pid && $0.id == row.id } } } } @MainActor private struct OwnedRealAppProcess { let application: NSRunningApplication let receipt: RealAppLaunchReceipt } private struct RealAppDiscardReceipt: Codable { let launch: RealAppLaunchReceipt var startedAt = Date() var requestAt: Date? var finishedAt: Date? var requestAccepted: Bool? var closeRequested = false var processGone = false var observations: [Observation] = [] var identities: [RealAppProcessExitObservation] = [] var actions: [RealAppDiscardProgress.Action] = [] var failure: String? } private struct RealAppProcessExitObservation: Codable { var observedAt = Date() let retained: RealAppProcessIdentity let current: RealAppProcessIdentity? let presence: RealAppProcessPresence let childRunning: Bool? } private struct RealAppCleanupReceipt: Codable { let remainingPIDs: [Int32] let remainingWindows: [RealWindow] let removedArtifacts: [URL] let failures: [String] } @MainActor final class RealApps { let directory: URL let token: String let driver: RealityDriver? private(set) var windows: [OwnedWindow] = [] private var launched: [OwnedRealAppProcess] = [] private var expectedProcessExits: Set = [] private var nativeCloseRequests: [UInt32: RealAppNativeCloseRequest] = [:] private var artifacts: [RealAppOwnedArtifact] = [] private var unresolvedFinderDocuments: [URL] = [] private let artifactDirectory: URL private var created: [OwnedWindow] = [] private var nextDocument = 0 private var documents: [UInt32: URL] = [:] private var identificationWarnings: [String] = [] private var fixtures: [RealityFixture] = [] private var applicationChildren: [RealityApplicationChild] = [] private var editorProfiles: [RealityEditorProfile] = [] private var browserLaunchBoundaries: [BrowserLaunchBoundary] = [] func fixture(for window: OwnedWindow) throws -> RealityFixture { try requireOwned(window) guard window.app == .fixture, let fixture = fixtures.first(where: { $0.process.processIdentifier == window.pid }) else { throw RealityError("No owned fixture control channel for this window") } return fixture } var ownedProcessIDs: Set { Set(launched.map(\.receipt.pid)) } func validatedLaunchReceipt(for window: OwnedWindow) throws -> RealAppLaunchReceipt { try requireOwned(window) guard let process = launched.first(where: { $0.receipt.pid == window.pid && $0.receipt.app == window.app }) else { throw RealityError("Safety stop: owned launch receipt is missing for PID \(window.pid)") } guard let current = NSRunningApplication(processIdentifier: window.pid) else { if expectedProcessExits.contains(window.pid), try processIsGone(process) { throw RealityError( "Explicit owned close exited PID \(window.pid); live launch identity is no longer available") } throw RealityError("Safety stop: live launch identity is unavailable for owned PID \(window.pid)") } do { try process.receipt.validateDiscardIdentity( pid: current.processIdentifier, bundleID: current.bundleIdentifier, bundleURL: current.bundleURL, launchDate: current.launchDate, isTerminated: current.isTerminated) } catch { throw RealityError("Safety stop: refusing changed owned launch identity: \(error)") } return process.receipt } init(directory: URL, token: String, driver: RealityDriver? = nil) { self.directory = directory self.token = token self.driver = driver artifactDirectory = directory.resolvingSymlinksInPath().standardizedFileURL } static func freshLaunchConfiguration() -> NSWorkspace.OpenConfiguration { let configuration = NSWorkspace.OpenConfiguration() configuration.createsNewApplicationInstance = true configuration.promptsUserIfNeeded = false configuration.addsToRecentItems = false configuration.arguments = ["-ApplePersistenceIgnoreState", "YES"] return configuration } func open(_ kind: RealApp) async throws -> OwnedWindow { try await open(kind, existingDocument: nil) } func openSimultaneousFixtures(count: Int) async throws -> [OwnedWindow] { try TabViewConsoleSession.requireUnlockedConsole() guard driver != nil, count > 0 else { throw RealityError("Fixture launches require a driver and count") } let before = try FrameOracle.read() let preexisting = Set(NSWorkspace.shared.runningApplications.map(\.processIdentifier)) .union(before.map(\.pid)).union(ownedProcessIDs) var pending: [(RealityFixture, URL)] = [] for _ in 0.. [String] { _ = try RealAppOwnedArtifact(url: folder, kind: .finderFolder).cleanupURL(in: directory) guard folder.resolvingSymlinksInPath().standardizedFileURL.path == folder.standardizedFileURL.path else { throw RealityError("Refusing to populate a redirected Finder folder") } func contents() throws -> [String] { // Finder may write its own metadata as soon as the owned folder opens; leave it untouched. try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0 != ".DS_Store" }.sorted() } guard try contents().isEmpty else { throw RealityError("Refusing to populate a nonempty Finder folder") } let expected = (1...12).map { "Owned item \($0).txt" }.sorted() for index in 1...12 { let file = folder.appendingPathComponent("Owned item \(index).txt") try Data("Parcel reality owned Finder item \(index)\n".utf8).write(to: file, options: .withoutOverwriting) } let items = try contents() guard items == expected else { throw RealityError("Owned Finder population readback was incomplete") } return items } func reopen(_ window: OwnedWindow) async throws -> OwnedWindow { guard created.contains(where: { $0.id == window.id && $0.pid == window.pid }), !windows.contains(where: { $0.id == window.id }), let document = documents[window.id] else { throw RealityError("Refusing to reopen a document not created and closed by this run") } return try await open(window.app, existingDocument: document) } private func open(_ kind: RealApp, existingDocument: URL?) async throws -> OwnedWindow { try TabViewConsoleSession.requireUnlockedConsole() guard driver != nil else { throw RealityError("A signed reality driver is required") } let before = try FrameOracle.read() let existing = NSRunningApplication.runningApplications(withBundleIdentifier: kind.bundleID) let preexistingPIDs = Set(NSWorkspace.shared.runningApplications.map(\.processIdentifier)) .union(existing.map(\.processIdentifier)).union(before.map(\.pid)).union(ownedProcessIDs) let document: URL? if let existingDocument { document = existingDocument } else { document = try await makeDocument(kind) } let pid: Int32 if kind == .finder { guard let finder = existing.first, let document else { throw RealityError("Finder must be running; the harness never starts or quits it") } unresolvedFinderDocuments.append(document) let result = try await RealityProcess.run("/usr/bin/open", [document.path], directory: directory) guard result.status == 0 else { throw RealityError("Opening owned Finder folder failed: \(result.errors)") } pid = finder.processIdentifier } else { if kind.requiresExclusiveProcess, !existing.isEmpty { throw RealitySkip("\(kind.rawValue) is already running; shared native state cannot be isolated safely") } let url: URL if kind == .fixture { url = try makeFixtureBundle() } else { guard let installed = NSWorkspace.shared.urlForApplication(withBundleIdentifier: kind.bundleID) else { throw RealitySkip("\(kind.rawValue) is not installed") } url = installed } let configuration = Self.freshLaunchConfiguration() if [.firefox, .chromium, .vscode].contains(kind) { let arguments = try launchArguments(kind, application: url, document: document) guard let separator = arguments.firstIndex(of: "--args") else { throw RealityError("Profile-isolated launch omitted its arguments") } configuration.arguments = Array(arguments.dropFirst(separator + 1)) } // Only this request's returned process proves ownership; process-list deltas can be stale or unrelated. if kind == .firefox || kind == .chromium { browserLaunchBoundaries.append( BrowserLaunchBoundary( bundleID: kind.bundleID, applicationURL: url, preexistingPIDs: preexistingPIDs.sorted(), requestedAt: Date())) } let app: NSRunningApplication let documents = Self.documentsForLaunch(document, arguments: configuration.arguments) if kind == .fixture { let fixture = try RealityFixture( executable: url.appendingPathComponent("Contents/MacOS/FixtureApp"), token: token) fixtures.append(fixture) try await fixture.ready() guard let running = NSRunningApplication(processIdentifier: fixture.process.processIdentifier) else { throw RealityError("Owned fixture did not register its application identity") } app = running } else if kind == .vscode { let child = try RealityApplicationChild( applicationURL: url, bundleID: kind.bundleID, arguments: configuration.arguments, directory: directory) applicationChildren.append(child) app = try await child.launch() } else if !documents.isEmpty { app = try await NSWorkspace.shared.open( documents, withApplicationAt: url, configuration: configuration) } else { app = try await NSWorkspace.shared.openApplication(at: url, configuration: configuration) } let receipt = RealAppLaunchReceipt( app: kind, applicationURL: url, preexistingPIDs: preexistingPIDs.sorted(), pid: app.processIdentifier, bundleID: app.bundleIdentifier, bundleURL: app.bundleURL, isTerminated: app.isTerminated, launchDate: app.launchDate) let receiptURL = directory.appendingPathComponent("launch-identity-\(UUID().uuidString).json") do { pid = try receipt.validatedPID() } catch { try encodeJSON(receipt, to: receiptURL) throw error } launched.append(OwnedRealAppProcess(application: app, receipt: receipt)) try encodeJSON(receipt, to: receiptURL) try encodeJSON( launched.map(\.receipt.pid), to: directory.appendingPathComponent("launched-pids.json")) } return try await registerFreshWindow(kind, pid: pid, document: document, before: before) } func claimReopenedNotes( _ launch: SetupLaunchReceipt, applicationURL: URL, preexistingPIDs: Set, requestedAt: Date, respondedAt: Date, before: [RealWindow] ) async throws -> OwnedWindow { try TabViewConsoleSession.requireUnlockedConsole() guard let current = NSRunningApplication(processIdentifier: launch.pid) else { throw RealityError("Safety stop: setup launch receipt has no live Notes process; nothing was claimed") } let receipt: RealAppLaunchReceipt do { receipt = try launch.notesReceipt( applicationURL: applicationURL, preexistingPIDs: preexistingPIDs.union(ownedProcessIDs), requestedAt: requestedAt, respondedAt: respondedAt, liveLaunchDate: current.launchDate) try receipt.validateDiscardIdentity( pid: current.processIdentifier, bundleID: current.bundleIdentifier, bundleURL: current.bundleURL, launchDate: current.launchDate, isTerminated: current.isTerminated) let notes = NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.notes.bundleID) guard notes.count == 1, notes.first?.processIdentifier == receipt.pid else { throw RealityError("Setup reopen has ambiguous Notes processes") } } catch { throw RealityError("Safety stop: refusing setup process ownership: \(error)") } launched.append(OwnedRealAppProcess(application: current, receipt: receipt)) try encodeJSON(receipt, to: directory.appendingPathComponent("setup-reopened-notes-identity.json")) try encodeJSON(launched.map(\.receipt.pid), to: directory.appendingPathComponent("launched-pids.json")) return try await registerFreshWindow(.notes, pid: receipt.pid, document: nil, before: before) } private func registerFreshWindow( _ kind: RealApp, pid: Int32, document: URL?, before: [RealWindow] ) async throws -> OwnedWindow { guard let driver else { throw RealityError("A signed reality driver is required") } let oldIDs = Set(before.map(\.id)) var samples: [Observation] = [] var selectedID: UInt32? var roleSelections: [[UInt32]] = [] do { let result = try await pollRealFrames(timeout: .seconds(10), samples: &samples) { rows in var candidates = rows.filter { $0.pid == pid && !oldIDs.contains($0.id) && $0.onscreen }.map(\.id) if !candidates.isEmpty && (candidates.count > 1 || kind == .fixture) { let response = try await driver.send(.standardWindows(pid: pid, candidates: candidates)) guard let standard = response.windowIDs else { throw RealityError("Driver omitted AX window identities") } guard Set(standard).isSubset(of: Set(candidates)) else { throw RealityError("Driver returned an identity outside the fresh CG candidates") } roleSelections.append(standard) identificationWarnings += response.identificationWarnings ?? [] candidates = standard } guard candidates.count == 1, let id = candidates.first else { selectedID = nil return false } guard selectedID == id else { selectedID = id return false } return true } try encodeJSON( roleSelections, to: directory.appendingPathComponent("standard-window-identities-\(pid).json")) guard let candidate = result.first(where: { $0.id == selectedID && $0.pid == pid && $0.onscreen }) else { throw RealityError("Cannot uniquely identify new \(kind.rawValue) window") } if kind == .notes { guard let process = launched.first(where: { $0.receipt.pid == pid && $0.receipt.app == .notes }), let current = NSRunningApplication(processIdentifier: pid) else { throw RealityError("Safety stop: owned Notes process disappeared before window registration") } do { try process.receipt.validateDiscardIdentity( pid: current.processIdentifier, bundleID: current.bundleIdentifier, bundleURL: current.bundleURL, launchDate: current.launchDate, isTerminated: current.isTerminated) let notes = NSRunningApplication.runningApplications(withBundleIdentifier: RealApp.notes.bundleID) guard notes.count == 1, notes.first?.processIdentifier == pid else { throw RealityError("Another Notes process appeared before window registration") } } catch { throw RealityError("Safety stop: Notes identity changed before window registration: \(error)") } } let owned = OwnedWindow(app: kind, pid: candidate.pid, id: candidate.id) windows.append(owned) documents[owned.id] = document created.append(owned) if kind == .finder { unresolvedFinderDocuments.removeAll { $0 == document } } try encodeJSON(created, to: directory.appendingPathComponent("created-windows.json")) try writeOwnership() let warnings = try await driver.register(owned) identificationWarnings += warnings.map { "PID \(owned.pid), CGWindowID \(owned.id): \($0)" } try encodeJSON( identificationWarnings, to: directory.appendingPathComponent("driver-identification-warnings.json")) return owned } catch { try encodeJSON( roleSelections, to: directory.appendingPathComponent("standard-window-identities-\(pid).json")) try encodeJSON(samples, to: directory.appendingPathComponent("open-observations-\(pid).json")) throw error } } static func documentsForLaunch(_ document: URL?, arguments: [String]) -> [URL] { guard let document, !arguments.contains(document.path) else { return [] } return [document] } func launchArguments(_ kind: RealApp, application: URL, document: URL?) throws -> [String] { var arguments = ["-n", "-a", application.path] if kind == .firefox { guard let document else { throw RealityError("Firefox requires an owned local page") } // A separate profile and disabled remote reuse keep the user's browser completely outside our ledger. let profile = directory.appendingPathComponent("browser-profile-\(UUID().uuidString)") let artifact = RealAppOwnedArtifact(url: profile, kind: .browserProfile) _ = try artifact.cleanupURL(in: artifactDirectory) try FileManager.default.createDirectory(at: profile, withIntermediateDirectories: false) try registerArtifact(artifact) let preferences = """ user_pref("browser.shell.checkDefaultBrowser", false); user_pref("browser.startup.homepage_override.mstone", "ignore"); user_pref("browser.startup.page", 0); user_pref("datareporting.policy.dataSubmissionEnabled", false); user_pref("datareporting.policy.firstRunURL", ""); user_pref("browser.aboutwelcome.enabled", false); """ try Data(preferences.utf8).write(to: profile.appendingPathComponent("user.js")) arguments += ["--args", "--no-remote", "--profile", profile.path, "--new-window", document.path] } else if kind == .chromium || kind == .vscode { guard let document, document.lastPathComponent.contains(token) else { throw RealityError("Profile-isolated apps require an owned token-matched local document") } _ = try RealAppOwnedArtifact(url: document, kind: .document).cleanupURL(in: artifactDirectory) if kind == .chromium { let profile = try makeIsolatedDirectory(prefix: "browser-profile-", kind: .browserProfile) arguments += [ "--args", "--user-data-dir=\(profile.path)", "--no-first-run", "--no-default-browser-check", "--disable-background-networking", "--disable-component-update", "--disable-sync", "--disable-extensions", "--disable-default-apps", "--disable-features=MediaRouter,OptimizationHints", "--host-resolver-rules=MAP * ~NOTFOUND", "--new-window", document.path, ] } else { let profile = try makeEditorProfile() let extensions = try makeIsolatedDirectory(prefix: "editor-extensions-", kind: .editorExtensions) let shared = profile.appendingPathComponent("shared-data", isDirectory: true) try FileManager.default.createDirectory(at: shared, withIntermediateDirectories: false) let user = profile.appendingPathComponent("User", isDirectory: true) try FileManager.default.createDirectory(at: user, withIntermediateDirectories: false) let settings = """ { "workbench.startupEditor": "none", "window.restoreWindows": "none", "update.mode": "none", "extensions.autoCheckUpdates": false, "extensions.autoUpdate": false, "extensions.ignoreRecommendations": true, "telemetry.telemetryLevel": "off", "security.workspace.trust.enabled": false, "task.allowAutomaticTasks": "off", "terminal.integrated.enablePersistentSessions": false } """ try Data(settings.utf8).write(to: user.appendingPathComponent("settings.json"), options: .atomic) arguments += [ "--args", "--user-data-dir", profile.path, "--extensions-dir", extensions.path, "--shared-data-dir", shared.path, "--disable-extensions", "--new-window", "--skip-welcome", "--skip-release-notes", document.path, ] } } else { if let document { arguments.append(document.path) } arguments += ["--args", "-ApplePersistenceIgnoreState", "YES"] } return arguments } private func makeIsolatedDirectory(prefix: String, kind: RealAppOwnedArtifact.Kind) throws -> URL { let profile = directory.appendingPathComponent("\(prefix)\(UUID().uuidString)") let artifact = RealAppOwnedArtifact(url: profile, kind: kind) _ = try artifact.cleanupURL(in: artifactDirectory) try FileManager.default.createDirectory( at: profile, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) try registerArtifact(artifact) return profile } private func makeEditorProfile() throws -> URL { let profile = try RealityEditorProfile() editorProfiles.append(profile) try encodeJSON( editorProfiles.map(\.receipt), to: directory.appendingPathComponent("editor-profile-scopes.json")) return profile.url } func cleanupUnlaunchedEditorProfiles() throws { guard windows.isEmpty, launched.isEmpty, applicationChildren.allSatisfy({ !$0.process.isRunning }) else { throw RealityError("Cannot remove editor profiles while application ownership is active") } while let profile = editorProfiles.last { try profile.remove() editorProfiles.removeLast() } } private func makeDocument(_ kind: RealApp) async throws -> URL? { let file = directory.appendingPathComponent("\(token)-\(nextDocument)") nextDocument += 1 switch kind { case .finder: let artifact = RealAppOwnedArtifact(url: file, kind: .finderFolder) _ = try artifact.cleanupURL(in: artifactDirectory) try FileManager.default.createDirectory(at: file, withIntermediateDirectories: false) try registerArtifact(artifact) return file case .textEdit, .vscode: let document = file.appendingPathExtension("txt") let texture = (0..<60).map { "\($0): Parcel reality owned document — stripes and letters 0123456789" } .joined(separator: "\n") try createDocument(Data(texture.utf8), at: document) return document case .safari, .firefox, .chromium: let page = file.appendingPathExtension("html") try createDocument( Data("\(token)Parcel reality".utf8), at: page) return page case .quickTime: let movie = file.appendingPathExtension("mov") let artifact = RealAppOwnedArtifact(url: movie, kind: .document) _ = try artifact.cleanupURL(in: artifactDirectory) try registerArtifact(artifact) try await writeOwnedMovie(to: movie) return movie case .terminal: let command = file.appendingPathExtension("command") try createDocument(Data("#!/bin/bash\nprintf '\\033]0;\(token)\\007'\n".utf8), at: command) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: command.path) return command default: return nil } } private func makeFixtureBundle() throws -> URL { guard let path = ProcessInfo.processInfo.environment["PARCEL_FIXTURE_PATH"], FileManager.default.isExecutableFile(atPath: path) else { throw RealityError("Reality requires its built FixtureApp executable") } let bundle = directory.appendingPathComponent("fixture-\(UUID().uuidString).app") let artifact = RealAppOwnedArtifact(url: bundle, kind: .fixtureBundle) _ = try artifact.cleanupURL(in: artifactDirectory) try FileManager.default.createDirectory(at: bundle, withIntermediateDirectories: false) try registerArtifact(artifact) let executables = bundle.appendingPathComponent("Contents/MacOS") try FileManager.default.createDirectory(at: executables, withIntermediateDirectories: true) try FileManager.default.copyItem( at: URL(fileURLWithPath: path), to: executables.appendingPathComponent("FixtureApp")) let plist = [ "CFBundleIdentifier": RealApp.fixture.bundleID, "CFBundleExecutable": "FixtureApp", "CFBundleName": "FixtureApp", "CFBundlePackageType": "APPL", "CFBundleVersion": "1", "CFBundleShortVersionString": "1.0", "NSPrincipalClass": "NSApplication", ] try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) .write(to: bundle.appendingPathComponent("Contents/Info.plist")) return bundle } private func createDocument(_ data: Data, at url: URL) throws { let artifact = RealAppOwnedArtifact(url: url, kind: .document) let path = try artifact.cleanupURL(in: artifactDirectory) let descriptor = Darwin.open(path.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600) guard descriptor >= 0 else { throw RealityError("Cannot exclusively create owned document: errno \(errno)") } let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) var failures: [String] = [] do { try registerArtifact(artifact) try handle.write(contentsOf: data) } catch { failures.append(String(describing: error)) } do { try handle.close() } catch { failures.append(String(describing: error)) } if !failures.isEmpty { throw RealityError("Owned document creation failed: \(failures.joined(separator: "; "))") } } private func registerArtifact(_ artifact: RealAppOwnedArtifact) throws { artifacts.append(artifact) try encodeJSON(artifacts, to: directory.appendingPathComponent("owned-artifacts.json")) } func arrange(_ window: OwnedWindow, frame: ScreenRect, exactSize: Bool = true) async throws { try requireOwned(window) guard let driver else { throw RealityError("A signed reality driver is required") } let stamp = UUID().uuidString let response = try await driver.send( .move( pid: window.pid, windowID: window.id, x: frame.x, y: frame.y, width: frame.width, height: frame.height)) try encodeJSON(response, to: directory.appendingPathComponent("arrange-response-\(window.id)-\(stamp).json")) var samples: [Observation] = [] let evidence = directory.appendingPathComponent("arrange-observations-\(window.id)-\(stamp).json") do { _ = try await pollRealFrames(samples: &samples) { rows in guard let real = rows.first(where: { $0.id == window.id })?.frame else { return false } return exactSize ? real.matches(frame) : abs(real.x - frame.x) <= 3 && abs(real.y - frame.y) <= 3 } } catch { try encodeJSON(samples, to: evidence) throw error } try encodeJSON(samples, to: evidence) } func focus(_ window: OwnedWindow) async throws { try requireOwned(window) guard let driver else { throw RealityError("A signed reality driver is required") } if window.app != .finder && window.app != .fixture { let application = try await revalidatedFocusApplication(for: window) let activationAccepted = application.activate() var consecutive = 0 var activation: [RealAppFocusActivationObservation] = [] let evidence = directory.appendingPathComponent("focus-activation-\(window.id)-\(UUID().uuidString).json") do { for _ in 0..<10 { _ = try await revalidatedFocusApplication(for: window) let rows = try FrameOracle.read() let foregroundPID = NSWorkspace.shared.frontmostApplication?.processIdentifier activation.append( RealAppFocusActivationObservation( activationAccepted: activationAccepted, foregroundPID: foregroundPID, windows: rows)) consecutive = Self.focusedID(rows, foregroundPID: foregroundPID) == window.id ? consecutive + 1 : 0 if consecutive >= 3 { break } try await Task.sleep(for: .milliseconds(20)) } } catch { try encodeJSON(activation, to: evidence) throw error } try encodeJSON(activation, to: evidence) if consecutive >= 3 { return } } _ = try await driver.send(.focus(pid: window.pid, windowID: window.id)) var samples: [Observation] = [] _ = try await pollRealFrames(samples: &samples) { Self.focusedID($0) == window.id } } private func revalidatedFocusApplication(for window: OwnedWindow) async throws -> NSRunningApplication { try requireOwned(window) guard let process = launched.first(where: { $0.receipt.pid == window.pid && $0.receipt.app == window.app }) else { throw RealityError("Safety stop: owned focus launch receipt is missing") } let evidence = directory.appendingPathComponent("focus-launch-identity-\(window.id)-\(UUID().uuidString).json") var receipt = RealAppFocusIdentityReceipt(launch: process.receipt, window: window) let clock = ContinuousClock() let start = clock.now do { while true { try Task.checkCancellation() try requireOwned(window) let current = NSRunningApplication(processIdentifier: window.pid) let retained = RealAppProcessIdentity(process.application) let identity = current.map(RealAppProcessIdentity.init) let presence = RealAppProcessPresence.read(pid: window.pid) let rows = try FrameOracle.read(allLayers: true) let elapsed = start.duration(to: clock.now) let components = elapsed.components receipt.observations.append( RealAppFocusIdentityObservation( elapsedSeconds: Double(components.seconds) + Double(components.attoseconds) / 1e18, retained: retained, current: identity, presence: presence, windows: rows.filter { $0.pid == window.pid || $0.id == window.id })) let result = try RealAppLaunchReadback.focus( window: window, launch: process.receipt, retained: retained, current: identity, presence: presence, windows: rows, elapsed: elapsed) if result == .verified, let current { try encodeJSON(receipt, to: evidence) return current } try await Task.sleep(for: .milliseconds(20)) } } catch { receipt.failure = String(describing: error) try encodeJSON(receipt, to: evidence) throw error } } static func focusedID(_ rows: [RealWindow]) -> UInt32? { focusedID(rows, foregroundPID: NSWorkspace.shared.frontmostApplication?.processIdentifier) } private static func focusedID(_ rows: [RealWindow], foregroundPID: Int32?) -> UInt32? { guard let foregroundPID else { return nil } return rows.first { $0.pid == foregroundPID && $0.onscreen && $0.layer == 0 && $0.frame.isValid && $0.alpha > 0 }?.id } func requestNativeClose(_ window: OwnedWindow) async throws { try requireOwned(window) guard let driver else { throw RealityError("A signed reality driver is required") } try driver.requireObservedEffects() let input = try await driver.inputState() let launch = try validatedLaunchReceipt(for: window) var request = try RealAppNativeCloseRequest(launch: launch, window: window, owned: windows, input: input) let evidence = directory.appendingPathComponent("native-close-request-\(window.id)-\(UUID().uuidString).json") try encodeJSON(request, to: evidence) _ = try await driver.send(.close(pid: window.pid, windowID: window.id)) request.acknowledge() nativeCloseRequests[window.id] = request if request.authorizesProcessExit { expectedProcessExits.insert(window.pid) } try encodeJSON(request, to: evidence) } func recordNativeClosure(_ window: OwnedWindow) throws { try requireOwned(window) guard let request = nativeCloseRequests[window.id], request.acknowledged, request.window.pid == window.pid, request.window.app == window.app else { throw RealityError("Safety stop: native closure lacks its exact acknowledged owned request") } guard try !FrameOracle.read(allLayers: true).contains(where: { $0.pid == window.pid && $0.id == window.id }) else { throw RealityError("Safety stop: native close still has an owned CG window") } windows.removeAll { $0.pid == window.pid && $0.id == window.id } try writeOwnership() } func close(_ window: OwnedWindow) async throws { try requireOwned(window) if window.app == .finder, let driver { let receiptURL = directory.appendingPathComponent("discard-finder-\(window.id).json") try encodeJSON(RealAppDiscardStrategy.closeOwnedFinderWindow, to: receiptURL) _ = try await driver.send(.close(pid: window.pid, windowID: window.id)) var samples: [Observation] = [] do { _ = try await pollRealFrames(samples: &samples) { rows in !rows.contains { $0.pid == window.pid && $0.id == window.id } } } catch { try encodeJSON( samples, to: directory.appendingPathComponent("discard-finder-observations-\(window.id).json")) throw error } try encodeJSON( samples, to: directory.appendingPathComponent("discard-finder-observations-\(window.id).json")) windows.removeAll { $0.pid == window.pid && $0.id == window.id } try writeOwnership() } else if let process = launched.first(where: { $0.receipt.pid == window.pid && $0.receipt.app == window.app }) { try await discard(process) } else { throw RealityError("Refusing to discard an unowned app") } } private func discard(_ process: OwnedRealAppProcess, cleanup: Bool = false) async throws { let app = process.application let launch = process.receipt let receiptURL = directory.appendingPathComponent("discard-process-\(launch.pid)-\(UUID().uuidString).json") var receipt = RealAppDiscardReceipt(launch: launch) receipt.closeRequested = expectedProcessExits.contains(launch.pid) do { _ = try launch.validatedPID() guard launch.app != .finder else { throw RealityError("Finder must never be terminated") } receipt.identities.append(try exitObservation(process)) try encodeJSON(receipt, to: receiptURL) if launch.app == .fixture { let fixture = try ownedFixture(for: launch) receipt.closeRequested = true try encodeJSON(receipt, to: receiptURL) expectedProcessExits.insert(launch.pid) receipt.requestAt = Date() try await fixture.discardOwnedChild() receipt.requestAccepted = true try encodeJSON(receipt, to: receiptURL) } let clock = ContinuousClock() let start = clock.now var stable = 0 var progress = RealAppDiscardProgress() repeat { let rows = try FrameOracle.read(allLayers: true) let elapsed = start.duration(to: clock.now).components receipt.observations.append( Observation( elapsedSeconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18, windows: rows)) let identity = try exitObservation(process) receipt.identities.append(identity) let complete: Bool if launch.app == .fixture { receipt.processGone = try processIsGone( process, windows: rows, observation: identity, cleanup: cleanup) stable = receipt.processGone ? stable + 1 : 0 complete = stable >= 3 } else { let action = try progress.observe( launch: launch, retained: identity.retained, current: identity.current, presence: identity.presence, windows: rows, closeRequested: receipt.closeRequested, cleanup: cleanup) receipt.actions.append(action) if action == .requestDiscard { // A graceful quit can open save sheets. Full live identity permits this one discard only. receipt.closeRequested = true receipt.requestAt = Date() try encodeJSON(receipt, to: receiptURL) expectedProcessExits.insert(launch.pid) receipt.requestAccepted = app.forceTerminate() try encodeJSON(receipt, to: receiptURL) } receipt.processGone = progress.processGone complete = action == .complete } if complete { receipt.finishedAt = Date() try encodeJSON(receipt, to: receiptURL) windows.removeAll { $0.pid == launch.pid } try writeOwnership() return } try await Task.sleep(for: .milliseconds(40)) } while start.duration(to: clock.now) < .seconds(5) let request = receipt.requestAccepted.map { $0 ? "accepted" : "refused" } ?? "not sent" throw RealityError("Owned process or CG windows survived discard: \(launch.pid) (request \(request))") } catch { receipt.finishedAt = Date() receipt.failure = String(describing: error) try encodeJSON(receipt, to: receiptURL) throw error } } private func ownedFixture(for launch: RealAppLaunchReceipt) throws -> RealityFixture { guard launch.app == .fixture, let fixture = fixtures.first(where: { $0.process.processIdentifier == launch.pid }), fixture.process.executableURL?.deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().resolvingSymlinksInPath().standardizedFileURL == launch.applicationURL.resolvingSymlinksInPath().standardizedFileURL else { throw RealityError("Safety stop: fixture child process does not match its launch receipt") } return fixture } private func exitObservation(_ process: OwnedRealAppProcess) throws -> RealAppProcessExitObservation { let pid = try process.receipt.validatedPID() return RealAppProcessExitObservation( retained: RealAppProcessIdentity(process.application), current: NSRunningApplication(processIdentifier: pid).map(RealAppProcessIdentity.init), presence: RealAppProcessPresence.read(pid: pid), childRunning: process.receipt.app == .fixture ? try ownedFixture(for: process.receipt).process.isRunning : nil) } private func processIsGone( _ process: OwnedRealAppProcess, windows: [RealWindow]? = nil, observation: RealAppProcessExitObservation? = nil, cleanup: Bool = false ) throws -> Bool { let pid = try process.receipt.validatedPID() let identity = try observation ?? exitObservation(process) let rows = try windows ?? FrameOracle.read(allLayers: true) if process.receipt.app == .fixture { let fixture = try ownedFixture(for: process.receipt) guard let childRunning = identity.childRunning else { throw RealityError("Safety stop: fixture child termination readback is missing") } return try RealAppLaunchReadback.ownedChildExit( launch: process.receipt, childPID: fixture.process.processIdentifier, childRunning: childRunning, presence: identity.presence, windows: rows) } return try RealAppLaunchReadback.expectedExit( launch: process.receipt, closeRequested: expectedProcessExits.contains(pid), retained: identity.retained, current: identity.current, presence: identity.presence, windows: rows, cleanup: cleanup) } func cleanup() async throws { var failures: [String] = [] for process in launched.reversed() { do { try await discard(process, cleanup: true) } catch { failures.append(String(describing: error)) } } for fixture in fixtures { do { if !ownedProcessIDs.contains(fixture.process.processIdentifier) { try await fixture.discardOwnedChild() } try fixture.close() } catch { failures.append(String(describing: error)) } } for child in applicationChildren { do { try await child.discardOwnedChild() } catch { failures.append(String(describing: error)) } } for window in windows.reversed() where window.app == .finder { do { try await close(window) } catch { failures.append(String(describing: error)) } } var remainingPIDs = fixtures.filter { $0.process.isRunning }.map { $0.process.processIdentifier } remainingPIDs += applicationChildren.filter { $0.process.isRunning }.map { $0.process.processIdentifier } var remainingWindows: [RealWindow] = [] var removedArtifacts: [URL] = [] do { for process in launched where try !processIsGone(process, cleanup: true) { remainingPIDs.append(process.receipt.pid) } remainingWindows = RealAppCleanupSelection.remainingWindows( try FrameOracle.read(allLayers: true), processIDs: ownedProcessIDs, finderWindows: created.filter { $0.app == .finder }) guard remainingPIDs.isEmpty, remainingWindows.isEmpty else { throw RealityError( "Owned cleanup left PIDs \(remainingPIDs) or CG windows \(remainingWindows.map(\.id)); keeping owned artifacts" ) } guard unresolvedFinderDocuments.isEmpty else { throw RealityError( "Finder open lacks a verified window identity; keeping owned folders: \(unresolvedFinderDocuments.map(\.path))" ) } guard directory.resolvingSymlinksInPath().standardizedFileURL.path == artifactDirectory.path else { throw RealityError("Scenario directory identity changed; keeping owned artifacts") } let browserProfiles = artifacts.filter { $0.kind == .browserProfile }.map(\.url) if !browserProfiles.isEmpty { let unclaimed = BrowserProfileCleanup.unclaimedApplications( NSWorkspace.shared.runningApplications.map(RealAppProcessIdentity.init), launches: browserLaunchBoundaries, claimed: launched.map(\.receipt)) remainingPIDs.append(contentsOf: unclaimed.map(\.pid)) try encodeJSON( BrowserProfileCleanupReceipt( profiles: browserProfiles, launches: browserLaunchBoundaries, unclaimedApplications: unclaimed), to: directory.appendingPathComponent("browser-profile-cleanup.json")) guard unclaimed.isEmpty else { throw RealityError( "Safety stop: unclaimed browser applications \(unclaimed.map(\.pid)) remain (bundle URL unavailable: \(unclaimed.filter { $0.bundleURL == nil }.map(\.pid))); keeping all owned artifacts" ) } } for profile in editorProfiles { do { try profile.remove() removedArtifacts.append(profile.url) } catch { failures.append("\(profile.url.path): \(error)") } } let urls = try RealAppOwnedArtifact.cleanupURLs(artifacts, in: artifactDirectory) for url in urls { do { do { try FileManager.default.removeItem(at: url) } catch { let failure = error as NSError guard failure.domain == NSCocoaErrorDomain, failure.code == NSFileNoSuchFileError else { throw error } } guard !FileManager.default.fileExists(atPath: url.path) else { throw RealityError("Owned artifact survived removal: \(url.path)") } removedArtifacts.append(url) } catch { failures.append("\(url.path): \(error)") } } } catch { failures.append(String(describing: error)) } try encodeJSON( RealAppCleanupReceipt( remainingPIDs: remainingPIDs, remainingWindows: remainingWindows, removedArtifacts: removedArtifacts, failures: failures), to: directory.appendingPathComponent("owned-cleanup.json")) if !failures.isEmpty { throw RealityError("Owned cleanup failed: \(failures.joined(separator: "; "))") } } private func requireOwned(_ window: OwnedWindow) throws { guard windows.contains(where: { $0.id == window.id && $0.pid == window.pid && $0.app == window.app }) else { throw RealityError("Refusing to manipulate an unowned window \(window.id)") } } private func writeOwnership() throws { try encodeJSON(windows, to: directory.appendingPathComponent("owned-windows.json")) } } @MainActor func terminate(_ app: NSRunningApplication) async throws { if app.isTerminated { return } let requested = app.terminate() let clock = ContinuousClock() let deadline = clock.now.advanced(by: .seconds(5)) while requested && !app.isTerminated, clock.now < deadline { try await Task.sleep(for: .milliseconds(40)) } if !app.isTerminated { print("Forcing teardown of owned process \(app.processIdentifier) after its quit deadline") guard app.forceTerminate() else { throw RealityError("Owned app refused force termination: \(app.processIdentifier)") } while !app.isTerminated, clock.now < deadline.advanced(by: .seconds(3)) { try await Task.sleep(for: .milliseconds(40)) } } guard app.isTerminated else { throw RealityError("Owned app did not terminate: \(app.processIdentifier)") } } struct RealitySkip: Error, CustomStringConvertible { let description: String init(_ description: String) { self.description = description } } func encodeJSON(_ value: some Encodable, to url: URL) throws { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] try encoder.encode(value).write(to: url, options: .atomic) }