import Foundation import ParcelConfig import Testing @testable import ParcelApp @MainActor struct AppLanguageLaunchTests { @Test(arguments: [false, true], [false, true]) func isolatedRuntimeKeepsNativePreferencesAndLoginServiceUntouched(fixture: Bool, isolated: Bool) throws { let suite = "dev.vinnymac.parcel.runtime-isolation-tests.\(UUID())" let defaults = try #require(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite) } let directory = FileManager.default.temporaryDirectory.appendingPathComponent( "parcel-runtime-isolation-\(UUID())") let runtime = NativeAppRuntime( store: ConfigStore(fileURL: directory.appendingPathComponent("parcel.toml")), socketPath: directory.appendingPathComponent("ipc.sock").path, defaults: defaults, fixtureOnly: fixture, isolatedStorage: isolated, realitySession: true) defer { runtime.permissions.stop() } #expect(runtime.usesIsolatedState == (fixture || isolated)) guard runtime.usesIsolatedState else { return } #expect(try runtime.tourLoginStatus() == .disabled) try runtime.setLaunchAtLogin(true) #expect(try runtime.tourLoginStatus() == .enabled) try runtime.setLaunchAtLogin(false) #expect(try runtime.tourLoginStatus() == .disabled) #expect(defaults.persistentDomain(forName: suite)?.isEmpty != false) #expect(!FileManager.default.fileExists(atPath: directory.path)) } @Test func pseudoLaunchIsVolatileAndOverridesPersistentChoice() throws { let domain = "dev.vinnymac.parcel.pseudo-tests.\(UUID())" let defaults = try #require(UserDefaults(suiteName: domain)) let arguments = defaults.volatileDomain(forName: UserDefaults.argumentDomain) defer { defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain) defaults.removePersistentDomain(forName: domain) } defaults.setPersistentDomain(["AppleLanguages": ["fr"], "retained": true], forName: domain) AppLocalizationLaunch.configure(environment: ["PARCEL_PSEUDO_LOCALIZATION": "1"], defaults: defaults) #if DEBUG #expect(defaults.stringArray(forKey: "AppleLanguages") == ["en-XA"]) #else #expect(defaults.stringArray(forKey: "AppleLanguages") == ["fr"]) #endif #expect(defaults.persistentDomain(forName: domain)?["AppleLanguages"] as? [String] == ["fr"]) #expect(defaults.persistentDomain(forName: domain)?["retained"] as? Bool == true) } @Test(arguments: [[:], ["PARCEL_PSEUDO_LOCALIZATION": "0"], ["PARCEL_PSEUDO_LOCALIZATION": "true"]]) func normalLaunchLeavesDefaultsAlone(_ environment: [String: String]) throws { let defaults = try #require(UserDefaults(suiteName: "dev.vinnymac.parcel.pseudo-tests.\(UUID())")) let before = defaults.volatileDomain(forName: UserDefaults.argumentDomain) as NSDictionary AppLocalizationLaunch.configure(environment: environment, defaults: defaults) #expect(defaults.volatileDomain(forName: UserDefaults.argumentDomain) as NSDictionary == before) } @Test func fixtureLanguageDomainIsIsolatedAndStableAcrossRestart() throws { let token = UUID().uuidString let settings = try AppLaunchSettings(environment: ["PARCEL_E2E": "1", "PARCEL_E2E_TOKEN": token]) #expect(settings.preferencesDomain() == "dev.vinnymac.parcel.e2e.\(token)") #expect(try AppLaunchSettings(environment: [:]).preferencesDomain() == "dev.vinnymac.parcel") #expect( try AppLaunchSettings(environment: [:]).preferencesDomain(regularDomain: "org.example.parcel") == "org.example.parcel") } private func withRealityStorage( _ body: (AppIsolatedStorage, [String: String]) throws -> Void ) throws { let token = UUID() let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) .resolvingSymlinksInPath() let directory = root.appendingPathComponent("parcel-reality-\(token.uuidString)") try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) defer { if let defaults = UserDefaults(suiteName: "dev.vinnymac.parcel.reality.\(token.uuidString)") { defaults.removePersistentDomain(forName: "dev.vinnymac.parcel.reality.\(token.uuidString)") } do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } } let storage = try AppIsolatedStorage(token: token.uuidString, path: directory.path) let environment = [ "PARCEL_REALITY": "1", "PARCEL_REALITY_ISOLATION_TOKEN": token.uuidString, "PARCEL_REALITY_STATE_DIRECTORY": directory.path, "PARCEL_CONFIG_PATH": storage.fileURL("parcel.toml").path, "PARCEL_ACTIVITY_PATH": storage.fileURL("activity.json").path, "PARCEL_SETUPS_PATH": storage.fileURL("setups.json").path, ] try body(storage, environment) } @Test(arguments: AppIsolatedStorage.files, [false, true]) func realityStorageRejectsRedirectedOrSharedProductFiles(name: String, hardLink: Bool) throws { try withRealityStorage { storage, environment in let outside = storage.directory.deletingLastPathComponent().appendingPathComponent("sentinel") let bytes = Data("untouched".utf8) try bytes.write(to: outside) if hardLink { try FileManager.default.linkItem(at: outside, to: storage.fileURL(name)) } else { try FileManager.default.createSymbolicLink(at: storage.fileURL(name), withDestinationURL: outside) } #expect(throws: (any Error).self) { try AppIsolatedStorage( token: environment["PARCEL_REALITY_ISOLATION_TOKEN"], path: storage.directory.path) } #expect(try Data(contentsOf: outside) == bytes) } } @Test(arguments: ["Application Support", "Preferences", ".config"]) func realityStorageRejectsRealStatePathsBeforeOpeningThem(_ component: String) { let token = UUID().uuidString let path = "/uncreated/\(component)/parcel-reality-\(token)" #expect(throws: (any Error).self) { try AppIsolatedStorage(token: token, path: path) } } @Test func realityStorageRejectsWrongTokenPermissionsAliasesAndOverrides() throws { try withRealityStorage { storage, environment in #expect(throws: (any Error).self) { try AppIsolatedStorage(token: UUID().uuidString, path: storage.directory.path) } #expect(throws: (any Error).self) { try storage.requireOverride("/unowned/parcel.toml", file: "parcel.toml") } try storage.requireOverride(storage.fileURL("parcel.toml").path, file: "parcel.toml") let alias = storage.directory.deletingLastPathComponent().appendingPathComponent("alias") try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: storage.directory) #expect(throws: (any Error).self) { try AppIsolatedStorage(token: environment["PARCEL_REALITY_ISOLATION_TOKEN"], path: alias.path) } try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: storage.directory.path) #expect(throws: (any Error).self) { try AppIsolatedStorage( token: environment["PARCEL_REALITY_ISOLATION_TOKEN"], path: storage.directory.path) } } } @Test func realityLaunchAndReplacementRequireExplicitIsolationAndKeepRealAppsEnabled() throws { try withRealityStorage { storage, environment in #if DEBUG && PARCEL_REALITY let settings = try AppLaunchSettings(environment: environment, arguments: ["--reality-isolated"]) #expect(settings.isolated && !settings.fixtureOnly) #expect(settings.configURL == storage.fileURL("parcel.toml")) #expect(settings.preferencesDomain() == storage.preferencesDomain) let defaults = try settings.preferences() #expect(defaults.persistentDomain(forName: storage.preferencesDomain) == nil) defaults.setPersistentDomain( ["AppleLanguages": ["fr"], "automaticTilingEnabled": false], forName: storage.preferencesDomain) let replacement = try AppRelaunch.replacementSettings(environment: environment) #expect(replacement.preferencesDomain() == storage.preferencesDomain) #expect(replacement.configURL == settings.configURL) #expect( try replacement.preferences().persistentDomain(forName: storage.preferencesDomain)?[ "automaticTilingEnabled"] as? Bool == false) #expect(throws: (any Error).self) { try AppLaunchSettings(environment: environment) } var incomplete = environment incomplete["PARCEL_REALITY_STATE_DIRECTORY"] = nil #expect(throws: (any Error).self) { try AppRelaunch.replacementSettings(environment: incomplete) } #else #expect(throws: (any Error).self) { try AppLaunchSettings(environment: environment, arguments: ["--reality-isolated"]) } #expect(throws: (any Error).self) { try AppRelaunch.replacementSettings(environment: environment) } #endif } } #if DEBUG && PARCEL_REALITY @Test func isolatedLanguageLaunchReadsOnlyOwnedChoiceAndWritesOnlyVolatileArguments() throws { try withRealityStorage { storage, environment in let settings = try AppLaunchSettings(environment: environment, arguments: ["--reality-isolated"]) let owned = try settings.preferences() owned.setPersistentDomain(["AppleLanguages": ["fr"]], forName: storage.preferencesDomain) let domain = "dev.vinnymac.parcel.argument-tests.\(UUID())" let target = try #require(UserDefaults(suiteName: domain)) let arguments = target.volatileDomain(forName: UserDefaults.argumentDomain) defer { target.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain) target.removePersistentDomain(forName: domain) } target.setPersistentDomain(["AppleLanguages": ["ja"], "sentinel": true], forName: domain) try AppLocalizationLaunch.configure( settings: settings, environment: environment, argumentDefaults: target) #expect( target.volatileDomain(forName: UserDefaults.argumentDomain)["AppleLanguages"] as? [String] == ["fr"] ) #expect(target.persistentDomain(forName: domain)?["AppleLanguages"] as? [String] == ["ja"]) owned.set("bad", forKey: "AppleLanguages") #expect(throws: (any Error).self) { try AppLocalizationLaunch.configure( settings: settings, environment: environment, argumentDefaults: target) } } } @Test func realityDriverHostCannotFallThroughToProductStartup() throws { try withRealityStorage { storage, inherited in var environment = inherited environment["PARCEL_REALITY_DRIVER_SOCKET"] = storage.directory.deletingLastPathComponent().appendingPathComponent("driver.sock").path let validated = try AppRealityDriverHost.storage( environment: environment, arguments: ["--reality-driver-host"]) #expect(validated != nil) #expect(throws: (any Error).self) { try AppRealityDriverHost.storage(environment: environment, arguments: []) } #expect(throws: (any Error).self) { try AppRealityDriverHost.storage(environment: [:], arguments: ["--reality-driver-host"]) } environment["PARCEL_REALITY_STATE_DIRECTORY"] = nil #expect(throws: (any Error).self) { try AppRealityDriverHost.storage(environment: environment, arguments: ["--reality-driver-host"]) } } } #endif @Test(arguments: [ ["Parcel"], ["Parcel", "--smoke"], ]) func ordinaryArgumentsDoNotStartARelaunchHelper(_ arguments: [String]) throws { #expect(try AppRelaunch.parent(arguments: arguments) == nil) } @Test func relaunchParentMustBeExactAndPositive() throws { #expect(try AppRelaunch.parent(arguments: ["Parcel", AppRelaunch.option, "42"]) == 42) for arguments in [ ["Parcel", AppRelaunch.option], ["Parcel", AppRelaunch.option, "1"], ["Parcel", AppRelaunch.option, "-1"], ["Parcel", AppRelaunch.option, "bad"], ["Parcel", AppRelaunch.option, "42", "extra"], ] { #expect(throws: (any Error).self) { try AppRelaunch.parent(arguments: arguments) } } } @Test func restartUsesTheQuitRestorationBarrier() async throws { let termination = AppTermination(scheduler: TerminationScheduler()) var events: [String] = [] var gate: CheckedContinuation? termination.requestRestart( cleanup: { events.append("restoring") await withCheckedContinuation { gate = $0 } events.append("restored") }, prepare: { events.append("prepare-relaunch"); return {} }, terminate: { events.append("quit") }, report: { Issue.record($0) }) termination.requestRestart( cleanup: {}, prepare: { Issue.record("Duplicate restart"); return {} }, terminate: {}, report: { Issue.record($0) }) for _ in 0..<100 { if gate != nil { break } await Task.yield() } try #require(gate != nil) #expect(events == ["prepare-relaunch", "restoring"]) gate?.resume() for _ in 0..<100 { if termination.canTerminate { break } await Task.yield() } #expect(events == ["prepare-relaunch", "restoring", "restored", "quit"]) } @Test func restartUsesTheQuitTimeoutWithoutRepeatingAfterLateCleanup() async throws { let scheduler = TerminationScheduler() let termination = AppTermination(scheduler: scheduler) var gate: CheckedContinuation? var prepared = 0 var quit = 0 var restored = false termination.requestRestart( cleanup: { await withCheckedContinuation { gate = $0 } restored = true }, prepare: { prepared += 1; return {} }, terminate: { quit += 1 }, report: { Issue.record($0) }) for _ in 0..<100 { if gate != nil { break } await Task.yield() } try #require(gate != nil) scheduler.fire() #expect(termination.didTimeOut) #expect(prepared == 1 && quit == 1) #expect(!restored) gate?.resume() for _ in 0..<100 { if restored { break } await Task.yield() } #expect(restored) #expect(prepared == 1 && quit == 1) } @Test func failedRelaunchPreparationKeepsRunningAndAllowsRetry() async { let scheduler = TerminationScheduler() let termination = AppTermination(scheduler: scheduler) var events: [String] = [] termination.requestRestart( cleanup: { events.append("restored") }, prepare: { throw CocoaError(.fileNoSuchFile) }, terminate: { events.append("quit") }, report: { _ in events.append("error") }) for _ in 0..<100 { if !events.isEmpty { break } await Task.yield() } #expect(events == ["error"]) #expect(!termination.canTerminate) #expect(scheduler.delays.isEmpty) termination.requestRestart( cleanup: { events.append("restored") }, prepare: { events.append("ready"); return {} }, terminate: { events.append("quit") }, report: { Issue.record($0) }) for _ in 0..<100 { if termination.canTerminate { break } await Task.yield() } #expect(events == ["error", "ready", "restored", "quit"]) } @Test func logoutDuringRestartCancelsThePreparedHelper() async throws { let termination = AppTermination(scheduler: TerminationScheduler()) var gate: CheckedContinuation? var cancelled = false var replied = false var quit = false termination.requestRestart( cleanup: { await withCheckedContinuation { gate = $0 } }, prepare: { return { cancelled = true } }, terminate: { quit = true }, report: { Issue.record($0) }) for _ in 0..<100 { if gate != nil { break } await Task.yield() } let continuation = try #require(gate) _ = termination.request(cleanup: {}, reply: { replied = true }) #expect(cancelled) continuation.resume() for _ in 0..<100 { if termination.canTerminate { break } await Task.yield() } #expect(replied) #expect(!quit) } @Test(arguments: [false, true]) func quitAfterHelperReadinessCancelsRelaunchDuringCleanup(timeout: Bool) async throws { let scheduler = TerminationScheduler() let termination = AppTermination(scheduler: scheduler) var gate: CheckedContinuation? var events: [String] = [] termination.requestRestart( cleanup: { events.append("cleanup") await withCheckedContinuation { gate = $0 } }, prepare: { { events.append("cancel-helper") } }, terminate: { events.append("restart") }, report: { Issue.record($0) }) for _ in 0..<100 { if gate != nil { break } await Task.yield() } let continuation = try #require(gate) #expect( termination.requestQuit( cleanup: { Issue.record("Duplicate cleanup") }, terminate: { events.append("quit") }) == .terminateLater) #expect(events == ["cleanup", "cancel-helper"]) if timeout { scheduler.fire() } continuation.resume() for _ in 0..<100 { if termination.canTerminate { break } await Task.yield() } #expect(events == ["cleanup", "cancel-helper", "quit"]) #expect(termination.canTerminate) } @Test(arguments: [false, true]) func restartDuringQuitIsReportedWithoutPreparingHelper(logout: Bool) async throws { let termination = AppTermination(scheduler: TerminationScheduler()) var gate: CheckedContinuation? var reports = 0 let cleanup: @MainActor @Sendable () async -> Void = { await withCheckedContinuation { gate = $0 } } if logout { _ = termination.request(cleanup: cleanup, reply: {}) } else { _ = termination.requestQuit(cleanup: cleanup, terminate: {}) } termination.requestRestart( cleanup: { Issue.record("Restart must not replace pending cleanup") }, prepare: { Issue.record("Restart must not spawn during quit"); return {} }, terminate: {}, report: { _ in reports += 1 }) #expect(reports == 1) for _ in 0..<100 { if gate != nil { break } await Task.yield() } let continuation = try #require(gate) continuation.resume() } @Test func cleanupWaitsForHelperConfirmation() async throws { let termination = AppTermination(scheduler: TerminationScheduler()) var confirmation: CheckedContinuation? var cleaned = false termination.requestRestart( cleanup: { cleaned = true }, prepare: { await withCheckedContinuation { confirmation = $0 }; return {} }, terminate: {}, report: { Issue.record($0) }) for _ in 0..<100 { if confirmation != nil { break } await Task.yield() } let continuation = try #require(confirmation) #expect(!cleaned) #expect(!termination.canTerminate) continuation.resume() for _ in 0..<100 { if termination.canTerminate { break } await Task.yield() } #expect(cleaned) } @Test func quitDuringPreparationCancelsLateHelperWithoutRestarting() async throws { let termination = AppTermination(scheduler: TerminationScheduler()) var confirmation: CheckedContinuation? var cancelled = false var quit = false termination.requestRestart( cleanup: { Issue.record("Restart cleanup must not run") }, prepare: { await withCheckedContinuation { confirmation = $0 }; return { cancelled = true } }, terminate: { Issue.record("Restart callback must not run") }, report: { Issue.record($0) }) for _ in 0..<100 { if confirmation != nil { break } await Task.yield() } let continuation = try #require(confirmation) _ = termination.requestQuit(cleanup: {}, terminate: { quit = true }) continuation.resume() for _ in 0..<100 { if cancelled && quit { break } await Task.yield() } #expect(cancelled && quit) } @Test(arguments: [UInt8(1), UInt8(0)]) func helperReadinessRequiresExactAcknowledgement(byte: UInt8) async throws { let output = Pipe() defer { output.fileHandleForReading.closeFile() } output.fileHandleForWriting.write(Data([byte])) output.fileHandleForWriting.closeFile() if byte == AppRelaunch.ready { try await AppRelaunch.confirmReadiness(descriptor: output.fileHandleForReading.fileDescriptor) } else { await #expect(throws: (any Error).self) { try await AppRelaunch.confirmReadiness(descriptor: output.fileHandleForReading.fileDescriptor) } } } @Test(arguments: [false, true]) func helperReadinessRejectsExitAndTimeout(closed: Bool) async { let output = Pipe() defer { output.fileHandleForReading.closeFile() if !closed { output.fileHandleForWriting.closeFile() } } if closed { output.fileHandleForWriting.closeFile() } await #expect(throws: (any Error).self) { try await AppRelaunch.confirmReadiness( descriptor: output.fileHandleForReading.fileDescriptor, timeoutMilliseconds: 10) } } @Test func unbundledRestartDoesNotPrepareAHelper() async { await #expect(throws: (any Error).self) { _ = try await AppRelaunch.prepare(bundle: .module) } } @Test(arguments: [false, true]) func bundledHelperMustStartAndConfirmReadiness(executable: Bool) async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let contents = root.appendingPathComponent("Parcel.app/Contents") let binaries = contents.appendingPathComponent("MacOS") try FileManager.default.createDirectory(at: binaries, withIntermediateDirectories: true) defer { do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } } let info = ["CFBundleIdentifier": "dev.vinnymac.parcel.restart-test", "CFBundleExecutable": "Parcel"] try PropertyListEncoder().encode(info).write(to: contents.appendingPathComponent("Info.plist")) let program = binaries.appendingPathComponent("Parcel") try Data("#!/bin/sh\nexit 1\n".utf8).write(to: program) try FileManager.default.setAttributes( [.posixPermissions: executable ? 0o700 : 0o600], ofItemAtPath: program.path) let bundle = try #require(Bundle(url: contents.deletingLastPathComponent())) await #expect(throws: (any Error).self) { _ = try await AppRelaunch.prepare(bundle: bundle) } } @Test func restartFailureNoticeIsIsolatedAndConsumedOnce() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } } let config = root.appendingPathComponent("parcel.toml") #expect(try !AppRelaunchFailureNotice.consume(configURL: config)) try AppRelaunchFailureNotice.record(configURL: config) #expect(try AppRelaunchFailureNotice.consume(configURL: config)) #expect(try !AppRelaunchFailureNotice.consume(configURL: config)) } @Test func invalidRestartFailureNoticeIsNotDiscarded() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) defer { do { try FileManager.default.removeItem(at: root) } catch { Issue.record(error) } } let source = root.appendingPathComponent("restart-failure.json") try Data("{\"version\":2}".utf8).write(to: source) #expect(throws: (any Error).self) { try AppRelaunchFailureNotice.consume(configURL: root.appendingPathComponent("parcel.toml")) } #expect(FileManager.default.fileExists(atPath: source.path)) } }