Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / CompanionScheduleTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | @testable import InkspringSchedule |
| 5 | |
| 6 | @Test func companionHistoryKeepsPublishedReceiptsAndSupportsOldSchedules() throws { |
| 7 | let date = Date(timeIntervalSince1970: 1_800_000_000) |
| 8 | var draft = WorkspaceRecord.new("draft", projectID: "studio") |
| 9 | draft.fields["schedule"] = ["status": "posted", "postedAt": workspaceTimestamp(date)] |
| 10 | draft["updatedAt"] = workspaceTimestamp(date.addingTimeInterval(120)) |
| 11 | var receipt = WorkspaceRecord.new("publication", projectID: "studio") |
| 12 | receipt["draftId"] = draft.id |
| 13 | receipt["title"] = "An X post" |
| 14 | receipt["platform"] = "x" |
| 15 | receipt["status"] = "published" |
| 16 | receipt["publishedAt"] = workspaceTimestamp(date) |
| 17 | receipt.fields["steps"] = [ |
| 18 | ["url": "https://x.com/i/web/status/123"], |
| 19 | ["url": "https://x.com/i/web/status/456"], |
| 20 | ["url": "javascript:alert(0)"] |
| 21 | ] |
| 22 | var newsletter = WorkspaceRecord.new("newsletter", projectID: "studio") |
| 23 | newsletter["title"] = "The newsletter" |
| 24 | newsletter["state"] = "published" |
| 25 | newsletter["publishedAt"] = workspaceTimestamp(date.addingTimeInterval(60)) |
| 26 | newsletter["updatedAt"] = workspaceTimestamp(date.addingTimeInterval(180)) |
| 27 | newsletter["postUrl"] = "https://fixture.substack.com/p/newsletter" |
| 28 | |
| 29 | let history = PublishedPostFeed.entries(in: [draft, newsletter, receipt]) |
| 30 | #expect(history.map(\.id) == [newsletter.id, draft.id]) |
| 31 | #expect(history.map(\.lastUpdatedAt) == [date.addingTimeInterval(180), date.addingTimeInterval(120)]) |
| 32 | #expect(history.last?.publishedAt == date) |
| 33 | #expect(history.last?.links.map(\.absoluteString) == ["https://x.com/i/web/status/123", "https://x.com/i/web/status/456"]) |
| 34 | #expect(PublishedPostFeed.entries(in: [receipt]).first?.id == draft.id) |
| 35 | |
| 36 | let upcoming = CompanionPost(id: "next", revision: "1", title: "Next post", project: "Studio", |
| 37 | channel: "X", scheduledAt: date, state: .queued, canCancel: true) |
| 38 | var schedule = CompanionSchedule(workspaceID: UUID(), posts: [upcoming]) |
| 39 | let oldPayload = try JSONEncoder().encode(schedule) |
| 40 | #expect(try JSONDecoder().decode(CompanionSchedule.self, from: oldPayload).published == nil) |
| 41 | #expect(try JSONDecoder().decode(CompanionSchedule.self, from: oldPayload).posts.first?.lastUpdatedAt == nil) |
| 42 | try schedule.setPublished(history) |
| 43 | try schedule.cancel(upcoming) |
| 44 | let payload = try JSONEncoder().encode(schedule) |
| 45 | #expect(try JSONDecoder().decode(CompanionSchedule.self, from: payload).published == history) |
| 46 | try schedule.setPublished(Array(repeating: history[0], count: 3_000)) |
| 47 | #expect(schedule.hasOlderPublications == true) |
| 48 | #expect(try JSONEncoder().encode(schedule).count < CompanionSchedule.maxEncodedSize) |
| 49 | #expect(schedule.posts.first?.state == .cancelled) |
| 50 | } |
| 51 | |
| 52 | @Test func phoneScheduleKeepsOutagesReadOnlyAndDropsResponsesFromAnOldAccount() throws { |
| 53 | let post = CompanionPost(id: "fixture", revision: "first", title: "Synthetic post", project: "Studio", |
| 54 | channel: "X", scheduledAt: .now, state: .queued, canCancel: true) |
| 55 | let snapshot = CompanionSchedule(workspaceID: UUID(), posts: [post]) |
| 56 | var state = CompanionScheduleViewState() |
| 57 | let firstRequest = state.begin(.refresh) |
| 58 | let first = try #require(firstRequest) |
| 59 | let accepted = state.confirmAccount("first", for: first) |
| 60 | #expect(accepted) |
| 61 | state.complete(snapshot, for: first) |
| 62 | #expect(state.canCancel) |
| 63 | |
| 64 | let offlineRequest = state.begin(.refresh) |
| 65 | let disconnected = try #require(offlineRequest) |
| 66 | #expect(!state.canCancel) |
| 67 | state.fail("iCloud offline", keepSchedule: true, for: disconnected) |
| 68 | #expect(state.schedule == snapshot) |
| 69 | #expect(!state.canCancel) |
| 70 | let blockedCancel = state.begin(.cancel) |
| 71 | #expect(blockedCancel == nil) |
| 72 | |
| 73 | let reconnectRequest = state.begin(.refresh) |
| 74 | let reconnecting = try #require(reconnectRequest) |
| 75 | let changed = state.confirmAccount("second", for: reconnecting) |
| 76 | #expect(changed) |
| 77 | #expect(state.schedule == nil) |
| 78 | state = CompanionScheduleViewState() |
| 79 | let nextRequest = state.begin(.refresh) |
| 80 | let next = try #require(nextRequest) |
| 81 | let expired = state.confirmAccount("second", for: reconnecting) |
| 82 | #expect(!expired) |
| 83 | state.complete(snapshot, for: reconnecting) |
| 84 | #expect(state.schedule == nil) |
| 85 | let newAccount = state.confirmAccount("third", for: next) |
| 86 | #expect(newAccount) |
| 87 | state.complete(snapshot, for: next) |
| 88 | let cancelRequest = state.begin(.cancel) |
| 89 | let cancel = try #require(cancelRequest) |
| 90 | var result = snapshot |
| 91 | try result.cancel(post) |
| 92 | state.complete(result, for: cancel) |
| 93 | #expect(state.schedule?.posts.first?.state == .cancelled) |
| 94 | } |
| 95 | |
| 96 | @Test func companionCancellationAndSendClaimAreExclusive() throws { |
| 97 | let post = CompanionPost(id: "post", revision: "first", title: "A draft", project: "Studio", |
| 98 | channel: "LinkedIn", scheduledAt: .now, state: .queued, canCancel: true) |
| 99 | var cancelled = CompanionSchedule(workspaceID: UUID(), posts: [post]) |
| 100 | try cancelled.cancel(post) |
| 101 | cancelled.mirror([post]) |
| 102 | #expect(cancelled.posts.first?.state == .cancelled) |
| 103 | #expect(throws: CompanionScheduleError.cancelled) { try cancelled.claim(post) } |
| 104 | |
| 105 | var sending = CompanionSchedule(workspaceID: UUID(), posts: [post]) |
| 106 | try sending.claim(post) |
| 107 | #expect(throws: CompanionScheduleError.sending) { try sending.cancel(post) } |
| 108 | sending.mirror([post]) |
| 109 | #expect(sending.posts.first?.state == .sending) |
| 110 | sending.mirror([post], recoverAbandonedSends: true) |
| 111 | #expect(sending.posts.first?.state == .queued) |
| 112 | try sending.cancel(post) |
| 113 | sending.mirror([post], recoverAbandonedSends: true) |
| 114 | #expect(sending.posts.first?.state == .cancelled) |
| 115 | |
| 116 | let revised = CompanionPost(id: post.id, revision: "second", title: post.title, project: post.project, |
| 117 | channel: post.channel, scheduledAt: post.scheduledAt, state: .queued, canCancel: true) |
| 118 | cancelled.mirror([revised]) |
| 119 | #expect(throws: CompanionScheduleError.changed) { try cancelled.cancel(post) } |
| 120 | try cancelled.claim(revised) |
| 121 | #expect(cancelled.posts.first?.state == .sending) |
| 122 | } |
| 123 | |
| 124 | @Test func companionKeepsRemoteNewsletterSchedulesReadOnly() throws { |
| 125 | let newsletter = CompanionPost(id: "newsletter", revision: "scheduled", title: "An update", project: "Studio", |
| 126 | channel: "Substack", scheduledAt: .now, state: .queued, canCancel: false) |
| 127 | var schedule = CompanionSchedule(workspaceID: UUID(), posts: [newsletter]) |
| 128 | #expect(throws: CompanionScheduleError.changed) { try schedule.cancel(newsletter) } |
| 129 | let serialized = try JSONEncoder().encode(schedule) |
| 130 | #expect(try JSONDecoder().decode(CompanionSchedule.self, from: serialized) == schedule) |
| 131 | schedule.sharing = false |
| 132 | #expect(throws: CompanionScheduleError.missing) { try schedule.cancel(newsletter) } |
| 133 | } |
| 134 | |
| 135 | @Test @MainActor func restoredMacCanTakeOverAnIdleCompanionSchedule() async throws { |
| 136 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 137 | defer { try? FileManager.default.removeItem(at: folder) } |
| 138 | let workspace = Workspace(directory: folder) |
| 139 | let oldWorkspace = UUID() |
| 140 | let time = Date.now.addingTimeInterval(3600) |
| 141 | var matching = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 142 | matching["title"] = "Matching scheduled post" |
| 143 | matching.fields["schedule"] = ["status": "queued", "slotAt": workspaceTimestamp(time), "companionRevision": "same"] |
| 144 | try workspace.save(matching) |
| 145 | var revised = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 146 | revised["title"] = "Reviewed again on the new Mac" |
| 147 | revised.fields["schedule"] = ["status": "queued", "slotAt": workspaceTimestamp(time), "companionRevision": "new"] |
| 148 | try workspace.save(revised) |
| 149 | try workspace.set("autoPost", to: true) |
| 150 | |
| 151 | let cancelled = CompanionPost(id: matching.id, revision: "same", title: matching.title, project: "Fixture", |
| 152 | channel: "X", scheduledAt: time, state: .cancelled, canCancel: true) |
| 153 | let outdated = CompanionPost(id: revised.id, revision: "previous", title: revised.title, project: "Fixture", |
| 154 | channel: "X", scheduledAt: time, state: .cancelled, canCancel: true) |
| 155 | let sending = CompanionPost(id: "in-flight", revision: "1", title: "Already sending", project: "Fixture", |
| 156 | channel: "X", scheduledAt: time, state: .sending, canCancel: true) |
| 157 | let cloud = ScheduleFixture(CompanionSchedule(workspaceID: oldWorkspace, posts: [cancelled, outdated, sending])) |
| 158 | await workspace.setCompanionSharing(true, cloud: cloud) |
| 159 | let offer = try #require(workspace.companionTransfer) |
| 160 | #expect(offer.previousWorkspace == oldWorkspace) |
| 161 | #expect(!workspace.companionSharing) |
| 162 | #expect(cloud.schedule?.workspaceID == oldWorkspace) |
| 163 | |
| 164 | cloud.account = "switched" |
| 165 | await workspace.transferCompanionSchedule(offer, cloud: cloud) |
| 166 | #expect(cloud.schedule?.workspaceID == oldWorkspace) |
| 167 | #expect(workspace.settings["autoPost"] as? Bool == true) |
| 168 | cloud.account = "fixture" |
| 169 | |
| 170 | await workspace.transferCompanionSchedule(offer, cloud: cloud) |
| 171 | #expect(workspace.companionError == CompanionScheduleError.sending.errorDescription) |
| 172 | #expect(cloud.schedule?.workspaceID == oldWorkspace) |
| 173 | #expect(workspace.settings["autoPost"] as? Bool == false) |
| 174 | |
| 175 | let reopened = Workspace(directory: folder) |
| 176 | await reopened.syncCompanion(cloud: cloud) |
| 177 | #expect(reopened.companionTransfer == offer) |
| 178 | cloud.schedule?.posts.removeAll { $0.state == .sending } |
| 179 | await reopened.transferCompanionSchedule(offer, cloud: cloud) |
| 180 | let moved = try #require(cloud.schedule) |
| 181 | #expect(moved.workspaceID != oldWorkspace) |
| 182 | #expect(reopened.companionError == nil) |
| 183 | #expect(reopened.companionSharing) |
| 184 | #expect(reopened.companionTransfer == nil) |
| 185 | #expect(reopened.settings["companionSetupPending"] as? Bool == false) |
| 186 | #expect(reopened.settings["autoPost"] as? Bool == false) |
| 187 | #expect(reopened.drafts.first { $0.id == matching.id }?.scheduleStatus == "ready") |
| 188 | #expect(reopened.drafts.first { $0.id == revised.id }?.scheduleStatus == "queued") |
| 189 | #expect(moved.posts.first { $0.id == revised.id }?.revision == "new") |
| 190 | await #expect(throws: CompanionScheduleError.anotherMac) { |
| 191 | _ = try await cloud.update(workspaceID: oldWorkspace, createIfMissing: false, expectedAccount: "fixture") { try $0.claim(sending) } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | @Test @MainActor func macCompanionSyncAndSendClaimRequireTheOriginalAccount() async throws { |
| 196 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 197 | defer { try? FileManager.default.removeItem(at: folder) } |
| 198 | let workspace = Workspace(directory: folder) |
| 199 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 200 | draft["title"] = "Scheduled fixture" |
| 201 | draft["platform"] = "x" |
| 202 | draft["content"] = "Synthetic post text." |
| 203 | draft = try workspace.save(draft) |
| 204 | draft = try workspace.scheduleDraft(draft, at: .now.addingTimeInterval(3600)) |
| 205 | let cloud = ScheduleFixture(nil) |
| 206 | |
| 207 | cloud.switchAfterLoad = "other" |
| 208 | await workspace.setCompanionSharing(true, cloud: cloud) |
| 209 | #expect(cloud.schedule == nil) |
| 210 | #expect(workspace.companionError == CompanionScheduleError.accountChanged.errorDescription) |
| 211 | |
| 212 | cloud.account = "fixture" |
| 213 | cloud.switchAfterLoad = nil |
| 214 | await workspace.syncCompanion(cloud: cloud) |
| 215 | let original = try #require(cloud.schedule) |
| 216 | #expect(original.posts.first?.title == draft.title) |
| 217 | |
| 218 | cloud.account = "other" |
| 219 | draft["title"] = "Revised fixture" |
| 220 | draft = try workspace.save(draft) |
| 221 | draft = try workspace.scheduleDraft(draft, at: .now.addingTimeInterval(7200)) |
| 222 | await workspace.syncCompanion(cloud: cloud) |
| 223 | #expect(cloud.schedule == original) |
| 224 | #expect(workspace.companionError == CompanionScheduleError.accountChanged.errorDescription) |
| 225 | await #expect(throws: CompanionScheduleError.cloudUnavailable) { |
| 226 | _ = try await workspace.claimCompanionPublication(draft, cloud: cloud) |
| 227 | } |
| 228 | #expect(cloud.schedule == original) |
| 229 | |
| 230 | cloud.account = "fixture" |
| 231 | await workspace.syncCompanion(cloud: cloud) |
| 232 | #expect(workspace.companionError == nil) |
| 233 | #expect(cloud.schedule?.posts.first?.title == draft.title) |
| 234 | } |
| 235 | |
| 236 | @MainActor |
| 237 | private final class ScheduleFixture: CompanionScheduleAccess { |
| 238 | var schedule: CompanionSchedule? |
| 239 | var account = "fixture" |
| 240 | var switchAfterLoad: String? |
| 241 | |
| 242 | init(_ schedule: CompanionSchedule?) { self.schedule = schedule } |
| 243 | |
| 244 | func accountKey() async throws -> String { account } |
| 245 | func load(confirmedAccount: String) async throws -> CompanionSchedule? { |
| 246 | guard account == confirmedAccount else { throw CompanionScheduleError.accountChanged } |
| 247 | if let switchAfterLoad { account = switchAfterLoad } |
| 248 | return schedule |
| 249 | } |
| 250 | |
| 251 | func update(workspaceID: UUID, createIfMissing: Bool, expectedAccount: String, |
| 252 | _ update: (inout CompanionSchedule) throws -> Void) async throws -> CompanionSchedule { |
| 253 | guard account == expectedAccount else { throw CompanionScheduleError.accountChanged } |
| 254 | guard schedule != nil || createIfMissing else { throw CompanionScheduleError.missing } |
| 255 | var current = schedule ?? CompanionSchedule(workspaceID: workspaceID, posts: []) |
| 256 | guard current.workspaceID == workspaceID else { throw CompanionScheduleError.anotherMac } |
| 257 | try update(¤t) |
| 258 | schedule = current |
| 259 | return current |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | @Test @MainActor func mobileSchedulingRequestAppearsInTheMirroredSchedule() async throws { |
| 264 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 265 | defer { try? FileManager.default.removeItem(at: folder) } |
| 266 | let mac = Workspace(directory: folder) |
| 267 | let cloud = ScheduleFixture(nil) |
| 268 | await mac.setCompanionSharing(true, cloud: cloud) |
| 269 | let schedule = try #require(cloud.schedule) |
| 270 | var draft = WorkspaceRecord.new("draft", projectID: mac.projectID) |
| 271 | draft["title"] = "Schedule from mobile" |
| 272 | draft["content"] = "A synthetic post." |
| 273 | draft = try mac.save(draft) |
| 274 | |
| 275 | let tomorrow = try #require(Calendar.current.date(byAdding: .day, value: 1, to: .now)) |
| 276 | let hour = try #require(Calendar.current.date(bySettingHour: 11, minute: 0, second: 0, of: tomorrow)) |
| 277 | var library = mac.makeCompanionLibrary(workspaceID: schedule.workspaceID) |
| 278 | let item = try #require(library.items.first { $0.id == draft.id }) |
| 279 | try library.enqueue(.init(action: .scheduleDraft, itemID: item.id, revision: item.revision, text: hour.formatted(.iso8601))) |
| 280 | let synced = try JSONDecoder().decode(CompanionLibrary.self, from: JSONEncoder().encode(library)) |
| 281 | let results = try synced.pending.map(mac.applyCompanionLibraryChange) |
| 282 | #expect(results.count == 1) |
| 283 | #expect(results.first?.error == nil) |
| 284 | library.acknowledge(results) |
| 285 | #expect(library.pending.isEmpty) |
| 286 | |
| 287 | await mac.syncCompanion(cloud: cloud) |
| 288 | let post = try #require(cloud.schedule?.posts.first { $0.id == item.id }) |
| 289 | let minute = Calendar.current.component(.minute, from: post.scheduledAt) |
| 290 | #expect(post.state == .queued) |
| 291 | #expect(Calendar.current.isDate(post.scheduledAt, equalTo: hour, toGranularity: .hour)) |
| 292 | #expect((7...55).contains(minute) && minute % 5 != 0) |
| 293 | } |