Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 6 additions & 39 deletions Sources/Hushtype/CloudSync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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"
Expand Down Expand Up @@ -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) }
Expand All @@ -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)
Expand All @@ -100,45 +95,17 @@ 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 {
// Let the change notifications from these assignments pass before echoing resumes.
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 }
Expand Down
135 changes: 97 additions & 38 deletions Sources/Hushtype/DeviceSync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)

Expand All @@ -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<AnyCancellable> = []
private var timer: Task<Void, Never>?
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.
Expand All @@ -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 () }
Expand All @@ -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() {
Expand All @@ -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)
Comment on lines +104 to 106

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Merge iCloud data before joining the server group

When iCloud sync is on and this Mac has vocabulary that exists only in iCloud, joining a server group sends only localLedger() to the server. apply() then writes the server/local result back to vocabulary.v1, replacing those iCloud-only words and snippets. Merge the iCloud ledger into the join input before syncing so pairing does not discard existing shared data.

Useful? React with 👍 / 👎.

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 {
Expand All @@ -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
Expand All @@ -133,33 +164,61 @@ 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)
applying = true
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Wait for iCloud's initial download before marking legacy data imported

On a Mac whose iCloud key-value store has not received its initial download, this permanently sets the migration flag before reading legacy values; the subsequent initial-sync notification calls syncNow() again, but the flag then prevents importing them. Apple's synchronize() documentation notes that initial values need not be immediately available, so defer marking the migration complete until the legacy values are available to avoid skipping an existing dictionary or snippets on a new device.

Useful? React with 👍 / 👎.

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() {
Expand Down
6 changes: 3 additions & 3 deletions Sources/Hushtype/DeviceSyncViews.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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) {
Expand Down
4 changes: 1 addition & 3 deletions Sources/Hushtype/SettingsWindow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
Loading
Loading