import AppKit import Darwin import Foundation import ParcelConfig import ParcelCore import RealityDriverSupport struct RealityInputBalance: Codable, Sendable { struct Observation: Codable, Sendable { let stage: String let state: DriverInputState } let baseline: DriverInputState private(set) var observations: [Observation] = [] private(set) var failures: [String] = [] mutating func observe(_ state: DriverInputState, stage: String) { observations.append(Observation(stage: stage, state: state)) do { try state.requireRestored(to: baseline) } catch { failures.append("\(stage): \(error)") } } func requireRestored() throws { guard failures.isEmpty else { throw RealityError("Safety stop: \(failures.joined(separator: "; "))") } } } @MainActor final class RealitySession { let directory: URL var realDesktopEvidence: URL? let apps: RealApps let appURL: URL let visible: ScreenRect let socket: URL var config: URL { storage.fileURL("parcel.toml") } let ignoredBundles: [String] let driver: RealityDriver let inputBaseline: DriverInputState private(set) var parcel: NSRunningApplication? private(set) var observations: [Observation] = [] private(set) var expectations: [String] = [] private var protectedWindows: [RealWindow] = [] private(set) var launchInstant: ContinuousClock.Instant? private(set) var setupOwnedVisibility: SetupOwnedVisibility? var setupUnrelatedVisibility: [SetupApplicationVisibility] = [] private var languagePreferenceBackup: LanguagePreferenceBackup? private(set) var storage: RealityStorage private var previousStorage: [RealityStorage] = [] private var storagePrepared = false init(directory: URL, appURL: URL, visible: ScreenRect, inputBaseline: DriverInputState) throws { self.inputBaseline = inputBaseline self.directory = directory self.appURL = appURL self.visible = visible socket = URL(fileURLWithPath: "/tmp/pr-\(UUID().uuidString.prefix(8)).sock") ignoredBundles = Array(Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier))).sorted() let token = "ParcelReality-\(UUID().uuidString.prefix(8))" driver = RealityDriver(appURL: appURL) apps = RealApps(directory: directory, token: token, driver: driver) try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) storage = try RealityStorage(parent: directory) driver.auditURL = directory.appendingPathComponent("input-audit.json") } func configuredLayout() throws -> LayoutValues { try storage.validate() let result = ConfigValidator.validate( try TOMLDocument(parsing: String(contentsOf: config, encoding: .utf8))) guard let configuration = result.configuration, result.diagnostics.isEmpty else { throw RealityError("Isolated reality configuration is invalid: \(result.diagnostics)") } return configuration.layout.global } func configure( layout: String = "columns", cap: Int = 0, memory: Bool = false, minSize: Bool = false, outerGap: Double = RealityGeometry.defaultGaps.outer, innerGap: Double = RealityGeometry.defaultGaps.inner, reservedTop: Double = 0, reservedLeft: Double = 0, reservedRight: Double = 0, ratio: Double = 0.5, whenDisplayFull: ConfigWhenDisplayFull = .swap, shortcutsEnabled: Bool = true, collectActivity: Bool = true, whenFull: ConfigWhenFull = .stack, motionEnabled: Bool = false, motionSpeed: Double = 1, defaultClassifiedBundles: Set = [] ) throws { guard defaultClassifiedBundles.isSubset(of: [RealApp.fixture.bundleID]) else { throw RealityError("Default-classification reality overrides are limited to the exclusively owned fixture") } var text = """ version = 1 [general] when-display-full = "\(whenDisplayFull.rawValue)" shortcuts-enabled = \(shortcutsEnabled) collect-activity = \(collectActivity) [layout] default = "\(layout)" portrait-layout = "\(layout)" window-cap = \(cap) when-full = "\(whenFull.rawValue)" ratio = \(ratio) [layout.gaps] inner = \(innerGap) outer = \(outerGap) [layout.reserved] top = \(reservedTop) left = \(reservedLeft) right = \(reservedRight) [motion] enabled = \(motionEnabled) speed = \(motionSpeed) highlight = "none" [memory] enabled = \(memory) restore-windows = \(memory) [mouse] swap-modifiers = "\(RealityInputDefaults.swapModifiers)" [keybindings] \(RealityInputDefaults.configuration) """ let ignored = Set(ignoredBundles).union(RealApp.allCases.filter(\.tokenMatched).map(\.bundleID)) for bundle in ignored.subtracting(defaultClassifiedBundles).sorted() { text += "\n[[rules]]\nbundle-id = \(RealityProcess.quoted(bundle))\naction = \"ignore\"\n" } for app in RealApp.allCases where app.tokenMatched && !defaultClassifiedBundles.contains(app.bundleID) { text += "\n[[rules]]\nbundle-id = \(RealityProcess.quoted(app.bundleID))\ntitle-contains = \(RealityProcess.quoted(apps.token))\naction = \"tile\"\n" } if minSize { text += "\n[[rules]]\nbundle-id = \"com.apple.systempreferences\"\naction = \"tile\"\n" } try storage.validate() let data = Data(text.utf8) try data.write(to: config, options: .atomic) try storage.validate() } func startingWindows(_ kinds: [RealApp] = [.textEdit, .finder, .terminal]) async throws -> [OwnedWindow] { let permissions = try await driver.preflight() try encodeJSON(permissions, to: directory.appendingPathComponent("driver-preflight.json")) var owned: [OwnedWindow] = [] for kind in kinds { let window = try await apps.open(kind) owned.append(window) if kind.tokenMatched { let offset = Double(owned.count - 1) * 35 let target = ScreenRect(x: visible.x + 80 + offset, y: visible.y + 70 + offset, width: 600, height: 400) try await apps.arrange(window, frame: target, exactSize: kind != .terminal) expectations.append( "Starting \(kind.rawValue) frame disturbed through AX; CGWindowList readback recorded") } else { expectations.append("Starting \(kind.rawValue) frame is the measured native default") } } protectedWindows = FrameOracle.protectedWindows( try FrameOracle.read(), ownedIDs: Set(apps.windows.map(\.id)), ownedPIDs: apps.ownedProcessIDs) try encodeJSON(protectedWindows, to: directory.appendingPathComponent("protected-before.json")) try encodeJSON( try FrameOracle.read().filter { row in owned.contains { $0.id == row.id } }, to: directory.appendingPathComponent("starting-frames.json")) return owned } func start( setupHideTarget: OwnedWindow? = nil, recoveryHooks: RealityRecoveryHooks? = nil, droppedDestroyWindow: OwnedWindow? = nil, firstRun: Bool = false, tourLanguage: String? = nil, resumeTourRecovery: Bool = false ) async throws { guard tourLanguage == nil || firstRun && tourLanguage == "de" else { throw RealityError("Tour capture language requires a fresh owned German scenario") } guard parcel == nil else { throw RealityError("Safety stop: an owned Parcel instance is already running") } guard !firstRun || launchInstant == nil && recoveryHooks?.kind == .tourRollback else { throw RealityError("First-run reality requires a fresh isolated launch with tour hooks") } guard !resumeTourRecovery || !firstRun && launchInstant != nil && recoveryHooks?.kind == .tourRollback else { throw RealityError("Tour recovery relaunch requires an earlier owned launch and isolated tour hooks") } if let recoveryHooks, UUID(uuidString: recoveryHooks.token) == nil { throw RealityError("Recovery hooks require a UUID token before launching Parcel") } if launchInstant != nil { let replacement = try storage.successor() previousStorage.append(storage) storage = replacement storagePrepared = true } try storage.validate() if !storagePrepared { try storage.prepare(firstRun: firstRun) storagePrepared = true } if let tourLanguage { let defaults = try storage.preferences() defaults.set([tourLanguage], forKey: "AppleLanguages") guard defaults.synchronize(), defaults.stringArray(forKey: "AppleLanguages") == [tourLanguage] else { throw RealityError("Owned tour language preference could not be saved") } } if let setupHideTarget { setupOwnedVisibility = try SetupOwnedVisibility(window: setupHideTarget, apps: apps) } let identities = setupOwnedVisibility.map { [$0.identity] } ?? [] let hideAllowlist = String(decoding: try JSONEncoder().encode(identities), as: UTF8.self) try encodeJSON(identities, to: directory.appendingPathComponent("setup-hide-allowlist.json")) guard NSRunningApplication.runningApplications(withBundleIdentifier: "dev.vinnymac.parcel") .allSatisfy({ $0.processIdentifier == driver.host?.processIdentifier }) else { throw RealityError("Safety stop: another Parcel instance appeared while the screen lock was held") } let configuration = NSWorkspace.OpenConfiguration() configuration.activates = firstRun || resumeTourRecovery configuration.addsToRecentItems = false configuration.createsNewApplicationInstance = true var environment = coverageLaunchEnvironment(ProcessInfo.processInfo.environment, hooks: recoveryHooks) if firstRun || resumeTourRecovery { environment["PARCEL_E2E_FIRST_RUN"] = "1" } if recoveryHooks != nil { environment["PARCEL_E2E_WAKE_RECEIPT"] = directory.appendingPathComponent("wake-receipt.json").path } if let droppedDestroyWindow { guard recoveryHooks?.kind == .missedDestroy else { throw RealityError("Dropped-destroy target requires its recovery hook") } environment["PARCEL_E2E_DESTROY_WINDOW_ID"] = String(droppedDestroyWindow.id) environment["PARCEL_E2E_DESTROY_RECEIPT"] = directory.appendingPathComponent("dropped-destroy-receipt.json").path } environment.merge(storage.environment) { _, isolated in isolated } environment["PARCEL_CONFIG_PATH"] = config.path environment["PARCEL_SOCKET_PATH"] = socket.path environment["PARCEL_SETUPS_PATH"] = storage.directory.appendingPathComponent("setups.json").path environment["PARCEL_ACTIVITY_PATH"] = storage.directory.appendingPathComponent("activity.json").path configuration.arguments = storage.arguments environment["PARCEL_REALITY_SETUP_HIDE_ALLOWLIST"] = hideAllowlist environment["PARCEL_REALITY_RELAUNCH_RECEIPT"] = directory.appendingPathComponent("language-relaunch.json").path configuration.environment = environment try encodeJSON( storage.receipt, to: directory.appendingPathComponent("storage-launch-\(previousStorage.count).json")) launchInstant = ContinuousClock.now parcel = try await NSWorkspace.shared.openApplication(at: appURL, configuration: configuration) guard parcel?.bundleURL?.resolvingSymlinksInPath().path == appURL.resolvingSymlinksInPath().path else { throw RealityError("Safety stop: Launch Services did not open the requested Parcel bundle") } } func startRealDesktop() async throws { _ = try RealDesktopOptions(environment: ProcessInfo.processInfo.environment, fixtureSentinel: false) guard parcel == nil, NSRunningApplication.runningApplications(withBundleIdentifier: "dev.vinnymac.parcel") .allSatisfy({ $0.processIdentifier == driver.host?.processIdentifier }) else { throw RealityError("Safety stop: another Parcel instance is running") } // NSWorkspace merges this harness's own PARCEL_REALITY_* variables into the launched app, which makes a // reality build refuse a non-isolated launch. /usr/bin/open run with a scrubbed environment still // launches through Launch Services (so Parcel is its own responsible process for Accessibility) but // passes only the variables listed here. let inherited = coverageLaunchEnvironment(ProcessInfo.processInfo.environment, hooks: nil) var launch: [String: String] = [:] for key in ["HOME", "USER", "LOGNAME", "TMPDIR", "PATH", "SHELL", "LANG", "__CF_USER_TEXT_ENCODING"] { launch[key] = inherited[key] } let parcelEnvironment = [ "PARCEL_E2E": "0", "PARCEL_REAL_DESKTOP": "1", "PARCEL_SOCKET_PATH": socket.path, ] let open = Process() open.executableURL = URL(fileURLWithPath: "/usr/bin/open") open.environment = launch open.arguments = ["-n"] + parcelEnvironment.sorted { $0.key < $1.key }.flatMap { ["--env", "\($0.key)=\($0.value)"] } + [appURL.path] try open.run() open.waitUntilExit() guard open.terminationStatus == 0 else { throw RealityError("Safety stop: /usr/bin/open failed to launch Parcel (\(open.terminationStatus))") } let expected = appURL.resolvingSymlinksInPath().appendingPathComponent("Contents/MacOS/Parcel").path let host = driver.host?.processIdentifier let deadline = ContinuousClock.now + .seconds(10) while parcel == nil, ContinuousClock.now < deadline { if let found = RealitySession.pids(executing: expected).first(where: { $0 != host }), let launched = NSRunningApplication(processIdentifier: found) { parcel = launched } else { try await Task.sleep(for: .milliseconds(50)) } } guard let parcel, RealitySession.executablePath(of: parcel.processIdentifier) == expected else { throw RealityError( "Safety stop: Launch Services did not keep the requested Parcel bundle running (\(expected)); see the dev.vinnymac.parcel lifecycle log" ) } } func adoptLanguageRelaunch(replacing original: NSRunningApplication, previousLaunchDate: Date) async throws { guard original.isTerminated else { throw RealityError("Original Parcel has not exited") } let receipt = try JSONDecoder().decode( LanguageRelaunchReceipt.self, from: Data(contentsOf: directory.appendingPathComponent("language-relaunch.json"))) guard receipt.parent == original.processIdentifier, receipt.helper > 1, receipt.bundlePath == appURL.resolvingSymlinksInPath().path, receipt.replacement != nil else { throw RealityError("Safety stop: language relaunch receipt is unverified") } let candidates = NSRunningApplication.runningApplications(withBundleIdentifier: "dev.vinnymac.parcel") .filter { $0.processIdentifier != driver.host?.processIdentifier } guard candidates.count == 1, let replacement = candidates.first, replacement.bundleURL?.resolvingSymlinksInPath() == appURL.resolvingSymlinksInPath(), replacement.processIdentifier != original.processIdentifier, replacement.processIdentifier == receipt.replacement, replacement.launchDate == receipt.launchDate, let launched = replacement.launchDate, launched > previousLaunchDate else { throw RealityError("Safety stop: language relaunch identity is unverified") } parcel = replacement } func stop() async throws { if let parcel { try await terminate(parcel) } parcel = nil } func isolateLanguagePreference() throws { guard languagePreferenceBackup == nil else { throw RealityError("Language preference isolation is already active") } let backup = try LanguagePreferenceBackup(storage: storage) try encodeJSON(backup.snapshot, to: directory.appendingPathComponent("language-preference-backup.json")) languagePreferenceBackup = backup } func languageState() async throws -> LanguagePreferenceReadback { try await languageControl("reality-language-state") } func chooseLanguage(_ id: String) async throws { guard languagePreferenceBackup != nil else { throw RealityError("Language preference must be backed up before choosing") } let state = try await languageControl("reality-language-choose", id) try await requireSavedLanguage(id, state: state, needsRestart: true, stage: "chosen") expectations.append("Settings language choice saved exactly \(id) in Parcel's own preference domain") } func requireSavedLanguageAfterRestart(_ id: String) async throws { let state = try await languageState() try await requireSavedLanguage(id, state: state, needsRestart: false, stage: "reopened") expectations.append("Reopened Parcel reads the saved language with no pending restart") } private func requireSavedLanguage( _ id: String, state: LanguagePreferenceReadback, needsRestart: Bool, stage: String ) async throws { guard let backup = languagePreferenceBackup else { throw RealityError("Language preference backup is missing") } try encodeJSON(state, to: directory.appendingPathComponent("language-\(stage)-state.json")) let deadline = ContinuousClock.now.advanced(by: .seconds(5)) var saved = try backup.refresh() while saved.languages != [id], ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(40)) saved = try backup.refresh() } try encodeJSON(saved, to: directory.appendingPathComponent("language-\(stage)-preference.json")) try LanguageRestartOracle.requireSavedChoice(id, state: state, saved: saved, needsRestart: needsRestart) } private func languageControl(_ name: String, _ arguments: String...) async throws -> LanguagePreferenceReadback { let result = try await cli(["run", "--json", name] + arguments) guard result.status == 0 else { throw RealityError("prcl \(name) failed: \(result.output) \(result.errors)") } let state = try JSONDecoder().decode(LanguagePreferenceReadback.self, from: Data(result.output.utf8)) guard state.accepted else { throw RealityError("Parcel rejected \(name): \(result.output)") } return state } func requestLanguageRestart() async throws { guard languagePreferenceBackup != nil else { throw RealityError("Language preference must be backed up before restarting") } _ = try await command("reality-language-restart") } private func restoreLanguagePreference() throws { guard let backup = languagePreferenceBackup else { return } guard parcel == nil, NSRunningApplication.runningApplications(withBundleIdentifier: "dev.vinnymac.parcel") .allSatisfy({ $0.processIdentifier == driver.host?.processIdentifier }) else { throw RealityError("Safety stop: Parcel must stop before restoring the language preference") } try backup.restore() try encodeJSON(try backup.refresh(), to: directory.appendingPathComponent("language-preference-restored.json")) languagePreferenceBackup = nil } struct CommandAcceptance: Decodable { let accepted: Bool let automaticTiling: Bool? let reports: [Report]? enum CodingKeys: String, CodingKey { case accepted, reports case automaticTiling = "automatic_tiling" } } @discardableResult func command(_ name: String, _ arguments: String...) async throws -> CommandAcceptance { expectations.append( "Command \(name) \(arguments.joined(separator: " ")) must be accepted; physical effect is checked separately" ) let result = try await cli(["run", "--json", name] + arguments) guard result.status == 0 else { throw RealityError("prcl \(name) failed: \(result.output) \(result.errors)") } let acceptance = try JSONDecoder().decode(CommandAcceptance.self, from: Data(result.output.utf8)) guard acceptance.accepted else { throw RealityError("Parcel rejected \(name): \(result.output)") } return acceptance } func cli(_ arguments: [String], timeout: Duration = .seconds(15)) async throws -> CommandOutput { let clock = ContinuousClock() let deadline = clock.now.advanced(by: .seconds(5)) while !FileManager.default.fileExists(atPath: socket.path), clock.now < deadline { if let parcel, parcel.isTerminated { throw RealityError("Parcel exited before IPC was ready") } try await Task.sleep(for: .milliseconds(40)) } var environment = ProcessInfo.processInfo.environment environment["PARCEL_SOCKET"] = socket.path return try await RealityProcess.run( appURL.appendingPathComponent("Contents/Resources/bin/prcl").path, arguments, directory: directory, environment: environment, timeout: timeout) } func expect( _ description: String, timeout: Duration = .seconds(4), predicate: @MainActor ([RealWindow]) throws -> Bool ) async throws { expectations.append(description) var samples: [Observation] = [] defer { observations.append(contentsOf: samples) } do { _ = try await pollRealFrames(timeout: timeout, samples: &samples, predicate: predicate) } catch { let prefix = RealityLaneDecision.afterScenario(failures: [error], cleanupFailed: false).stopsLane ? "Safety stop: " : "" throw RealityError("\(prefix)\(description): \(error)") } try requireProtectedFrames() try driver.confirmObservedEffect(description) } func tiles(_ owned: [OwnedWindow], timeout: Duration = .seconds(4)) async throws { let ids = owned.map(\.id) let gaps = try configuredLayout().gaps try await expect("\(ids) must tile \(visible) with inner=\(gaps.inner), outer=\(gaps.outer)", timeout: timeout) { FrameOracle.tiles( try FrameOracle.frames($0, ids: ids), visible: self.visible, inner: gaps.inner, outer: gaps.outer) } } func recordExpectation(_ description: String) { expectations.append(description) } func readFrames(_ owned: [OwnedWindow]) throws -> [ScreenRect] { try FrameOracle.frames(FrameOracle.read(), ids: owned.map(\.id)) } func requireProtectedFrames() throws { let current = try FrameOracle.read() for window in protectedWindows { if let now = current.first(where: { $0.id == window.id }), !now.frame.matches(window.frame) { throw RealityError( "Safety stop: unowned window \(window.id) changed from \(window.frame) to \(now.frame)") } } } func artifacts() async throws { try encodeJSON(try FrameOracle.read(), to: directory.appendingPathComponent("real-frames.json")) try encodeJSON(observations, to: directory.appendingPathComponent("observations.json")) try encodeJSON(expectations, to: directory.appendingPathComponent("expected.json")) var failures: [String] = [] if launchInstant == nil { try encodeJSON( ["Parcel was not launched; IPC and app-log capture do not apply"], to: directory.appendingPathComponent("artifact-errors.json")) return } for resource in ["windows", "workspaces", "displays", "spaces"] { do { let result = try await cli(["query", "--json", resource]) try encodeJSON(result, to: directory.appendingPathComponent("query-\(resource).json")) } catch { failures.append("query \(resource): \(error)") } } do { try encodeJSON(try await cli(["diagnostics"]), to: directory.appendingPathComponent("diagnostics.json")) } catch { failures.append("diagnostics: \(error)") } do { let logs = try await RealityProcess.run( "/usr/bin/log", [ "show", "--last", "30s", "--style", "compact", "--predicate", "subsystem BEGINSWITH \"dev.vinnymac.parcel\" OR subsystem == \"com.parcel\"", ], directory: directory, timeout: .seconds(30)) try encodeJSON(logs, to: directory.appendingPathComponent("unified-log.json")) if logs.status != 0 { failures.append("log show: \(logs.errors)") } } catch { failures.append("log show: \(error)") } try encodeJSON(failures, to: directory.appendingPathComponent("artifact-errors.json")) try driver.requireObservedEffects() } func cleanup() async throws { var failures: [String] = [] var inputBalance = RealityInputBalance(baseline: inputBaseline) inputBalance.observe(DriverInputState.capture(), stage: "Before owned-key release") do { _ = try await driver.send(.releaseOwnedKeys) } catch { failures.append("Owned-key release failed: \(error)") } do { inputBalance.observe(try await driver.inputState(), stage: "After owned-key release") } catch { failures.append("Driver input-state read failed: \(error)") } do { try await stop() } catch { failures.append(String(describing: error)) } do { try restoreLanguagePreference() } catch { failures.append(String(describing: error)) } if let setupOwnedVisibility { do { guard parcel == nil else { throw RealityError("Safety stop: Parcel must stop before owned visibility restoration") } try await setupOwnedVisibility.restore(apps: apps, directory: directory) } catch { failures.append(String(describing: error)) } } for application in setupUnrelatedVisibility { do { try application.requireUnchanged() } catch { failures.append(String(describing: error)) } } do { try requireProtectedFrames() } catch { failures.append(String(describing: error)) } do { try await apps.cleanup() } catch { failures.append(String(describing: error)) } do { try await driver.stop() } catch { failures.append(String(describing: error)) } do { guard parcel == nil, driver.host == nil else { throw RealityError( "Safety stop: Parcel and the driver host must stop before removing owned preferences") } let domains = previousStorage + [storage] for owned in domains { try owned.removePreferences() } try encodeJSON( ["removedDomains": domains.map(\.preferencesDomain)], to: directory.appendingPathComponent("storage-cleanup.json")) } catch { failures.append(String(describing: error)) } do { try requireProtectedFrames() } catch { failures.append(String(describing: error)) } inputBalance.observe(DriverInputState.capture(), stage: "After scenario cleanup") do { try inputBalance.requireRestored() } catch { failures.append(String(describing: error)) } do { try encodeJSON(inputBalance, to: directory.appendingPathComponent("input-restoration.json")) } catch { failures.append("Input restoration receipt failed: \(error)") } if !failures.isEmpty { throw RealityError("Safety stop: cleanup failed: \(failures.joined(separator: "; "))") } } } extension RealitySession { /// Every running process whose resolved executable path is `path`. static func pids(executing path: String) -> [pid_t] { var pids = [pid_t](repeating: 0, count: 8192) let bytes = proc_listallpids(&pids, Int32(pids.count * MemoryLayout.size)) guard bytes > 0 else { return [] } return pids.prefix(Int(bytes)).filter { $0 > 0 && executablePath(of: $0) == path } } /// The resolved executable path of a running process, or nil if it already exited. static func executablePath(of pid: pid_t) -> String? { var buffer = [UInt8](repeating: 0, count: Int(MAXPATHLEN) * 4) let length = proc_pidpath(pid, &buffer, UInt32(buffer.count)) guard length > 0 else { return nil } let path = String(decoding: buffer.prefix(Int(length)), as: UTF8.self) return URL(fileURLWithPath: path).resolvingSymlinksInPath().path } }