Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
Keep dictation responsive and add quiet update notifications (#1044)
ALTIC980780b375e9
diff --git a/.github/screenshots/nonmodal-update-prompt.png b/.github/screenshots/nonmodal-update-prompt.pngnew file mode 100644index 00000000..7450d5faBinary files /dev/null and b/.github/screenshots/nonmodal-update-prompt.png differdiff --git a/.github/screenshots/update-topbar-indicator.png b/.github/screenshots/update-topbar-indicator.pngnew file mode 100644index 00000000..ea907994Binary files /dev/null and b/.github/screenshots/update-topbar-indicator.png differdiff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex 17f1a9b4..cff8e548 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -113,6 +113,7 @@A5B000000000000000000017 /* AppUpdater in Frameworks */ = {isa = PBXBuildFile; productRef = 7CE006BC2E80EBE600DDCCD6 /* AppUpdater */; };A5B000000000000000000018 /* MediaRemoteAdapter in Embed Frameworks */ = {isa = PBXBuildFile; productRef = 7C5AF14A2F15041600DE21B0 /* MediaRemoteAdapter */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };A5B000000000000000000023 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7CDB0A2C2F3C4D5600FB7CAD /* XCTest.framework */; };+ D1C7A7100000000000000002 /* UpdatePromptIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1C7A7100000000000000001 /* UpdatePromptIntegrationTests.swift */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -253,6 +254,7 @@A5B00000000000000000000E /* stage-inputs.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "stage-inputs.sh"; sourceTree = "<group>"; };A5B00000000000000000000F /* placeholder.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = placeholder.json; sourceTree = "<group>"; };A5B00000000000000000001D /* FluidASRBaselineTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = FluidASRBaselineTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ D1C7A7100000000000000001 /* UpdatePromptIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdatePromptIntegrationTests.swift; sourceTree = "<group>"; };/* End PBXFileReference section *//* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */@@ -364,6 +366,7 @@children = (7CDB0A262F3C4D5600FB7CAD /* Helpers */,7CDB0A272F3C4D5600FB7CAD /* Resources */,+ D1C7A7100000000000000001 /* UpdatePromptIntegrationTests.swift */,7CDB0A292F3C4D5600FB7CAD /* DictationE2ETests.swift */,CD1C7A0000000000000000B1 /* CustomDictionaryManualEntryTests.swift */,7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */,@@ -719,6 +722,7 @@buildActionMask = 2147483647;files = (7CDB0A2E2F3C4D5600FB7CAD /* AudioFixtureLoader.swift in Sources */,+ D1C7A7100000000000000002 /* UpdatePromptIntegrationTests.swift in Sources */,7CDB0A2D2F3C4D5600FB7CAD /* DictationE2ETests.swift in Sources */,B52000000000000000000002 /* PrivateAIDictationTokenBudgetTests.swift in Sources */,CD1C7A0000000000000000B2 /* CustomDictionaryManualEntryTests.swift in Sources */,diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swiftindex 50206f24..884c9ead 100644--- a/Sources/Fluid/AppDelegate.swift+++ b/Sources/Fluid/AppDelegate.swift@@ -7,7 +7,6 @@import AppKitimport Carbon-import PromiseKitimport SwiftUIimport UserNotifications@@ -34,6 +33,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele}}+ private let updatePromptPresenter = UpdatePromptPresenter.shared+ #if DEBUG+ private var updateUISimulationObserver: NSObjectProtocol?+ #endifprivate var updateCheckTimer: Timer?private var didRevealMainWindowOnLaunch = falseprivate var didRequestMainWindowReopen = false@@ -48,6 +51,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelefunc applicationDidFinishLaunching(_ notification: Notification) {AccessibilityMessagingTimeout.configure()#if DEBUG+ self.updateUISimulationObserver = UpdatePromptSimulation.register(self)+ #endif+ #if DEBUG// Stage 0.5, Trial A, and C2 autoruns must return before Core Audio observers,// logging, AppServices, and UI startup. Each owns one bounded diagnostic stream.if MeetingStage05EvidenceAutorun.startIfRequested() {@@ -136,6 +142,12 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele}func applicationWillTerminate(_ notification: Notification) {+ #if DEBUG+ if let observer = self.updateUISimulationObserver {+ DistributedNotificationCenter.default().removeObserver(observer)+ self.updateUISimulationObserver = nil+ }+ #endifif Self.restartPrepared {// Launch only after this process exits: never overlap two app instances.let helper = Process()@@ -440,153 +452,61 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele// MARK: - Manual Update Check@objc func checkForUpdatesManually() {- // Confirm invocation- DebugLogger.shared.info("🔎 Manual update check triggered", source: "AppDelegate")-- // Get current app version for debugging- let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"- DebugLogger.shared.info(- "Manual update check requested. Current version: \(currentVersion)",- source: "AppDelegate"- )- DebugLogger.shared.info("Checking repository: altic-dev/Fluid-oss", source: "AppDelegate")- DebugLogger.shared.debug("🔍 DEBUG: Manual update check started - Current version: \(currentVersion)", source: "AppDelegate")- DebugLogger.shared.debug("🔍 DEBUG: Repository: altic-dev/Fluid-oss", source: "AppDelegate")- let includePrerelease = SettingsStore.shared.betaReleasesEnabled- DebugLogger.shared.info(- "Beta releases opt-in: \(SettingsStore.shared.betaReleasesEnabled)",- source: "AppDelegate"- )-- Task { @MainActor in- do {- // Use our tolerant updater to handle v-prefixed tags and 2-part versions- try await SimpleUpdater.shared.checkAndUpdate(- owner: "altic-dev",- repo: "Fluid-oss",- includePrerelease: includePrerelease- )- } catch SimpleUpdateError.updateAlreadyInProgress {- DebugLogger.shared.info("Update installation already in progress", source: "AppDelegate")- } catch {- if let pmkError = error as? PMKError, pmkError.isCancelled {- DebugLogger.shared.info("App is already up-to-date", source: "AppDelegate")- let isBeta = SettingsStore.shared.betaReleasesEnabled- self.showUpdateAlert(- title: isBeta ? "No Beta Updates" : "No Updates",- message: isBeta- ? "You're already running the latest build available in the beta channel."- : "You're already running the latest version of Fluid!"- )- } else {- DebugLogger.shared.error("Update check failed: \(error)", source: "AppDelegate")- self.showUpdateAlert(- title: "Update Check Failed",- message: "Unable to check for updates. Please try again later.\n\nError: \(error.localizedDescription)"- )- }- }- }+ SimpleUpdater.shared.checkForUpdatesManually()}// MARK: - Automatic Update Checkprivate func checkForUpdatesAutomatically() {- // Check if we should perform an automatic update check- guard SettingsStore.shared.shouldCheckForUpdates() else {- let reason = !SettingsStore.shared.autoUpdateCheckEnabled ? "disabled by user" : "checked recently"- DebugLogger.shared.debug("Automatic update check skipped (\(reason))", source: "AppDelegate")- return- }-- DebugLogger.shared.info("Scheduling automatic update check...", source: "AppDelegate")-- // Delay check slightly to avoid slowing down app launch+ #if DEBUG+ guard !UpdatePromptSimulation.isEnabled else { return }+ #endif+ guard SettingsStore.shared.shouldCheckForUpdates() else { return }Task {- // Wait 3 seconds after launch before checking+ // Keep the existing launch delay; the updater rechecks current preferences.try? await Task.sleep(nanoseconds: 3_000_000_000)-- DebugLogger.shared.info("Performing automatic update check for altic-dev/Fluid-oss", source: "AppDelegate")-- do {- let includePrerelease = SettingsStore.shared.betaReleasesEnabled- let result = try await SimpleUpdater.shared.checkForUpdate(- owner: "altic-dev",- repo: "Fluid-oss",- includePrerelease: includePrerelease- )-- // Update the last check date regardless of result- await MainActor.run {- SettingsStore.shared.updateLastCheckDate()- }-- if result.hasUpdate {- DebugLogger.shared.info("✅ Update available: \(result.latestVersion)", source: "AppDelegate")-- guard !SimpleUpdater.shared.isUpdateInProgress else {- DebugLogger.shared.debug(- "Update prompt skipped because installation is already in progress",- source: "AppDelegate"- )- return- }-- // Check if user snoozed this version (clicked "Later")- if SettingsStore.shared.shouldShowUpdatePrompt(forVersion: result.latestVersion) {- // Show update notification on main thread- await MainActor.run {- self.showUpdateNotification(version: result.latestVersion)- }- } else {- DebugLogger.shared.debug("Update prompt snoozed for \(result.latestVersion), skipping notification", source: "AppDelegate")- }- } else {- DebugLogger.shared.info("✅ App is up to date", source: "AppDelegate")- }- } catch {- // Silently log the error, don't bother the user with failed automatic checks- DebugLogger.shared.debug("Automatic update check failed: \(error.localizedDescription)", source: "AppDelegate")-- // Still update last check date to avoid hammering the API on failure- await MainActor.run {- SettingsStore.shared.updateLastCheckDate()- }- }+ guard !Task.isCancelled, SettingsStore.shared.shouldCheckForUpdates() else { return }+ SimpleUpdater.shared.checkForUpdatesAutomatically()}}@MainActor- private func showUpdateNotification(version: String) {- DebugLogger.shared.info("Showing update notification for version \(version)", source: "AppDelegate")-- let alert = NSAlert()- alert.messageText = "Update Available"- alert.informativeText = "FluidVoice \(version) is now available. Would you like to install it now?\n\nThe app will restart automatically after installation."- alert.alertStyle = .informational- alert.addButton(withTitle: "Install Now")- alert.addButton(withTitle: "Later")-- let response = alert.runModal()-- if response == .alertFirstButtonReturn {- DebugLogger.shared.info("User chose to install update now", source: "AppDelegate")- SettingsStore.shared.clearUpdateSnooze() // Clear snooze since they're installing- self.checkForUpdatesManually()- } else {- DebugLogger.shared.info("User postponed update for 24 hours", source: "AppDelegate")- SettingsStore.shared.snoozeUpdatePrompt(forVersion: version)- }+ private func showUpdateAlert(title: String, message: String) {+ DebugLogger.shared.info("🔔 Showing alert: \(title)", source: "AppDelegate")+ self.updatePromptPresenter.presentFloatingPrompt(+ title: title,+ message: message,+ actions: [FloatingPromptAction(title: "OK") {}]+ )}+ #if DEBUG@MainActor- private func showUpdateAlert(title: String, message: String) {- DebugLogger.shared.info("🔔 Showing alert: \(title)", source: "AppDelegate")- let alert = NSAlert()- alert.messageText = title- alert.informativeText = message- alert.alertStyle = .informational- alert.addButton(withTitle: "OK")- alert.runModal()+ func simulateUpdateUI(_ scenario: String) {+ guard UpdatePromptSimulation.isEnabled else { return }+ switch scenario {+ case "offer":+ guard !SimpleUpdater.shared.isUpdateInProgress else { return }+ SimpleUpdater.shared.simulationHasUpdate = true+ SimpleUpdater.shared.checkForUpdatesAutomatically()+ case "manual":+ SimpleUpdater.shared.simulationHasUpdate = true+ self.checkForUpdatesManually()+ case "no-update":+ SimpleUpdater.shared.simulationHasUpdate = false+ self.checkForUpdatesManually()+ case "progress":+ Task { try? await SimpleUpdater.shared.checkAndUpdate(owner: "altic-dev", repo: "Fluid-oss") }+ case "failure":+ SimpleUpdater.shared.finishSimulatedUpdate()+ self.showUpdateAlert(title: "Update Check Failed", message: "Simulated download failure. No update was downloaded or installed.")+ case "dismiss":+ SimpleUpdater.shared.finishSimulatedUpdate()+ self.updatePromptPresenter.dismissAll()+ default:+ return+ }+ DebugLogger.shared.info("Update UI simulation: \(scenario)", source: "AppDelegate")}+ #endif}diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 2d250612..533b6df3 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -2023,6 +2023,8 @@ struct ContentView: View {.accessibilityLabel(self.columnVisibility == .detailOnly ? "Show sidebar" : "Hide sidebar")}ToolbarItemGroup(placement: .primaryAction) {+ UpdateAvailableToolbarButton()+self.todayStatsButton.buttonStyle(.automatic)@@ -6140,6 +6142,28 @@ private extension ContentView {}}+private struct UpdateAvailableToolbarButton: View {+ @Environment(\.theme) private var theme+ @ObservedObject private var updater = SimpleUpdater.shared++ var body: some View {+ if let version = self.updater.availableUpdateVersion {+ Button {+ self.updater.showAvailableUpdate()+ } label: {+ Image(systemName: "arrow.down.circle.fill")+ .fluidToolbarIcon()+ .foregroundStyle(self.theme.palette.accent)+ }+ .buttonStyle(.automatic)+ .disabled(self.updater.isCheckingForUpdates || self.updater.isUpdateInProgress)+ .help("Update available: \(version). View update.")+ .accessibilityLabel("Update available: \(version)")+ .accessibilityHint("View update details")+ }+ }+}+private struct TodayStatsToolbarButton: View {@ObservedObject private var historyStore = TranscriptionHistoryStore.shareddiff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swiftindex c95e0f84..7b6a6cf0 100644--- a/Sources/Fluid/Persistence/BackupService.swift+++ b/Sources/Fluid/Persistence/BackupService.swift@@ -56,6 +56,8 @@ struct SettingsBackupPayload: Codable, Equatable {// from this build decode on app versions that require it. Ignored on restore.let transcriptionSoundIndependentVolume: Bool?let autoUpdateCheckEnabled: Bool+ // Missing in older backups; preserve the user's current preference on restore.+ var showUpdatePopups: Bool? = nillet betaReleasesEnabled: Boollet enableDebugLogs: Boollet shareAnonymousAnalytics: Booldiff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex 4e8ab39b..d9d9f132 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -11,6 +11,17 @@ import FluidAudio// swiftlint:disable file_length type_body_lengthfinal class SettingsStore: ObservableObject {+ enum UpdateKeys {+ static let autoUpdateCheckEnabled = "AutoUpdateCheckEnabled"+ static let showUpdatePopups = "ShowUpdatePopups"+ static let popupPreferenceRevision = "UpdatePopupPreferenceRevision"+ static let betaReleasesEnabled = "BetaReleasesEnabled"+ static let channelPreferenceRevision = "UpdateChannelPreferenceRevision"+ static let lastUpdateCheckDate = "LastUpdateCheckDate"+ static let updatePromptSnoozedUntil = "UpdatePromptSnoozedUntil"+ static let snoozedUpdateVersion = "SnoozedUpdateVersion"+ }+static let microphonePriorityMigrationVersion = 4static let shared = SettingsStore()@@ -2753,15 +2764,33 @@ final class SettingsStore: ObservableObject {return value as? Bool ?? true // Default to enabled}set {+ guard newValue != self.autoUpdateCheckEnabled else { return }+ objectWillChange.send()self.defaults.set(newValue, forKey: Keys.autoUpdateCheckEnabled)}}+ var showUpdatePopups: Bool {+ get { self.defaults.object(forKey: Keys.showUpdatePopups) as? Bool ?? true }+ set {+ guard newValue != self.showUpdatePopups else { return }+ objectWillChange.send()+ self.defaults.set(newValue, forKey: Keys.showUpdatePopups)+ let revision = self.defaults.integer(forKey: UpdateKeys.popupPreferenceRevision)+ self.defaults.set(revision &+ 1, forKey: UpdateKeys.popupPreferenceRevision)+ Task { @MainActor in+ SimpleUpdater.shared.automaticUpdatePopupPreferenceDidChange(isEnabled: newValue)+ }+ }+ }+var lastUpdateCheckDate: Date? {get {return self.defaults.object(forKey: Keys.lastUpdateCheckDate) as? Date}set {+ guard newValue != self.lastUpdateCheckDate else { return }+ objectWillChange.send()self.defaults.set(newValue, forKey: Keys.lastUpdateCheckDate)}}@@ -3580,6 +3609,7 @@ final class SettingsStore: ObservableObject {transcriptionSoundVolume: self.transcriptionSoundVolume,transcriptionSoundIndependentVolume: false,autoUpdateCheckEnabled: self.autoUpdateCheckEnabled,+ showUpdatePopups: self.showUpdatePopups,betaReleasesEnabled: self.betaReleasesEnabled,enableDebugLogs: self.enableDebugLogs,shareAnonymousAnalytics: self.shareDetailedAnalytics,@@ -3726,6 +3756,9 @@ final class SettingsStore: ObservableObject {self.transcriptionStartSound = payload.transcriptionStartSoundself.transcriptionSoundVolume = payload.transcriptionSoundVolumeself.autoUpdateCheckEnabled = payload.autoUpdateCheckEnabled+ if let showUpdatePopups = payload.showUpdatePopups {+ self.showUpdatePopups = showUpdatePopups+ }self.betaReleasesEnabled = payload.betaReleasesEnabledself.enableDebugLogs = payload.enableDebugLogsself.shareDetailedAnalytics = payload.shareAnonymousAnalytics@@ -5822,11 +5855,12 @@ private extension SettingsStore {static let spokenSendPhrase = "SpokenSendPhrase"static let spokenSendKey = "SpokenSendKey"static let reliablePasteMigrationV1 = "TextInsertionModeMigratedToReliablePasteV1"- static let autoUpdateCheckEnabled = "AutoUpdateCheckEnabled"- static let betaReleasesEnabled = "BetaReleasesEnabled"- static let lastUpdateCheckDate = "LastUpdateCheckDate"- static let updatePromptSnoozedUntil = "UpdatePromptSnoozedUntil"- static let snoozedUpdateVersion = "SnoozedUpdateVersion"+ static let autoUpdateCheckEnabled = UpdateKeys.autoUpdateCheckEnabled+ static let showUpdatePopups = UpdateKeys.showUpdatePopups+ static let betaReleasesEnabled = UpdateKeys.betaReleasesEnabled+ static let lastUpdateCheckDate = UpdateKeys.lastUpdateCheckDate+ static let updatePromptSnoozedUntil = UpdateKeys.updatePromptSnoozedUntil+ static let snoozedUpdateVersion = UpdateKeys.snoozedUpdateVersionstatic let playgroundUsed = "PlaygroundUsed"static let onboardingCompleted = "OnboardingCompleted"static let onboardingGeneration = "OnboardingGeneration"@@ -6081,10 +6115,16 @@ extension SettingsStore {return value as? Bool ?? false // Default to stable-only updates}set {+ guard newValue != self.betaReleasesEnabled else { return }objectWillChange.send()self.defaults.set(newValue, forKey: Keys.betaReleasesEnabled)+ let revision = self.defaults.integer(forKey: UpdateKeys.channelPreferenceRevision)+ self.defaults.set(revision &+ 1, forKey: UpdateKeys.channelPreferenceRevision)self.lastUpdateCheckDate = nilself.clearUpdateSnooze()+ Task { @MainActor in+ SimpleUpdater.shared.updateChannelDidChange()+ }}}diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swiftindex 03518095..ce3b4a12 100644--- a/Sources/Fluid/Services/MenuBarManager.swift+++ b/Sources/Fluid/Services/MenuBarManager.swift@@ -1,6 +1,5 @@import AppKitimport Combine-import PromiseKitimport SwiftUIenum MenuBarNavigationDestination: String {@@ -1256,38 +1255,7 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {@objc private func checkForUpdates(_ sender: Any?) {DebugLogger.shared.info("🔎 Menu action: Check for Updates…", source: "MenuBarManager")- // Call the AppDelegate's manual update check method if available- if let appDelegate = NSApp.delegate as? AppDelegate {- appDelegate.checkForUpdatesManually()- return- }-- // Fallback: perform direct, tolerant check so the menu item always does something- Task { @MainActor in- do {- try await SimpleUpdater.shared.checkAndUpdate(- owner: "altic-dev",- repo: "Fluid-oss",- includePrerelease: SettingsStore.shared.betaReleasesEnabled- )- } catch SimpleUpdateError.updateAlreadyInProgress {- DebugLogger.shared.info("Update installation already in progress", source: "MenuBarManager")- } catch {- let msg = NSAlert()- if let pmkError = error as? PMKError, pmkError.isCancelled {- let isBeta = SettingsStore.shared.betaReleasesEnabled- msg.messageText = isBeta ? "You’re Up To Date (Beta)" : "You’re Up To Date"- msg.informativeText = isBeta- ? "You're already running the latest build available in the beta channel."- : "You're already running the latest version of FluidVoice."- } else {- msg.messageText = "Update Check Failed"- msg.informativeText = "Unable to check for updates. Please try again later.\n\nError: \(error.localizedDescription)"- }- msg.alertStyle = .informational- msg.runModal()- }- }+ SimpleUpdater.shared.checkForUpdatesManually()}@objc private func rollbackToPreviousVersion(_ sender: Any?) {diff --git a/Sources/Fluid/Services/SimpleUpdater.swift b/Sources/Fluid/Services/SimpleUpdater.swiftindex 1f2ccdf2..89c16d2c 100644--- a/Sources/Fluid/Services/SimpleUpdater.swift+++ b/Sources/Fluid/Services/SimpleUpdater.swift@@ -1,4 +1,5 @@import AppKit+import Combineimport Foundationimport PromiseKit@@ -8,6 +9,7 @@ enum SimpleUpdateError: Error, LocalizedError {case jsonDecodingcase noSuitableReleasecase noAsset+ case releaseChangedcase updateAlreadyInProgresscase downloadFailedcase unzipFailed@@ -22,6 +24,7 @@ enum SimpleUpdateError: Error, LocalizedError {case .invalidResponse: return "Invalid HTTP response from GitHub."case .jsonDecoding: return "The data couldn’t be read because it isn’t in the correct format."case .noSuitableRelease: return "No suitable release found."+ case .releaseChanged: return "A different update is now available. Please review it before installing."case .noAsset: return "No matching asset found in the latest release."case .updateAlreadyInProgress: return "An update is already being installed."case .downloadFailed: return "Failed to download update."@@ -109,7 +112,7 @@ private struct SemanticVersion: Comparable {}@MainActor-final class SimpleUpdater {+final class SimpleUpdater: ObservableObject {struct ReleaseBuildOption {let version: Stringlet url: URL@@ -125,7 +128,47 @@ final class SimpleUpdater {}static let shared = SimpleUpdater()- init() {}+ init(+ session: URLSession = .shared,+ defaults: UserDefaults = .standard,+ promptPresenter: UpdatePromptPresenter = .shared+ ) {+ self.updateSession = session+ self.updateDefaults = defaults+ self.updatePrompts = promptPresenter+ }++ @Published private(set) var availableUpdateVersion: String?+ @Published private(set) var isCheckingForUpdates = false+ @Published private(set) var isUpdateInProgress = false+ private let updateSession: URLSession+ private let updateDefaults: UserDefaults+ private let updatePrompts: UpdatePromptPresenter+ private var checkTask: Task<Void, Never>?+ private var checkID: UUID?+ private var checkIsExplicit = false+ private var checkChannelRevision: Int?+ private var availableChannelRevision: Int?+ #if DEBUG+ var simulationInstallHandler: (@MainActor () async throws -> Void)?+ var simulationHasUpdate = true+ #endif++ private var betaChannel: Bool {+ self.updateDefaults.bool(forKey: SettingsStore.UpdateKeys.betaReleasesEnabled)+ }++ private var channelRevision: Int {+ self.updateDefaults.integer(forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ }++ private var popupRevision: Int {+ self.updateDefaults.integer(forKey: SettingsStore.UpdateKeys.popupPreferenceRevision)+ }++ private var popupsEnabled: Bool {+ self.updateDefaults.object(forKey: SettingsStore.UpdateKeys.showUpdatePopups) as? Bool ?? true+ }private let fileManager = FileManager.defaultprivate let maxRollbackBackups = 3@@ -133,10 +176,6 @@ final class SimpleUpdater {private var updateOperationGate = UpdateOperationGate()private var updateStatusWindow: NSWindow?- var isUpdateInProgress: Bool {- return self.updateOperationGate.isActive- }-private var installedAppName: String {return Bundle.main.bundleURL.deletingPathExtension().lastPathComponent}@@ -159,6 +198,11 @@ final class SimpleUpdater {throw SimpleUpdateError.updateAlreadyInProgress}+ self.isUpdateInProgress = true+ self.cancelUpdateCheck()+ self.availableUpdateVersion = nil+ self.availableChannelRevision = nil+ self.updatePrompts.dismissUpdateOffers()var shouldKeepOperationActive = falsedefer {if !shouldKeepOperationActive {@@ -307,6 +351,12 @@ final class SimpleUpdater {throw SimpleUpdateError.updateAlreadyInProgress}+ #if DEBUG+ if self === Self.shared, UpdatePromptSimulation.isEnabled {+ return (self.simulationHasUpdate, "Simulation")+ }+ #endif+let releases = try await self.fetchReleases(owner: owner, repo: repo)guard let latest = self.selectLatestRelease(@@ -332,15 +382,182 @@ final class SimpleUpdater {return (latestVersion > current, latestTag)}+ func checkForUpdatesAutomatically() {+ guard self.updateDefaults.object(forKey: SettingsStore.UpdateKeys.autoUpdateCheckEnabled) as? Bool ?? true else { return }+ self.startUpdateCheck(explicit: false)+ }++ func checkForUpdatesManually() {+ self.startUpdateCheck(explicit: true)+ }++ func showAvailableUpdate() {+ guard !self.isUpdateInProgress,+ let version = self.availableUpdateVersion,+ self.availableChannelRevision == self.channelRevision+ else { return }+ self.presentUpdateOffer(version: version, automatic: false)+ }++ func automaticUpdatePopupPreferenceDidChange(isEnabled _: Bool) {+ // The callback may arrive after another toggle. Read the current preference.+ if !self.popupsEnabled { self.updatePrompts.dismissAutomaticUpdateOffers() }+ }++ func updateChannelDidChange() {+ let revision = self.channelRevision+ if self.checkID != nil, self.checkChannelRevision != revision { self.cancelUpdateCheck() }+ if self.availableChannelRevision != revision {+ self.availableUpdateVersion = nil+ self.availableChannelRevision = nil+ self.updatePrompts.dismissUpdateOffers()+ }+ }++ private func startUpdateCheck(explicit: Bool) {+ guard !self.isUpdateInProgress else { return }+ if explicit { self.updatePrompts.dismissUpdateCheckResults() }+ self.updateChannelDidChange()+ if self.checkID != nil {+ self.checkIsExplicit = self.checkIsExplicit || explicit+ return+ }+ let requestID = UUID()+ let channel = self.betaChannel+ let channelRevision = self.channelRevision+ let popupRevision = self.popupRevision+ self.checkID = requestID+ self.checkChannelRevision = channelRevision+ self.checkIsExplicit = explicit+ self.isCheckingForUpdates = true+ self.checkTask = Task { [weak self] in+ guard let self else { return }+ defer {+ if self.checkID == requestID { self.cancelUpdateCheck() }+ }+ do {+ let result = try await self.checkForUpdate(owner: "altic-dev", repo: "Fluid-oss", includePrerelease: channel)+ guard self.checkID == requestID, self.channelRevision == channelRevision, !self.isUpdateInProgress else { return }+ self.recordUpdateCheckDate()+ self.availableChannelRevision = channelRevision+ self.availableUpdateVersion = result.hasUpdate ? result.latestVersion : nil+ if result.hasUpdate {+ if self.checkIsExplicit {+ self.presentUpdateOffer(version: result.latestVersion, automatic: false)+ } else if self.popupsEnabled, self.popupRevision == popupRevision,+ self.updateDefaults.object(forKey: SettingsStore.UpdateKeys.autoUpdateCheckEnabled) as? Bool ?? true,+ self.shouldShowUpdateOffer(version: result.latestVersion)+ {+ self.presentUpdateOffer(version: result.latestVersion, automatic: true)+ }+ } else {+ self.updatePrompts.dismissUpdateOffers()+ if self.checkIsExplicit {+ self.showUpdateCheckResult(title: channel ? "No Beta Updates" : "No Updates", message: "You're already running the latest available version of FluidVoice.")+ }+ }+ } catch {+ guard self.checkID == requestID, self.channelRevision == channelRevision, !self.isUpdateInProgress else { return }+ self.recordUpdateCheckDate()+ self.availableUpdateVersion = nil+ self.availableChannelRevision = nil+ self.updatePrompts.dismissUpdateOffers()+ if self.checkIsExplicit {+ self.showUpdateCheckResult(title: "Update Check Failed", message: "Unable to check for updates. Please try again later.\n\nError: \(error.localizedDescription)")+ } else {+ DebugLogger.shared.debug("Automatic update check failed: \(error.localizedDescription)", source: "SimpleUpdater")+ }+ }+ }+ }++ private func recordUpdateCheckDate() {+ #if DEBUG+ if self === Self.shared, UpdatePromptSimulation.isEnabled { return }+ #endif+ self.updateDefaults.set(Date(), forKey: SettingsStore.UpdateKeys.lastUpdateCheckDate)+ }++ private func cancelUpdateCheck() {+ self.checkID = nil+ self.checkChannelRevision = nil+ self.checkTask?.cancel()+ self.checkTask = nil+ self.isCheckingForUpdates = false+ self.checkIsExplicit = false+ }++ private func shouldShowUpdateOffer(version: String) -> Bool {+ if let snoozed = self.updateDefaults.string(forKey: SettingsStore.UpdateKeys.snoozedUpdateVersion), snoozed != version { return true }+ guard let until = self.updateDefaults.object(forKey: SettingsStore.UpdateKeys.updatePromptSnoozedUntil) as? Date else { return true }+ return Date() >= until+ }++ private func presentUpdateOffer(version: String, automatic: Bool) {+ let channel = self.betaChannel+ let revision = self.channelRevision+ self.updatePrompts.presentFloatingPrompt(+ title: "Update Available",+ message: "FluidVoice \(version) is now available. The app will restart automatically after installation.",+ actions: [+ FloatingPromptAction(title: "Install Now") { [weak self] in+ guard let self, self.availableUpdateVersion == version, self.channelRevision == revision, !self.isUpdateInProgress else { return }+ self.installApprovedUpdate(version: version, channel: channel)+ },+ FloatingPromptAction(title: "Later") { [weak self] in+ guard let self, self.availableUpdateVersion == version, self.channelRevision == revision else { return }+ #if DEBUG+ if self === Self.shared, UpdatePromptSimulation.isEnabled { return }+ #endif+ self.updateDefaults.set(version, forKey: SettingsStore.UpdateKeys.snoozedUpdateVersion)+ self.updateDefaults.set(Date().addingTimeInterval(24 * 60 * 60), forKey: SettingsStore.UpdateKeys.updatePromptSnoozedUntil)+ },+ ],+ isAutomaticUpdateOffer: automatic+ )+ }++ private func installApprovedUpdate(version: String, channel: Bool) {+ Task {+ do {+ try await self.checkAndUpdate(owner: "altic-dev", repo: "Fluid-oss", includePrerelease: channel, expectedVersion: version)+ } catch SimpleUpdateError.releaseChanged {+ if self.availableUpdateVersion != nil, self.availableChannelRevision == self.channelRevision {+ self.showAvailableUpdate()+ } else {+ self.checkForUpdatesManually()+ }+ } catch SimpleUpdateError.updateAlreadyInProgress {+ return+ } catch {+ let cancelled = (error as? PMKError)?.isCancelled == true+ self.showUpdateCheckResult(+ title: cancelled ? "No Updates" : "Update Failed",+ message: cancelled ? "You're already running the latest available version of FluidVoice."+ : "Unable to install the update. Please try again later.\n\nError: \(error.localizedDescription)"+ )+ }+ }+ }++ private func showUpdateCheckResult(title: String, message: String) {+ self.updatePrompts.presentFloatingPrompt(title: title, message: message, actions: [FloatingPromptAction(title: "OK") {}])+ }+func checkAndUpdate(owner: String,repo: String,- includePrerelease: Bool = false+ includePrerelease: Bool = false,+ expectedVersion: String? = nil) async throws {guard self.updateOperationGate.begin() else {throw SimpleUpdateError.updateAlreadyInProgress}+ let approvedChannelRevision = self.channelRevision+ self.isUpdateInProgress = true+ self.cancelUpdateCheck()+ self.updatePrompts.dismissUpdateOffers()var shouldKeepOperationActive = falsedefer {if !shouldKeepOperationActive {@@ -348,6 +565,14 @@ final class SimpleUpdater {}}+ #if DEBUG+ if self === Self.shared, UpdatePromptSimulation.isEnabled {+ self.showUpdateInstallStatus(version: "Simulation")+ shouldKeepOperationActive = true+ return+ }+ #endif+let releases = try await self.fetchReleases(owner: owner, repo: repo)guard let latest = self.selectLatestRelease(@@ -372,9 +597,33 @@ final class SimpleUpdater {let currentBundle = Bundle.main// up to dateif !(latestVersion > current) {+ self.availableUpdateVersion = nil+ self.availableChannelRevision = nilthrow PMKError.cancelled // mimic AppUpdater semantics for up-to-date}+ if expectedVersion != nil, self.channelRevision != approvedChannelRevision {+ self.availableUpdateVersion = nil+ self.availableChannelRevision = nil+ throw SimpleUpdateError.releaseChanged+ }+ if let expectedVersion, expectedVersion != latestTag {+ self.availableChannelRevision = self.channelRevision+ self.availableUpdateVersion = latestTag+ throw SimpleUpdateError.releaseChanged+ }+ if expectedVersion != nil, self.betaChannel != includePrerelease {+ throw SimpleUpdateError.releaseChanged+ }+ self.updateDefaults.removeObject(forKey: SettingsStore.UpdateKeys.updatePromptSnoozedUntil)+ self.updateDefaults.removeObject(forKey: SettingsStore.UpdateKeys.snoozedUpdateVersion)+ #if DEBUG+ if let simulationInstallHandler {+ try await simulationInstallHandler()+ return+ }+ #endif+// Find asset matching: "{repo-lower}-{version-from-tag}.*" and zip preferredlet rawVersion = latestTag.hasPrefix("v") ? String(latestTag.dropFirst()) : latestTaglet prefix = "\(repo.lowercased())-\(rawVersion)"@@ -470,6 +719,7 @@ final class SimpleUpdater {// MARK: - Helpersfunc showUpdateInstallStatus(version: String) {+ self.updatePrompts.dismissAll()guard self.updateStatusWindow == nil else { return }let panel = NSPanel(@@ -527,8 +777,16 @@ final class SimpleUpdater {self.updateStatusWindow = panel}+ #if DEBUG+ func finishSimulatedUpdate() {+ guard UpdatePromptSimulation.isEnabled else { return }+ self.resetUpdateOperation()+ }+ #endif+private func resetUpdateOperation() {self.updateOperationGate.finish()+ self.isUpdateInProgress = falseself.dismissUpdateInstallStatus()}@@ -543,7 +801,7 @@ final class SimpleUpdater {throw SimpleUpdateError.invalidURL}- let (data, response) = try await URLSession.shared.data(from: releasesURL)+ let (data, response) = try await self.updateSession.data(from: releasesURL)guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {throw SimpleUpdateError.invalidResponse}@@ -896,6 +1154,9 @@ final class SimpleUpdater {finalAppURL = installedAppURL}+ self.availableUpdateVersion = nil+ self.availableChannelRevision = nil+// Installation is finished. Do not leave the floating progress window owned by// the old process until it exits: quitting may be delayed or cancelled by AppKit.// Keep the operation gate active so that old process cannot start another install.diff --git a/Sources/Fluid/UI/SettingsSearch.swift b/Sources/Fluid/UI/SettingsSearch.swiftindex db540366..6408fe95 100644--- a/Sources/Fluid/UI/SettingsSearch.swift+++ b/Sources/Fluid/UI/SettingsSearch.swift@@ -253,7 +253,7 @@ enum SettingsSearchIndex {.init(target: .automaticUpdates,title: "Automatic Updates",- terms: ["beta releases check for updates release notes rollback previous builds version"]+ terms: ["beta releases check for updates release notes rollback previous builds version popup pop-ups notifications update available"]),.init(target: .analyticsPrivacy,diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex 7885038c..51a9f1ea 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -7,7 +7,6 @@import AppKitimport AVFoundation-import PromiseKitimport SwiftUIimport UniformTypeIdentifiers@@ -28,6 +27,7 @@ struct SettingsView: View {@Environment(\.theme) private var theme@Environment(\.accessibilityReduceMotion) private var accessibilityReduceMotion@ObservedObject private var settings = SettingsStore.shared+ @ObservedObject private var updater = SimpleUpdater.sharedlet selectedSection: SettingsSectionlet searchResults: [SettingsSearchResult]let searchScrollRequest: Int@@ -403,6 +403,27 @@ struct SettingsView: View {.labelsHidden()}+ HStack(alignment: .center) {+ VStack(alignment: .leading, spacing: 2) {+ Text("Show update pop-ups")+ .font(self.theme.typography.bodyStrong)+ .foregroundStyle(self.settingsTitleText)+ Text("When off, available updates appear in the top bar and here without automatic pop-ups.")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.settingsSecondaryText)+ }++ Spacer()++ Toggle("Show update pop-ups", isOn: Binding(+ get: { self.settings.showUpdatePopups },+ set: { self.settings.showUpdatePopups = $0 }+ ))+ .toggleStyle(.switch)+ .tint(self.theme.palette.accent)+ .labelsHidden()+ }+HStack(alignment: .center) {VStack(alignment: .leading, spacing: 2) {Text("Beta Releases")@@ -442,42 +463,33 @@ struct SettingsView: View {}.settingsSearchTarget(.automaticUpdates)+ if let version = self.updater.availableUpdateVersion {+ HStack(spacing: 10) {+ Label("Update available · \(version)", systemImage: "arrow.down.circle")+ .font(self.theme.typography.bodyStrong)+ .foregroundStyle(self.theme.palette.accent)+ .fixedSize(horizontal: false, vertical: true)++ Spacer()++ Button("View Update") {+ self.updater.showAvailableUpdate()+ }+ .fluidOutlinedButton()+ .controlSize(.regular)+ .disabled(self.updater.isCheckingForUpdates || self.updater.isUpdateInProgress)+ }+ }+// Update ButtonsHStack(spacing: 10) {Button("Check for Updates") {- Task { @MainActor in- do {- let includePrerelease = SettingsStore.shared.betaReleasesEnabled- try await SimpleUpdater.shared.checkAndUpdate(- owner: "altic-dev",- repo: "Fluid-oss",- includePrerelease: includePrerelease- )- } catch SimpleUpdateError.updateAlreadyInProgress {- DebugLogger.shared.info(- "Update installation already in progress",- source: "SettingsView"- )- } catch {- let msg = NSAlert()- if let pmkError = error as? PMKError, pmkError.isCancelled {- let isBeta = SettingsStore.shared.betaReleasesEnabled- msg.messageText = isBeta ? "You're Up To Date (Beta)" : "You're Up To Date"- msg.informativeText = isBeta- ? "You're already running the latest build available in the beta channel."- : "You're already running the latest version of FluidVoice."- } else {- msg.messageText = "Update Check Failed"- msg.informativeText = "Unable to check for updates. Please try again later.\n\nError: \(error.localizedDescription)"- }- msg.alertStyle = .informational- msg.runModal()- }- }+ self.updater.checkForUpdatesManually()}.buttonStyle(.borderedProminent).tint(self.theme.palette.accent).controlSize(.regular)+ .disabled(self.updater.isCheckingForUpdates || self.updater.isUpdateInProgress)Button("Release Notes") {if let url = URL(string: "https://github.com/altic-dev/Fluid-oss/releases") {diff --git a/Sources/Fluid/UI/UpdatePromptPresenter.swift b/Sources/Fluid/UI/UpdatePromptPresenter.swiftnew file mode 100644index 00000000..d8c99ba4--- /dev/null+++ b/Sources/Fluid/UI/UpdatePromptPresenter.swift@@ -0,0 +1,242 @@+import AppKit++/// Adapted from PR #837. Prompt presentation never takes focus or enters a modal loop.+@MainActor+final class UpdatePromptPresenter {+ static let shared = UpdatePromptPresenter()+ private var floatingPromptWindow: FloatingPromptPanel?+ private var floatingPromptQueue: [FloatingPrompt] = []+ private static let maxQueuedFloatingPrompts = 4++ func presentFloatingPrompt(+ title: String,+ message: String,+ actions: [FloatingPromptAction],+ isAutomaticUpdateOffer: Bool = false+ ) {+ guard !actions.isEmpty else { return }+ if let index = self.floatingPromptQueue.firstIndex(where: { $0.title == title }) {+ let existing = self.floatingPromptQueue[index]+ let promotesToManual = existing.isAutomaticUpdateOffer && !isAutomaticUpdateOffer+ guard existing.message != message || promotesToManual else { return }+ self.floatingPromptQueue[index] = FloatingPrompt(+ title: title,+ message: message,+ actions: actions,+ isAutomaticUpdateOffer: existing.isAutomaticUpdateOffer && isAutomaticUpdateOffer+ )+ if index == 0 {+ let wasKey = self.floatingPromptWindow?.isKeyWindow == true+ self.floatingPromptWindow?.close()+ self.floatingPromptWindow = nil+ self.showNextFloatingPromptIfIdle()+ if wasKey { self.floatingPromptWindow?.makeKey() }+ }+ return+ }+ guard self.floatingPromptQueue.count < Self.maxQueuedFloatingPrompts else {+ return+ }++ self.floatingPromptQueue.append(FloatingPrompt(+ title: title,+ message: message,+ actions: actions,+ isAutomaticUpdateOffer: isAutomaticUpdateOffer+ ))+ self.showNextFloatingPromptIfIdle()+ }++ private func showNextFloatingPromptIfIdle() {+ guard self.floatingPromptWindow == nil, let prompt = self.floatingPromptQueue.first else { return }++ let title = prompt.title+ let message = prompt.message+ let actions = prompt.actions+ let margin: CGFloat = 22+ let textLeading: CGFloat = 92+ let buttonHeight: CGFloat = 30+ let buttonSpacing: CGFloat = 10++ let buttons = actions.enumerated().map { index, action in+ let button = FloatingPromptButton(title: action.title) { [weak self] in+ guard let self, self.floatingPromptQueue.first?.id == prompt.id else { return }+ self.finishVisibleFloatingPrompt()+ action.handler()+ self.showNextFloatingPromptIfIdle()+ }+ if index == 0 {+ button.keyEquivalent = "\r"+ }+ return button+ }+ let buttonWidths = buttons.enumerated().map { index, button in+ max(ceil(button.fittingSize.width), index == 0 ? 96 : 80)+ }+ let buttonsWidth = buttonWidths.reduce(0, +) + buttonSpacing * CGFloat(max(buttons.count - 1, 0))+ let panelWidth = max(420, margin * 2 + buttonsWidth)+ let textWidth = panelWidth - textLeading - margin++ let titleLabel = NSTextField(labelWithString: title)+ titleLabel.font = .fluidSystemFont(ofSize: 16, weight: .semibold)+ let titleHeight = ceil(titleLabel.fittingSize.height)++ let detail = NSTextField(wrappingLabelWithString: message)+ detail.font = .fluidSystemFont(ofSize: 13)+ detail.textColor = .secondaryLabelColor+ detail.preferredMaxLayoutWidth = textWidth+ let detailHeight = ceil(detail.fittingSize.height)++ let buttonsY = margin - 2+ let detailY = buttonsY + buttonHeight + 16+ let titleY = detailY + detailHeight + 8+ let panelHeight = titleY + titleHeight + margin++ titleLabel.frame = NSRect(x: textLeading, y: titleY, width: textWidth, height: titleHeight)+ detail.frame = NSRect(x: textLeading, y: detailY, width: textWidth, height: detailHeight)++ var buttonTrailing = panelWidth - margin+ for (button, width) in zip(buttons, buttonWidths) {+ button.frame = NSRect(x: buttonTrailing - width, y: buttonsY, width: width, height: buttonHeight)+ buttonTrailing -= width + buttonSpacing+ }++ let panel = FloatingPromptPanel(+ contentRect: NSRect(x: 0, y: 0, width: panelWidth, height: panelHeight),+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.title = title+ if let cancelButton = buttons.last {+ panel.onCancel = { [weak cancelButton] in cancelButton?.performClick(nil) }+ }+ panel.isFloatingPanel = true+ panel.level = .floating+ panel.isOpaque = false+ panel.backgroundColor = .clear+ panel.hasShadow = true+ panel.isMovableByWindowBackground = true+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]++ let content = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: panelWidth, height: panelHeight))+ content.material = .popover+ content.blendingMode = .behindWindow+ content.state = .active+ content.wantsLayer = true+ content.layer?.cornerRadius = 16+ content.layer?.masksToBounds = true+ content.autoresizingMask = [.width, .height]++ let icon = NSImageView(frame: NSRect(x: margin, y: panelHeight - margin - 52, width: 52, height: 52))+ icon.image = NSApp.applicationIconImage+ icon.imageScaling = .scaleProportionallyUpOrDown+ content.addSubview(icon)+ content.addSubview(titleLabel)+ content.addSubview(detail)+ for button in buttons {+ content.addSubview(button)+ }++ panel.contentView = content+ panel.initialFirstResponder = buttons.first+ panel.center()+ // Even our own search/editor field may be receiving dictation. Never make this key here.+ panel.orderFrontRegardless()+ self.floatingPromptWindow = panel+ }++ private func finishVisibleFloatingPrompt() {+ self.floatingPromptWindow?.close()+ self.floatingPromptWindow = nil+ if !self.floatingPromptQueue.isEmpty {+ self.floatingPromptQueue.removeFirst()+ }+ }++ func dismissAutomaticUpdateOffers() {+ self.dismissPrompts { $0.isAutomaticUpdateOffer }+ }++ func dismissUpdateOffers() {+ self.dismissPrompts { $0.title == "Update Available" }+ }++ func dismissUpdateCheckResults() {+ self.dismissPrompts {+ $0.title == "No Updates" || $0.title == "No Beta Updates" || $0.title == "Update Check Failed"+ }+ }++ private func dismissPrompts(where shouldDismiss: (FloatingPrompt) -> Bool) {+ let removesVisiblePrompt = self.floatingPromptQueue.first.map(shouldDismiss) == true+ self.floatingPromptQueue.removeAll(where: shouldDismiss)+ if removesVisiblePrompt {+ self.floatingPromptWindow?.close()+ self.floatingPromptWindow = nil+ self.showNextFloatingPromptIfIdle()+ }+ }++ func dismissAll() {+ self.floatingPromptWindow?.close()+ self.floatingPromptWindow = nil+ self.floatingPromptQueue.removeAll()+ }+}++struct FloatingPromptAction {+ let title: String+ let handler: @MainActor () -> Void+}++private struct FloatingPrompt {+ let id = UUID()+ let title: String+ let message: String+ let actions: [FloatingPromptAction]+ let isAutomaticUpdateOffer: Bool+}++private final class FloatingPromptPanel: NSPanel {+ var onCancel: (@MainActor () -> Void)?++ override var canBecomeKey: Bool {+ return true+ }++ override func cancelOperation(_ sender: Any?) {+ let onCancel = self.onCancel+ onCancel?()+ }+}++private final class FloatingPromptButton: NSButton {+ private let onClick: @MainActor () -> Void++ init(title: String, onClick: @escaping @MainActor () -> Void) {+ self.onClick = onClick+ super.init(frame: .zero)+ self.title = title+ self.bezelStyle = .rounded+ self.target = self+ self.action = #selector(self.handleClick)+ self.sizeToFit()+ }++ @available(*, unavailable)+ required init?(coder: NSCoder) {+ fatalError("FloatingPromptButton is created in code only")+ }++ override func acceptsFirstMouse(for event: NSEvent?) -> Bool {+ return true+ }++ @objc private func handleClick() {+ let onClick = self.onClick+ onClick()+ }+}diff --git a/Sources/Fluid/UI/UpdatePromptSimulation.swift b/Sources/Fluid/UI/UpdatePromptSimulation.swiftnew file mode 100644index 00000000..99ce1b10--- /dev/null+++ b/Sources/Fluid/UI/UpdatePromptSimulation.swift@@ -0,0 +1,23 @@+#if DEBUG+import AppKit++/// Explicit launch-only diagnostics. Release builds have no observer or simulated installer.+@MainActor+enum UpdatePromptSimulation {+ static let isEnabled = ProcessInfo.processInfo.environment["FLUIDVOICE_UPDATE_UI_SIMULATION"] == "1"++ static func register(_ delegate: AppDelegate) -> NSObjectProtocol? {+ guard self.isEnabled else { return nil }+ return DistributedNotificationCenter.default().addObserver(+ forName: Notification.Name("com.FluidApp.debug.updateUI"),+ object: String(ProcessInfo.processInfo.processIdentifier),+ queue: .main+ ) { [weak delegate] notification in+ guard let scenario = notification.userInfo?["scenario"] as? String else { return }+ Task { @MainActor [weak delegate] in+ delegate?.simulateUpdateUI(scenario)+ }+ }+ }+}+#endifdiff --git a/Tests/FluidDictationIntegrationTests/UpdatePromptIntegrationTests.swift b/Tests/FluidDictationIntegrationTests/UpdatePromptIntegrationTests.swiftnew file mode 100644index 00000000..241a0ce7--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/UpdatePromptIntegrationTests.swift@@ -0,0 +1,560 @@+import AppKit+@testable import FluidVoice_Debug+import XCTest++@MainActor+final class UpdatePromptIntegrationTests: XCTestCase {+ func testPopupPreferenceBackupDecodesFalseAndMissingLegacyField() throws {+ var payload = SettingsStore.shared.makeBackupPayload()+ payload.showUpdatePopups = false+ let encoded = try JSONEncoder().encode(payload)+ XCTAssertEqual(try JSONDecoder().decode(SettingsBackupPayload.self, from: encoded).showUpdatePopups, false)+ var legacy = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ legacy.removeValue(forKey: "showUpdatePopups")+ let legacyData = try JSONSerialization.data(withJSONObject: legacy)+ XCTAssertNil(try JSONDecoder().decode(SettingsBackupPayload.self, from: legacyData).showUpdatePopups)+ }++ func testOfferWithQueuedFailureTransitionsToOnlyInstallStatus() async throws {+ let presenter = UpdatePromptPresenter.shared+ let updater = SimpleUpdater()+ presenter.dismissAll()+ defer {+ presenter.dismissAll()+ updater.dismissUpdateInstallStatus()+ }+ let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier+ let keyWindow = NSApp.keyWindow+ let firstResponder = keyWindow?.firstResponder+ var installActions = 0+ var failureActions = 0+ let version = "offer-test-\(UUID().uuidString)"++ presenter.presentFloatingPrompt(title: "Update Available", message: "Your dictation can continue.", actions: [+ FloatingPromptAction(title: "Install Now") {+ installActions += 1+ updater.showUpdateInstallStatus(version: version)+ },+ FloatingPromptAction(title: "Later") {},+ ])+ let offer = try self.visibleWindow("Update Available")+ let install = try self.button("Install Now", in: offer)+ presenter.presentFloatingPrompt(title: "Update Check Failed", message: "Queued notice", actions: [+ FloatingPromptAction(title: "OK") { failureActions += 1 },+ ])+ install.performClick(nil)++ XCTAssertEqual(installActions, 1)+ XCTAssertFalse(offer.isVisible)+ XCTAssertFalse(self.isVisible("Update Check Failed"))+ let status = try self.visibleWindow("Installing FluidVoice \(version)")+ let progress = try XCTUnwrap(status.contentView?.subviews.compactMap { $0 as? NSProgressIndicator }.first)+ XCTAssertTrue(progress.isIndeterminate)+ XCTAssertFalse(progress.isHidden)+ XCTAssertFalse(updater.isUpdateInProgress, "UI-only status must not begin an install or download")+ XCTAssertNil(NSApp.modalWindow)+ XCTAssertEqual(NSWorkspace.shared.frontmostApplication?.processIdentifier, frontmostPID)+ XCTAssertTrue(NSApp.keyWindow === keyWindow)+ XCTAssertTrue(keyWindow?.firstResponder === firstResponder)++ var mainActorRan = false+ await Task { @MainActor in mainActorRan = true }.value+ XCTAssertTrue(mainActorRan && status.isVisible)+ install.performClick(nil)+ XCTAssertEqual(installActions, 1, "A retained button cannot start installation twice")++ // Mirror failure cleanup: progress closes before the nonmodal error opens.+ updater.dismissUpdateInstallStatus()+ XCTAssertFalse(status.isVisible)+ presenter.presentFloatingPrompt(title: "Update Check Failed", message: "Simulated failure", actions: [+ FloatingPromptAction(title: "OK") { failureActions += 1 },+ ])+ let failure = try self.visibleWindow("Update Check Failed")+ XCTAssertNil(NSApp.modalWindow)+ XCTAssertEqual(NSWorkspace.shared.frontmostApplication?.processIdentifier, frontmostPID)+ XCTAssertTrue(NSApp.keyWindow === keyWindow)+ XCTAssertTrue(keyWindow?.firstResponder === firstResponder)+ mainActorRan = false+ await Task { @MainActor in mainActorRan = true }.value+ XCTAssertTrue(mainActorRan && failure.isVisible)+ failure.cancelOperation(nil)+ XCTAssertEqual(failureActions, 1, "Discarded queued notice must never run its handler")+ XCTAssertFalse(failure.isVisible)+ }++ func testDirectInstallStatusInvalidatesOutstandingOfferAndQueue() throws {+ let presenter = UpdatePromptPresenter.shared+ let updater = SimpleUpdater()+ presenter.dismissAll()+ defer {+ presenter.dismissAll()+ updater.dismissUpdateInstallStatus()+ }+ var staleActions = 0+ presenter.presentFloatingPrompt(title: "Update Available", message: "Outstanding offer", actions: [+ FloatingPromptAction(title: "Install Now") { staleActions += 1 },+ ])+ let offer = try self.visibleWindow("Update Available")+ let staleInstall = try self.button("Install Now", in: offer)+ presenter.presentFloatingPrompt(title: "Update Check Failed", message: "Queued notice", actions: [+ FloatingPromptAction(title: "OK") { staleActions += 1 },+ ])+ let version = "direct-test-\(UUID().uuidString)"+ updater.showUpdateInstallStatus(version: version)+ let status = try self.visibleWindow("Installing FluidVoice \(version)")+ XCTAssertFalse(offer.isVisible)+ XCTAssertFalse(self.isVisible("Update Check Failed"))+ staleInstall.performClick(nil)+ XCTAssertEqual(staleActions, 0)+ XCTAssertTrue(status.isVisible)+ updater.dismissUpdateInstallStatus()+ XCTAssertFalse(status.isVisible)+ XCTAssertFalse(updater.isUpdateInProgress)+ XCTAssertNil(NSApp.modalWindow)+ }++ private func visibleWindow(_ title: String) throws -> NSWindow {+ try XCTUnwrap(NSApp.windows.first { $0.isVisible && $0.title == title })+ }++ private func isVisible(_ title: String) -> Bool {+ NSApp.windows.contains { $0.isVisible && $0.title == title }+ }++ private func button(_ title: String, in window: NSWindow) throws -> NSButton {+ try XCTUnwrap(window.contentView?.subviews.compactMap { $0 as? NSButton }.first { $0.title == title })+ }++ func testDefaultAutomaticOfferAndDisabledPopupsStillDiscover() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: "v99.0.0")+ XCTAssertNil(context.defaults.object(forKey: SettingsStore.UpdateKeys.showUpdatePopups))+ context.updater.checkForUpdatesAutomatically()+ try await self.finishCheck(context)+ XCTAssertEqual(context.updater.availableUpdateVersion, "v99.0.0")+ XCTAssertTrue(self.isVisible("Update Available"))+ XCTAssertNotNil(context.defaults.object(forKey: SettingsStore.UpdateKeys.lastUpdateCheckDate))+ XCTAssertFalse(context.updater.isUpdateInProgress)++ context.defaults.set(false, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.updater.automaticUpdatePopupPreferenceDidChange(isEnabled: false)+ XCTAssertFalse(self.isVisible("Update Available"))+ context.defaults.removeObject(forKey: SettingsStore.UpdateKeys.lastUpdateCheckDate)+ context.fixture.setReply(version: "v100.0.0")+ context.updater.checkForUpdatesAutomatically()+ try await self.finishCheck(context, requests: 2)+ XCTAssertEqual(context.updater.availableUpdateVersion, "v100.0.0")+ XCTAssertFalse(self.isVisible("Update Available"))+ XCTAssertNotNil(context.defaults.object(forKey: SettingsStore.UpdateKeys.lastUpdateCheckDate))+ XCTAssertNil(context.defaults.object(forKey: SettingsStore.UpdateKeys.updatePromptSnoozedUntil))+ XCTAssertNil(context.defaults.object(forKey: SettingsStore.UpdateKeys.snoozedUpdateVersion))+ }++ func testExplicitCheckOffersBeforeInstallingWhenPopupsAreDisabled() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.defaults.set(false, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.fixture.setReply(version: "v99.0.0")+ var installs = 0+ context.updater.simulationInstallHandler = { installs += 1 }+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context)+ let offer = try self.visibleWindow("Update Available")+ let install = try self.button("Install Now", in: offer)+ XCTAssertEqual(installs, 0)+ XCTAssertEqual(context.fixture.requestCount, 1, "Discovery must not fetch assets or start installation before approval")+ XCTAssertFalse(context.updater.isUpdateInProgress)+ context.updater.automaticUpdatePopupPreferenceDidChange(isEnabled: false)+ XCTAssertTrue(offer.isVisible, "Turning automatic popups off must preserve explicit offers")+ try self.button("Later", in: offer).performClick(nil)+ install.performClick(nil)+ XCTAssertEqual(installs, 0)+ XCTAssertEqual(context.updater.availableUpdateVersion, "v99.0.0")+ context.updater.showAvailableUpdate()+ let cachedOffer = try self.visibleWindow("Update Available")+ try self.button("Install Now", in: cachedOffer).performClick(nil)+ try await self.waitFor { installs == 1 }+ install.performClick(nil)+ XCTAssertEqual(installs, 1)+ XCTAssertEqual(context.fixture.requestCount, 2, "Confirmation revalidates the release; the simulated installer never downloads")+ }++ func testPopupTogglesDuringHeldCheckUseFinalPreferenceWithoutExtraRequests() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: "v99.0.0", held: true)+ context.updater.checkForUpdatesAutomatically()+ try await self.waitFor { context.fixture.requestCount == 1 }+ for enabled in [false, true, false] {+ context.defaults.set(enabled, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ let revision = context.defaults.integer(forKey: SettingsStore.UpdateKeys.popupPreferenceRevision)+ context.defaults.set(revision &+ 1, forKey: SettingsStore.UpdateKeys.popupPreferenceRevision)+ context.updater.automaticUpdatePopupPreferenceDidChange(isEnabled: enabled)+ }+ context.fixture.release()+ try await self.finishCheck(context)+ XCTAssertEqual(context.updater.availableUpdateVersion, "v99.0.0")+ XCTAssertFalse(self.isVisible("Update Available"))+ context.defaults.set(true, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.updater.automaticUpdatePopupPreferenceDidChange(isEnabled: true)+ XCTAssertFalse(self.isVisible("Update Available"), "Enabling popups must not unexpectedly display cached offers")+ XCTAssertEqual(context.fixture.requestCount, 1)+ XCTAssertFalse(context.updater.isUpdateInProgress)+ }++ func testRepeatedManualRequestsClaimAutomaticCheckWithoutDuplicateFetch() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.defaults.set(false, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.fixture.setReply(version: "v99.0.0", held: true)+ context.updater.checkForUpdatesAutomatically()+ try await self.waitFor { context.fixture.requestCount == 1 }+ for _ in 0..<8 {+ context.updater.checkForUpdatesManually()+ }+ XCTAssertEqual(context.fixture.requestCount, 1)+ context.fixture.release()+ try await self.finishCheck(context)+ let offer = try self.visibleWindow("Update Available")+ XCTAssertEqual(NSApp.windows.filter { $0.isVisible && $0.title == "Update Available" }.count, 1)+ context.updater.automaticUpdatePopupPreferenceDidChange(isEnabled: false)+ XCTAssertTrue(offer.isVisible)+ XCTAssertFalse(context.updater.isUpdateInProgress)+ }++ func testNoUpdateAndFailedRefreshClearStaleAvailability() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.defaults.set(false, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.fixture.setReply(version: "v99.0.0")+ context.updater.checkForUpdatesAutomatically()+ try await self.finishCheck(context)+ context.defaults.removeObject(forKey: SettingsStore.UpdateKeys.lastUpdateCheckDate)+ context.fixture.setReply(version: nil, status: 503)+ context.updater.checkForUpdatesAutomatically()+ try await self.finishCheck(context, requests: 2)+ XCTAssertNil(context.updater.availableUpdateVersion)+ XCTAssertFalse(self.isVisible("Update Check Failed"))+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context, requests: 3)+ XCTAssertTrue(self.isVisible("Update Check Failed"))+ XCTAssertNil(context.updater.availableUpdateVersion)+ context.presenter.dismissAll()+ context.fixture.setReply(version: nil)+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context, requests: 4)+ XCTAssertNil(context.updater.availableUpdateVersion)+ XCTAssertFalse(self.isVisible("Update Available"))+ XCTAssertFalse(context.updater.isUpdateInProgress)+ XCTAssertNil(NSApp.modalWindow)+ }++ func testChannelChangeRejectsHeldOldResult() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: "v99.0.0", held: true)+ context.updater.checkForUpdatesAutomatically()+ try await self.waitFor { context.fixture.requestCount == 1 }+ context.defaults.set(true, forKey: SettingsStore.UpdateKeys.betaReleasesEnabled)+ let revision = context.defaults.integer(forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ context.defaults.set(revision &+ 1, forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ context.updater.updateChannelDidChange()+ XCTAssertNil(context.updater.availableUpdateVersion)+ XCTAssertFalse(self.isVisible("Update Available"))+ context.fixture.setReply(version: "v100.0.0")+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context, requests: 2)+ context.fixture.release()+ try await Task.sleep(nanoseconds: 30_000_000)+ XCTAssertEqual(context.updater.availableUpdateVersion, "v100.0.0")+ let offer = try self.visibleWindow("Update Available")+ XCTAssertTrue(offer.contentView?.subviews.compactMap { $0 as? NSTextField }.contains { $0.stringValue.contains("v100.0.0") } == true)+ XCTAssertFalse(context.updater.isUpdateInProgress)+ }++ func testChangedReleaseRequiresFreshApprovalBeforeInstalling() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: "v99.0.0")+ var installs = 0+ context.updater.simulationInstallHandler = { installs += 1 }+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context)+ let oldOffer = try self.visibleWindow("Update Available")+ let oldInstall = try self.button("Install Now", in: oldOffer)+ context.fixture.setReply(version: "v100.0.0")+ oldInstall.performClick(nil)+ try await self.waitFor { context.fixture.requestCount == 2 && !context.updater.isUpdateInProgress }+ XCTAssertEqual(installs, 0, "A release discovered after approval must not install silently")+ let freshOffer = try self.visibleWindow("Update Available")+ XCTAssertTrue(freshOffer.contentView?.subviews.compactMap { $0 as? NSTextField }.contains { $0.stringValue.contains("v100.0.0") } == true)+ oldInstall.performClick(nil)+ XCTAssertEqual(installs, 0)+ try self.button("Install Now", in: freshOffer).performClick(nil)+ try await self.waitFor { installs == 1 && !context.updater.isUpdateInProgress }+ XCTAssertEqual(context.fixture.requestCount, 3)+ }++ func testChannelChangeDuringApprovedInstallRechecksAndRequiresFreshApproval() async throws {+ for currentChannelVersion in ["v100.0.0", nil] as [String?] {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: "v99.0.0")+ var installs = 0+ context.updater.simulationInstallHandler = { installs += 1 }+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context)+ let oldOffer = try self.visibleWindow("Update Available")+ let oldInstall = try self.button("Install Now", in: oldOffer)+ context.fixture.setReply(version: "v99.0.0", held: true)+ oldInstall.performClick(nil)+ try await self.waitFor { context.fixture.requestCount == 2 && context.updater.isUpdateInProgress }+ context.defaults.set(true, forKey: SettingsStore.UpdateKeys.betaReleasesEnabled)+ let revision = context.defaults.integer(forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ context.defaults.set(revision &+ 1, forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ context.updater.updateChannelDidChange()+ context.fixture.setReply(version: currentChannelVersion)+ context.fixture.release()+ try await self.finishCheck(context, requests: 3)+ XCTAssertFalse(context.updater.isUpdateInProgress)+ XCTAssertEqual(installs, 0, "A channel change must invalidate approval before installation")+ oldInstall.performClick(nil)+ XCTAssertEqual(installs, 0)+ if let currentChannelVersion {+ let freshOffer = try self.visibleWindow("Update Available")+ XCTAssertTrue(freshOffer.contentView?.subviews.compactMap { $0 as? NSTextField }.contains { $0.stringValue.contains(currentChannelVersion) } == true)+ try self.button("Install Now", in: freshOffer).performClick(nil)+ try await self.waitFor { installs == 1 && !context.updater.isUpdateInProgress }+ XCTAssertEqual(context.fixture.requestCount, 4)+ } else {+ XCTAssertTrue(self.isVisible("No Beta Updates"))+ XCTAssertFalse(self.isVisible("Update Available"))+ XCTAssertNil(context.updater.availableUpdateVersion)+ XCTAssertEqual(context.fixture.requestCount, 3)+ }+ }+ }++ func testInstallRejectsResultFromPreviouslyPendingDiscovery() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.defaults.set(false, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.fixture.setReply(version: "v99.0.0")+ context.updater.checkForUpdatesAutomatically()+ try await self.finishCheck(context)+ context.fixture.setReply(version: "v100.0.0", held: true)+ context.updater.checkForUpdatesManually()+ try await self.waitFor { context.fixture.requestCount == 2 }+ context.updater.showAvailableUpdate()+ let cachedOffer = try self.visibleWindow("Update Available")+ context.fixture.setReply(version: "v99.0.0")+ var installs = 0+ context.updater.simulationInstallHandler = {+ installs += 1+ try await Task.sleep(nanoseconds: 150_000_000)+ }+ try self.button("Install Now", in: cachedOffer).performClick(nil)+ try await self.waitFor { installs == 1 && context.updater.isUpdateInProgress }+ context.fixture.release()+ try await self.waitFor { !context.updater.isCheckingForUpdates }+ XCTAssertFalse(self.isVisible("Update Available"), "A stale discovery cannot reopen an offer during installation")+ try await self.waitFor { !context.updater.isUpdateInProgress }+ XCTAssertFalse(self.isVisible("Update Available"))+ XCTAssertEqual(installs, 1)+ XCTAssertEqual(context.fixture.requestCount, 3)+ }++ func testFailedInstallReleasesGateAndAllowsExplicitRetry() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: "v99.0.0")+ var attempts = 0+ context.updater.simulationInstallHandler = {+ attempts += 1+ throw URLError(.cannotConnectToHost)+ }+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context)+ let offer = try self.visibleWindow("Update Available")+ let staleInstall = try self.button("Install Now", in: offer)+ staleInstall.performClick(nil)+ try await self.waitFor { attempts == 1 && !context.updater.isUpdateInProgress }+ let failure = try self.visibleWindow("Update Failed")+ XCTAssertFalse(offer.isVisible)+ XCTAssertNil(NSApp.modalWindow)+ staleInstall.performClick(nil)+ XCTAssertEqual(attempts, 1)+ failure.cancelOperation(nil)+ context.updater.simulationInstallHandler = { attempts += 1 }+ context.updater.showAvailableUpdate()+ let retry = try self.visibleWindow("Update Available")+ try self.button("Install Now", in: retry).performClick(nil)+ try await self.waitFor { attempts == 2 && !context.updater.isUpdateInProgress }+ XCTAssertEqual(context.fixture.requestCount, 3)+ XCTAssertFalse(self.isVisible("Update Failed"))+ XCTAssertFalse(self.isVisible("Update Available"))+ }++ func testNewExplicitCheckReplacesOldResultAndPreservesUnrelatedInstallFailure() async throws {+ let context = try UpdateTestContext()+ defer { context.cleanup() }+ context.fixture.setReply(version: nil)+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context)+ let noUpdates = try self.visibleWindow("No Updates")+ context.fixture.setReply(version: "v99.0.0")+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context, requests: 2)+ XCTAssertFalse(noUpdates.isVisible)+ let offer = try self.visibleWindow("Update Available")+ XCTAssertTrue(offer.contentView?.subviews.compactMap { $0 as? NSTextField }.contains { $0.stringValue.contains("v99.0.0") } == true)+ offer.cancelOperation(nil)++ context.fixture.setReply(version: nil)+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context, requests: 3)+ let secondResult = try self.visibleWindow("No Updates")+ context.presenter.presentFloatingPrompt(title: "Update Failed", message: "Unrelated installation failure", actions: [FloatingPromptAction(title: "OK") {}])+ context.fixture.setReply(version: "v100.0.0")+ context.updater.checkForUpdatesManually()+ try await self.finishCheck(context, requests: 4)+ XCTAssertFalse(secondResult.isVisible)+ let installFailure = try self.visibleWindow("Update Failed")+ context.defaults.set(false, forKey: SettingsStore.UpdateKeys.showUpdatePopups)+ context.updater.automaticUpdatePopupPreferenceDidChange(isEnabled: false)+ XCTAssertTrue(installFailure.isVisible, "Check-result cleanup and popup preference changes must preserve unrelated installation errors")+ installFailure.cancelOperation(nil)+ let freshOffer = try self.visibleWindow("Update Available")+ XCTAssertTrue(freshOffer.contentView?.subviews.compactMap { $0 as? NSTextField }.contains { $0.stringValue.contains("v100.0.0") } == true)+ XCTAssertFalse(context.updater.isUpdateInProgress)+ }++ private func finishCheck(_ context: UpdateTestContext, requests: Int = 1) async throws {+ try await self.waitFor { context.fixture.requestCount >= requests && !context.updater.isCheckingForUpdates }+ }++ private func waitFor(_ condition: @MainActor () -> Bool) async throws {+ for _ in 0..<200 {+ if condition() { return }+ try await Task.sleep(nanoseconds: 10_000_000)+ }+ XCTFail("Isolated update fixture did not finish within two seconds")+ throw URLError(.timedOut)+ }+}++private final nonisolated class UpdateFixture: @unchecked Sendable {+ private let lock = NSLock()+ private var pending: [(UpdateFixtureURLProtocol, Int, String)] = []+ private var count = 0+ private var held = false+ private var body = "[]"+ private var status = 200++ var requestCount: Int { self.lock.withLock { self.count } }++ func setReply(version: String?, status: Int = 200, held: Bool = false) {+ self.lock.withLock {+ self.status = status+ self.held = held+ self.body = version.map {+ """+ [{"tag_name":"\($0)","prerelease":false,"assets":[]}]+ """+ } ?? "[{\"tag_name\":\"v0.0.1\",\"prerelease\":false,\"assets\":[]}]"+ }+ }++ func receive(_ loading: UpdateFixtureURLProtocol) {+ let (held, status, body) = self.lock.withLock {+ self.count += 1+ if self.held { self.pending.append((loading, self.status, self.body)) }+ return (self.held, self.status, self.body)+ }+ if !held { self.respond(to: loading, status: status, body: body) }+ }++ func release() {+ let pending = self.lock.withLock {+ self.held = false+ let result = self.pending+ self.pending.removeAll()+ return result+ }+ for (loading, status, body) in pending {+ self.respond(to: loading, status: status, body: body)+ }+ }++ private func respond(to loading: UpdateFixtureURLProtocol, status: Int, body: String) {+ guard let url = loading.request.url,+ let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil)+ else { loading.client?.urlProtocol(loading, didFailWithError: URLError(.badURL)); return }+ loading.client?.urlProtocol(loading, didReceive: response, cacheStoragePolicy: .notAllowed)+ loading.client?.urlProtocol(loading, didLoad: Data(body.utf8))+ loading.client?.urlProtocolDidFinishLoading(loading)+ }+}++private nonisolated class UpdateFixtureURLProtocol: URLProtocol, @unchecked Sendable {+ private static let lock = NSLock()+ private nonisolated(unsafe) static var fixtures: [String: UpdateFixture] = [:]++ static func register(_ fixture: UpdateFixture, token: String) {+ self.lock.withLock { self.fixtures[token] = fixture }+ }++ static func remove(token: String) {+ _ = self.lock.withLock { self.fixtures.removeValue(forKey: token) }+ }++ override class func canInit(with request: URLRequest) -> Bool { true }+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }++ override func startLoading() {+ guard self.request.url?.host == "api.github.com", self.request.url?.path.hasSuffix("/releases") == true,+ let token = self.request.value(forHTTPHeaderField: "X-Update-Test"),+ let fixture = Self.lock.withLock({ Self.fixtures[token] })+ else {+ XCTFail("Unexpected network/download request: \(self.request.url?.absoluteString ?? "nil")")+ self.client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL))+ return+ }+ fixture.receive(self)+ }++ override func stopLoading() {}+}++@MainActor+private final class UpdateTestContext {+ let token = UUID().uuidString+ let defaults: UserDefaults+ let session: URLSession+ let presenter = UpdatePromptPresenter()+ let fixture = UpdateFixture()+ let updater: SimpleUpdater++ init() throws {+ self.defaults = try XCTUnwrap(UserDefaults(suiteName: self.token))+ let configuration = URLSessionConfiguration.ephemeral+ configuration.protocolClasses = [UpdateFixtureURLProtocol.self]+ configuration.httpAdditionalHeaders = ["X-Update-Test": self.token]+ self.session = URLSession(configuration: configuration)+ UpdateFixtureURLProtocol.register(self.fixture, token: self.token)+ self.updater = SimpleUpdater(session: self.session, defaults: self.defaults, promptPresenter: self.presenter)+ self.updater.simulationInstallHandler = {}+ }++ func cleanup() {+ let revision = self.defaults.integer(forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ self.defaults.set(revision &+ 1, forKey: SettingsStore.UpdateKeys.channelPreferenceRevision)+ self.updater.updateChannelDidChange()+ self.updater.dismissUpdateInstallStatus()+ self.presenter.dismissAll()+ self.session.invalidateAndCancel()+ UpdateFixtureURLProtocol.remove(token: self.token)+ self.defaults.removePersistentDomain(forName: self.token)+ }+}diff --git a/Tests/UpdatePromptTests.swift b/Tests/UpdatePromptTests.swiftnew file mode 100644index 00000000..07c62619--- /dev/null+++ b/Tests/UpdatePromptTests.swift@@ -0,0 +1,282 @@+import AppKit++@main+private enum UpdatePromptTests {+ @MainActor+ static func main() {+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ DispatchQueue.global().asyncAfter(deadline: .now() + 15) {+ print("FAIL: prompt blocked the main actor")+ exit(2)+ }+ DispatchQueue.main.async {+ Task { @MainActor in+ await self.run()+ exit(0)+ }+ }+ app.run()+ }++ @MainActor+ private static func run() async {+ let originalApp = NSWorkspace.shared.frontmostApplication+ defer { originalApp?.activate(options: []) }+ let presenter = UpdatePromptPresenter()+ var installed = 0+ var postponed = 0+ let actions = [+ FloatingPromptAction(title: "Install Now") { installed += 1 },+ FloatingPromptAction(title: "Later") { postponed += 1 },+ ]+ let frontmostPID = originalApp?.processIdentifier+ let keyWindow = NSApp.keyWindow+ let firstResponder = keyWindow?.firstResponder+ presenter.presentFloatingPrompt(title: "Update Available", message: "FluidVoice v1.6.10 is now available. The app will restart automatically after installation.", actions: actions)+ assert(NSWorkspace.shared.frontmostApplication?.processIdentifier == frontmostPID)+ assert(NSApp.keyWindow === keyWindow && keyWindow?.firstResponder === firstResponder)+ assert(NSApp.modalWindow == nil)+ let offer = self.visiblePanel("Update Available")+ assert(offer.styleMask.contains(.nonactivatingPanel))+ assert(!offer.isKeyWindow && offer.level == .floating)+ assert(installed == 0 && postponed == 0)+ let primary = self.button("Install Now", in: offer)+ let later = self.button("Later", in: offer)+ assert(primary.acceptsFirstMouse(for: nil))+ self.checkLayout(offer)++ // A queued dictation/hotkey job must run before the unanswered prompt is dismissed.+ var callbackRan = false+ let callback = Task { @MainActor in callbackRan = true }+ await callback.value+ try? await Task.sleep(nanoseconds: 20_000_000)+ assert(callbackRan && offer.isVisible)+ assert(installed == 0 && postponed == 0)++ presenter.presentFloatingPrompt(title: "Update Available", message: "FluidVoice v1.6.10 is now available. The app will restart automatically after installation.", actions: actions)+ presenter.presentFloatingPrompt(title: "Update Check Failed", message: "The download failed. Please try again later.", actions: [FloatingPromptAction(title: "OK") {}])+ assert(NSApp.windows.filter { $0.title == "Update Available" && $0.isVisible }.count == 1)+ assert(self.visiblePanel("Update Available") === offer)+ later.performClick(nil)+ assert(postponed == 1 && installed == 0 && !offer.isVisible)+ primary.performClick(nil) // A stale button must not answer the next prompt or start installation.+ assert(installed == 0)+ let failure = self.visiblePanel("Update Check Failed")+ failure.cancelOperation(nil)+ assert(!failure.isVisible)++ // Keep our own text destination key too, while FluidVoice is already active.+ let destination = NSWindow(contentRect: NSRect(x: 40, y: 40, width: 360, height: 120), styleMask: [.titled], backing: .buffered, defer: false)+ destination.isReleasedWhenClosed = false+ destination.title = "Dictation destination"+ let field = NSTextField(frame: NSRect(x: 20, y: 40, width: 320, height: 24))+ destination.contentView?.addSubview(field)+ NSApp.activate(ignoringOtherApps: true)+ destination.makeKeyAndOrderFront(nil)+ destination.makeFirstResponder(field)+ try? await Task.sleep(nanoseconds: 100_000_000)+ guard let editor = destination.firstResponder as? NSTextView else { fatalError("No text destination") }+ editor.insertText("Current dictation", replacementRange: editor.selectedRange())+ presenter.presentFloatingPrompt(title: "Update Available", message: "Your dictation can continue.", actions: actions)+ assert(NSApp.keyWindow === destination && destination.firstResponder === editor)+ editor.insertText(" completes", replacementRange: editor.selectedRange())+ assert(editor.string == "Current dictation completes")+ let secondOffer = self.visiblePanel("Update Available")+ secondOffer.makeKey()+ assert(secondOffer.performKeyEquivalent(with: self.returnKey(for: secondOffer)))+ assert(installed == 1 && postponed == 1 && !secondOffer.isVisible)+ destination.close()++ // Repeated checks stay bounded and every retained prompt still gets its action.+ var answered: [Int] = []+ for index in 0..<8 {+ presenter.presentFloatingPrompt(title: "Queue \(index)", message: "Check \(index)", actions: [FloatingPromptAction(title: "OK") { answered.append(index) }])+ }+ for index in 0..<4 {+ self.visiblePanel("Queue \(index)").cancelOperation(nil)+ }+ assert(answered == [0, 1, 2, 3])+ assert(!NSApp.windows.contains { $0.isVisible && $0.title.hasPrefix("Queue ") })+ presenter.presentFloatingPrompt(title: "Empty", message: "No actions", actions: [])+ assert(!NSApp.windows.contains { $0.isVisible && $0.title == "Empty" })+ presenter.presentFloatingPrompt(title: "Recovered", message: "Ready for the next update", actions: [FloatingPromptAction(title: "OK") {}])+ self.visiblePanel("Recovered").cancelOperation(nil)++ // Installation/dismissal clears every waiting notice and invalidates retained buttons.+ presenter.presentFloatingPrompt(title: "Update Available", message: "Dismissed offer", actions: actions)+ let dismissedOffer = self.visiblePanel("Update Available")+ let staleInstall = self.button("Install Now", in: dismissedOffer)+ presenter.presentFloatingPrompt(title: "Queued failure", message: "Discarded notice", actions: [FloatingPromptAction(title: "OK") { postponed += 1 }])+ presenter.dismissAll()+ presenter.dismissAll()+ assert(!dismissedOffer.isVisible)+ assert(!NSApp.windows.contains { $0.isVisible && $0.title == "Queued failure" })+ staleInstall.performClick(nil)+ assert(installed == 1 && postponed == 1)+ presenter.presentFloatingPrompt(title: "Update Available", message: "Fresh offer", actions: actions)+ staleInstall.performClick(nil)+ assert(installed == 1 && self.visiblePanel("Update Available").isVisible)+ self.visiblePanel("Update Available").cancelOperation(nil)+ assert(postponed == 2)+ self.checkNewerOffers(presenter)+ self.checkFocusedOfferRefresh(presenter)+ self.checkAutomaticOfferRemoval(presenter)+ print("PASS: main actor responsive; focus preserved; text completes; actions, direct cancellation, duplicate/newer offers, stale buttons, queue order, dismiss-all and recovery checks")+ }++ @MainActor+ private static func checkAutomaticOfferRemoval(_ presenter: UpdatePromptPresenter) {+ var answered: [String] = []+ let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier+ let keyWindow = NSApp.keyWindow+ let firstResponder = keyWindow?.firstResponder+ presenter.presentFloatingPrompt(+ title: "Update Available",+ message: "Automatic version",+ actions: [FloatingPromptAction(title: "Install Now") { answered.append("automatic") }],+ isAutomaticUpdateOffer: true+ )+ let automatic = self.visiblePanel("Update Available")+ let oldInstall = self.button("Install Now", in: automatic)+ presenter.presentFloatingPrompt(title: "Update Check Failed", message: "Explicit error", actions: [FloatingPromptAction(title: "OK") { answered.append("error") }])+ presenter.dismissAutomaticUpdateOffers()+ assert(!automatic.isVisible && self.visiblePanel("Update Check Failed").isVisible)+ oldInstall.performClick(nil)+ assert(answered.isEmpty)+ assert(NSWorkspace.shared.frontmostApplication?.processIdentifier == frontmostPID)+ assert(NSApp.keyWindow === keyWindow && keyWindow?.firstResponder === firstResponder)+ presenter.presentFloatingPrompt(title: "Update Available", message: "Queued automatic", actions: [FloatingPromptAction(title: "Install Now") { answered.append("queued automatic") }], isAutomaticUpdateOffer: true)+ presenter.dismissAutomaticUpdateOffers()+ self.visiblePanel("Update Check Failed").cancelOperation(nil)+ assert(answered == ["error"])+ assert(!NSApp.windows.contains { $0.isVisible && $0.title == "Update Available" })++ // An explicit request promotes identical automatic content to a manual offer.+ presenter.presentFloatingPrompt(title: "Update Available", message: "Same version", actions: [FloatingPromptAction(title: "Install Now") { answered.append("old automatic") }], isAutomaticUpdateOffer: true)+ let promotedFrom = self.visiblePanel("Update Available")+ let staleAutomaticInstall = self.button("Install Now", in: promotedFrom)+ presenter.presentFloatingPrompt(title: "Update Available", message: "Same version", actions: [FloatingPromptAction(title: "Install Now") { answered.append("manual") }])+ let manual = self.visiblePanel("Update Available")+ assert(manual !== promotedFrom && !promotedFrom.isVisible)+ presenter.presentFloatingPrompt(title: "Update Available", message: "Same version", actions: [FloatingPromptAction(title: "Install Now") { answered.append("downgraded automatic") }], isAutomaticUpdateOffer: true)+ presenter.dismissAutomaticUpdateOffers()+ assert(self.visiblePanel("Update Available") === manual)+ staleAutomaticInstall.performClick(nil)+ assert(answered == ["error"])+ self.button("Install Now", in: manual).performClick(nil)+ assert(answered == ["error", "manual"])+ assert(NSWorkspace.shared.frontmostApplication?.processIdentifier == frontmostPID)+ assert(NSApp.keyWindow === keyWindow && keyWindow?.firstResponder === firstResponder)+ }++ @MainActor+ private static func checkFocusedOfferRefresh(_ presenter: UpdatePromptPresenter) {+ var answered: [String] = []+ presenter.presentFloatingPrompt(title: "Update Available", message: "Focused version 1", actions: [+ FloatingPromptAction(title: "Install Now") { answered.append("old install") },+ FloatingPromptAction(title: "Later") { answered.append("old later") },+ ])+ let oldOffer = self.visiblePanel("Update Available")+ let oldInstall = self.button("Install Now", in: oldOffer)+ oldOffer.makeKey()+ assert(oldOffer.isKeyWindow)+ let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier+ presenter.presentFloatingPrompt(title: "Update Available", message: "Focused version 2", actions: [+ FloatingPromptAction(title: "Install Now") { answered.append("fresh install") },+ FloatingPromptAction(title: "Later") { answered.append("fresh later") },+ ])+ let refreshedOffer = self.visiblePanel("Update Available")+ assert(refreshedOffer !== oldOffer && !oldOffer.isVisible)+ assert(refreshedOffer.isKeyWindow, "Refreshing a deliberately focused offer must preserve keyboard focus")+ assert(NSWorkspace.shared.frontmostApplication?.processIdentifier == frontmostPID)+ oldInstall.performClick(nil)+ assert(answered.isEmpty && refreshedOffer.isVisible)+ assert(refreshedOffer.performKeyEquivalent(with: self.returnKey(for: refreshedOffer)))+ assert(answered == ["fresh install"] && !refreshedOffer.isVisible)+ }++ @MainActor+ private static func checkNewerOffers(_ presenter: UpdatePromptPresenter) {+ let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier+ let keyWindow = NSApp.keyWindow+ let firstResponder = keyWindow?.firstResponder+ var answered: [String] = []+ presenter.presentFloatingPrompt(title: "Update Available", message: "Version 1", actions: [+ FloatingPromptAction(title: "Install Now") { answered.append("old install") },+ FloatingPromptAction(title: "Later") { answered.append("old later") },+ ])+ let oldOffer = self.visiblePanel("Update Available")+ let oldInstall = self.button("Install Now", in: oldOffer)+ let oldLater = self.button("Later", in: oldOffer)+ presenter.presentFloatingPrompt(title: "First notice", message: "Keep queue position", actions: [FloatingPromptAction(title: "OK") { answered.append("first notice") }])+ presenter.presentFloatingPrompt(title: "Update Available", message: "Version 2", actions: [+ FloatingPromptAction(title: "Install Now") { answered.append("new install") },+ FloatingPromptAction(title: "Later") { answered.append("new later") },+ ])+ let newerOffer = self.visiblePanel("Update Available")+ assert(newerOffer !== oldOffer && !oldOffer.isVisible)+ assert(self.hasMessage("Version 2", in: newerOffer))+ assert(NSWorkspace.shared.frontmostApplication?.processIdentifier == frontmostPID)+ assert(NSApp.keyWindow === keyWindow && keyWindow?.firstResponder === firstResponder)+ oldInstall.performClick(nil)+ oldLater.performClick(nil)+ assert(answered.isEmpty && newerOffer.isVisible)+ self.button("Later", in: newerOffer).performClick(nil)+ assert(answered == ["new later"])++ // Replace a queued offer in its original position, preserving surrounding notices.+ presenter.presentFloatingPrompt(title: "Update Available", message: "Queued version 1", actions: [FloatingPromptAction(title: "Install Now") { answered.append("old queued install") }])+ presenter.presentFloatingPrompt(title: "Last notice", message: "Keep final queue position", actions: [FloatingPromptAction(title: "OK") { answered.append("last notice") }])+ presenter.presentFloatingPrompt(title: "Update Available", message: "Queued version 2", actions: [FloatingPromptAction(title: "Install Now") { answered.append("new queued install") }])+ assert(self.visiblePanel("First notice").isVisible)+ assert(NSWorkspace.shared.frontmostApplication?.processIdentifier == frontmostPID)+ assert(NSApp.keyWindow === keyWindow && keyWindow?.firstResponder === firstResponder)+ self.visiblePanel("First notice").cancelOperation(nil)+ let queuedOffer = self.visiblePanel("Update Available")+ assert(self.hasMessage("Queued version 2", in: queuedOffer))+ assert(!NSApp.windows.contains { $0.isVisible && $0.title == "Last notice" })+ oldInstall.performClick(nil)+ oldLater.performClick(nil)+ assert(answered == ["new later", "first notice"] && queuedOffer.isVisible)+ self.button("Install Now", in: queuedOffer).performClick(nil)+ self.visiblePanel("Last notice").cancelOperation(nil)+ assert(answered == ["new later", "first notice", "new queued install", "last notice"])+ assert(!NSApp.windows.contains { $0.isVisible && $0.title == "Update Available" })+ }++ @MainActor+ private static func hasMessage(_ message: String, in panel: NSWindow) -> Bool {+ panel.contentView?.subviews.compactMap { $0 as? NSTextField }.contains { $0.stringValue == message } == true+ }++ @MainActor+ private static func visiblePanel(_ title: String) -> NSWindow {+ guard let panel = NSApp.windows.first(where: { $0.title == title && $0.isVisible }) else { fatalError("Missing prompt: \(title)") }+ return panel+ }++ @MainActor+ private static func button(_ title: String, in panel: NSWindow) -> NSButton {+ guard let button = panel.contentView?.subviews.compactMap({ $0 as? NSButton }).first(where: { $0.title == title }) else { fatalError("Missing button: \(title)") }+ return button+ }++ @MainActor+ private static func checkLayout(_ panel: NSWindow) {+ guard let content = panel.contentView else { fatalError("Missing content") }+ for view in content.subviews {+ assert(content.bounds.contains(view.frame))+ if let label = view as? NSTextField { assert(label.frame.height >= ceil(label.fittingSize.height)) }+ if let button = view as? NSButton { assert(button.frame.width >= ceil(button.fittingSize.width)) }+ }+ }++ @MainActor+ private static func returnKey(for panel: NSWindow) -> NSEvent {+ guard let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: panel.windowNumber, context: nil, characters: "\r", charactersIgnoringModifiers: "\r", isARepeat: false, keyCode: 36) else {+ fatalError("Cannot create return-key event")+ }+ return event+ }+}diff --git a/Tests/run_update_prompt_tests.sh b/Tests/run_update_prompt_tests.shnew file mode 100644index 00000000..8fd18278--- /dev/null+++ b/Tests/run_update_prompt_tests.sh@@ -0,0 +1,42 @@+#!/bin/sh+set -eu+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"+test -d "$task_developer_dir/Platforms/MacOSX.platform" || { echo "Full Xcode required" >&2; exit 1; }+export DEVELOPER_DIR="$task_developer_dir"+task_repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)+task_test_dir=$(mktemp -d /tmp/fluidvoice-update-prompt-tests.XXXXXX)+trap 'rm -rf "$task_test_dir"' EXIT+xcrun swiftc "$task_repo_dir/Sources/Fluid/Theme/FluidTypography.swift" "$task_repo_dir/Sources/Fluid/UI/UpdatePromptPresenter.swift" "$task_repo_dir/Tests/UpdatePromptTests.swift" -o "$task_test_dir/update-prompt-tests"+"$task_test_dir/update-prompt-tests"+python3 - "$task_repo_dir" <<'PYTEST'+from pathlib import Path+import sys+source = (Path(sys.argv[1]) / 'Sources/Fluid/AppDelegate.swift').read_text()+automatic = source[source.index(' private func checkForUpdatesAutomatically('):source.index(' private func showUpdateAlert(')]+assert 'SimpleUpdater.shared.checkForUpdatesAutomatically()' in automatic+assert 'checkAndUpdate(' not in automatic+for relative_path, start, end in [+ ('Sources/Fluid/UI/SettingsView.swift', 'Button("Check for Updates")', 'Button("Release Notes")'),+ ('Sources/Fluid/Services/MenuBarManager.swift', '@objc private func checkForUpdates(', '@objc private func rollbackToPreviousVersion('),+]:+ text = (Path(sys.argv[1]) / relative_path).read_text()+ update_section = text[text.index(start):text.index(end, text.index(start))]+ assert 'runModal' not in update_section, relative_path+ assert 'checkForUpdatesManually()' in update_section, relative_path+ assert 'checkAndUpdate(' not in update_section, relative_path+updater = (Path(sys.argv[1]) / 'Sources/Fluid/Services/SimpleUpdater.swift').read_text()+manual = updater[updater.index(' func checkForUpdatesManually('):updater.index(' func showAvailableUpdate(')]+assert 'startUpdateCheck(explicit: true)' in manual+assert 'checkAndUpdate(' not in manual+assert 'runModal' not in updater+assert 'self.updatePrompts.presentFloatingPrompt(' in updater+assert 'isAutomaticUpdateOffer: automatic' in updater+assert 'expectedVersion: version' in updater+assert 'self.updateDefaults.set(version, forKey: SettingsStore.UpdateKeys.snoozedUpdateVersion)' in updater+status = updater[updater.index(' func showUpdateInstallStatus('):updater.index(' private func resetUpdateOperation(')]+assert 'self.updatePrompts.dismissAll()' in status+assert 'progress.startAnimation(nil)' in status+trigger = (Path(sys.argv[1]) / 'Tests/trigger_update_ui_simulation.swift').read_text()+assert 'toggleRecording' not in trigger and 'dictation-toggle' not in trigger+print('PASS: automatic discovery and explicit confirmation remain separate; update results nonmodal; approval revalidates version; simulation trigger cannot record')+PYTESTdiff --git a/Tests/trigger_update_ui_simulation.swift b/Tests/trigger_update_ui_simulation.swiftnew file mode 100644index 00000000..0729c966--- /dev/null+++ b/Tests/trigger_update_ui_simulation.swift@@ -0,0 +1,17 @@+import Foundation++let arguments = CommandLine.arguments+let scenarios: Set<String> = ["offer", "manual", "progress", "failure", "dismiss", "no-update"]+guard arguments.count == 3, let pid = Int32(arguments[1]), pid > 0,+ scenarios.contains(arguments[2])+else {+ FileHandle.standardError.write(Data("Usage: swift Tests/trigger_update_ui_simulation.swift <simulation-app-pid> offer|manual|progress|failure|dismiss|no-update\n".utf8))+ exit(64)+}++DistributedNotificationCenter.default().postNotificationName(+ Notification.Name("com.FluidApp.debug.updateUI"),+ object: String(pid),+ userInfo: ["scenario": arguments[2]],+ deliverImmediately: true+)