Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/Next/SyncStore.swift3// Description: One account, synced: owns the VQuantKit sync engine of the signed-in person (encrypted replica in Application Support), the typed collections the windows read, the one-time migration of this Mac's 1.x watchlists and layouts, and the bridge between the synced preference object and local settings.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89/// Everything that exists for one signed-in person: the engine and one observable collection per object kind.10/// Created at sign-in, dropped at sign-out or lock. Views read `app.sync.active` (nil while nobody is signed in).11@Observable final class SyncSession {12 let personId: String13 let engine: VQSyncEngine14 let status: VQSyncStatusStore15 let watchlists: VQSyncedCollection<VQWatchlist>16 let portfolios: VQSyncedCollection<VQPortfolio>17 let charts: VQSyncedCollection<VQChart>18 let workspaces: VQSyncedCollection<VQWorkspace>19 let projects: VQSyncedCollection<VQProject>20 let notes: VQSyncedCollection<VQNote>21 let reviews: VQSyncedCollection<VQReview>22 let preferences: VQSyncedCollection<VQPreference>23 @ObservationIgnored fileprivate var tasks: [Task<Void, Never>] = []2425 init(personId: String, engine: VQSyncEngine) {26 self.personId = personId; self.engine = engine27 status = VQSyncStatusStore(engine: engine)28 watchlists = VQSyncedCollection(engine: engine); portfolios = VQSyncedCollection(engine: engine)29 charts = VQSyncedCollection(engine: engine); workspaces = VQSyncedCollection(engine: engine)30 projects = VQSyncedCollection(engine: engine); notes = VQSyncedCollection(engine: engine)31 reviews = VQSyncedCollection(engine: engine); preferences = VQSyncedCollection(engine: engine)32 }3334 fileprivate func observe() {35 tasks = [36 Task { [status] in await status.observe() },37 Task { [watchlists] in await watchlists.observe() }, Task { [portfolios] in await portfolios.observe() },38 Task { [charts] in await charts.observe() }, Task { [workspaces] in await workspaces.observe() },39 Task { [projects] in await projects.observe() }, Task { [notes] in await notes.observe() },40 Task { [reviews] in await reviews.observe() }, Task { [preferences] in await preferences.observe() },41 ]42 }43 fileprivate func cancel() { tasks.forEach { $0.cancel() }; tasks = [] }4445 /// The single preference object (`preference/default`), or an empty one while it does not exist.46 var preference: VQPreference { preferences[VQObjectID.defaultPreference]?.data ?? VQPreference() }47 func updatePreference(_ change: (inout VQPreference) -> Void) async {48 var p = preference; change(&p)49 await preferences.save(p, id: VQObjectID.defaultPreference)50 }51 /// The theme VQuantUI components read (up/down pair, number format, reduce motion).52 var theme: VQTheme { VQTheme(preference: preference) }53}5455/// What the toolbar shows about synchronisation.56enum SyncIndicator: Equatable {57 case off, connecting, synced, pending(Int), offline(pending: Int), locked, attention(Int)58 var label: String {59 switch self {60 case .off: "Sync off"; case .connecting: "Connecting…"; case .synced: "Synced"61 case .pending(let n): "Sending \(n) change\(n == 1 ? "" : "s")…"62 case .offline(let n): n == 0 ? "Offline" : "Offline · \(n) change\(n == 1 ? "" : "s") queued"63 case .locked: "Signed out on the server"64 case .attention(let n): "\(n) sync notice\(n == 1 ? "" : "s")"65 }66 }67 var symbol: String {68 switch self {69 case .off: "icloud.slash"; case .connecting: "arrow.triangle.2.circlepath"; case .synced: "checkmark.icloud"70 case .pending: "arrow.up.circle"; case .offline: "icloud.slash"; case .locked: "lock.icloud"; case .attention: "exclamationmark.icloud"71 }72 }73}7475@Observable final class SyncStore {76 private(set) var active: SyncSession?77 /// Outcome of the one-time migration of this Mac's 1.x data, for Settings and the test report.78 private(set) var migrationNote: String?7980 @ObservationIgnored private let client: VQClient81 @ObservationIgnored private let cache: DiskCache82 @ObservationIgnored private let root: URL83 @ObservationIgnored private let inMemory: Bool84 @ObservationIgnored private let defaults: UserDefaults85 @ObservationIgnored private let settings: SettingsStore86 @ObservationIgnored private let localWatchlists: JSONFile<[Watchlist]>87 @ObservationIgnored private let layouts: LayoutStore88 @ObservationIgnored private var hintTask: Task<Void, Never>?89 @ObservationIgnored private var prefTask: Task<Void, Never>?90 /// Called for each `hint` of the sync stream (a conversation, an analysis or a quant job changed on any device).91 @ObservationIgnored var onHint: ((VQSyncHint) -> Void)?9293 init(client: VQClient, cache: DiskCache, root: URL, inMemory: Bool, defaults: UserDefaults, settings: SettingsStore, localWatchlists: JSONFile<[Watchlist]>, layouts: LayoutStore) {94 self.client = client; self.cache = cache; self.root = root; self.inMemory = inMemory; self.defaults = defaults; self.settings = settings95 self.localWatchlists = localWatchlists; self.layouts = layouts96 }9798 private func directory(_ person: String) -> URL {99 let safe = person.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) ? String($0) : "_" }.joined()100 return root.appendingPathComponent(safe, isDirectory: true)101 }102103 // MARK: lifecycle104105 /// After sign-in (or unlock): loads the replica, opens the stream, pulls, then migrates 1.x local data once.106 func start(person: String) {107 guard active?.personId != person else { return }108 if let old = active { old.cancel(); let e = old.engine; Task { await e.stop() } }109 let dir = directory(person)110 let storage: any VQSyncStorage = (try? VQFileSyncStorage(directory: dir, cipher: CacheCipher(cache: cache))) ?? VQMemorySyncStorage()111 var values = URLResourceValues(); values.isExcludedFromBackup = true112 var d = dir; try? d.setResourceValues(values)113 // The three clients share one conflict convention (lead decision, 2026-11-20): non-list fields are114 // last-writer-wins PER FIELD (two devices changing different preferences, or a note's title and its body, do115 // not undo each other); `workspace` stays whole-object (the kit's default `wholeObjectKinds`); lists merge116 // element-wise as the contract says.117 var configuration = VQSyncEngine.Configuration()118 configuration.granularity = .field119 let engine = VQSyncEngine(client: client, storage: storage, configuration: configuration)120 let session = SyncSession(personId: person, engine: engine)121 active = session122 session.observe()123 hintTask?.cancel()124 hintTask = Task { [weak self] in125 await engine.start()126 for await hint in await engine.hints() { self?.onHint?(hint) }127 }128 prefTask?.cancel()129 prefTask = Task { [weak self] in130 // the first complete round decides what the server already holds: only then is local data migrated131 for attempt in 0..<40 {132 if Task.isCancelled { return }133 do { try await engine.syncNow(); break } catch { try? await Task.sleep(for: .seconds(min(30, 2 + attempt * 2))) }134 }135 guard let self, !Task.isCancelled, self.active === session else { return }136 await session.preferences.refresh(); await session.watchlists.refresh(); await session.workspaces.refresh()137 await self.migrateLocalData(session)138 self.applyPreference(session.preference)139 await self.followPreference(session)140 }141 }142143 /// Lock: the stream stops, the replica stays sealed on disk. Sign-out (or a session ended by the server): the144 /// replica, the write queue and the conflict records are erased, like the cache.145 func stop(erase: Bool) {146 hintTask?.cancel(); hintTask = nil; prefTask?.cancel(); prefTask = nil147 guard let session = active else { return }148 session.cancel(); active = nil149 let engine = session.engine; let dir = directory(session.personId)150 Task { if erase { await engine.reset(); try? FileManager.default.removeItem(at: dir) } else { await engine.stop() } }151 }152153 func syncNow() async {154 guard let e = active?.engine else { return }155 try? await e.syncNow()156 }157158 var indicator: SyncIndicator {159 guard let s = active?.status.status else { return .off }160 if s.conflictsNeedingAttention > 0 { return .attention(s.conflictsNeedingAttention) }161 switch s.connection {162 case .stopped: return .off163 case .connecting: return .connecting164 case .locked: return .locked165 case .reconnecting: return .offline(pending: s.pendingWrites)166 case .connected: return s.pendingWrites == 0 ? .synced : .pending(s.pendingWrites)167 }168 }169170 // MARK: migration of 1.x local data (once per person and Mac; never a loss, never a duplicate)171172 /// The object id of a migrated list is derived from the local list's UUID, so running the migration again (a173 /// crash before the flag is written, a second Mac restored from the same backup) writes the same objects.174 static func migratedID(_ local: UUID) -> String { "mac-" + local.uuidString.lowercased() }175176 private func migrateLocalData(_ session: SyncSession) async {177 let flag = "sync.migrated.\(session.personId)"178 guard !inMemory, !defaults.bool(forKey: flag) else { return }179 var notes: [String] = []180 if let lists = localWatchlists.load(), !lists.isEmpty {181 var moved = 0182 for l in lists {183 let id = Self.migratedID(l.id)184 if session.watchlists[id] == nil {185 await session.watchlists.save(VQWatchlist(name: l.name, symbols: Array(l.symbols.prefix(VQWatchlist.maxSymbols))), id: id)186 if session.watchlists.lastError == nil { moved += 1 }187 }188 }189 // the local file is kept as a backup under another name: nothing is deleted by the migration190 let backup = localWatchlists.url.deletingLastPathComponent().appendingPathComponent("watchlists.migrated-1x.json")191 try? FileManager.default.removeItem(at: backup)192 try? FileManager.default.moveItem(at: localWatchlists.url, to: backup)193 notes.append("\(lists.count) watchlist\(lists.count == 1 ? "" : "s") of this Mac moved to your account (\(moved) new)")194 } else if session.watchlists.items.isEmpty {195 await session.watchlists.save(VQWatchlist(name: "Watchlist", symbols: ["AAPL", "MSFT", "NVDA", "GOOGL", "AMZN", "SPY"]), id: "mac-default")196 }197 var synced = 0, local = 0198 for layout in layouts.saved {199 if let w = WorkspaceMapping.workspace(from: layout) {200 let id = Self.migratedID(layout.id)201 if session.workspaces[id] == nil { await session.workspaces.save(w, id: id) }202 synced += 1203 } else { local += 1 }204 }205 if synced > 0 { layouts.removeSynced { WorkspaceMapping.workspace(from: $0) != nil } }206 if synced + local > 0 { notes.append("\(synced) window layout\(synced == 1 ? "" : "s") synced, \(local) kept on this Mac (they contain windows the shared layout model cannot describe)") }207 defaults.set(true, forKey: flag)208 if !notes.isEmpty { migrationNote = notes.joined(separator: "; ") + "." }209 }210211 // MARK: preference/default ↔ local settings212213 /// The synced preference decides the up/down pair and the research defaults on every device. Light/dark214 /// appearance is a per-device choice: `preference.theme` is neither applied nor written by this app (it is215 /// preserved untouched, like every key the app does not edit). Mac-only settings (refresh cadence, app lock,216 /// notifications, chart defaults) stay in UserDefaults.217 private func applyPreference(_ p: VQPreference) {218 if let m = p.defaultMode, let mode = ResearchMode(rawValue: m), settings.researchMode != mode { settings.researchMode = mode }219 if let m = p.defaultModel, !m.isEmpty, settings.researchModel != m { settings.researchModel = m }220 if let c = p.upDownColors?.known { let cvd = c == .cvd; if settings.colorVisionSafe != cvd { settings.colorVisionSafe = cvd } }221 }222223 private func followPreference(_ session: SyncSession) async {224 for await event in await session.engine.events() {225 if Task.isCancelled { return }226 if case .objectsChanged(let kinds) = event, kinds.contains(.preference) {227 await session.preferences.refresh()228 applyPreference(session.preference)229 }230 }231 }232233 /// Settings panes call this after changing a synced setting locally.234 func pushSettings() {235 guard let session = active else { return }236 let s = settings237 Task {238 await session.updatePreference { p in239 p.defaultMode = s.researchMode.rawValue240 p.defaultModel = s.researchModel241 p.upDownColors = .known(s.colorVisionSafe ? .cvd : .classic)242 }243 }244 }245}246247// `WorkspaceMapping` (window layouts ↔ the shared `workspace` object) lives in App/Next/WorkspaceMapping.swift.248