From 7ba3e1ca7eea4922b1ccb4b8eaa20beda8ac8ca6 Mon Sep 17 00:00:00 2001 From: kageroumado Date: Tue, 3 Nov 2026 07:38:48 +0100 Subject: [PATCH 1/4] Terminate the old instance from the run loop so a terminateLater delegate can reply installAndRelaunch() called NSApp.terminate from inside its main-actor job. A delegate that returns .terminateLater and replies from a Task or DispatchQueue.main then never replies: AppKit waits in a nested loop that cannot drain the main queue while that job holds it. The old instance stayed alive running the removed backup, and the fallback relauncher gave up after 30 seconds. Co-Authored-By: Claude Opus 5.5 --- AppUpdater.swift | 22 ++++++++++++++++- README.md | 5 +++- Tests/AppUpdaterTests/AppUpdaterTests.swift | 26 +++++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/AppUpdater.swift b/AppUpdater.swift index b0452bf..35280d6 100644 --- a/AppUpdater.swift +++ b/AppUpdater.swift @@ -1276,10 +1276,30 @@ struct InstallationDriver { launch: { url in try await ApplicationLauncher.launchNewInstance(at: url) }, - terminate: { NSApp.terminate(nil) } + terminate: { ApplicationTerminator.terminateFromRunLoop() } ) } +@MainActor +enum ApplicationTerminator { + /// Terminates the app once the current main-actor job has returned. + /// + /// `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 runs outside the queue. + static func terminateFromRunLoop( + terminate: @escaping @MainActor () -> Void = { NSApp.terminate(nil) } + ) { + // The main run loop runs its blocks on the main thread. + RunLoop.main.perform(inModes: [.default, .modalPanel, .eventTracking]) { + MainActor.assumeIsolated { terminate() } + } + } +} + @MainActor enum ApplicationLauncher { static func launchNewInstance(at url: URL) async throws { diff --git a/README.md b/README.md index b88284e..c1b7cef 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 once its own main-actor job has returned, 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..d8fa0d6 100644 --- a/Tests/AppUpdaterTests/AppUpdaterTests.swift +++ b/Tests/AppUpdaterTests/AppUpdaterTests.swift @@ -1196,6 +1196,32 @@ final class AppUpdaterTests: XCTestCase { ]) } + /// A delegate that returns `.terminateLater` and replies from the main + /// queue: `NSApp.terminate` waits in a nested `.modalPanel` loop, which + /// cannot drain the queue while the job that called it still holds it. + @MainActor + func testTerminationWaitsForTheMainActorJobToReturn() async { + var terminated = false + var queuedReplyRan = false + ApplicationTerminator.terminateFromRunLoop { terminated = true } + XCTAssertFalse(terminated) + + DispatchQueue.main.async { queuedReplyRan = true } + spinModalPanelLoop(until: { terminated }) + XCTAssertTrue(terminated) + XCTAssertFalse(queuedReplyRan) + } + + /// The nested loop `NSApp.terminate` runs while it waits for a reply. + /// Synchronous, so the async test above calls it from inside its job. + @MainActor + private func spinModalPanelLoop(until done: () -> Bool) { + let deadline = Date().addingTimeInterval(1) + while !done(), Date() < deadline { + RunLoop.main.run(mode: .modalPanel, before: deadline) + } + } + @MainActor func testRelaunchRejectsUnreadySpawnedProcess() async { do { From 992ce0264bafdd4724f27ed8e85942dfb60ac9ad Mon Sep 17 00:00:00 2001 From: kageroumado Date: Tue, 3 Nov 2026 19:50:53 +0100 Subject: [PATCH 2/4] Wait for the calling job to return before terminating A run-loop block also fires inside a nested loop the caller starts after installAndRelaunch() returns, such as a modal alert, while its job still holds the main queue. Registering the block from the main queue defers it until that job has returned. The test now checks that a reply queued on the main queue runs inside the termination's nested loop. Co-Authored-By: Claude Opus 5.5 --- AppUpdater.swift | 15 +++++--- Tests/AppUpdaterTests/AppUpdaterTests.swift | 40 ++++++++++++--------- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/AppUpdater.swift b/AppUpdater.swift index 35280d6..b4b119a 100644 --- a/AppUpdater.swift +++ b/AppUpdater.swift @@ -1289,13 +1289,20 @@ enum ApplicationTerminator { /// `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 runs outside the queue. + /// backup. + /// + /// A run-loop block alone also fires inside a nested loop the calling job + /// starts after the install, such as a modal alert, while that job still + /// holds the queue. So the block is registered from the main queue, which + /// runs once the calling job has returned, and then runs outside it. static func terminateFromRunLoop( terminate: @escaping @MainActor () -> Void = { NSApp.terminate(nil) } ) { - // The main run loop runs its blocks on the main thread. - RunLoop.main.perform(inModes: [.default, .modalPanel, .eventTracking]) { - MainActor.assumeIsolated { terminate() } + DispatchQueue.main.async { + // The main run loop runs its blocks on the main thread. + RunLoop.main.perform(inModes: [.default, .modalPanel, .eventTracking]) { + MainActor.assumeIsolated { terminate() } + } } } } diff --git a/Tests/AppUpdaterTests/AppUpdaterTests.swift b/Tests/AppUpdaterTests/AppUpdaterTests.swift index d8fa0d6..f33639d 100644 --- a/Tests/AppUpdaterTests/AppUpdaterTests.swift +++ b/Tests/AppUpdaterTests/AppUpdaterTests.swift @@ -1197,26 +1197,34 @@ final class AppUpdaterTests: XCTestCase { } /// A delegate that returns `.terminateLater` and replies from the main - /// queue: `NSApp.terminate` waits in a nested `.modalPanel` loop, which - /// cannot drain the queue while the job that called it still holds it. + /// queue: `NSApp.terminate` waits in a nested loop for the reply, which + /// can run only once no main-queue job holds the queue. The calling job + /// here keeps it and runs a nested loop of its own, as a host showing a + /// modal alert after the install would. @MainActor - func testTerminationWaitsForTheMainActorJobToReturn() async { - var terminated = false - var queuedReplyRan = false - ApplicationTerminator.terminateFromRunLoop { terminated = true } - XCTAssertFalse(terminated) - - DispatchQueue.main.async { queuedReplyRan = true } - spinModalPanelLoop(until: { terminated }) - XCTAssertTrue(terminated) - XCTAssertFalse(queuedReplyRan) + func testTerminationWaitsForTheCallingJobToReturn() async { + // AppKit makes `.modalPanel` a common mode, which serves the main + // queue, when the application object is created. + _ = NSApplication.shared + var replied: Bool? + await withCheckedContinuation { (continuation: CheckedContinuation) in + ApplicationTerminator.terminateFromRunLoop { + var didReply = false + DispatchQueue.main.async { didReply = true } + self.spinNestedLoop(for: 1, until: { didReply }) + replied = didReply + continuation.resume() + } + spinNestedLoop(for: 0.2, until: { replied != nil }) + XCTAssertNil(replied, "terminated while the calling job held the main queue") + } + XCTAssertEqual(replied, true) } - /// The nested loop `NSApp.terminate` runs while it waits for a reply. - /// Synchronous, so the async test above calls it from inside its job. + /// The `.modalPanel` loop `NSApp.terminate` waits in. @MainActor - private func spinModalPanelLoop(until done: () -> Bool) { - let deadline = Date().addingTimeInterval(1) + private func spinNestedLoop(for seconds: TimeInterval, until done: () -> Bool) { + let deadline = Date().addingTimeInterval(seconds) while !done(), Date() < deadline { RunLoop.main.run(mode: .modalPanel, before: deadline) } From 7ac9159c4a21ed5e23f250e54585b3e524b6e054 Mon Sep 17 00:00:00 2001 From: kageroumado Date: Tue, 3 Nov 2026 22:47:25 +0100 Subject: [PATCH 3/4] Say why termination runs from the run loop Co-Authored-By: Claude Opus 5.5 --- AppUpdater.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/AppUpdater.swift b/AppUpdater.swift index b4b119a..1629daf 100644 --- a/AppUpdater.swift +++ b/AppUpdater.swift @@ -1299,7 +1299,9 @@ enum ApplicationTerminator { terminate: @escaping @MainActor () -> Void = { NSApp.terminate(nil) } ) { DispatchQueue.main.async { - // The main run loop runs its blocks on the main thread. + // The main queue has returned to the run loop by the time this + // block runs, so the delegate's reply can use it. The run loop + // runs blocks on the main thread. RunLoop.main.perform(inModes: [.default, .modalPanel, .eventTracking]) { MainActor.assumeIsolated { terminate() } } From a7c59ba637f2392f02be51b5b6b5d603cc157dae Mon Sep 17 00:00:00 2001 From: kageroumado Date: Wed, 4 Nov 2026 12:39:13 +0100 Subject: [PATCH 4/4] Terminate only when no main-queue job is on the stack A run-loop block also fires inside a nested loop that a later main-queue job runs, such as a modal alert queued behind the install. The block now checks that the main queue is free, by queuing a probe and running one zero-timeout pass of the loop, and otherwise tries again after the current job. The test queues such a job behind the call. Co-Authored-By: Claude Fable 5.1 --- AppUpdater.swift | 43 ++++++++++++++++----- README.md | 4 +- Tests/AppUpdaterTests/AppUpdaterTests.swift | 22 ++++++++--- 3 files changed, 52 insertions(+), 17 deletions(-) diff --git a/AppUpdater.swift b/AppUpdater.swift index 1629daf..4954b49 100644 --- a/AppUpdater.swift +++ b/AppUpdater.swift @@ -1282,7 +1282,7 @@ struct InstallationDriver { @MainActor enum ApplicationTerminator { - /// Terminates the app once the current main-actor job has returned. + /// 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 @@ -1291,22 +1291,47 @@ enum ApplicationTerminator { /// it never arrives and the old instance keeps running from the removed /// backup. /// - /// A run-loop block alone also fires inside a nested loop the calling job - /// starts after the install, such as a modal alert, while that job still - /// holds the queue. So the block is registered from the main queue, which - /// runs once the calling job has returned, and then runs outside it. + /// 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 { - // The main queue has returned to the run loop by the time this - // block runs, so the delegate's reply can use it. The run loop - // runs blocks on the main thread. RunLoop.main.perform(inModes: [.default, .modalPanel, .eventTracking]) { - MainActor.assumeIsolated { terminate() } + 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 diff --git a/README.md b/README.md index c1b7cef..f7d4ab5 100644 --- a/README.md +++ b/README.md @@ -120,8 +120,8 @@ the old instance exits and an armed fallback launches the installed app. > AppUpdater is copying the replacement, the transaction cannot finish or > relaunch the app. Let `installAndRelaunch()` terminate the old instance after > replacement and validation complete. It calls `NSApp.terminate(_:)` from the -> main run loop once its own main-actor job has returned, so a delegate that -> answers `.terminateLater` can reply from a `Task` or the main queue. The call +> 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 f33639d..fafa1fb 100644 --- a/Tests/AppUpdaterTests/AppUpdaterTests.swift +++ b/Tests/AppUpdaterTests/AppUpdaterTests.swift @@ -1198,35 +1198,45 @@ 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. The calling job - /// here keeps it and runs a nested loop of its own, as a host showing a - /// modal alert after the install would. + /// 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 testTerminationWaitsForTheCallingJobToReturn() async { + 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. + /// 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 { - RunLoop.main.run(mode: .modalPanel, before: deadline) + CFRunLoopRunInMode(CFRunLoopMode(RunLoop.Mode.modalPanel.rawValue as CFString), 0, true) + usleep(1000) } }