diff --git a/AppUpdater.swift b/AppUpdater.swift index b0452bf..4954b49 100644 --- a/AppUpdater.swift +++ b/AppUpdater.swift @@ -1276,10 +1276,64 @@ struct InstallationDriver { launch: { url in try await ApplicationLauncher.launchNewInstance(at: url) }, - terminate: { NSApp.terminate(nil) } + terminate: { ApplicationTerminator.terminateFromRunLoop() } ) } +@MainActor +enum ApplicationTerminator { + /// Terminates the app from the main run loop, outside any main-queue job. + /// + /// `installAndRelaunch()` runs inside a main-actor job, which holds the + /// main queue. A delegate that returns `.terminateLater` makes + /// `NSApp.terminate` wait in a nested run loop for a reply, and a reply + /// sent from a `Task` or `DispatchQueue.main` needs that same queue, so + /// it never arrives and the old instance keeps running from the removed + /// backup. + /// + /// A run-loop block fires in any nested loop a main-queue job runs, such + /// as a modal alert, while that job still holds the queue. So the block + /// terminates only when the queue is free, and otherwise tries again once + /// the current job has returned. + static func terminateFromRunLoop( + terminate: @escaping @MainActor () -> Void = { NSApp.terminate(nil) } + ) { + // Registered from the main queue, so the block cannot fire inside the + // calling job. The run loop runs blocks on the main thread. + DispatchQueue.main.async { + RunLoop.main.perform(inModes: [.default, .modalPanel, .eventTracking]) { + MainActor.assumeIsolated { + if isMainQueueFree() { + terminate() + } else { + terminateFromRunLoop(terminate: terminate) + } + } + } + } + } + + /// Whether no main-queue job is on the stack. + /// + /// A job's nested run loop cannot drain the main queue again, so a block + /// queued here runs during one pass of the loop only when the queue is + /// free. The pass uses the current mode, so a modal or tracking loop + /// processes nothing it would not have processed anyway. + private static func isMainQueueFree() -> Bool { + let probe = Probe() + DispatchQueue.main.async { + MainActor.assumeIsolated { probe.ran = true } + } + let mode = CFRunLoopCopyCurrentMode(CFRunLoopGetMain()) ?? .defaultMode + CFRunLoopRunInMode(mode, 0, true) + return probe.ran + } + + private final class Probe { + var ran = false + } +} + @MainActor enum ApplicationLauncher { static func launchNewInstance(at url: URL) async throws { diff --git a/README.md b/README.md index b88284e..f7d4ab5 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,10 @@ the old instance exits and an armed fallback launches the installed app. > must suppress that behavior during installation. If the host exits while > AppUpdater is copying the replacement, the transaction cannot finish or > relaunch the app. Let `installAndRelaunch()` terminate the old instance after -> replacement and validation complete. +> replacement and validation complete. It calls `NSApp.terminate(_:)` from the +> main run loop, outside any main-queue job, so a delegate that answers +> `.terminateLater` can reply from a `Task` or the main queue. The call +> therefore returns before the app quits, and code after the `await` runs. ## Configuration diff --git a/Tests/AppUpdaterTests/AppUpdaterTests.swift b/Tests/AppUpdaterTests/AppUpdaterTests.swift index df9f735..fafa1fb 100644 --- a/Tests/AppUpdaterTests/AppUpdaterTests.swift +++ b/Tests/AppUpdaterTests/AppUpdaterTests.swift @@ -1196,6 +1196,50 @@ final class AppUpdaterTests: XCTestCase { ]) } + /// A delegate that returns `.terminateLater` and replies from the main + /// queue: `NSApp.terminate` waits in a nested loop for the reply, which + /// can run only once no main-queue job holds the queue. Two jobs hold it + /// here with nested loops of their own, as a host showing a modal alert + /// would: the calling job, and a second job queued behind the call. + @MainActor + func testTerminationWaitsForTheMainQueueToBeFree() async { + // AppKit makes `.modalPanel` a common mode, which serves the main + // queue, when the application object is created. + _ = NSApplication.shared + var replied: Bool? + var terminations = 0 + await withCheckedContinuation { (continuation: CheckedContinuation) in + ApplicationTerminator.terminateFromRunLoop { + terminations += 1 + var didReply = false + DispatchQueue.main.async { didReply = true } + self.spinNestedLoop(for: 1, until: { didReply }) + replied = didReply + continuation.resume() + } + DispatchQueue.main.async { + self.spinNestedLoop(for: 0.2, until: { replied != nil }) + XCTAssertNil(replied, "terminated while a later job held the main queue") + } + spinNestedLoop(for: 0.2, until: { replied != nil }) + XCTAssertNil(replied, "terminated while the calling job held the main queue") + } + XCTAssertEqual(replied, true) + XCTAssertEqual(terminations, 1) + } + + /// The `.modalPanel` loop `NSApp.terminate` waits in. Polled with a zero + /// timeout: the run loop's own timeout cannot fire inside a main-queue + /// job, which is where this loop runs. + @MainActor + private func spinNestedLoop(for seconds: TimeInterval, until done: () -> Bool) { + let deadline = Date().addingTimeInterval(seconds) + while !done(), Date() < deadline { + CFRunLoopRunInMode(CFRunLoopMode(RunLoop.Mode.modalPanel.rawValue as CFString), 0, true) + usleep(1000) + } + } + @MainActor func testRelaunchRejectsUnreadySpawnedProcess() async { do {