diff --git a/Sources/Hushtype/CloudSync.swift b/Sources/Hushtype/CloudSync.swift index c9d9f59..3c3990b 100644 --- a/Sources/Hushtype/CloudSync.swift +++ b/Sources/Hushtype/CloudSync.swift @@ -2,9 +2,10 @@ import Combine import Foundation import HushtypeCore -/// Mirrors the settings that follow a person, not a Mac, through iCloud key-value storage: the -/// dictionary, snippets and style choices. The dictation key, microphone, login item and history -/// stay on each Mac, and so does "keep history", since turning it off erases that Mac's history. +/// Mirrors the style choices, which follow a person rather than a Mac, through iCloud key-value +/// storage. DeviceSync carries the dictionary and snippets (through iCloud too, merged word by +/// word with the iPhone). The dictation key, microphone, login item and history stay on each +/// Mac, and so does "keep history", since turning it off erases that Mac's history. /// This Mac's copy stays the source of truth; iCloud carries changes between Macs. @MainActor final class CloudSync { @@ -18,8 +19,6 @@ final class CloudSync { private var applyingRemote = false private enum Key { - static let dictionary = "dictionary" - static let snippets = "snippets" static let cleanupEnabled = "cleanupEnabled" static let useContext = "useContext" static let language = "language" @@ -61,8 +60,6 @@ final class CloudSync { pull(merging: true) pushAll() - watch(settings.$dictionaryText) { [weak self] _ in self?.pushDictionary() } - watch(settings.$snippets) { [weak self] _ in self?.pushSnippets() } watch(settings.$cleanupEnabled) { [weak self] in self?.push($0, Key.cleanupEnabled) } watch(settings.$useContext) { [weak self] in self?.push($0, Key.useContext) } watch(settings.$language) { [weak self] in self?.push($0, Key.language) } @@ -87,8 +84,6 @@ final class CloudSync { // MARK: Sending private func pushAll() { - pushDictionary() - pushSnippets() push(settings.cleanupEnabled, Key.cleanupEnabled) push(settings.useContext, Key.useContext) push(settings.language, Key.language) @@ -100,25 +95,10 @@ final class CloudSync { private func push(_ value: Bool, _ key: String) { store.set(value, forKey: key) } private func push(_ value: String, _ key: String) { store.set(value, forKey: key) } - /// Hushtype device sync carries the dictionary and snippets when it's on. iCloud copies them - /// only by replacing the whole list, which would undo that sync's per-word merging. - private var deviceSyncOn: Bool { UserDefaults.standard.bool(forKey: DeviceSync.enabledKey) } - - private func pushDictionary() { - guard !deviceSyncOn else { return } - store.set(settings.dictionaryText, forKey: Key.dictionary) - } - - private func pushSnippets() { - guard !deviceSyncOn else { return } - if let data = try? JSONEncoder().encode(settings.snippets) { store.set(data, forKey: Key.snippets) } - } - // MARK: Receiving - /// Applies what's in iCloud. When sync is first turned on, words and snippets are merged so - /// nothing on either side is lost; after that iCloud's copy replaces this Mac's, so a word - /// removed on one Mac is removed on the others too. + /// Applies the style choices in iCloud. The dictionary and snippets go through DeviceSync, + /// which merges them word by word with the iPhone and the sync server. private func pull(merging: Bool) { applyingRemote = true defer { @@ -126,19 +106,6 @@ final class CloudSync { DispatchQueue.main.async { [weak self] in self?.applyingRemote = false } } - if !deviceSyncOn, let remote = store.string(forKey: Key.dictionary) { - if merging { - settings.addToDictionary(DictationPipeline.vocabulary(from: remote)) - } else if remote != settings.dictionaryText { - settings.dictionaryText = remote - } - } - if !deviceSyncOn, let data = store.data(forKey: Key.snippets), - let remote = try? JSONDecoder().decode([Snippet].self, from: data) { - let updated = merging ? SnippetSync.merge(settings.snippets, remote) : remote - if updated != settings.snippets { settings.snippets = updated } - } - // Simple choices take the latest value from iCloud. if let value = bool(Key.cleanupEnabled), value != settings.cleanupEnabled { settings.cleanupEnabled = value } if let value = bool(Key.useContext), value != settings.useContext { settings.useContext = value } diff --git a/Sources/Hushtype/DeviceSync.swift b/Sources/Hushtype/DeviceSync.swift index 4ce0989..6c3eb19 100644 --- a/Sources/Hushtype/DeviceSync.swift +++ b/Sources/Hushtype/DeviceSync.swift @@ -3,9 +3,11 @@ import Combine import HushtypeCore import os -/// Keeps the dictionary and snippets in step with the person's other devices (Macs, iPhone, -/// Android) through the Hushtype sync server. Everything is encrypted on this Mac with a secret -/// only the paired devices know; pairing hands that secret over as a QR code or a typed code. +/// Keeps the dictionary and snippets in step with the person's other devices, two ways at once: +/// - iCloud, when "Sync with iCloud" is on: Macs and iPhones on the same Apple ID, no pairing. +/// - The Hushtype sync server, once paired: any device, Android too. Everything is encrypted on +/// this Mac with a secret only the paired devices know; pairing hands it over as a QR code. +/// Both hold the same per-word record (`SyncVocabulary`), so each round merges whatever both say. @MainActor final class DeviceSync: ObservableObject { enum Status: Equatable { @@ -15,10 +17,9 @@ final class DeviceSync: ObservableObject { case failed(String) } - /// Read by iCloud sync, which leaves the dictionary and snippets alone while this is on. - static let enabledKey = "deviceSyncEnabled" private static let ledgerKey = "deviceSyncLedger" private static let lastSyncKey = "deviceSyncLast" + private static let legacyImportedKey = "deviceSyncImportedLegacyICloud" private static let keychainAccount = "device-sync-secret" private static let interval: Duration = .seconds(10 * 60) @@ -27,10 +28,11 @@ final class DeviceSync: ObservableObject { private let settings: SettingsStore private let defaults = UserDefaults.standard + private let cloud = NSUbiquitousKeyValueStore.default private let log = Logger(subsystem: "app.hushtype.Hushtype", category: "sync") private var subscriptions: Set = [] private var timer: Task? - private var wakeObserver: NSObjectProtocol? + private var observers: [NSObjectProtocol] = [] private var running = false private var runAgain = false /// True while synced words are written into Settings, so that write doesn't start a sync. @@ -41,8 +43,7 @@ final class DeviceSync: ObservableObject { if let secret = Keychain.read(account: Self.keychainAccount).flatMap({ Data(base64Encoded: $0) }) { keys = SyncKeys(secret: secret) } - if keys != nil, let last = defaults.object(forKey: Self.lastSyncKey) as? Date { status = .upToDate(last) } - defaults.set(keys != nil, forKey: Self.enabledKey) + if isOn, let last = defaults.object(forKey: Self.lastSyncKey) as? Date { status = .upToDate(last) } // Edits sync a couple of seconds after they settle. settings.$dictionaryText.map { _ in () } @@ -52,18 +53,39 @@ final class DeviceSync: ObservableObject { .debounce(for: .seconds(2), scheduler: DispatchQueue.main) .sink { [weak self] in self?.syncNow() } .store(in: &subscriptions) - wakeObserver = NSWorkspace.shared.notificationCenter.addObserver( - forName: NSWorkspace.didWakeNotification, object: nil, queue: .main - ) { [weak self] _ in - MainActor.assumeIsolated { self?.syncNow() } - } + settings.$iCloudSync + .dropFirst() + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + guard let self else { return } + if !self.isOn { self.status = .off } + self.syncNow() + } + .store(in: &subscriptions) + observers = [ + NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.didWakeNotification, object: nil, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.syncNow() } + }, + NotificationCenter.default.addObserver( + forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: cloud, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.syncNow() } + }, + ] + cloud.synchronize() startTimer() syncNow() } - var isOn: Bool { keys != nil } + /// Paired through the sync server. + var isPaired: Bool { keys != nil } + /// Syncing words through iCloud. + var usesICloud: Bool { settings.iCloudSync } + var isOn: Bool { isPaired || usesICloud } - // MARK: Turning it on and off + // MARK: Pairing /// Starts a new group with this Mac's words. Other devices join by scanning its code. func turnOn() { @@ -72,33 +94,35 @@ final class DeviceSync: ObservableObject { syncNow() } - /// Joins the group another device started. Throws, leaving sync off, when the code is wrong or - /// the server can't be reached. + /// Joins the group another device started. Throws, leaving pairing off, when the code is + /// wrong or the server can't be reached. func join(code: String) async throws { guard let joined = SyncKeys(pairingCode: code) else { throw PairingError.notACode } status = .syncing - let ledger = loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + let ledger = localLedger() do { let merged = try await SyncClient(keys: joined).sync(ledger, joining: true) save(joined) apply(merged, startedFrom: ledger) finished() } catch { - status = keys == nil ? .off : status + status = isOn ? .failed(error.localizedDescription) : .off throw error } } - /// Stops syncing on this Mac. Its words stay; the other devices keep syncing with each other. + /// Unpairs this Mac. Its words stay; the other devices keep syncing with each other, and + /// iCloud keeps syncing if it's on. func turnOff() { Keychain.delete(account: Self.keychainAccount) - defaults.removeObject(forKey: Self.ledgerKey) - defaults.removeObject(forKey: Self.lastSyncKey) - defaults.set(false, forKey: Self.enabledKey) keys = nil - status = .off + if !usesICloud { + defaults.removeObject(forKey: Self.ledgerKey) + defaults.removeObject(forKey: Self.lastSyncKey) + status = .off + } } enum PairingError: LocalizedError { @@ -111,20 +135,27 @@ final class DeviceSync: ObservableObject { private func save(_ new: SyncKeys) { Keychain.write(new.secret.base64EncodedString(), account: Self.keychainAccount) keys = new - defaults.set(true, forKey: Self.enabledKey) } // MARK: Syncing func syncNow() { - guard let keys else { return } + guard isOn else { return } if running { runAgain = true return } running = true status = .syncing - let ledger = loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + let keys = self.keys + let iCloud = usesICloud + if iCloud { importLegacyICloudOnce() } + // `local` is what this device's words say. `start` adds what iCloud holds, and goes to the + // server. Applying has to reconcile against `local`: against `start`, words that just came + // from iCloud aren't in Settings yet and would look removed here, and be deleted everywhere. + let local = localLedger() + let fromICloud = iCloud ? CloudVocabulary.read(from: cloud) : nil + let start = fromICloud.map { SyncVocabulary.merge(local: local, remote: $0) } ?? local Task { defer { running = false @@ -133,25 +164,39 @@ final class DeviceSync: ObservableObject { syncNow() } } - do { - let merged = try await SyncClient(keys: keys).sync(ledger) - guard self.keys == keys else { return } - apply(merged, startedFrom: ledger) + var merged = start + var failure: Error? + if let keys { + do { + merged = try await SyncClient(keys: keys).sync(start) + } catch { + failure = error + } + } + guard self.keys == keys, usesICloud == iCloud else { return } + apply(merged, startedFrom: local) + if let failure { + log.error("Sync failed: \(failure.localizedDescription, privacy: .public)") + status = .failed(failure.localizedDescription) + } else { finished() - } catch { - guard self.keys == keys else { return } - log.error("Sync failed: \(error.localizedDescription, privacy: .public)") - status = .failed(error.localizedDescription) } } } + /// This Mac's record, updated with edits made since the last round. + private func localLedger() -> SyncVocabulary { + loadLedger().reconciled(terms: settings.vocabulary, snippets: settings.snippets) + } + /// Writes the merged words into Settings without losing edits made while the request was out: - /// those are folded in with newer timestamps and go up on the next round. + /// those are folded in with newer timestamps and go up on the next round. Then iCloud gets the + /// result. private func apply(_ merged: SyncVocabulary, startedFrom ledger: SyncVocabulary) { let current = ledger.reconciled(terms: settings.vocabulary, snippets: settings.snippets) - let final = SyncVocabulary.merge(local: current, remote: merged) + let final = SyncVocabulary.merge(local: current, remote: merged).compacted() saveLedger(final) + if usesICloud { CloudVocabulary.write(final, to: cloud) } let words = final.dictionary(keepingOrderOf: settings.vocabulary) let snippets = final.snippetList(keepingOrderOf: settings.snippets) @@ -159,7 +204,21 @@ final class DeviceSync: ObservableObject { if words != settings.vocabulary { settings.dictionaryText = words.joined(separator: "\n") } if snippets != settings.snippets { settings.snippets = snippets } DispatchQueue.main.async { [weak self] in self?.applying = false } - if final != merged { runAgain = true } + if isPaired, final != merged { runAgain = true } + } + + /// Hushtype 0.3.7 and earlier kept the whole dictionary as one iCloud value. Its words are + /// added here once, so nothing an older Mac synced is lost. + private func importLegacyICloudOnce() { + guard !defaults.bool(forKey: Self.legacyImportedKey) else { return } + defaults.set(true, forKey: Self.legacyImportedKey) + let legacy = CloudVocabulary.legacy(from: cloud) + applying = true + if !legacy.terms.isEmpty { settings.addToDictionary(legacy.terms) } + let known = Set(settings.snippets.map(\.id)) + let missing = legacy.snippets.filter { !known.contains($0.id) } + if !missing.isEmpty { settings.snippets += missing } + DispatchQueue.main.async { [weak self] in self?.applying = false } } private func finished() { diff --git a/Sources/Hushtype/DeviceSyncViews.swift b/Sources/Hushtype/DeviceSyncViews.swift index 2dccf45..13a90c2 100644 --- a/Sources/Hushtype/DeviceSyncViews.swift +++ b/Sources/Hushtype/DeviceSyncViews.swift @@ -13,7 +13,7 @@ struct DeviceSyncSection: View { var body: some View { SectionLabel("Your devices") SettingsCard { - if sync.isOn { + if sync.isPaired { SettingsRow(title: "Dictionary and snippets sync", subtitle: statusText, symbol: "arrow.clockwise", @@ -36,8 +36,8 @@ struct DeviceSyncSection: View { Button("Turn Off") { sync.turnOff() } } } else { - SettingsRow(title: "Sync with your iPhone and Android", - subtitle: "Your dictionary and snippets, end-to-end encrypted. No account needed.", + SettingsRow(title: "Sync with Android and other devices", + subtitle: "For devices that aren't on your Apple ID. End-to-end encrypted, no account needed.", symbol: "arrow.clockwise", info: Self.privacyNote) { HStack(spacing: 8) { diff --git a/Sources/Hushtype/SettingsWindow.swift b/Sources/Hushtype/SettingsWindow.swift index 05052fd..e2a7215 100644 --- a/Sources/Hushtype/SettingsWindow.swift +++ b/Sources/Hushtype/SettingsWindow.swift @@ -1370,9 +1370,7 @@ private struct GeneralPane: View { SectionLabel("iCloud") SettingsCard { ToggleRow(title: "Sync with iCloud", - subtitle: deviceSync.isOn - ? "Your style settings follow you to your other Macs. Your dictionary and snippets sync with your devices above." - : "Your dictionary, snippets and style settings follow you to your other Macs. The dictation key, microphone and history stay on this Mac.", + subtitle: "Your dictionary, snippets and style settings follow you to your iPhone and other Macs on this Apple ID, with no pairing. The dictation key, microphone and history stay on this Mac.", symbol: "icloud", isOn: $settings.iCloudSync) SettingsRow(title: "Include Anthropic API key", subtitle: keySyncError ?? "Kept in iCloud Keychain, end-to-end encrypted, so you only paste it once.", diff --git a/Sources/HushtypeCore/CloudVocabulary.swift b/Sources/HushtypeCore/CloudVocabulary.swift new file mode 100644 index 0000000..4696a36 --- /dev/null +++ b/Sources/HushtypeCore/CloudVocabulary.swift @@ -0,0 +1,39 @@ +import Foundation + +/// The dictionary and snippets in iCloud key-value storage, so a Mac and an iPhone on the same +/// Apple ID sync with no pairing. It holds the same `SyncVocabulary` as the sync server and merges +/// the same way, item by item, so iCloud and the server can both be on without fighting: each +/// device merges whatever it finds in both places. +/// +/// The Mac app and the iPhone app share one store: both apps' entitlements set +/// `com.apple.developer.ubiquity-kvstore-identifier` to `.app.hushtype.Hushtype`. +public enum CloudVocabulary { + static let key = "vocabulary.v1" + /// What Hushtype 0.3.7 and earlier wrote on the Mac: the whole dictionary as text, and the + /// snippets as JSON. Read once and merged in, never written any more. + static let legacyDictionaryKey = "dictionary" + static let legacySnippetsKey = "snippets" + + public static func read(from store: NSUbiquitousKeyValueStore = .default) -> SyncVocabulary? { + store.data(forKey: key).flatMap { try? JSONDecoder().decode(SyncVocabulary.self, from: $0) } + } + + /// Writes only when something changed, since iCloud rate-limits writes. + public static func write(_ vocabulary: SyncVocabulary, to store: NSUbiquitousKeyValueStore = .default) { + guard read(from: store) != vocabulary, let data = try? JSONEncoder().encode(vocabulary) else { return } + store.set(data, forKey: key) + store.synchronize() + } + + /// The words and snippets an older Mac left in iCloud, for a one-time merge. + public static func legacy(from store: NSUbiquitousKeyValueStore = .default) -> (terms: [String], snippets: [Snippet]) { + let terms = store.string(forKey: legacyDictionaryKey).map(DictationPipeline.vocabulary(from:)) ?? [] + let snippets = store.data(forKey: legacySnippetsKey) + .flatMap { try? JSONDecoder().decode([Snippet].self, from: $0) } ?? [] + return (terms, snippets) + } + + /// True when this device is signed in to iCloud. Doesn't say whether this build has the + /// iCloud entitlement; without it, reads come back empty and writes go nowhere. + public static var isSignedIn: Bool { FileManager.default.ubiquityIdentityToken != nil } +} diff --git a/Tests/HushtypeCoreTests/SyncTests.swift b/Tests/HushtypeCoreTests/SyncTests.swift index bdf7d46..c9d45ef 100644 --- a/Tests/HushtypeCoreTests/SyncTests.swift +++ b/Tests/HushtypeCoreTests/SyncTests.swift @@ -274,3 +274,21 @@ final class LiveSyncTests: XCTestCase { } } } + +final class SyncApplyTests: XCTestCase { + /// Words arriving from iCloud aren't in the device's dictionary yet. Reconciling against the + /// merged copy would read them as removed and delete them everywhere; DeviceSync reconciles + /// against the device's own record instead. + func testWordsFromAnotherDeviceSurviveApplying() { + let local = SyncVocabulary().reconciled(terms: ["Alpha"], snippets: [], now: 10) + let remote = SyncVocabulary().reconciled(terms: ["Beta"], snippets: [], now: 20) + let merged = SyncVocabulary.merge(local: local, remote: remote) + + let current = local.reconciled(terms: ["Alpha"], snippets: [], now: 30) + let final = SyncVocabulary.merge(local: current, remote: merged) + XCTAssertEqual(final.dictionary(keepingOrderOf: ["Alpha"]), ["Alpha", "Beta"]) + + let wrong = merged.reconciled(terms: ["Alpha"], snippets: [], now: 30) + XCTAssertEqual(wrong.liveTerms.map(\.text), ["Alpha"], "the bug this guards against") + } +}