Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Sync/SyncCoordinator.swift3// Description: Applies the server's sync feed to the stores: long-lived event stream, pull on activation, coalesced refreshes, offline draft outbox.4import SwiftUI5import SPChatCore67/// Drafts that could not be saved on the server (offline). They survive a relaunch (local cache) and are pushed when8/// the connection is back, unless the server already holds a newer draft for the same scope.9actor DraftOutbox {10 private let cache: CacheStore?11 private var drafts: [String: PendingDraft] = [:]12 private var loaded = false13 private static let key = "drafts.outbox"1415 init(cache: CacheStore?) { self.cache = cache }1617 private func load() async { guard !loaded else { return }; loaded = true; drafts = (try? await cache?.get([String: PendingDraft].self, for: Self.key)) ?? [:] }18 private func persist() async { try? await cache?.set(drafts, for: Self.key) }1920 func keep(_ draft: PendingDraft) async { await load(); drafts[draft.scope] = draft; await persist() }21 func discard(scope: String) async { await load(); guard drafts[scope] != nil else { return }; drafts[scope] = nil; await persist() }22 func pending() async -> [PendingDraft] { await load(); return drafts.values.sorted { $0.updatedAt < $1.updatedAt } }23 func draft(scope: String) async -> PendingDraft? { await load(); return drafts[scope] }2425 /// Pushes every kept draft; returns how many reached the server. A network failure keeps the rest for the next attempt.26 @discardableResult27 func flush(api: APIClient) async -> Int {28 await load()29 var sent = 030 for d in drafts.values.sorted(by: { $0.updatedAt < $1.updatedAt }) {31 do {32 let server = try await api.draftRecord(scope: d.scope)33 if d.shouldReplace(serverUpdatedAt: server?.updatedAt) { try await api.saveDraft(scope: d.scope, text: d.text, attachmentIds: d.attachmentIds); sent += 1 }34 drafts[d.scope] = nil35 } catch let e as APIError where e.isNetwork { break }36 catch { drafts[d.scope] = nil } // refused by the server (conversation deleted…): nothing to retry37 }38 await persist()39 return sent40 }41}4243@Observable final class SyncCoordinator {44 enum State: Equatable { case idle, connecting, live, reconnecting }45 private(set) var state: State = .idle46 /// Last sequence number applied.47 private(set) var cursor: Int48 private(set) var lastChangeAt: Date?49 @ObservationIgnored private let client: SyncClient50 @ObservationIgnored private let preferences: Preferences51 @ObservationIgnored private weak var env: AppEnvironment?52 @ObservationIgnored private var streamTask: Task<Void, Never>?53 @ObservationIgnored private var applyTask: Task<Void, Never>?54 @ObservationIgnored private var pending = SyncInvalidation()55 /// Called after a batch was applied (tests, and screens that keep their own lists: prompts, memory, providers).56 @ObservationIgnored var onApplied: ((SyncInvalidation) -> Void)?5758 init(client: SyncClient, preferences: Preferences) { self.client = client; self.preferences = preferences; cursor = preferences.syncSeq }59 func attach(_ env: AppEnvironment) { self.env = env }6061 var isRunning: Bool { streamTask != nil }6263 /// Opens the long-lived stream (idempotent). The first connection starts from the head: stores were just loaded.64 func start() {65 guard streamTask == nil, let env, env.session.phase == .signedIn, !env.options.isHostedTest || env.options.forceSync else { return }66 state = .connecting67 streamTask = Task { [weak self] in68 guard let self else { return }69 await self.catchUp()70 for await update in self.client.events(after: self.cursor) {71 if Task.isCancelled { break }72 switch update {73 case .connected(let head):74 let wasReconnecting = self.state == .reconnecting75 self.state = .live76 if self.cursor == 0 { self.setCursor(head) }77 if wasReconnecting { await self.flushOutbox() }78 case .invalidate(let inv): self.enqueue(inv)79 case .disconnected: self.state = .reconnecting80 case .sessionEnded: self.state = .idle81 }82 }83 }84 }8586 func stop(resetCursor: Bool = false) {87 streamTask?.cancel(); streamTask = nil; applyTask?.cancel(); applyTask = nil; pending = SyncInvalidation(); state = .idle88 if resetCursor { setCursor(0) }89 }9091 private func setCursor(_ seq: Int) { cursor = seq; preferences.syncSeq = seq }9293 /// `GET /api/sync?after=` — when the app becomes active, and before the stream opens: applies what was missed.94 func catchUp() async {95 guard let env, env.session.phase == .signedIn else { return }96 // first run on this Mac: everything was just loaded; the stream's `hello` gives the position in the feed97 guard cursor > 0 else { return }98 guard let feed = try? await client.pull(after: cursor) else { return }99 let inv = SyncInvalidation.reduce(feed, after: cursor)100 if feed.head < cursor { var all = SyncInvalidation(); all.markEverything(head: feed.head); setCursor(feed.head); await apply(all) }101 else if !inv.isEmpty { await apply(inv) } else { setCursor(max(cursor, feed.head)) }102 await flushOutbox()103 }104105 /// Changes arrive in bursts (a turn touches the conversation, two messages, usage…): they are merged and applied once.106 private func enqueue(_ inv: SyncInvalidation) {107 pending.merge(inv)108 guard applyTask == nil else { return }109 applyTask = Task { [weak self] in110 try? await Task.sleep(for: .milliseconds(350))111 guard let self, !Task.isCancelled else { return }112 let batch = self.pending; self.pending = SyncInvalidation(); self.applyTask = nil113 await self.apply(batch)114 }115 }116117 /// The feed says what changed; each store re-reads it from the server (the server row is the truth).118 func apply(_ inv: SyncInvalidation) async {119 guard let env else { return }120 if inv.head > cursor || inv.everything { setCursor(inv.everything ? inv.head : max(cursor, inv.head)) }121 lastChangeAt = Date()122 for id in inv.deletedConversations { env.forget(conversationId: id); try? await env.cache?.deleteConversation(id) }123 async let list: Void = { if inv.conversationList || inv.everything { await env.conversations.refreshQuietly() } }()124 async let models: Void = { if inv.models || inv.everything { await env.catalog.reloadModels() } }()125 async let settings: Void = { if inv.settings || inv.everything { await env.catalog.reloadSettings() } }()126 async let projects: Void = { if inv.projects || inv.everything { await env.catalog.reloadProjects() } }()127 async let presets: Void = { if inv.presets || inv.everything { await env.catalog.reloadPresets() } }()128 async let prompts: Void = { if inv.prompts || inv.everything { await env.catalog.reloadPrompts() } }()129 _ = await (list, models, settings, projects, presets, prompts)130 // open conversations: another device added messages, switched a version, renamed…131 for chat in env.liveChats {132 guard let id = chat.conversationId else { if inv.drafts.contains(where: { $0.hasPrefix("new") }) { await chat.syncDraft() }; continue }133 if inv.touchesConversation(id) || inv.attachments || inv.artifacts { await chat.syncRefresh() }134 if inv.drafts.contains(id) { await chat.syncDraft() }135 }136 NotificationCenter.default.post(name: .spchatSyncApplied, object: SyncNotice(invalidation: inv))137 onApplied?(inv)138 }139140 private func flushOutbox() async { guard let env else { return }; await env.outbox.flush(api: env.api) }141}142143/// Posted after a sync batch was applied, for screens that own their lists (prompts, memory, providers, files).144final class SyncNotice: NSObject { let invalidation: SyncInvalidation; init(invalidation: SyncInvalidation) { self.invalidation = invalidation } }145extension Notification.Name { static let spchatSyncApplied = Notification.Name("spchat.syncApplied") }146147extension View {148 /// Runs `action` when the sync feed reports a change matching `predicate` (another device edited prompts, memory…).149 func onSync(_ predicate: @escaping (SyncInvalidation) -> Bool, perform action: @escaping () -> Void) -> some View {150 onReceive(NotificationCenter.default.publisher(for: .spchatSyncApplied)) { note in151 if let n = note.object as? SyncNotice, n.invalidation.everything || predicate(n.invalidation) { action() }152 }153 }154}155