Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / InkspringSchedule / CompanionLibrary.swift

Raw 52.7 KB on 332c2458022ae8f6648ea05f3c733b528a595172
1import CryptoKit
2import Foundation
3
4public struct ContentRevision: Codable, Equatable, Identifiable, Sendable {
5 public let id: String
6 public let savedAt: String?
7 public let title: String
8 public let text: String
9 public let format: String?
10 public let subtitle: String?
11 public let source: String
12
13 public init(id: String = UUID().uuidString, savedAt: String?, title: String, text: String,
14 format: String? = nil, subtitle: String? = nil, source: String) {
15 self.id = id; self.savedAt = savedAt; self.title = title; self.text = text
16 self.format = format; self.subtitle = subtitle; self.source = source
17 }
18
19 public var valid: Bool {
20 !id.isEmpty && id.utf8.count <= 200 && title.utf16.count <= 300 && text.utf16.count <= 200_000
21 && (subtitle?.utf16.count ?? 0) <= 1000 && !text.contains("\0")
22 && (format?.utf16.count ?? 0) <= 100 && source.utf16.count <= 100
23 }
24
25 public var date: Date? {
26 savedAt.flatMap {
27 (try? Date($0, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)))
28 ?? (try? Date($0, strategy: .iso8601))
29 }
30 }
31}
32
33public enum XPostStyle: String, CaseIterable, Identifiable, Sendable {
34 case post, followup, thread
35 public var id: String { rawValue }
36 public var title: String {
37 switch self {
38 case .post: "Single post"
39 case .followup: "Post with reply"
40 case .thread: "Thread"
41 }
42 }
43 public var instructions: String {
44 switch self {
45 case .post: "Write one X post."
46 case .followup: "Write exactly two X posts. Make the opening substantial and put all supplied URLs in the follow-up reply."
47 case .thread: "Write a coherent thread of 3 to 8 X posts. Put supplied URLs in the final reply."
48 }
49 }
50}
51
52// The local reference travels with its reply through edits, history and iCloud.
53public struct XReplyArticle {
54 public static let prefix = "[[X article: "
55 public let copy: String
56 public let reference: String?
57
58 public init(_ post: String) {
59 guard let range = post.range(of: #"\[\[X article: [A-Z]{3}-[0-9]+\]\]\z"#, options: .regularExpression) else {
60 copy = post
61 reference = nil
62 return
63 }
64 let before = post[..<range.lowerBound]
65 copy = String(before.hasSuffix("\n") ? before.dropLast() : before)
66 reference = String(post[range].dropFirst(Self.prefix.count).dropLast(2))
67 }
68
69 public static func attach(_ reference: String?, to copy: String) -> String {
70 guard let reference else { return copy }
71 return copy + (copy.isEmpty ? "" : "\n") + prefix + reference + "]]"
72 }
73}
74
75public enum XThreadText {
76 // Reply boundaries must not share the same representation as paragraphs.
77 public static let separator = "\n\n<!-- inkspring:x-reply -->\n\n"
78 public static let limit = 25
79 private static let marker = "<!-- inkspring:x-reply -->"
80 private static let markerBoundary = #"(?m)(?:\r?\n){0,2}^[ \t]*<!-- inkspring:x-reply -->[ \t]*(?=\r?$)(?:\r?\n){0,2}"#
81 private static let boundary = #"\r?\n\s*\r?\n"#
82
83 public static func parts(in text: String) -> [String] {
84 if text.contains(marker) {
85 let separated = text.replacingOccurrences(of: markerBoundary, with: "\u{0}", options: .regularExpression)
86 if separated != text { return separated.components(separatedBy: "\u{0}") }
87 }
88 // Read existing drafts without rewriting or losing empty editor fields.
89 return text.replacingOccurrences(of: boundary, with: "\u{0}", options: .regularExpression)
90 .components(separatedBy: "\u{0}")
91 }
92
93 public static func posts(in text: String) -> [String] {
94 parts(in: text).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
95 .filter { !$0.isEmpty }
96 }
97
98 public static func singlePost(_ text: String) -> String {
99 text.trimmingCharacters(in: .whitespacesAndNewlines)
100 }
101
102 public static func validSinglePost(_ text: String) -> Bool {
103 let post = singlePost(text)
104 return !post.isEmpty && !post.contains("\0") && !post.contains(marker)
105 && XReplyArticle(post).reference == nil && weight(post) <= 280
106 }
107
108 public static func weight(_ text: String) -> Int {
109 let link = XReplyArticle(text)
110 let measured = link.reference == nil ? text : link.copy + (link.copy.isEmpty ? "" : "\n") + "https://x.com/article"
111 let links = measured.replacingOccurrences(of: #"(?i)https?://\S+"#, with: String(repeating: "x", count: 23),
112 options: .regularExpression)
113 return links.unicodeScalars.reduce(0) { $0 + ($1.value > 0x10ff ? 2 : 1) }
114 }
115
116 public static func valid(_ text: String, format: String, openingLimit: Int = 280) -> Bool {
117 let posts = posts(in: text)
118 let count = format == "followup" ? 2...2 : 2...limit
119 return count.contains(posts.count) && posts.enumerated().allSatisfy { index, post in
120 weight(post) <= (index == 0 ? openingLimit : 280)
121 }
122 }
123}
124
125public struct CompanionPostingWindow: Codable, Equatable, Sendable {
126 public let firstHour: Int
127 public let lastHour: Int
128
129 public init(firstHour: Int = 9, lastHour: Int = 17) {
130 self.firstHour = min(max(firstHour, 0), 23)
131 self.lastHour = min(max(lastHour, self.firstHour), 23)
132 }
133
134 public var hours: ClosedRange<Int> {
135 let normalized = Self(firstHour: firstHour, lastHour: lastHour)
136 return normalized.firstHour...normalized.lastHour
137 }
138}
139
140public struct CompanionLibrary: Codable, Equatable, Sendable {
141 public let workspaceID: UUID
142 public var enabled = true
143 public var projects: [Project] = []
144 public var items: [Item] = []
145 // Separate from items so older companions can still decode the library.
146 public var articles: [Item]?
147 public var scripts: [Item]?
148 public var supportsScripts: Bool?
149 public var supportsXArticlePublishing: Bool?
150 // Explicitly disable the retired writing format in older mobile releases.
151 public var supportsLinkedInArticles: Bool?
152 public var xArticleAccountKey: String?
153 public var xArticleAccountName: String?
154 public var supportsWritingTools: Bool?
155 public var supportsAgentFeatures: Bool?
156 public var writingAgent: String?
157 public var writingProviders: [WritingProvider]?
158
159 public struct WritingModel: Codable, Equatable, Hashable, Identifiable, Sendable {
160 public let id: String
161 public let name: String
162
163 public init(id: String, name: String) {
164 self.id = id
165 self.name = name
166 }
167 }
168
169 public struct WritingProvider: Codable, Equatable, Identifiable, Sendable {
170 public let id: String
171 public let name: String
172 public let defaultModel: String?
173 public let models: [WritingModel]
174 public let isAvailable: Bool
175
176 public init(id: String, name: String, defaultModel: String?, models: [WritingModel], isAvailable: Bool = true) {
177 self.id = id
178 self.name = name
179 self.defaultModel = defaultModel
180 self.models = models
181 self.isAvailable = isAvailable
182 }
183 }
184
185 public struct WritingSelection: Codable, Equatable, Sendable {
186 public let provider: String
187 public let model: String?
188
189 public init(provider: String, model: String?) {
190 self.provider = provider
191 self.model = model
192 }
193
194 var valid: Bool {
195 provider.range(of: #"\A[a-z][a-z0-9-]{0,99}\z"#, options: .regularExpression) != nil
196 && (model.map { $0.range(of: #"\A[A-Za-z0-9][A-Za-z0-9._:-]{0,99}\z"#, options: .regularExpression) != nil } ?? true)
197 }
198 }
199 public var newsletters: [Item]?
200 public var hasMoreNewsletters: Bool?
201 public var fullText: TextVersion?
202 public var pending: [Change] = []
203 public var results: [Result] = []
204 public var hasMore = false
205 public var supportsDraftEdits: Bool?
206 public var supportsNewsletterEdits: Bool?
207 public var supportsItemManagement: Bool?
208 public var supportsXReplyArticles: Bool?
209 public var supportsXThreads: Bool?
210 public var supportsXParagraphs: Bool?
211 public var supportsRevisionHistory: Bool?
212 public var supportsContentPlans: Bool?
213 public var supportsClaudeIdeaDrafts: Bool?
214 public var supportsMediaDrafts: Bool?
215 public var supportsIdeaImages: Bool?
216 public var ideaImageProvider: String?
217 public var additionalImagePreviews: [String: Data]?
218 public var supportsRevisionWithdrawal: Bool?
219 public var supportsQuickXPost: Bool?
220 public var postingWindows: [String: CompanionPostingWindow]?
221 public var postingTimeZone: String?
222 public var updatedAt = Date.now
223
224 public init(workspaceID: UUID) { self.workspaceID = workspaceID }
225
226 public func imagePreview(for id: String) -> Data? {
227 additionalImagePreviews?[id]
228 ?? items.first(where: { $0.id == id })?.imagePreview
229 ?? newsletters?.first(where: { $0.id == id })?.imagePreview
230 ?? articles?.first(where: { $0.id == id })?.imagePreview
231 ?? scripts?.first(where: { $0.id == id })?.imagePreview
232 }
233
234 public static let ideaDraftPlatforms = ["x", "linkedin", "reddit", "x-article", "linkedin-article", "substack", "youtube"]
235
236 public static func draftPlatforms(hasIdeaImage: Bool) -> [String] {
237 hasIdeaImage ? Array(ideaDraftPlatforms.prefix(3)) + ["instagram", "tiktok"] + Array(ideaDraftPlatforms.dropFirst(3)) : ideaDraftPlatforms
238 }
239
240 public struct Project: Codable, Equatable, Identifiable, Sendable {
241 public let id: String
242 public let name: String
243 public init(id: String, name: String) { self.id = id; self.name = name }
244 }
245
246 public struct RevisionRequest: Codable, Equatable, Identifiable, Sendable {
247 public enum State: String, Codable, Sendable {
248 case pending, actedOn, waitingForEditable, savedNote
249 }
250
251 public let id: String
252 public let text: String
253 public let date: String?
254 public let state: State
255
256 public init(id: String, text: String, date: String?, state: State) {
257 self.id = id
258 self.text = text
259 self.date = date
260 self.state = state
261 }
262 }
263
264 public struct Item: Codable, Equatable, Identifiable, Sendable {
265 public var draftedIdeaPlatforms: [String]?
266 public var draftedIdeaIDs: [String: String]?
267 public var publicationStatus: String?
268 public var publicationURL: String?
269 public var publicationError: String?
270 public var writingError: String?
271 public var writingReply: String?
272 public var history: [ContentRevision]?
273 public enum Kind: String, Codable, Sendable { case draft, idea, newsletter, script, article }
274 public var isLongForm: Bool { kind == .newsletter || kind == .script || kind == .article }
275 public enum Attachment: String, Codable, Sendable { case image, video }
276 public let id: String
277 public let revision: String
278 public let kind: Kind
279 public let projectID: String
280 public let title: String
281 public var body: String
282 public var shortened: Bool
283 public let platform: String
284 public let status: String
285 public let notes: [String]
286 public let noteDates: [String]?
287 public let referenceID: String?
288 public var format: String?
289 public var generationStatus: String?
290 public var noteStates: [String?]?
291 public var revisionRequests: [RevisionRequest]?
292 public let attachment: Attachment?
293 public var imagePreview: Data?
294 public var isTrashed: Bool?
295 public var requiresMacScheduling: Bool?
296 public var planMarkdown: String?
297 public var previousPlanMarkdown: String?
298
299 public init(id: String, revision: String, kind: Kind, projectID: String, title: String, body: String,
300 shortened: Bool, platform: String, status: String, notes: [String],
301 noteDates: [String]? = nil, attachment: Attachment? = nil, referenceID: String? = nil) {
302 self.id = id
303 self.revision = revision
304 self.kind = kind
305 self.projectID = projectID
306 self.title = title
307 self.body = body
308 self.shortened = shortened
309 self.platform = platform
310 self.status = status
311 self.notes = notes
312 self.noteDates = noteDates
313 self.attachment = attachment
314 self.referenceID = referenceID
315 }
316
317 public var indexEntry: Item {
318 var entry = self
319 entry.history = nil
320 entry.revisionRequests = nil
321 entry.planMarkdown = nil
322 entry.previousPlanMarkdown = nil
323 entry.imagePreview = nil
324 guard body.utf8.count > 512 else { return entry }
325 entry.body = ""
326 entry.shortened = true
327 return entry
328 }
329 }
330
331 public struct TextVersion: Codable, Equatable, Sendable {
332 public static let partSize = 500_000
333 public let digest: String
334 public let partCount: Int
335
336 public init(data: Data) {
337 digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
338 partCount = data.isEmpty ? 0 : (data.count - 1) / Self.partSize + 1
339 }
340 }
341
342 public static func encodeFullText(_ bodies: [String: String]) throws -> Data {
343 let encoder = JSONEncoder()
344 encoder.outputFormatting = .sortedKeys
345 return try (encoder.encode(bodies) as NSData).compressed(using: .zlib) as Data
346 }
347
348 public mutating func separateFullText() throws -> Data? {
349 var bodies = Dictionary(uniqueKeysWithValues: (additionalImagePreviews ?? [:]).map {
350 ("image:" + $0.key, $0.value.base64EncodedString())
351 })
352 additionalImagePreviews = nil
353 func separate(_ item: Item) -> Item {
354 var entry = item.indexEntry
355 if let plan = item.planMarkdown { bodies["plan:" + item.id] = plan; entry.planMarkdown = nil }
356 if let previous = item.previousPlanMarkdown { bodies["previousPlan:" + item.id] = previous; entry.previousPlanMarkdown = nil }
357 if let image = item.imagePreview { bodies["image:" + item.id] = image.base64EncodedString() }
358 if entry.shortened && !item.shortened { bodies[item.id] = item.body }
359 if let history = item.history, !history.isEmpty,
360 let data = try? JSONEncoder().encode(history) {
361 bodies["history:" + item.id] = String(decoding: data, as: UTF8.self)
362 }
363 if let requests = item.revisionRequests, !requests.isEmpty,
364 let data = try? JSONEncoder().encode(requests) {
365 bodies["revisionRequests:" + item.id] = String(decoding: data, as: UTF8.self)
366 }
367 return entry
368 }
369 items = items.map(separate)
370 newsletters = newsletters?.map(separate)
371 scripts = scripts?.map(separate)
372 articles = articles?.map(separate)
373 let data = try bodies.isEmpty ? nil : Self.encodeFullText(bodies)
374 fullText = data.map(TextVersion.init(data:))
375 return data
376 }
377
378 public mutating func applyFullText(_ data: Data) throws {
379 guard fullText == TextVersion(data: data) else { throw CompanionScheduleError.changed }
380 let decoded = try (data as NSData).decompressed(using: .zlib) as Data
381 let bodies = try JSONDecoder().decode([String: String].self, from: decoded)
382 func complete(_ item: Item) throws -> Item {
383 var item = item
384 item.planMarkdown = bodies["plan:" + item.id] ?? item.planMarkdown
385 item.previousPlanMarkdown = bodies["previousPlan:" + item.id] ?? item.previousPlanMarkdown
386 if let image = bodies["image:" + item.id], image.utf8.count <= 160_000 {
387 item.imagePreview = Data(base64Encoded: image)
388 }
389 if item.shortened {
390 guard let body = bodies[item.id] else { throw CompanionScheduleError.changed }
391 item.body = body
392 item.shortened = false
393 }
394 if let history = bodies["history:" + item.id] {
395 item.history = try JSONDecoder().decode([ContentRevision].self, from: Data(history.utf8))
396 }
397 if let requests = bodies["revisionRequests:" + item.id] {
398 item.revisionRequests = try JSONDecoder().decode([RevisionRequest].self, from: Data(requests.utf8))
399 }
400 return item
401 }
402 let completedItems = try items.map(complete)
403 let completedNewsletters = try newsletters?.map(complete)
404 let completedScripts = try scripts?.map(complete)
405 let completedArticles = try articles?.map(complete)
406 let itemIDs = Set((completedItems + (completedNewsletters ?? []) + (completedScripts ?? []) + (completedArticles ?? [])).map(\.id))
407 let additional = bodies.compactMap { key, value -> (String, Data)? in
408 guard key.hasPrefix("image:"), value.utf8.count <= 160_000 else { return nil }
409 let id = String(key.dropFirst("image:".count))
410 guard !itemIDs.contains(id), let data = Data(base64Encoded: value) else { return nil }
411 return (id, data)
412 }
413 additionalImagePreviews = additional.isEmpty ? nil : Dictionary(uniqueKeysWithValues: additional)
414 items = completedItems
415 newsletters = completedNewsletters
416 scripts = completedScripts
417 articles = completedArticles
418 }
419
420 public struct MediaDraft: Codable, Equatable, Sendable {
421 public static let limit = 30_000_000
422 public let platform: String
423 public let fileName: String
424 public let byteCount: Int
425 public let version: TextVersion
426 public let ideaID: String?
427
428 public init(platform: String, fileName: String, data: Data, ideaID: String? = nil) {
429 self.platform = platform
430 self.fileName = fileName
431 byteCount = data.count
432 version = TextVersion(data: data)
433 self.ideaID = ideaID
434 }
435
436 public var isVideo: Bool { ["mp4", "mov"].contains(fileExtension) }
437 public var fileExtension: String { URL(fileURLWithPath: fileName).pathExtension.lowercased() }
438
439 var valid: Bool {
440 ((platform == "tiktok" && isVideo) || (platform == "instagram" && (isVideo || ["png", "jpg", "jpeg"].contains(fileExtension))))
441 && !fileName.isEmpty && fileName.utf8.count <= 200 && !fileName.contains("/")
442 && !fileName.contains("\\") && !fileName.contains("\0")
443 && (1...Self.limit).contains(byteCount)
444 && version.partCount == (byteCount - 1) / TextVersion.partSize + 1
445 }
446
447 func matches(_ data: Data) -> Bool { data.count == byteCount && TextVersion(data: data) == version }
448 }
449
450 public struct Change: Codable, Equatable, Identifiable, Sendable {
451 public enum Action: String, Codable, Sendable {
452 case addIdea, note, skipIdea, restoreIdea, editDraft, editIdea, trashItem, restoreItem, deleteItem, scheduleDraft, saveRevision
453 }
454 public let id: UUID
455 public let action: Action
456 public let itemID: String
457 public let revision: String
458 public let title: String
459 public let text: String
460 // Newsletter edits use the existing wire action so older clients can decode the queue.
461 public let publishesXArticle: Bool?
462 public let xArticleAccountKey: String?
463 public let requestsWritingHelp: Bool?
464 public let writingKind: String?
465 public let baseScriptTitle: String?
466 public let editsScript: Bool?
467 public let createsScript: Bool?
468 public var isLongFormEdit: Bool { editsNewsletter == true || editsScript == true }
469 public let editsNewsletter: Bool?
470 public let baseNewsletterText: String?
471 public let xFormat: String?
472 public let generatesXDraft: Bool?
473 public let historySnapshot: ContentRevision?
474 public let restoresRevision: Bool?
475 public let subtitle: String?
476 public var contentOperation: CompanionContentOperation?
477 public var basePlan: String?
478 public var initialPlan: String?
479 public var ideaDraftPlatforms: [String]?
480 public var writingSelection: WritingSelection?
481 public var mediaDraft: MediaDraft?
482 public var ideaImagePrompt: String?
483 public var withdrawsRevision: UUID?
484 public var quickXAccountKey: String?
485
486 public init(id: UUID = UUID(), action: Action, itemID: String, revision: String = "",
487 title: String = "", text: String = "", editsNewsletter: Bool? = nil,
488 baseNewsletterText: String? = nil, xFormat: String? = nil, generatesXDraft: Bool? = nil,
489 historySnapshot: ContentRevision? = nil, restoresRevision: Bool? = nil, subtitle: String? = nil,
490 editsScript: Bool? = nil, createsScript: Bool? = nil, baseScriptTitle: String? = nil, writingKind: String? = nil, requestsWritingHelp: Bool? = nil, publishesXArticle: Bool? = nil, xArticleAccountKey: String? = nil) {
491 self.id = id
492 self.action = action
493 self.itemID = itemID
494 self.revision = revision
495 self.title = action == .editDraft ? title : title.trimmingCharacters(in: .whitespacesAndNewlines)
496 self.text = action == .editDraft || createsScript == true ? text : text.trimmingCharacters(in: .whitespacesAndNewlines)
497 self.publishesXArticle = publishesXArticle
498 self.xArticleAccountKey = xArticleAccountKey
499 self.requestsWritingHelp = requestsWritingHelp
500 self.writingKind = writingKind
501 self.baseScriptTitle = baseScriptTitle
502 self.editsScript = editsScript
503 self.createsScript = createsScript
504 self.editsNewsletter = editsNewsletter
505 self.baseNewsletterText = baseNewsletterText
506 self.xFormat = xFormat
507 self.generatesXDraft = generatesXDraft
508 self.historySnapshot = historySnapshot
509 self.restoresRevision = restoresRevision
510 self.subtitle = subtitle
511 }
512
513 public var valid: Bool {
514 if let withdrawsRevision {
515 return withdrawsRevision != id && action == .note && (1...200).contains(itemID.utf8.count)
516 && revision.isEmpty && text.isEmpty && title.isEmpty && writesOnlyMedia
517 && quickXAccountKey == nil && ideaImagePrompt == nil && mediaDraft == nil && writingSelection == nil
518 && ideaDraftPlatforms == nil && !isLongFormEdit && createsScript != true && generatesXDraft != true
519 }
520 if let prompt = ideaImagePrompt {
521 return action == .note && !itemID.isEmpty && itemID.utf8.count <= 200
522 && !revision.isEmpty && revision.utf8.count <= 100 && title.isEmpty && text.isEmpty
523 && prompt.utf16.count <= 4_000 && !prompt.contains("\0") && writesOnlyMedia
524 && mediaDraft == nil && ideaDraftPlatforms == nil && writingSelection == nil
525 && !isLongFormEdit && createsScript != true && generatesXDraft != true
526 }
527 if let writingSelection {
528 guard writingSelection.valid, usesMacAgent,
529 quickXAccountKey == nil, mediaDraft == nil else { return false }
530 }
531 if let account = quickXAccountKey {
532 return (1...500).contains(account.utf8.count) && !account.contains("\0")
533 && action == .note && (1...200).contains(itemID.utf8.count) && revision.isEmpty && title.isEmpty
534 && XThreadText.validSinglePost(text) && writesOnlyMedia && mediaDraft == nil && ideaDraftPlatforms == nil
535 && !isLongFormEdit && createsScript != true && generatesXDraft != true
536 }
537 if let mediaDraft {
538 return action == .note && mediaDraft.valid && title == mediaDraft.fileName
539 && (1...200).contains(itemID.utf8.count) && revision.isEmpty
540 && text.utf16.count <= 2_200 && !text.contains("\0")
541 && ideaDraftPlatforms == nil && !isLongFormEdit && createsScript != true && generatesXDraft != true
542 && writesOnlyMedia
543 }
544 if let platforms = ideaDraftPlatforms {
545 let allowed = CompanionLibrary.draftPlatforms(hasIdeaImage: true)
546 return action == .note && (1...allowed.count).contains(platforms.count)
547 && Set(platforms).count == platforms.count && platforms.allSatisfy(allowed.contains)
548 && !itemID.isEmpty && itemID.utf8.count <= 200 && !revision.isEmpty && revision.utf8.count <= 100
549 && (platforms.contains("x") ? xFormat.flatMap(XPostStyle.init(rawValue:)) != nil : xFormat == nil)
550 && title.isEmpty && text.isEmpty && !isLongFormEdit && createsScript != true && generatesXDraft != true
551 && requestsWritingHelp != true && publishesXArticle != true && xArticleAccountKey == nil
552 && historySnapshot == nil && restoresRevision != true && writingKind == nil
553 && contentOperation == nil && initialPlan == nil && basePlan == nil
554 && baseNewsletterText == nil && baseScriptTitle == nil && subtitle == nil
555 }
556 if let initialPlan {
557 guard initialPlan.utf16.count <= ContentPlan.limit, !initialPlan.contains("\0"),
558 (action == .addIdea && generatesXDraft != true && createsScript != true || contentOperation.map({ [.createDraft, .createNewsletter].contains($0) }) == true) else { return false }
559 }
560 if let operation = contentOperation {
561 guard action == .editDraft, !itemID.isEmpty, itemID.utf8.count <= 200,
562 title.utf16.count <= 200, text.utf16.count <= ContentPlan.limit,
563 !text.contains("\0"), !title.contains("\0"), !isLongFormEdit,
564 generatesXDraft != true, xFormat == nil, createsScript != true,
565 publishesXArticle != true, xArticleAccountKey == nil, requestsWritingHelp != true,
566 writingKind == nil, historySnapshot == nil, restoresRevision != true,
567 baseNewsletterText == nil, baseScriptTitle == nil, subtitle == nil else { return false }
568 switch operation {
569 case .savePlan: return !revision.isEmpty && title.isEmpty && basePlan != nil
570 && (basePlan?.utf16.count ?? 0) <= ContentPlan.limit && basePlan?.contains("\0") != true
571 case .createDraft, .createNewsletter, .createProject: return !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && basePlan == nil
572 case .setTitle: return !revision.isEmpty && title.isEmpty && (1...200).contains(text.utf16.count) && basePlan == nil
573 case .moveProject: return !revision.isEmpty && !text.isEmpty && title.isEmpty && basePlan == nil
574 }
575 }
576 guard basePlan == nil else { return false }
577 if publishesXArticle == true {
578 return action == .note && !itemID.isEmpty && itemID.utf8.count <= 200 && !revision.isEmpty && revision.utf8.count <= 100
579 && text == "Publish X article" && title.isEmpty && !isLongFormEdit && createsScript != true
580 && requestsWritingHelp != true && generatesXDraft != true && historySnapshot == nil
581 && baseNewsletterText == nil && writingKind == nil && xFormat == nil && restoresRevision != true
582 && xArticleAccountKey.map { !$0.isEmpty && $0.utf8.count <= 500 } == true
583 }
584 guard xArticleAccountKey == nil else { return false }
585
586 guard (requestsWritingHelp != true || action == .note && !isLongFormEdit && createsScript != true && generatesXDraft != true && historySnapshot == nil),
587 (writingKind == nil || ["script", "article", "newsletter"].contains(writingKind ?? "") && (createsScript == true || editsScript == true)
588 || writingKind == "linkedin-article" && createsScript == true),
589 !(editsScript == true && editsNewsletter == true),
590 !(generatesXDraft == true && (editsScript == true || createsScript == true)),
591 !itemID.isEmpty, itemID.utf8.count <= 200, revision.utf8.count <= 100 else { return false }
592 if createsScript == true {
593 return action == .addIdea && !isLongFormEdit && generatesXDraft != true && xFormat == nil
594 && historySnapshot == nil && baseNewsletterText == nil && !title.isEmpty && title.utf16.count <= 300
595 && text.utf16.count <= 200_000 && !text.contains("\0")
596 }
597 if action == .saveRevision {
598 return historySnapshot?.valid == true && title.isEmpty && text.isEmpty && editsNewsletter != true && xFormat == nil
599 }
600 guard historySnapshot == nil else { return false }
601 if generatesXDraft == true {
602 return action == .addIdea && editsNewsletter != true && baseNewsletterText == nil
603 && xFormat.flatMap(XPostStyle.init(rawValue:)) != nil
604 && (1...200).contains(title.utf16.count) && (1...10_000).contains(text.utf16.count)
605 && !text.contains("\0")
606 }
607 if let xFormat {
608 guard action == .editDraft, editsNewsletter != true, XPostStyle(rawValue: xFormat) != nil else { return false }
609 }
610 if isLongFormEdit {
611 return action == .editDraft && !revision.isEmpty && (title.isEmpty || (restoresRevision == true || editsScript == true || baseScriptTitle != nil) && title.utf16.count <= 300)
612 && text.utf16.count <= 200_000 && !text.contains("\0")
613 && (subtitle?.utf16.count ?? 0) <= 1000
614 && (baseScriptTitle?.utf16.count ?? 0) <= 300
615 && (baseNewsletterText.map { $0.utf16.count <= 200_000 && !$0.contains("\0") } ?? true)
616 }
617 guard baseNewsletterText == nil else { return false }
618 switch action {
619 case .addIdea: return (1...140).contains(title.utf16.count) && (1...2000).contains(text.utf16.count)
620 case .note: return !revision.isEmpty && (1...1000).contains(text.utf16.count) && title.isEmpty
621 case .skipIdea, .restoreIdea: return !revision.isEmpty && text.isEmpty && title.isEmpty
622 case .trashItem, .restoreItem, .deleteItem: return !revision.isEmpty && text.isEmpty && title.isEmpty
623 case .editIdea:
624 return !revision.isEmpty && (1...140).contains(title.utf16.count) && (1...2000).contains(text.utf16.count)
625 case .editDraft:
626 return !revision.isEmpty && !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
627 && title.utf16.count <= 200 && text.utf16.count <= 40_000
628 case .scheduleDraft:
629 return !revision.isEmpty && title.isEmpty && postingHour != nil
630 case .saveRevision: return false
631 }
632 }
633
634 private var writesOnlyMedia: Bool {
635 requestsWritingHelp != true && publishesXArticle != true && xArticleAccountKey == nil
636 && historySnapshot == nil && restoresRevision != true && writingKind == nil && xFormat == nil
637 && contentOperation == nil && initialPlan == nil && basePlan == nil
638 && baseNewsletterText == nil && baseScriptTitle == nil && subtitle == nil
639 }
640
641 public var needsWritingTools: Bool {
642 requestsWritingHelp == true || createsScript == true && writingKind == "newsletter" ||
643 editsNewsletter == true && !title.isEmpty && restoresRevision != true && baseScriptTitle != nil
644 }
645
646 public var usesMacAgent: Bool { requestsWritingHelp == true || generatesXDraft == true || ideaDraftPlatforms != nil }
647
648 public var postingHour: Date? {
649 guard action == .scheduleDraft, text.utf8.count <= 32 else { return nil }
650 return try? Date(text, strategy: .iso8601)
651 }
652
653 var payloadLimit: Int { createsScript == true || [.editDraft, .saveRevision].contains(action) ? 245_000 : 14_000 }
654 }
655
656 public struct Result: Codable, Equatable, Identifiable, Sendable {
657 public let id: UUID
658 public let error: String?
659 public let newsletterRevision: String?
660 public let publicationURL: String?
661
662 public init(id: UUID, error: String? = nil, newsletterRevision: String? = nil, publicationURL: String? = nil) {
663 self.id = id
664 self.error = error
665 self.newsletterRevision = newsletterRevision
666 self.publicationURL = publicationURL
667 }
668 }
669
670 public mutating func enqueue(_ change: Change) throws {
671 guard enabled else { throw CompanionLibraryError.disabled }
672 guard change.ideaDraftPlatforms == nil || supportsClaudeIdeaDrafts == true else { throw CompanionLibraryError.disabled }
673 guard change.writingSelection == nil || writingProviders != nil else { throw CompanionLibraryError.disabled }
674 guard change.mediaDraft == nil || supportsMediaDrafts == true else { throw CompanionLibraryError.disabled }
675 guard change.ideaImagePrompt == nil || supportsIdeaImages == true && ideaImageProvider != nil else { throw CompanionLibraryError.disabled }
676 if change.ideaDraftPlatforms?.contains(where: { ["instagram", "tiktok"].contains($0) }) == true, supportsIdeaImages != true {
677 throw CompanionLibraryError.disabled
678 }
679 guard change.quickXAccountKey == nil || supportsQuickXPost == true else { throw CompanionLibraryError.disabled }
680 guard (change.createsScript != true && change.editsScript != true) || supportsScripts == true else { throw CompanionLibraryError.disabled }
681 guard change.publishesXArticle != true || supportsXArticlePublishing == true else { throw CompanionLibraryError.disabled }
682 guard change.writingKind != "linkedin-article" || supportsLinkedInArticles == true else { throw CompanionLibraryError.disabled }
683 guard !change.needsWritingTools || supportsWritingTools == true else { throw CompanionLibraryError.disabled }
684 guard !change.usesMacAgent || supportsAgentFeatures == true else { throw CompanionLibraryError.disabled }
685 guard change.valid else { throw CompanionLibraryError.invalid }
686 guard change.withdrawsRevision == nil || supportsRevisionWithdrawal == true else { throw CompanionLibraryError.disabled }
687 if change.xFormat != nil, change.text.contains(XThreadText.separator), supportsXParagraphs != true {
688 throw CompanionLibraryError.disabled
689 }
690 if change.action == .saveRevision, supportsRevisionHistory != true { throw CompanionLibraryError.disabled }
691 if change.contentOperation != nil || change.initialPlan != nil, supportsContentPlans != true { throw CompanionLibraryError.disabled }
692 if change.action == .editDraft, supportsDraftEdits != true { throw CompanionLibraryError.disabled }
693 if change.editsNewsletter == true, supportsNewsletterEdits != true { throw CompanionLibraryError.disabled }
694 if [.editIdea, .trashItem, .restoreItem, .deleteItem].contains(change.action), supportsItemManagement != true { throw CompanionLibraryError.disabled }
695 if change.action == .scheduleDraft, postingWindows == nil { throw CompanionLibraryError.disabled }
696 if pending.contains(where: { $0.id == change.id }) || results.contains(where: { $0.id == change.id }) { return }
697 var next = pending
698 if let target = change.withdrawsRevision {
699 next.removeAll { $0.itemID == change.itemID && $0.requestsWritingHelp == true && $0.id == target }
700 }
701 // Reserve a bounded control lane so a full queue of edits cannot delay withdrawal.
702 let withdrawing = change.withdrawsRevision != nil
703 guard next.count < (withdrawing ? 48 : 24) else { throw CompanionLibraryError.full }
704 guard try JSONEncoder().encode(change).count <= change.payloadLimit else { throw CompanionLibraryError.invalid }
705 next.append(change)
706 guard try JSONEncoder().encode(next).count <= (withdrawing ? 300_000 : 280_000) else { throw CompanionLibraryError.full }
707 pending = next
708 }
709
710 public mutating func acknowledge(_ finished: [Result]) {
711 let ids = Set(finished.map(\.id))
712 pending.removeAll { ids.contains($0.id) }
713 results = Array((results.filter { !ids.contains($0.id) } + finished).suffix(48))
714 }
715
716 public mutating func clear() {
717 enabled = false
718 projects = []
719 items = []
720 newsletters = nil
721 scripts = nil
722 articles = nil
723 supportsScripts = nil
724 supportsXArticlePublishing = nil
725 supportsLinkedInArticles = nil
726 xArticleAccountKey = nil
727 xArticleAccountName = nil
728 supportsWritingTools = nil
729 supportsAgentFeatures = nil
730 supportsIdeaImages = nil
731 ideaImageProvider = nil
732 additionalImagePreviews = nil
733 writingAgent = nil
734 writingProviders = nil
735 hasMoreNewsletters = nil
736 fullText = nil
737 pending = []
738 results = []
739 hasMore = false
740 updatedAt = .now
741 supportsDraftEdits = nil
742 supportsNewsletterEdits = nil
743 supportsItemManagement = nil
744 supportsContentPlans = nil
745 supportsClaudeIdeaDrafts = nil
746 supportsMediaDrafts = nil
747 supportsRevisionWithdrawal = nil
748 supportsQuickXPost = nil
749 postingWindows = nil
750 postingTimeZone = nil
751 }
752}
753
754public enum CompanionLibraryError: LocalizedError {
755 case disabled, invalid, full, macUpdateForIdeaDrafts
756
757 public var errorDescription: String? {
758 switch self {
759 case .disabled: "Turn on library sync in Inkspring on your Mac."
760 case .invalid: "Check the text and try again."
761 case .full: "There are changes waiting for your Mac. Open Inkspring on your Mac to sync them."
762 case .macUpdateForIdeaDrafts: "Update and open Inkspring on your Mac to draft from an idea."
763 }
764 }
765}
766
767struct CompanionLibraryOutbox: Codable, Equatable {
768 struct Entry: Codable, Equatable, Identifiable {
769 var id: UUID
770 let action: CompanionLibrary.Change.Action
771 var itemID: String?
772 var revision: String
773 var title: String
774 let text: String
775 var workspaceID: UUID?
776 var account: String?
777 var error: String?
778 var afterTrash: UUID?
779 var retryID: UUID?
780 var trashRetries: Int?
781 var publishesXArticle: Bool?
782 var xArticleAccountKey: String?
783 var requestsWritingHelp: Bool?
784 var writingKind: String?
785 var baseScriptTitle: String?
786 var editsScript: Bool?
787 var createsScript: Bool?
788 var isLongFormEdit: Bool { editsNewsletter == true || editsScript == true }
789 var editsNewsletter: Bool?
790 var newsletterPrepared: Bool?
791 var afterNewsletterEdit: UUID?
792 var baseNewsletterText: String?
793 var xFormat: String?
794 var generatesXDraft: Bool?
795 var historySnapshot: ContentRevision?
796 var restoresRevision: Bool?
797 var subtitle: String?
798 var contentOperation: CompanionContentOperation?
799 var basePlan: String?
800 var initialPlan: String?
801 var ideaDraftPlatforms: [String]?
802 var writingSelection: CompanionLibrary.WritingSelection?
803 var mediaDraft: CompanionLibrary.MediaDraft?
804 var ideaImagePrompt: String?
805 var quickXAccountKey: String?
806 var savedAt: Date?
807 var revisionPrepared: Bool?
808 var withdrawsRevision: UUID?
809
810 var requestID: UUID { retryID ?? id }
811 var movesToTrash: Bool { action == .trashItem || action == .skipIdea }
812
813 var change: CompanionLibrary.Change? {
814 guard let itemID else { return nil }
815 var change = CompanionLibrary.Change(id: requestID, action: action, itemID: itemID, revision: revision,
816 title: title, text: text, editsNewsletter: editsNewsletter,
817 baseNewsletterText: baseNewsletterText, xFormat: xFormat, generatesXDraft: generatesXDraft,
818 historySnapshot: historySnapshot, restoresRevision: restoresRevision, subtitle: subtitle, editsScript: editsScript, createsScript: createsScript, baseScriptTitle: baseScriptTitle, writingKind: writingKind, requestsWritingHelp: requestsWritingHelp, publishesXArticle: publishesXArticle, xArticleAccountKey: xArticleAccountKey)
819 change.contentOperation = contentOperation
820 change.basePlan = basePlan
821 change.initialPlan = initialPlan
822 change.ideaDraftPlatforms = ideaDraftPlatforms
823 change.writingSelection = writingSelection
824 change.mediaDraft = mediaDraft
825 change.ideaImagePrompt = ideaImagePrompt
826 change.quickXAccountKey = quickXAccountKey
827 change.withdrawsRevision = withdrawsRevision
828 // Keep the existing edit limit even when the original plus the edit exceed one record.
829 if baseNewsletterText != nil, let size = try? JSONEncoder().encode(change).count, size > change.payloadLimit {
830 return .init(id: requestID, action: action, itemID: itemID, revision: revision, title: title, text: text,
831 editsNewsletter: editsNewsletter, restoresRevision: restoresRevision, subtitle: subtitle, editsScript: editsScript, createsScript: createsScript, baseScriptTitle: baseScriptTitle, writingKind: writingKind, requestsWritingHelp: requestsWritingHelp, publishesXArticle: publishesXArticle, xArticleAccountKey: xArticleAccountKey)
832 }
833 return change
834 }
835 }
836
837 var entries: [Entry] = []
838
839 mutating func withdrawRevision(_ target: UUID, itemID: String, workspaceID: UUID, account: String,
840 supportedByMac: Bool) throws {
841 let original = entries.first { $0.workspaceID == workspaceID && $0.account == account && $0.itemID == itemID
842 && $0.requestsWritingHelp == true && $0.requestID == target }
843 let localOnly = original?.revisionPrepared == false
844 guard localOnly || supportedByMac else { throw CompanionLibraryError.disabled }
845 if let original { entries.removeAll { $0.id == original.id } }
846 // Once prepared for upload, cloud delivery can already be in flight. Persist a withdrawal even if no receipt exists.
847 if !localOnly && !entries.contains(where: { $0.workspaceID == workspaceID && $0.account == account
848 && $0.itemID == itemID && $0.withdrawsRevision == target }) {
849 entries.append(.init(id: UUID(), action: .note, itemID: itemID, revision: "", title: "", text: "",
850 workspaceID: workspaceID, account: account, withdrawsRevision: target))
851 }
852 }
853
854 mutating func queueNewsletterEdit(_ edit: Entry) {
855 var edit = edit
856 let matches = entries.filter {
857 $0.action == .editDraft && $0.itemID == edit.itemID &&
858 $0.workspaceID == edit.workspaceID && $0.account == edit.account
859 }
860 // Entries from before this flag was added may already be in CloudKit.
861 let predecessor = matches.last { $0.error == nil && $0.newsletterPrepared != false }
862 if let unsent = matches.first(where: { $0.error == nil && $0.newsletterPrepared == false }) {
863 edit.baseNewsletterText = unsent.baseNewsletterText
864 edit.baseScriptTitle = unsent.baseScriptTitle ?? edit.baseScriptTitle
865 if edit.title.isEmpty { edit.title = unsent.title }
866 edit.revision = unsent.revision
867 }
868 let replaced = Set(matches.map(\.id))
869 entries.removeAll { replaced.contains($0.id) && $0.id != predecessor?.id }
870 edit.newsletterPrepared = false
871 edit.afterNewsletterEdit = predecessor?.requestID ?? edit.afterNewsletterEdit
872 entries.append(edit)
873 }
874
875 mutating func migrateIdeas(from data: Data) throws {
876 struct SavedIdea: Decodable {
877 struct Delivery: Decodable {
878 let workspaceID: UUID
879 let changeID: UUID
880 }
881 let id: UUID
882 let title: String
883 let body: String
884 let delivery: Delivery?
885 let failure: String?
886 }
887 for idea in try JSONDecoder().decode([SavedIdea].self, from: data) {
888 let id = idea.delivery?.changeID ?? (idea.failure == nil ? idea.id : UUID())
889 guard !entries.contains(where: { $0.id == id }) else { continue }
890 entries.append(.init(id: id, action: .addIdea, revision: "", title: idea.title, text: idea.body,
891 workspaceID: idea.delivery?.workspaceID))
892 }
893 }
894
895 mutating func prepare(for library: CompanionLibrary, account: String) -> [CompanionLibrary.Change] {
896 var changes: [CompanionLibrary.Change] = []
897 let results = Dictionary(library.results.map { ($0.id, $0) }, uniquingKeysWith: { _, newer in newer })
898 let pendingIDs = Set(library.pending.map(\.id))
899 let items = Dictionary(library.items.map { ($0.id, $0) }, uniquingKeysWith: { _, latest in latest })
900 let newsletters = Dictionary(((library.newsletters ?? []) + (library.scripts ?? []) + (library.articles ?? [])).map { ($0.id, $0) }, uniquingKeysWith: { _, latest in latest })
901 let waitingNewsletterEdits = entries.filter { $0.workspaceID == library.workspaceID && $0.account == account }
902 let predecessors = Dictionary(waitingNewsletterEdits.filter { $0.action == .editDraft || $0.createsScript == true }
903 .map { ($0.requestID, $0) }, uniquingKeysWith: { _, latest in latest })
904 let superseded = Set(waitingNewsletterEdits.compactMap(\.afterNewsletterEdit))
905 let requestIDs = Dictionary(entries.map { ($0.id, $0.requestID) }, uniquingKeysWith: { _, latest in latest })
906 let retryItems = Dictionary(entries.compactMap { entry -> (UUID, CompanionLibrary.Item)? in
907 guard entry.movesToTrash, entry.error == nil, (entry.trashRetries ?? 0) < 3,
908 entry.workspaceID == library.workspaceID, entry.account == account,
909 let error = results[entry.requestID]?.error,
910 ["This item changed since you opened it.", "Wait for the current publishing attempt to finish."].contains(error),
911 let itemID = entry.itemID, let item = items[itemID], item.isTrashed != true else { return nil }
912 return (entry.id, item)
913 }, uniquingKeysWith: { _, latest in latest })
914 entries = entries.compactMap { entry in
915 var entry = entry
916 guard entry.workspaceID == nil || entry.workspaceID == library.workspaceID,
917 entry.account == nil || entry.account == account else { return entry }
918 if let item = retryItems[entry.id] {
919 entry.retryID = UUID()
920 entry.trashRetries = (entry.trashRetries ?? 0) + 1
921 entry.revision = item.revision
922 } else if let result = results[entry.requestID] {
923 guard let error = result.error else { return nil }
924 if entry.isLongFormEdit, superseded.contains(entry.requestID) { return nil }
925 if entry.movesToTrash, let itemID = entry.itemID, items[itemID]?.isTrashed == true { return nil }
926 entry.error = error
927 } else if entry.action == .addIdea, (items[entry.id.uuidString.lowercased()] ?? newsletters[entry.id.uuidString.lowercased()]) != nil {
928 return nil
929 }
930 entry.workspaceID = library.workspaceID
931 entry.account = account
932 if let previous = entry.afterNewsletterEdit {
933 guard let receipt = results[previous] else { return entry }
934 entry.afterNewsletterEdit = nil
935 let newsletter = entry.itemID.flatMap { newsletters[$0] ?? items[$0] }
936 if let error = receipt.error {
937 entry.error = error
938 } else if entry.change?.baseNewsletterText != nil {
939 entry.revision = receipt.newsletterRevision ?? newsletter?.revision ?? entry.revision
940 // The Mac compares this edit's own base against its current body, including any
941 // changes already merged while processing the predecessor.
942 } else if let newsletter,
943 receipt.newsletterRevision == newsletter.revision ||
944 (receipt.newsletterRevision == nil && !newsletter.shortened
945 && predecessors[previous]?.text == newsletter.body) {
946 entry.revision = newsletter.revision
947 } else {
948 entry.error = "This newsletter changed on your Mac before the edit could sync."
949 }
950 }
951 if let afterTrash = entry.afterTrash {
952 guard entry.error == nil, retryItems[afterTrash] == nil,
953 let result = results[requestIDs[afterTrash] ?? afterTrash] else { return entry }
954 guard let itemID = entry.itemID, let item = items[itemID], item.isTrashed == true else {
955 entry.error = result.error == nil ? "This item is no longer available in Trash. Refresh and try again."
956 : "This item could not be moved to Trash. Try moving it again before deleting."
957 return entry
958 }
959 entry.revision = item.revision
960 entry.afterTrash = nil
961 }
962 if entry.action == .addIdea, entry.generatesXDraft != true, entry.createsScript != true,
963 entry.itemID == nil || !library.projects.contains(where: { $0.id == entry.itemID }),
964 !pendingIDs.contains(entry.id),
965 let project = library.projects.first {
966 if entry.error != nil { entry.id = UUID() }
967 entry.itemID = project.id
968 entry.error = nil
969 }
970 if entry.action == .trashItem, entry.revision == "pending-add",
971 let itemID = entry.itemID, let item = items[itemID] {
972 entry.revision = item.revision
973 }
974 if entry.error == nil, !pendingIDs.contains(entry.requestID), let change = entry.change,
975 entry.revision != "pending-add",
976 (entry.action != .editDraft || library.supportsDraftEdits == true),
977 (change.publishesXArticle != true || library.supportsXArticlePublishing == true),
978 (change.writingKind != "linkedin-article" || library.supportsClaudeIdeaDrafts == true && library.supportsLinkedInArticles == true),
979 (!change.needsWritingTools || library.supportsWritingTools == true),
980 (!change.usesMacAgent || library.supportsAgentFeatures == true),
981 (entry.action != .saveRevision || library.supportsRevisionHistory == true),
982 (entry.ideaDraftPlatforms == nil || library.supportsClaudeIdeaDrafts == true),
983 (entry.writingSelection == nil || library.writingProviders != nil),
984 (entry.mediaDraft == nil || library.supportsMediaDrafts == true),
985 (entry.ideaImagePrompt == nil || library.supportsIdeaImages == true),
986 (entry.ideaDraftPlatforms?.contains(where: { ["instagram", "tiktok"].contains($0) }) != true || library.supportsIdeaImages == true),
987 (entry.withdrawsRevision == nil || library.supportsRevisionWithdrawal == true),
988 (entry.quickXAccountKey == nil || library.supportsQuickXPost == true),
989 (entry.xFormat == nil || library.supportsXThreads == true),
990 (entry.xFormat == nil || !entry.text.contains(XThreadText.separator) || library.supportsXParagraphs == true),
991 (entry.editsNewsletter != true || library.supportsNewsletterEdits == true),
992 ((entry.editsScript != true && entry.createsScript != true) || library.supportsScripts == true),
993 (entry.contentOperation == nil && entry.initialPlan == nil || library.supportsContentPlans == true),
994 (entry.action != .scheduleDraft || library.postingWindows != nil),
995 (![.editIdea, .trashItem, .restoreItem, .deleteItem].contains(entry.action) || library.supportsItemManagement == true) {
996 if entry.action == .editDraft { entry.newsletterPrepared = true }
997 if entry.requestsWritingHelp == true { entry.revisionPrepared = true }
998 changes.append(change)
999 }
1000 return entry
1001 }
1002 return changes.filter { $0.withdrawsRevision != nil }
1003 + changes.filter { $0.withdrawsRevision == nil && $0.action != .saveRevision }
1004 + changes.filter { $0.action == .saveRevision }
1005 }
1006}