From dd61f43d4cacc4767d75f8484c4592e3da0ee97e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 21 Nov 2026 21:06:45 +0700 Subject: [PATCH 1/2] feat(modules): make Compare & Sync a module that stays on for existing installs --- .claude/rules/data-sync-storage.md | 1 + apple/TablePro/AppDelegate.swift | 9 +- .../Core/Compare/CompareSyncLauncher.swift | 31 ++- .../Core/Compare/CompareSyncRunRegistry.swift | 14 +- .../Core/Menu/DatabaseMenuBuilder.swift | 40 +++- apple/TablePro/Core/Modules/AppModule.swift | 24 +- .../Core/Modules/AppModuleActivation.swift | 4 +- .../Core/Modules/AppModuleSettings.swift | 4 + .../Infrastructure/WindowOpener.swift | 14 -- .../Core/Storage/AppSettingsStorage.swift | 5 + .../ViewModels/WelcomeViewModel+Library.swift | 1 + .../Compare/CompareSyncWindowController.swift | 17 +- .../Views/Welcome/WelcomeMenuSpec.swift | 7 +- .../CompareSyncModuleResidueTests.swift | 211 ++++++++++++++++++ .../LiveMessagesModuleResidueTests.swift | 8 +- .../Core/Modules/AppModuleDefaultTests.swift | 101 +++++++++ .../Core/Modules/AppModuleSettingsTests.swift | 11 +- .../Infrastructure/WindowOpenerTests.swift | 32 --- .../Views/Welcome/WelcomeMenuSpecTests.swift | 4 +- 19 files changed, 456 insertions(+), 82 deletions(-) create mode 100644 apple/TableProTests/Core/Compare/CompareSyncModuleResidueTests.swift create mode 100644 apple/TableProTests/Core/Modules/AppModuleDefaultTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index ffc9fefebf..f81530ac83 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -177,6 +177,7 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Server Dashboard tiles, per connection | UserDefaults, device-local | `ServerDashboardTileStorage` | | Table Health history, per connection and database: when each finding was first and last seen, resolved findings, ignored findings | JSON, one file per connection under `TableHealth/`, device-local, never synced | `TableHealthHistoryStorage` | | Module on/off (Settings > Extensions) | UserDefaults, device-local, never synced | `AppModuleSettings` | +| A module's default on this Mac, for one that was core before: on when an earlier build ran here, written once at the first launch that knows the module, restored by Reset All Settings | UserDefaults `com.TablePro.modules..default`, device-local, never synced | `AppModule.recordDefaults`, called first in `applicationWillFinishLaunching` | | Routine debugger start options, per connection and field | UserDefaults, device-local | `RoutineDebugOptionStore` | | Whether the toolbar arrangement already carries the debug items | UserDefaults, device-local | `MainWindowToolbar` | | Trusted external links (loopback only) | UserDefaults | `ExternalConnectionTrustStore` | diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index b15592456e..5e76ec815b 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -20,12 +20,16 @@ class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) { LaunchTracer.shared.mark(.willFinishLaunchingBegan) + // First: the migration below writes the flag that tells an existing install from a new one. + AppModule.recordDefaults( + in: AppStorageEnvironment.shared.defaults, + isExistingInstall: AppSettingsStorage.shared.hasLaunchedBefore() + ) AppSettingsStorage.shared.migrateStartupBehaviorToReopenLastIfNeeded() AppSettingsStorage.shared.removeRetiredFieldHeightKeys() AIProviderRegistration.registerAll() - /// Installed before any window exists, so the bar is correct from the first frame. - /// Nothing else owns it now that the app no longer runs a SwiftUI `App`. + // Before any window exists, so the bar is right from the first frame. MainMenuBuilder.install(keyboard: AppSettingsManager.shared.keyboard) MainMenuBuilder.syncKeyEquivalentsOnKeyWindowChange() LaunchTracer.shared.mark(.menuInstalled) @@ -81,7 +85,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { WindowOpener.shared.setConnectionFormPresenter { ConnectionFormWindowController.present($0) } WindowOpener.shared.setIntegrationsActivityPresenter { IntegrationsActivityWindowController.present() } WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present(pane: $0) } - WindowOpener.shared.setCompareSyncPresenter { CompareSyncWindowController.present(prefillSource: $0) } KeyRepeatFilter.shared.install() TableClickFocus.shared.install() RecentTabSwitcherController.installEditorKeyClaim() diff --git a/apple/TablePro/Core/Compare/CompareSyncLauncher.swift b/apple/TablePro/Core/Compare/CompareSyncLauncher.swift index ad4574d74c..d764610215 100644 --- a/apple/TablePro/Core/Compare/CompareSyncLauncher.swift +++ b/apple/TablePro/Core/Compare/CompareSyncLauncher.swift @@ -2,20 +2,39 @@ // CompareSyncLauncher.swift // TablePro // -// Single entry point for opening Compare & Sync, so the license gate is -// enforced in one place no matter which menu or context menu was used. -// import AppKit import Foundation +import os +// Every way into Compare & Sync passes here, so the module switch and the license gate are checked in one place. @MainActor internal enum CompareSyncLauncher { + internal enum Launch: Equatable { + case moduleOff + case needsLicense + case open + } + + private static let logger = Logger(subsystem: "com.TablePro", category: "CompareSync") + + // The license is not read while the module is off. + internal static func launch(moduleEnabled: Bool, isLicensed: () -> Bool) -> Launch { + guard moduleEnabled else { return .moduleOff } + return isLicensed() ? .open : .needsLicense + } + internal static func open(prefillSource connectionId: UUID? = nil) { - guard FeatureAccess.shared.isAvailable(.compareSync) else { + let decision = launch(moduleEnabled: AppModuleSettings.shared.isEnabled(.compareSync)) { + FeatureAccess.shared.isAvailable(.compareSync) + } + switch decision { + case .moduleOff: + logger.notice("Compare & Sync was asked to open while its module is off") + case .needsLicense: LicenseGateAlert.present(for: .compareSync, in: NSApp.keyWindow) - return + case .open: + CompareSyncWindowController.present(prefillSource: connectionId) } - WindowOpener.shared.openCompareSync(prefillSource: connectionId) } } diff --git a/apple/TablePro/Core/Compare/CompareSyncRunRegistry.swift b/apple/TablePro/Core/Compare/CompareSyncRunRegistry.swift index f18f125a78..d42e3ec6a7 100644 --- a/apple/TablePro/Core/Compare/CompareSyncRunRegistry.swift +++ b/apple/TablePro/Core/Compare/CompareSyncRunRegistry.swift @@ -12,14 +12,15 @@ internal final class CompareSyncRunRegistry { private struct Entry { weak var session: CompareSyncSession? let windowId: UUID + let close: @MainActor () -> Void } private var entries: [ObjectIdentifier: Entry] = [:] internal init() {} - internal func track(_ session: CompareSyncSession, windowId: UUID) { - entries[ObjectIdentifier(session)] = Entry(session: session, windowId: windowId) + internal func track(_ session: CompareSyncSession, windowId: UUID, close: @escaping @MainActor () -> Void) { + entries[ObjectIdentifier(session)] = Entry(session: session, windowId: windowId, close: close) } internal func windowId(of session: CompareSyncSession) -> UUID? { @@ -34,6 +35,15 @@ internal final class CompareSyncRunRegistry { } } + // The module was turned off: every run stops and every window closes, without the close prompt. + internal func endAll() { + entries = entries.filter { $0.value.session != nil } + for entry in entries.values { + entry.session?.cancelRunningWork() + entry.close() + } + } + internal static func runningWork(for session: CompareSyncSession) -> RunningWork? { guard session.isBusy else { return nil } let endpoints = [session.source, session.target].compactMap { $0 } diff --git a/apple/TablePro/Core/Menu/DatabaseMenuBuilder.swift b/apple/TablePro/Core/Menu/DatabaseMenuBuilder.swift index 167aff86f2..2638a7d179 100644 --- a/apple/TablePro/Core/Menu/DatabaseMenuBuilder.swift +++ b/apple/TablePro/Core/Menu/DatabaseMenuBuilder.swift @@ -10,6 +10,8 @@ import AppKit enum DatabaseMenuBuilder { static let identifier = NSUserInterfaceItemIdentifier("menu.database") static let liveMessagesIdentifier = NSUserInterfaceItemIdentifier("menu.database.liveMessages") + static let compareIdentifier = NSUserInterfaceItemIdentifier("menu.database.compare") + static let compareSeparatorIdentifier = NSUserInterfaceItemIdentifier("menu.database.compareSeparator") static let manualCommitFootnoteIdentifier = NSUserInterfaceItemIdentifier("menu.database.manualCommitFootnote") static let manualCommitUnavailableFootnoteIdentifier = NSUserInterfaceItemIdentifier( "menu.database.manualCommitUnavailableFootnote" @@ -166,9 +168,7 @@ enum DatabaseMenuBuilder { MenuItemFactory.item( String(localized: "Reconnect"), action: #selector(MainSplitViewController.retryConnection) - ), - MenuItemFactory.separator, - compareSubmenu() + ) ]) item.identifier = identifier if let menu = item.submenu { @@ -177,10 +177,15 @@ enum DatabaseMenuBuilder { return item } - // Live Messages… sits with the other connection-wide tabs, and exists only while its module is on. static func applyModules(_ modules: Set, to menu: NSMenu) { + applyLiveMessages(modules.contains(.liveMessages), to: menu) + applyCompare(modules.contains(.compareSync), to: menu) + } + + // Live Messages… sits with the other connection-wide tabs, and exists only while its module is on. + private static func applyLiveMessages(_ enabled: Bool, to menu: NSMenu) { let existing = menu.items.first { $0.identifier == liveMessagesIdentifier } - switch (modules.contains(.liveMessages), existing) { + switch (enabled, existing) { case (true, nil): let anchor = menu.items.firstIndex { $0.action == #selector(MainSplitViewController.showTableHealth(_:)) } let item = MenuItemFactory.item( @@ -196,12 +201,25 @@ enum DatabaseMenuBuilder { } } - /// The HIG asks that every toolbar item also be a menu-bar command. These are the Compare & - /// Sync window's toolbar, mirrored here; they route by nil target, so they reach - /// `CompareSyncWindowController` only while that window is key and validate to disabled - /// everywhere else. + // Closes the menu behind its own separator, and exists only while the Compare & Sync module is on. + private static func applyCompare(_ enabled: Bool, to menu: NSMenu) { + let existing = menu.items.filter { $0.identifier == compareIdentifier || $0.identifier == compareSeparatorIdentifier } + switch (enabled, existing.isEmpty) { + case (true, true): + let separator = MenuItemFactory.separator + separator.identifier = compareSeparatorIdentifier + menu.addItem(separator) + menu.addItem(compareSubmenu()) + case (false, false): + existing.forEach { menu.removeItem($0) } + default: + return + } + } + + // The window's toolbar mirrored as menu commands (HIG). Nil target, so they validate to disabled unless it is key. private static func compareSubmenu() -> NSMenuItem { - MenuItemFactory.submenu(String(localized: "Compare"), items: [ + let submenu = MenuItemFactory.submenu(String(localized: "Compare"), items: [ MenuItemFactory.item( String(localized: "Compare & Sync Databases…"), action: #selector(AppDelegate.compareAndSyncDatabases(_:)) @@ -238,6 +256,8 @@ enum DatabaseMenuBuilder { action: #selector(CompareSyncWindowController.stopComparison(_:)) ) ]) + submenu.identifier = compareIdentifier + return submenu } private static let favoriteDatabaseDelegate = FavoriteDatabaseMenuDelegate() diff --git a/apple/TablePro/Core/Modules/AppModule.swift b/apple/TablePro/Core/Modules/AppModule.swift index a4dad1f91d..1b2f1755b1 100644 --- a/apple/TablePro/Core/Modules/AppModule.swift +++ b/apple/TablePro/Core/Modules/AppModule.swift @@ -3,11 +3,13 @@ import Foundation enum AppModule: String, CaseIterable, Sendable { case routineDebugger case liveMessages + case compareSync var title: String { switch self { case .routineDebugger: String(localized: "Routine Debugger") case .liveMessages: String(localized: "Live Messages") + case .compareSync: String(localized: "Compare & Sync") } } @@ -15,11 +17,14 @@ enum AppModule: String, CaseIterable, Sendable { switch self { case .routineDebugger: String(localized: "Step through PL/pgSQL and PL/SQL routines with breakpoints.") case .liveMessages: String(localized: "Watch PostgreSQL notifications, Redis channels and Kafka topics as messages arrive.") + case .compareSync: String(localized: "Compare structure or data between two connections and generate the sync script.") } } - var defaultEnabled: Bool { + // Shipped as core before it became a module, so a Mac that ran an earlier build keeps it on. + var wasCore: Bool { switch self { + case .compareSync: true case .routineDebugger, .liveMessages: false } } @@ -28,8 +33,23 @@ enum AppModule: String, CaseIterable, Sendable { "com.TablePro.modules.\(rawValue).enabled" } + var recordedDefaultKey: String { + "com.TablePro.modules.\(rawValue).default" + } + + func defaultEnabled(in defaults: UserDefaults) -> Bool { + defaults.bool(forKey: recordedDefaultKey) + } + static func enabledModules(in defaults: UserDefaults) -> Set { - Set(allCases.filter { (defaults.object(forKey: $0.defaultsKey) as? Bool) ?? $0.defaultEnabled }) + Set(allCases.filter { (defaults.object(forKey: $0.defaultsKey) as? Bool) ?? $0.defaultEnabled(in: defaults) }) + } + + // Once per Mac and module, at the first launch of a build that knows the module; later launches keep the answer. + static func recordDefaults(in defaults: UserDefaults, isExistingInstall: Bool) { + for module in allCases where module.wasCore && defaults.object(forKey: module.recordedDefaultKey) == nil { + defaults.set(isExistingInstall, forKey: module.recordedDefaultKey) + } } // For value types that cannot reach the main actor; reads the same keys `AppModuleSettings` writes. diff --git a/apple/TablePro/Core/Modules/AppModuleActivation.swift b/apple/TablePro/Core/Modules/AppModuleActivation.swift index 01ab20851d..1f82e5b9dd 100644 --- a/apple/TablePro/Core/Modules/AppModuleActivation.swift +++ b/apple/TablePro/Core/Modules/AppModuleActivation.swift @@ -23,7 +23,7 @@ enum AppModuleActivation { static func resetToDefaults(settings: AppModuleSettings = .shared) { for module in AppModule.allCases { - setEnabled(module.defaultEnabled, for: module, settings: settings) + setEnabled(settings.defaultEnabled(module), for: module, settings: settings) } } @@ -33,6 +33,8 @@ enum AppModuleActivation { Task { await RoutineDebugSessions.shared.stopAll() } case .liveMessages: LiveMessageSessions.shared.endAll(closingTabs: true) + case .compareSync: + CompareSyncRunRegistry.shared.endAll() } } } diff --git a/apple/TablePro/Core/Modules/AppModuleSettings.swift b/apple/TablePro/Core/Modules/AppModuleSettings.swift index 36f5104d88..768d04b71c 100644 --- a/apple/TablePro/Core/Modules/AppModuleSettings.swift +++ b/apple/TablePro/Core/Modules/AppModuleSettings.swift @@ -24,6 +24,10 @@ final class AppModuleSettings: ObservableObject { enabledModules.contains(module) } + func defaultEnabled(_ module: AppModule) -> Bool { + module.defaultEnabled(in: defaults) + } + func setEnabled(_ enabled: Bool, for module: AppModule) { guard isEnabled(module) != enabled else { return } defaults.set(enabled, forKey: module.defaultsKey) diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift index 7a028bc75c..366c740e00 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift @@ -16,7 +16,6 @@ internal final class WindowOpener: ObservableObject { private var openWelcomeAction: (() -> Void)? private var openConnectionFormAction: ((ConnectionFormRequest) -> Void)? private var openIntegrationsActivityAction: (() -> Void)? - private var openCompareSyncAction: ((UUID?) -> Void)? private var openSettingsAction: ((SettingsPane?) -> Void)? private var stagedDraftId: UUID? private var pendingCalls: [() -> Void] = [] @@ -101,14 +100,6 @@ internal final class WindowOpener: ObservableObject { } } - internal func openCompareSync(prefillSource connectionId: UUID? = nil) { - perform { opener in - guard let present = opener.openCompareSyncAction else { return false } - present(connectionId) - return true - } - } - internal func setWelcomePresenter(_ present: @escaping () -> Void) { openWelcomeAction = present drainPendingCalls() @@ -129,11 +120,6 @@ internal final class WindowOpener: ObservableObject { drainPendingCalls() } - internal func setCompareSyncPresenter(_ present: @escaping (UUID?) -> Void) { - openCompareSyncAction = present - drainPendingCalls() - } - /// Returns false when the presenter for that window has not been registered yet, which /// queues the call. Each window registers independently, so one that has already migrated /// to AppKit never waits on one that has not. diff --git a/apple/TablePro/Core/Storage/AppSettingsStorage.swift b/apple/TablePro/Core/Storage/AppSettingsStorage.swift index 2b78d39e5b..742bdfb3b6 100644 --- a/apple/TablePro/Core/Storage/AppSettingsStorage.swift +++ b/apple/TablePro/Core/Storage/AppSettingsStorage.swift @@ -62,6 +62,11 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.general) } + // Every launch since 0.51.0 sets the startup migration flag, with no user action; read it before this launch does. + func hasLaunchedBefore() -> Bool { + defaults.object(forKey: Keys.startupReopenMigration) != nil || defaults.bool(forKey: Keys.hasSeenWelcomeSheet) + } + func migrateStartupBehaviorToReopenLastIfNeeded() { guard !defaults.bool(forKey: Keys.startupReopenMigration) else { return } defaults.set(true, forKey: Keys.startupReopenMigration) diff --git a/apple/TablePro/ViewModels/WelcomeViewModel+Library.swift b/apple/TablePro/ViewModels/WelcomeViewModel+Library.swift index 676d4aa587..4b51e1319a 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel+Library.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel+Library.swift @@ -423,6 +423,7 @@ extension WelcomeViewModel { disconnectableConnectionIds: disconnectable, reconnectableConnectionIds: reconnectable, isSyncEnabled: services.appSettings.sync.enabled, + isCompareSyncEnabled: AppModuleSettings.shared.isEnabled(.compareSync), canPublishToTeamCatalog: services.featureAccess.isAvailable(.teamCatalog), teamLibraryTeams: services.featureAccess.isAvailable(.teamLibrary) ? TeamLibrarySync.shared.writableTeams : [], hasTeamLibraryConflicts: !TeamLibrarySync.shared.conflicts.isEmpty diff --git a/apple/TablePro/Views/Compare/CompareSyncWindowController.swift b/apple/TablePro/Views/Compare/CompareSyncWindowController.swift index 3474057634..993136a3d6 100644 --- a/apple/TablePro/Views/Compare/CompareSyncWindowController.swift +++ b/apple/TablePro/Views/Compare/CompareSyncWindowController.swift @@ -72,7 +72,9 @@ internal final class CompareSyncWindowController: NSWindowController, windowBackdrop = ThemeWindowBackdrop(window: window) super.init(window: window) - CompareSyncRunRegistry.shared.track(session, windowId: windowId) + CompareSyncRunRegistry.shared.track(session, windowId: windowId) { [weak self] in + self?.closeWithoutAsking() + } applyPrefill(connectionId) window.contentViewController = makeContentController() window.delegate = self @@ -749,6 +751,19 @@ internal final class CompareSyncWindowController: NSWindowController, return false } + // Sheets first: a window closed under one leaves the sheet on screen with nothing behind it. + private func closeWithoutAsking() { + isCloseApproved = true + guard let window else { return } + for presented in window.contentViewController?.presentedViewControllers ?? [] { + window.contentViewController?.dismiss(presented) + } + if let sheet = window.attachedSheet { + window.endSheet(sheet) + } + window.close() + } + internal func windowWillClose(_ notification: Notification) { // Stays listed until the run itself ends: a statement already sent can still be writing. session.cancelRunningWork() diff --git a/apple/TablePro/Views/Welcome/WelcomeMenuSpec.swift b/apple/TablePro/Views/Welcome/WelcomeMenuSpec.swift index e03d3b268f..c493594214 100644 --- a/apple/TablePro/Views/Welcome/WelcomeMenuSpec.swift +++ b/apple/TablePro/Views/Welcome/WelcomeMenuSpec.swift @@ -69,6 +69,7 @@ internal struct WelcomeMenuContext { internal let disconnectableConnectionIds: Set internal let reconnectableConnectionIds: Set internal let isSyncEnabled: Bool + internal let isCompareSyncEnabled: Bool internal let canPublishToTeamCatalog: Bool internal let teamLibraryTeams: [TeamLibraryTeam] internal let hasTeamLibraryConflicts: Bool @@ -151,12 +152,14 @@ internal enum WelcomeMenuSpec { primary.append(.command(Titles.disconnect, .disconnect(id))) } - let manage: [WelcomeMenuItem] = [ + var manage: [WelcomeMenuItem] = [ .command(Titles.edit, .edit(id)), .command(Titles.rename, .rename(.connection(id, section: section))), .command(Titles.duplicate, .duplicate(id)), - .command(Titles.compareAndSync, .compareAndSync(id)), ] + if context.isCompareSyncEnabled { + manage.append(.command(Titles.compareAndSync, .compareAndSync(id))) + } let currentGroupId = validGroupId(of: connection, groups: context.groups) var organize: [WelcomeMenuItem] = [ diff --git a/apple/TableProTests/Core/Compare/CompareSyncModuleResidueTests.swift b/apple/TableProTests/Core/Compare/CompareSyncModuleResidueTests.swift new file mode 100644 index 0000000000..4847416299 --- /dev/null +++ b/apple/TableProTests/Core/Compare/CompareSyncModuleResidueTests.swift @@ -0,0 +1,211 @@ +import AppKit +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import Testing + +// An off module leaves nothing behind (apple/AGENTS.md, Scope). No URL, AppleScript or MCP request opens Compare & Sync, +// so the menu bar and the Welcome connection menu are every way in. +@MainActor +struct CompareSyncModuleResidueTests { + private static let commands: Set = [ + #selector(AppDelegate.compareAndSyncDatabases(_:)), + #selector(CompareSyncWindowController.saveComparison(_:)), + #selector(CompareSyncWindowController.runComparison(_:)), + #selector(CompareSyncWindowController.swapEndpoints(_:)), + #selector(CompareSyncWindowController.showOptions(_:)), + #selector(CompareSyncWindowController.generateScript(_:)), + #selector(CompareSyncWindowController.applyToTarget(_:)), + #selector(CompareSyncWindowController.stopComparison(_:)), + ] + + private func flatten(_ menu: NSMenu) -> [NSMenuItem] { + menu.items.flatMap { item -> [NSMenuItem] in + guard let submenu = item.submenu else { return [item] } + return [item] + flatten(submenu) + } + } + + private func compareItems(in menu: NSMenu) -> [NSMenuItem] { + flatten(menu).filter { item in + if let action = item.action, Self.commands.contains(action) { return true } + return item.identifier == DatabaseMenuBuilder.compareIdentifier + || item.identifier == DatabaseMenuBuilder.compareSeparatorIdentifier + } + } + + private func databaseMenu(_ bar: NSMenu) throws -> NSMenu { + try #require(bar.items.first { $0.identifier == DatabaseMenuBuilder.identifier }?.submenu) + } + + private func modules(on: Bool, in suite: EphemeralDefaults) -> AppModuleSettings { + let settings = AppModuleSettings(defaults: suite.defaults, notificationCenter: NotificationCenter()) + settings.setEnabled(on, for: .compareSync) + return settings + } + + private func welcomeTitles(compareSyncOn: Bool) -> [String] { + let connection = DatabaseConnection(name: "Prod", type: .mysql) + let context = WelcomeMenuSpecTests().context( + rows: [.connection(connection.id, section: .connections)], + connections: [connection], + isCompareSyncEnabled: compareSyncOn + ) + return WelcomeMenuSpec.sections(for: context).flatMap(\.items).compactMap { item in + guard case .command(let entry) = item else { return nil } + return entry.title + } + } + + private func runningSession() -> CompareSyncSession { + let session = CompareSyncSession() + session.activity = .comparing + return session + } + + // MARK: - Off + + @Test("Off: the menu bar has no Compare submenu or command, and the Database menu ends at Reconnect") + func offLeavesNoMenu() throws { + let bar = MainMenuBuilder.build(keyboard: KeyboardSettings(), modules: []).bar + let leftovers = compareItems(in: bar).map(\.title) + let last = try #require(try databaseMenu(bar).items.last) + + #expect(leftovers.isEmpty, "Compare items in the menu bar with the module off: \(leftovers)") + #expect(!last.isSeparatorItem) + #expect(last.action == #selector(MainSplitViewController.retryConnection)) + } + + @Test("Off: a connection in the Welcome window offers no Compare & Sync With…") + func offLeavesNoWelcomeItem() { + let titles = welcomeTitles(compareSyncOn: false) + + #expect(!titles.contains(String(localized: "Compare & Sync With…"))) + #expect(titles.contains(String(localized: "Duplicate"))) + } + + @Test("Settings > Keyboard lists the same rows on or off, and no Compare command takes a key") + func keyboardIsUntouched() { + let rows: (Set) -> [ShortcutAction] = { enabled in + ShortcutCategory.allCases.flatMap { ShortcutAction.settingsRows(in: $0, enabledModules: enabled) } + } + let bar = MainMenuBuilder.build(keyboard: KeyboardSettings(), modules: [.compareSync]).bar + let keyed = compareItems(in: bar).filter { !$0.keyEquivalent.isEmpty }.map(\.title) + + #expect(rows([]) == rows([.compareSync])) + #expect(keyed.isEmpty, "Compare commands with a key equivalent: \(keyed)") + } + + // A statement already sent can still be writing, so quitting asks until the run itself ends, as after closing the window. + @Test("A run that turning the module off cancelled stays in the quit check until it ends") + func cancelledRunStaysInTheQuitCheck() { + let registry = CompareSyncRunRegistry() + let session = runningSession() + registry.track(session, windowId: UUID()) {} + + registry.endAll() + let draining = registry.runningWork().map { $0.id } + session.activity = .idle + + #expect(draining == [session.workId]) + #expect(registry.runningWork().isEmpty) + } + + @Test("Off: opening Compare & Sync opens nothing and never reads the license") + func offOpensNothing() { + var licenseReads = 0 + let decision = CompareSyncLauncher.launch(moduleEnabled: false) { + licenseReads += 1 + return true + } + + #expect(decision == .moduleOff) + #expect(licenseReads == 0) + } + + // The host's own module state, which no test turns on, as a new install has it. + @Test("Off: the launcher the menus call opens no window in the host") + func offHostOpensNoWindow() throws { + try #require(!AppModuleSettings.shared.isEnabled(.compareSync)) + CompareSyncLauncher.open(prefillSource: UUID()) + + #expect(!NSApp.windows.contains { $0.identifier?.rawValue == WindowIdentifier.compareSync }) + } + + // MARK: - On + + @Test("On: the Compare submenu closes the Database menu behind a separator, with its eight commands") + func onAddsTheSubmenu() throws { + let bar = MainMenuBuilder.build(keyboard: KeyboardSettings(), modules: [.compareSync]).bar + let items = try databaseMenu(bar).items + let last = try #require(items.last) + let commands = (last.submenu?.items ?? []).filter { !$0.isSeparatorItem } + let actions = Set(commands.compactMap { $0.action }) + let targeted = commands.filter { $0.target != nil }.map(\.title) + + #expect(last.identifier == DatabaseMenuBuilder.compareIdentifier) + #expect(items[items.count - 2].isSeparatorItem) + #expect(items[items.count - 2].identifier == DatabaseMenuBuilder.compareSeparatorIdentifier) + #expect(commands.count == 8) + #expect(actions == Self.commands) + #expect(targeted.isEmpty) + } + + @Test("On: a connection in the Welcome window offers Compare & Sync With… after Duplicate") + func onAddsTheWelcomeItem() throws { + let titles = welcomeTitles(compareSyncOn: true) + let duplicate = try #require(titles.firstIndex(of: String(localized: "Duplicate"))) + + #expect(titles[duplicate + 1] == String(localized: "Compare & Sync With…")) + } + + @Test("On: without a license opening asks for one, as before; with one it opens") + func onKeepsTheLicenseGate() { + #expect(CompareSyncLauncher.launch(moduleEnabled: true) { false } == .needsLicense) + #expect(CompareSyncLauncher.launch(moduleEnabled: true) { true } == .open) + } + + // MARK: - Switching + + @Test("Switching the module adds and removes the Compare submenu in the installed bar at once") + func switchingEditsTheInstalledBar() throws { + let built = MainMenuBuilder.build(keyboard: KeyboardSettings(), modules: []) + let offTitles = try databaseMenu(built.bar).items.map(\.title) + + MainMenuBuilder.applyModules([.compareSync], keyboard: KeyboardSettings(), to: built.bar, windowsMenu: built.windowsMenu) + MainMenuBuilder.applyModules([.compareSync], keyboard: KeyboardSettings(), to: built.bar, windowsMenu: built.windowsMenu) + let onTitles = try databaseMenu(built.bar).items.map(\.title) + let onBuilt = MainMenuBuilder.build(keyboard: KeyboardSettings(), modules: [.compareSync]).bar + let onBuiltTitles = try databaseMenu(onBuilt).items.map(\.title) + let compareCount = try databaseMenu(built.bar).items.filter { $0.identifier == DatabaseMenuBuilder.compareIdentifier }.count + + #expect(onTitles == onBuiltTitles) + #expect(compareCount == 1) + + MainMenuBuilder.applyModules([], keyboard: KeyboardSettings(), to: built.bar, windowsMenu: built.windowsMenu) + let switchedOffTitles = try databaseMenu(built.bar).items.map(\.title) + #expect(switchedOffTitles == offTitles) + #expect(compareItems(in: built.bar).isEmpty) + } + + // Through the Extensions checkbox's own path; it edits the host's menu bar, so the case ends with the module off. + @Test("Turning the module off stops every comparison and closes every Compare & Sync window") + func turningOffEndsEveryRun() throws { + let suite = try EphemeralDefaults() + let settings = modules(on: false, in: suite) + let running = runningSession() + let progress = Progress(totalUnitCount: 1) + running.progress = progress + let idle = CompareSyncSession() + var closed: [String] = [] + CompareSyncRunRegistry.shared.track(running, windowId: UUID()) { closed.append("running") } + CompareSyncRunRegistry.shared.track(idle, windowId: UUID()) { closed.append("idle") } + + AppModuleActivation.setEnabled(true, for: .compareSync, settings: settings) + #expect(closed.isEmpty) + AppModuleActivation.setEnabled(false, for: .compareSync, settings: settings) + + #expect(progress.isCancelled) + #expect(closed.sorted() == ["idle", "running"]) + } +} diff --git a/apple/TableProTests/Core/LiveMessages/LiveMessagesModuleResidueTests.swift b/apple/TableProTests/Core/LiveMessages/LiveMessagesModuleResidueTests.swift index 68cd0d6a71..8fc871e9c7 100644 --- a/apple/TableProTests/Core/LiveMessages/LiveMessagesModuleResidueTests.swift +++ b/apple/TableProTests/Core/LiveMessages/LiveMessagesModuleResidueTests.swift @@ -33,8 +33,10 @@ struct LiveMessagesModuleResidueTests { #expect(liveItems(in: built.bar).count == 1) } - @Test("The module is off by default") - func offByDefault() { - #expect(!AppModule.liveMessages.defaultEnabled) + @Test("The module is off by default, on a Mac that ran an earlier build too") + func offByDefault() throws { + let suite = try EphemeralDefaults() + AppModule.recordDefaults(in: suite.defaults, isExistingInstall: true) + #expect(!AppModule.liveMessages.defaultEnabled(in: suite.defaults)) } } diff --git a/apple/TableProTests/Core/Modules/AppModuleDefaultTests.swift b/apple/TableProTests/Core/Modules/AppModuleDefaultTests.swift new file mode 100644 index 0000000000..174ea73793 --- /dev/null +++ b/apple/TableProTests/Core/Modules/AppModuleDefaultTests.swift @@ -0,0 +1,101 @@ +import Foundation +@testable import TablePro +import Testing + +// A tool that was core before it became a module stays on for a Mac that ran an earlier build and starts off on a new one. +@MainActor +struct AppModuleDefaultTests { + private func launch(_ suite: EphemeralDefaults) -> AppModuleSettings { + let storage = AppSettingsStorage(userDefaults: suite.defaults) + AppModule.recordDefaults(in: suite.defaults, isExistingInstall: storage.hasLaunchedBefore()) + storage.migrateStartupBehaviorToReopenLastIfNeeded() + return AppModuleSettings(defaults: suite.defaults, notificationCenter: NotificationCenter()) + } + + private func existingInstall() throws -> EphemeralDefaults { + let suite = try EphemeralDefaults() + AppSettingsStorage(userDefaults: suite.defaults).migrateStartupBehaviorToReopenLastIfNeeded() + return suite + } + + @Test("A new install starts with Compare & Sync off, and the next launch keeps it off") + func newInstallStartsOff() throws { + let suite = try EphemeralDefaults() + + #expect(!launch(suite).isEnabled(.compareSync)) + #expect(!launch(suite).isEnabled(.compareSync)) + #expect(AppModule.enabledModules(in: suite.defaults).isEmpty) + } + + @Test("A Mac that ran an earlier build keeps Compare & Sync on, and only modules that were core") + func existingInstallKeepsItOn() throws { + let suite = try existingInstall() + let settings = launch(suite) + + #expect(settings.isEnabled(.compareSync)) + #expect(!settings.isEnabled(.routineDebugger)) + #expect(!settings.isEnabled(.liveMessages)) + #expect(launch(suite).isEnabled(.compareSync)) + } + + @Test("Finishing onboarding on an older build also marks an existing install") + func onboardingMarksAnExistingInstall() throws { + let suite = try EphemeralDefaults() + AppSettingsStorage(userDefaults: suite.defaults).markWelcomeSheetSeen() + + #expect(launch(suite).isEnabled(.compareSync)) + } + + @Test("The default is recorded once; a later launch never changes it") + func defaultIsRecordedOnce() throws { + let suite = try EphemeralDefaults() + AppModule.recordDefaults(in: suite.defaults, isExistingInstall: false) + AppModule.recordDefaults(in: suite.defaults, isExistingInstall: true) + + #expect(!AppModule.compareSync.defaultEnabled(in: suite.defaults)) + } + + @Test("Recording writes only the default keys: the on/off keys an older build reads stay unset") + func recordingLeavesTheOnOffKeys() throws { + let suite = try existingInstall() + _ = launch(suite) + + for module in AppModule.allCases { + #expect(suite.defaults.object(forKey: module.defaultsKey) == nil, "\(module.rawValue)") + } + #expect(suite.defaults.object(forKey: AppModule.routineDebugger.recordedDefaultKey) == nil) + #expect(suite.defaults.object(forKey: AppModule.liveMessages.recordedDefaultKey) == nil) + } + + @Test("Turning the module off on an existing install survives a relaunch") + func userChoiceWins() throws { + let suite = try existingInstall() + launch(suite).setEnabled(false, for: .compareSync) + + #expect(!launch(suite).isEnabled(.compareSync)) + } + + // Reset applies to the host's menu bar, so each case ends with the module off, as the host has it. + @Test("Reset All Settings turns Compare & Sync back on for a Mac that had it before") + func resetReturnsAnExistingInstallToOn() throws { + let suite = try existingInstall() + let settings = launch(suite) + defer { AppModuleActivation.setEnabled(false, for: .compareSync, settings: settings) } + settings.setEnabled(false, for: .compareSync) + + AppModuleActivation.resetToDefaults(settings: settings) + + #expect(settings.isEnabled(.compareSync)) + } + + @Test("Reset All Settings turns Compare & Sync back off on a new install") + func resetReturnsANewInstallToOff() throws { + let suite = try EphemeralDefaults() + let settings = launch(suite) + settings.setEnabled(true, for: .compareSync) + + AppModuleActivation.resetToDefaults(settings: settings) + + #expect(!settings.isEnabled(.compareSync)) + } +} diff --git a/apple/TableProTests/Core/Modules/AppModuleSettingsTests.swift b/apple/TableProTests/Core/Modules/AppModuleSettingsTests.swift index 9ba525bbbd..07a3e83395 100644 --- a/apple/TableProTests/Core/Modules/AppModuleSettingsTests.swift +++ b/apple/TableProTests/Core/Modules/AppModuleSettingsTests.swift @@ -4,13 +4,14 @@ import Testing @MainActor struct AppModuleSettingsTests { - @Test("Every module starts off on a Mac that never turned it on") + @Test("Every module starts off on a new install") func modulesStartOff() throws { let suite = try EphemeralDefaults() + AppModule.recordDefaults(in: suite.defaults, isExistingInstall: false) let settings = AppModuleSettings(defaults: suite.defaults, notificationCenter: NotificationCenter()) for module in AppModule.allCases { - #expect(module.defaultEnabled == false, "\(module.rawValue)") + #expect(!settings.defaultEnabled(module), "\(module.rawValue)") #expect(!settings.isEnabled(module), "\(module.rawValue)") } #expect(settings.enabledModules.isEmpty) @@ -42,7 +43,7 @@ struct AppModuleSettingsTests { AppModuleActivation.resetToDefaults(settings: settings) for module in AppModule.allCases { - #expect(settings.isEnabled(module) == module.defaultEnabled, "\(module.rawValue)") + #expect(settings.isEnabled(module) == settings.defaultEnabled(module), "\(module.rawValue)") } } @@ -87,9 +88,9 @@ struct AppModuleSettingsTests { #expect(suite.defaults.object(forKey: AppModule.routineDebugger.defaultsKey) == nil) } - @Test("The key is namespaced and per module") + @Test("The keys are namespaced and per module") func keysAreNamespaced() { - let keys = AppModule.allCases.map { $0.defaultsKey } + let keys = AppModule.allCases.flatMap { [$0.defaultsKey, $0.recordedDefaultKey] } #expect(Set(keys).count == keys.count) for key in keys { #expect(key.hasPrefix("com.TablePro.modules."), "\(key)") diff --git a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift index 2132427c87..4df579f945 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift @@ -10,14 +10,12 @@ import XCTest final class WindowOpenerTests: XCTestCase { private var openedRequests: [ConnectionFormRequest] = [] private var openedSettingsPanes: [SettingsPane?] = [] - private var openedCompareSources: [UUID?] = [] override func setUp() async throws { try await super.setUp() _ = WelcomeRouter.shared.consumePendingRequest() openedRequests = [] openedSettingsPanes = [] - openedCompareSources = [] WindowOpener.shared.setWelcomePresenter {} WindowOpener.shared.setConnectionFormPresenter { [weak self] request in self?.openedRequests.append(request) @@ -26,9 +24,6 @@ final class WindowOpenerTests: XCTestCase { WindowOpener.shared.setSettingsPresenter { [weak self] pane in self?.openedSettingsPanes.append(pane) } - WindowOpener.shared.setCompareSyncPresenter { [weak self] connectionId in - self?.openedCompareSources.append(connectionId) - } } override func tearDown() async throws { @@ -202,33 +197,6 @@ final class WindowOpenerTests: XCTestCase { XCTAssertEqual(openedSettingsPanes, [SettingsPane?.none]) } - func testCompareSyncCarriesThePrefilledSourceToThePresenter() { - let connectionId = UUID() - - WindowOpener.shared.openCompareSync(prefillSource: connectionId) - - XCTAssertEqual(openedCompareSources, [connectionId]) - } - - func testCompareSyncOpenedFromTheMenuCarriesNoSource() { - WindowOpener.shared.openCompareSync() - - XCTAssertEqual(openedCompareSources, [UUID?.none]) - } - - func testACompareSyncCallQueuedBeforeItsPresenterKeepsItsSource() { - let opener = WindowOpener() - var opened: [UUID?] = [] - let connectionId = UUID() - - opener.openCompareSync(prefillSource: connectionId) - XCTAssertTrue(opened.isEmpty, "No presenter yet, so the call has to wait") - - opener.setCompareSyncPresenter { opened.append($0) } - - XCTAssertEqual(opened, [connectionId]) - } - func testEditingTheSameConnectionTwiceRequestsTheSameWindow() { let connectionId = UUID() diff --git a/apple/TableProTests/Views/Welcome/WelcomeMenuSpecTests.swift b/apple/TableProTests/Views/Welcome/WelcomeMenuSpecTests.swift index 6cf45dfe87..8095c35916 100644 --- a/apple/TableProTests/Views/Welcome/WelcomeMenuSpecTests.swift +++ b/apple/TableProTests/Views/Welcome/WelcomeMenuSpecTests.swift @@ -10,7 +10,7 @@ import Testing @MainActor struct WelcomeMenuSpecTests { - private func context( + func context( rows: [LibraryRowID], connections: [DatabaseConnection] = [], groups: [ConnectionGroup] = [], @@ -18,6 +18,7 @@ struct WelcomeMenuSpecTests { reconnectable: Set = [], linkedFolders: Set = [], isSyncEnabled: Bool = false, + isCompareSyncEnabled: Bool = false, teamLibraryTeams: [TeamLibraryTeam] = [], hasTeamLibraryConflicts: Bool = false ) -> WelcomeMenuContext { @@ -48,6 +49,7 @@ struct WelcomeMenuSpecTests { disconnectableConnectionIds: disconnectable, reconnectableConnectionIds: reconnectable, isSyncEnabled: isSyncEnabled, + isCompareSyncEnabled: isCompareSyncEnabled, canPublishToTeamCatalog: false, teamLibraryTeams: teamLibraryTeams, hasTeamLibraryConflicts: hasTeamLibraryConflicts From 5f3432bc386288faf66624548a1ed07ae6eac86f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 21 Nov 2026 21:07:09 +0700 Subject: [PATCH 2/2] docs(changelog): add the Compare & Sync module fragment --- apple/changelog.d/4404.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 apple/changelog.d/4404.changed.md diff --git a/apple/changelog.d/4404.changed.md b/apple/changelog.d/4404.changed.md new file mode 100644 index 0000000000..37a1689a0b --- /dev/null +++ b/apple/changelog.d/4404.changed.md @@ -0,0 +1 @@ +Compare & Sync is now a module in Settings > Extensions: it stays on for existing installs and starts off on new ones.