Branchwell

Jotley / app · jotley.ai / Shared / Services / SummaryTemplateStore.swift

Raw 11.4 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1import Foundation
2import Combine
3import CryptoKit
4
5/// A detached definition is captured when generation starts, so editing a
6/// template cannot change an in-flight or recovered summary.
7public struct SummaryTemplateDefinition: Codable, Equatable, Identifiable, Sendable {
8 public let key: String
9 public let title: String
10 public let prompt: String
11 public var id: String { key }
12 public var isCustom: Bool { key.hasPrefix("custom/") }
13 public init(key: String, title: String, prompt: String) {
14 self.key = key; self.title = title; self.prompt = prompt
15 }
16 public init(_ builtIn: LocalSummaryTemplate) {
17 self.init(key: builtIn.key, title: builtIn.title, prompt: builtIn.prompt)
18 }
19}
20
21public struct CustomSummaryTemplate: Codable, Equatable, Identifiable, Sendable {
22 public let id: UUID
23 public var name: String
24 public var instructions: String
25 public let createdAt: Date
26 public var updatedAt: Date
27 public var deleted: Bool
28 public var key: String { "custom/" + id.uuidString.lowercased() }
29 public var definition: SummaryTemplateDefinition { .init(key: key, title: name, prompt: instructions) }
30 public var revision: String {
31 let encoder = JSONEncoder(); encoder.outputFormatting = .sortedKeys
32 return SHA256.hash(data: (try? encoder.encode(self)) ?? Data()).map { String(format: "%02x", $0) }.joined()
33 }
34}
35
36/// Small user-authored preferences use native iCloud key/value sync, one key
37/// per template. Local copies and deletion tombstones survive offline edits.
38/// The note database and its CloudKit schema are unchanged.
39@MainActor
40public final class SummaryTemplateStore: NSObject, ObservableObject {
41 public static let shared = SummaryTemplateStore(
42 defaults: .standard,
43 cloud: NoteSyncMode.application().isEnabled ? .default : nil)
44 public static let nameLimit = 60
45 public static let instructionByteLimit = 2000
46 public static let templateLimit = 100
47 private static let localKey = "jotleyCustomSummaryTemplates.v1"
48 private static let cloudPrefix = "jotley.summary-template."
49 @Published public private(set) var templates: [CustomSummaryTemplate] = []
50 @Published public private(set) var storageError: String?
51 public let syncEnabled: Bool
52 private let defaults: UserDefaults
53 private let cloud: NSUbiquitousKeyValueStore?
54 private var records: [CustomSummaryTemplate] = []
55 private var unreadable = false
56
57 public init(defaults: UserDefaults, cloud: NSUbiquitousKeyValueStore? = nil) {
58 self.defaults = defaults; self.cloud = cloud; self.syncEnabled = cloud != nil
59 super.init()
60 if let data = defaults.data(forKey: Self.localKey) {
61 do { records = try JSONDecoder().decode([CustomSummaryTemplate].self, from: data) }
62 catch { unreadable = true; storageError = "Your saved templates could not be read. The original data was preserved." }
63 }
64 refresh()
65 if let cloud {
66 NotificationCenter.default.addObserver(self, selector: #selector(cloudChanged(_:)),
67 name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: cloud)
68 cloud.synchronize()
69 mergeCloud()
70 }
71 }
72 deinit { NotificationCenter.default.removeObserver(self) }
73
74 public var definitions: [SummaryTemplateDefinition] {
75 LocalSummaryTemplate.allCases.map(SummaryTemplateDefinition.init) + templates.map(\.definition)
76 }
77 public func resolve(_ key: String?) throws -> SummaryTemplateDefinition {
78 if let key, key.hasPrefix("custom/") {
79 guard let value = templates.first(where: { $0.key == key }) else {
80 throw LocalError.message("This custom template is unavailable. Choose another template; the saved summary is unchanged.")
81 }
82 return value.definition
83 }
84 return .init(LocalSummaryTemplate.resolve(key))
85 }
86 public func title(for key: String?) -> String {
87 (try? resolve(key).title) ?? "Template unavailable"
88 }
89 @discardableResult
90 public func save(id: UUID? = nil, name: String, instructions: String, expectedRevision: String? = nil) throws -> CustomSummaryTemplate {
91 guard !unreadable else { throw LocalError.message(storageError ?? "The saved template library could not be read.") }
92 let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
93 let instructions = instructions.trimmingCharacters(in: .whitespacesAndNewlines)
94 guard !name.isEmpty, name.count <= Self.nameLimit else { throw LocalError.message("Enter a template name of 1–\(Self.nameLimit) characters.") }
95 guard !instructions.isEmpty, instructions.utf8.count <= Self.instructionByteLimit else {
96 throw LocalError.message("Enter instructions of 1–\(Self.instructionByteLimit) UTF-8 bytes. Short instructions leave room for your note in the on-device model.")
97 }
98 guard !templates.contains(where: { $0.id != id && $0.name.compare(name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) else {
99 throw LocalError.message("A template with this name already exists.")
100 }
101 let old: CustomSummaryTemplate?
102 if let id {
103 guard let found = templates.first(where: { $0.id == id }), found.revision == expectedRevision else {
104 throw LocalError.message("This template changed or was deleted. Reopen it before saving.")
105 }
106 old = found
107 } else {
108 guard templates.count < Self.templateLimit else { throw LocalError.message("You can save up to \(Self.templateLimit) custom templates.") }
109 guard records.count < 900 else { throw LocalError.message("The template library has reached its iCloud storage limit. Edit an existing template instead.") }
110 old = nil
111 }
112 let now = Date()
113 let record = CustomSummaryTemplate(id: old?.id ?? UUID(), name: name, instructions: instructions,
114 createdAt: old?.createdAt ?? now, updatedAt: now, deleted: false)
115 try replace(record)
116 return record
117 }
118 public func delete(id: UUID, expectedRevision: String) throws {
119 guard var record = templates.first(where: { $0.id == id }), record.revision == expectedRevision else {
120 throw LocalError.message("This template changed or was deleted. Reopen it before deleting.")
121 }
122 record.deleted = true; record.updatedAt = Date()
123 // Retain only a small tombstone, not the deleted instructions. This
124 // prevents stale devices resurrecting deletions without using the
125 // iCloud quota for the full history of removed prompts.
126 record.name = ""; record.instructions = ""
127 try replace(record)
128 }
129 private func replace(_ record: CustomSummaryTemplate) throws {
130 var next = records.filter { $0.id != record.id }; next.append(record)
131 let data = try JSONEncoder().encode(next)
132 defaults.set(data, forKey: Self.localKey)
133 records = next; refresh()
134 if let cloud {
135 cloud.set(try JSONEncoder().encode(record), forKey: Self.cloudPrefix + record.id.uuidString.lowercased())
136 cloud.synchronize()
137 }
138 }
139 private func refresh() {
140 templates = records.filter { !$0.deleted }.sorted {
141 let order = $0.name.localizedStandardCompare($1.name)
142 return order == .orderedSame ? $0.id.uuidString < $1.id.uuidString : order == .orderedAscending
143 }
144 }
145
146 struct BackupImport {
147 let records: [CustomSummaryTemplate]
148 let data: Data
149 let added: Int
150 }
151
152 func backupRecords() throws -> [CustomSummaryTemplate] {
153 guard !unreadable else { throw LocalError.message("Your saved templates could not be read. The original data was preserved.") }
154 return templates
155 }
156
157 /// Prepare before saving the note transaction. Existing IDs (including
158 /// deletion tombstones) win; no current prompt is replaced by an import.
159 func prepareBackupImport(_ incoming: [CustomSummaryTemplate]) throws -> BackupImport {
160 guard !unreadable else { throw LocalError.message(storageError ?? "The saved template library could not be read.") }
161 var merged = records
162 let existingIDs = Set(records.map(\.id))
163 var names = templates.map(\.name)
164 var added = 0
165 for var record in incoming where !existingIDs.contains(record.id) {
166 let original = record.name
167 var suffix = 1
168 while names.contains(where: { $0.compare(record.name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) {
169 let ending = suffix == 1 ? " (restored)" : " (restored \(suffix))"
170 record.name = String(original.prefix(Self.nameLimit - ending.count)) + ending
171 suffix += 1
172 }
173 names.append(record.name); merged.append(record); added += 1
174 }
175 guard merged.filter({ !$0.deleted }).count <= Self.templateLimit, merged.count < 900 else {
176 throw LocalError.message("Restoring these templates would exceed the template library limit. No data was changed.")
177 }
178 return BackupImport(records: merged, data: try JSONEncoder().encode(merged), added: added)
179 }
180
181 func applyBackupImport(_ plan: BackupImport) {
182 defaults.set(plan.data, forKey: Self.localKey)
183 records = plan.records
184 refresh()
185 if let cloud {
186 for record in records {
187 if let data = try? JSONEncoder().encode(record) {
188 cloud.set(data, forKey: Self.cloudPrefix + record.id.uuidString.lowercased())
189 }
190 }
191 cloud.synchronize()
192 }
193 }
194 @objc nonisolated private func cloudChanged(_ notification: Notification) {
195 let reason = notification.userInfo?[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int
196 // iCloud can deliver this notification on a background thread.
197 Task { @MainActor [weak self] in
198 guard let self else { return }
199 if reason == NSUbiquitousKeyValueStoreQuotaViolationChange {
200 storageError = "iCloud template storage is full. Your local templates are preserved."
201 } else {
202 mergeCloud()
203 }
204 }
205 }
206 private func mergeCloud() {
207 guard let cloud, !unreadable else { return }
208 var merged = Dictionary(records.map { ($0.id, $0) }, uniquingKeysWith: { first, second in first.updatedAt >= second.updatedAt ? first : second })
209 for (key, value) in cloud.dictionaryRepresentation where key.hasPrefix(Self.cloudPrefix) {
210 guard let data = value as? Data, let remote = try? JSONDecoder().decode(CustomSummaryTemplate.self, from: data),
211 key == Self.cloudPrefix + remote.id.uuidString.lowercased(), remote.name.count <= Self.nameLimit,
212 remote.instructions.utf8.count <= Self.instructionByteLimit else { continue }
213 if let local = merged[remote.id], local.updatedAt > remote.updatedAt || (local.updatedAt == remote.updatedAt && local.revision >= remote.revision) { continue }
214 merged[remote.id] = remote
215 }
216 records = Array(merged.values)
217 if let data = try? JSONEncoder().encode(records) { defaults.set(data, forKey: Self.localKey) }
218 refresh()
219 for record in records {
220 let key = Self.cloudPrefix + record.id.uuidString.lowercased()
221 if let data = try? JSONEncoder().encode(record), cloud.data(forKey: key) != data { cloud.set(data, forKey: key) }
222 }
223 }
224}