Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / XArticlePublishingTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | @testable import InkspringSchedule |
| 5 | |
| 6 | @MainActor private func articleAccount(_ key: String = "connected") -> ManagedSocialAccount { |
| 7 | ManagedSocialAccount(session: .init(accessToken: "fixture", refreshToken: nil, managedTicket: nil, |
| 8 | expiresAt: Int64(Date.now.addingTimeInterval(3600).timeIntervalSince1970 * 1000), scopes: "tweet.read tweet.write users.read"), |
| 9 | id: "123", name: "Fixture", username: "fixture", connectedAt: key) |
| 10 | } |
| 11 | |
| 12 | @MainActor private func articleWorkspace() throws -> (Workspace, WorkspaceRecord, URL) { |
| 13 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 14 | let workspace = Workspace(directory: folder) |
| 15 | var article = WorkspaceRecord.new("article", projectID: workspace.projectID) |
| 16 | article["title"] = "A complete article"; article["body"] = "# Our mission\n\nWe **build** useful tools. [Read more](https://example.com/mission)\n\n" + String(repeating: "Full text stays here. ", count: 1000) |
| 17 | article = try workspace.save(article) |
| 18 | return (workspace, article, folder) |
| 19 | } |
| 20 | |
| 21 | @Test @MainActor func xArticlePayloadUsesOfficialSchemaAndKeepsLinksAndFormatting() throws { |
| 22 | let payload = try XArticleDocument.payload(title: "Title", markdown: "# Heading\n\n😀 **bold** and [our site](https://example.com)\n\n- One\n- Two\n\n> Quote\n\n```swift\nlet value = 1\n```\n\n---") |
| 23 | let state = try #require(payload["content_state"] as? [String: Any]) |
| 24 | let blocks = try #require(state["blocks"] as? [[String: Any]]) |
| 25 | #expect(blocks[0]["type"] as? String == "header-one") |
| 26 | let styles = try #require(blocks[1]["inline_style_ranges"] as? [[String: Any]]) |
| 27 | #expect(styles[0]["style"] as? String == "bold") |
| 28 | #expect(styles[0]["offset"] as? Int == 3) // UTF-16 emoji pair plus space. |
| 29 | #expect(blocks.filter { $0["type"] as? String == "unordered-list-item" }.count == 2) |
| 30 | #expect(blocks.contains { $0["type"] as? String == "blockquote" }) |
| 31 | let entities = try #require(state["entities"] as? [[String: Any]]) |
| 32 | #expect((entities[0]["value"] as? [String: Any])?["type"] as? String == "link") |
| 33 | #expect(((entities[0]["value"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String == "https://example.com") |
| 34 | #expect(try JSONSerialization.data(withJSONObject: payload).count > 0) |
| 35 | } |
| 36 | |
| 37 | @Test @MainActor func xArticlePublishesFullDraftAndRecordsItsURLWithoutTweetConversion() async throws { |
| 38 | let (workspace, article, folder) = try articleWorkspace() |
| 39 | defer { try? FileManager.default.removeItem(at: folder) } |
| 40 | var paths: [String] = [] |
| 41 | let publisher = XArticlePublisher(workspace: workspace, transport: .init { request in |
| 42 | paths.append(request.url!.path) |
| 43 | #expect(request.httpMethod == "POST") |
| 44 | #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer fixture") |
| 45 | if paths.count == 1 { |
| 46 | let payload = try #require(JSONSerialization.jsonObject(with: request.httpBody!) as? [String: Any]) |
| 47 | #expect(payload["text"] == nil) |
| 48 | #expect(String(decoding: request.httpBody!, as: UTF8.self).components(separatedBy: "Full text stays here.").count - 1 == 1000) |
| 49 | return (Data(#"{"data":{"id":"456","title":"A complete article"}}"#.utf8), HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) |
| 50 | } |
| 51 | #expect(request.httpBody == nil) |
| 52 | return (Data(#"{"data":{"post_id":"789"}}"#.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) |
| 53 | }, authorize: { articleAccount() }) |
| 54 | let plan = try await publisher.review(article) |
| 55 | #expect(paths.isEmpty) |
| 56 | let receipt = try await publisher.publish(plan) |
| 57 | #expect(paths == ["/2/articles/draft", "/2/articles/456/publish"]) |
| 58 | #expect(receipt["status"] == "published") |
| 59 | let saved = try #require(workspace.records.first { $0.id == article.id }) |
| 60 | #expect(saved.body == article.body && saved["state"] == "published") |
| 61 | #expect(saved["articleURL"] == "https://x.com/i/web/status/789") |
| 62 | let snapshot = workspace.makeCompanionLibrary(workspaceID: UUID()) |
| 63 | #expect(snapshot.articles?.first?.publicationURL == saved["articleURL"]) |
| 64 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan) } |
| 65 | #expect(paths.count == 2) |
| 66 | } |
| 67 | |
| 68 | @Test @MainActor func xArticleKnownPublishFailureReusesRemoteDraftOnRetry() async throws { |
| 69 | let (workspace, article, folder) = try articleWorkspace() |
| 70 | defer { try? FileManager.default.removeItem(at: folder) } |
| 71 | var paths: [String] = [] |
| 72 | let publisher = XArticlePublisher(workspace: workspace, transport: .init { request in |
| 73 | paths.append(request.url!.path) |
| 74 | let status = paths.count == 2 ? 429 : paths.count == 1 ? 201 : 200 |
| 75 | let body = paths.count == 1 ? #"{"data":{"id":"456"}}"# : #"{"data":{"post_id":"789"}}"# |
| 76 | return (Data(body.utf8), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!) |
| 77 | }, authorize: { articleAccount() }) |
| 78 | let plan = try await publisher.review(article) |
| 79 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan) } |
| 80 | #expect(workspace.records.first { $0.id == article.id }?["state"] == "draft") |
| 81 | _ = try await publisher.publish(plan) |
| 82 | #expect(paths == ["/2/articles/draft", "/2/articles/456/publish", "/2/articles/456/publish"]) |
| 83 | } |
| 84 | |
| 85 | @Test @MainActor func xArticleAmbiguousPublicationBlocksRetriesAndRecoversSafely() async throws { |
| 86 | let (workspace, article, folder) = try articleWorkspace() |
| 87 | defer { try? FileManager.default.removeItem(at: folder) } |
| 88 | var writes = 0 |
| 89 | let publisher = XArticlePublisher(workspace: workspace, transport: .init { request in |
| 90 | writes += 1 |
| 91 | if writes > 1 { throw URLError(.networkConnectionLost) } |
| 92 | return (Data(#"{"data":{"id":"456"}}"#.utf8), HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) |
| 93 | }, authorize: { articleAccount() }) |
| 94 | let plan = try await publisher.review(article) |
| 95 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan) } |
| 96 | #expect(workspace.records.first { $0.id == article.id }?["state"] == "uncertain") |
| 97 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan) } |
| 98 | #expect(writes == 2) |
| 99 | let receipt = try #require(workspace.records.first { $0.kind == "publication" }) |
| 100 | #expect(receipt["remoteArticleId"] == "456") |
| 101 | try workspace.allowPublicationRetry(receipt.id) |
| 102 | #expect(workspace.records.first { $0.id == article.id }?["state"] == "draft") |
| 103 | // A process exit while the second request is active has the same protected recovery state. |
| 104 | _ = try workspace.beginXArticlePublication(plan, fromAgent: false) |
| 105 | workspace.recoverInterruptedPublications() |
| 106 | #expect(workspace.records.first { $0.id == article.id }?["state"] == "uncertain") |
| 107 | } |
| 108 | |
| 109 | @Test(arguments: [401, 402, 403]) @MainActor func xArticleDeclinedAccessKeepsDraftAndShowsUsefulMessage(status: Int) async throws { |
| 110 | let (workspace, article, folder) = try articleWorkspace() |
| 111 | defer { try? FileManager.default.removeItem(at: folder) } |
| 112 | let publisher = XArticlePublisher(workspace: workspace, transport: .init { request in |
| 113 | (Data(), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!) |
| 114 | }, authorize: { articleAccount() }) |
| 115 | do { _ = try await publisher.publish(publisher.review(article)); Issue.record("Expected rejection") } |
| 116 | catch { #expect(error.localizedDescription.contains(status == 402 ? "credits" : status == 403 ? "Article access" : "Reconnect")) } |
| 117 | #expect(workspace.records.first { $0.id == article.id }?.body == article.body) |
| 118 | #expect(workspace.records.first { $0.id == article.id }?["state"] == "draft") |
| 119 | } |
| 120 | |
| 121 | @Test @MainActor func xArticleRejectsStaleTextAccountChangesAndUnapprovedAgentPublishing() async throws { |
| 122 | let (workspace, article, folder) = try articleWorkspace() |
| 123 | defer { try? FileManager.default.removeItem(at: folder) } |
| 124 | var account = articleAccount() |
| 125 | var writes = 0 |
| 126 | let publisher = XArticlePublisher(workspace: workspace, transport: .init { _ in writes += 1; throw URLError(.badURL) }, authorize: { account }) |
| 127 | let plan = try await publisher.review(article) |
| 128 | account = articleAccount("reconnected") |
| 129 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan) } |
| 130 | account = articleAccount() |
| 131 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan, fromAgent: true) } |
| 132 | var edited = article; edited["body"] = "Author changed this."; _ = try workspace.save(edited) |
| 133 | await #expect(throws: Error.self) { _ = try await publisher.publish(plan) } |
| 134 | #expect(writes == 0) |
| 135 | } |
| 136 | |
| 137 | @Test @MainActor func mobileXArticleRequestIsCompatibleIdempotentAndBindsReviewedVersion() async throws { |
| 138 | let (workspace, article, folder) = try articleWorkspace() |
| 139 | defer { try? FileManager.default.removeItem(at: folder) } |
| 140 | let change = CompanionLibrary.Change(action: .note, itemID: article.id, revision: article["updatedAt"], |
| 141 | text: "Publish X article", publishesXArticle: true, xArticleAccountKey: articleAccount().connectionKey) |
| 142 | #expect(change.valid) |
| 143 | var library = CompanionLibrary(workspaceID: UUID()) |
| 144 | #expect(throws: CompanionLibraryError.self) { try library.enqueue(change) } |
| 145 | library.supportsXArticlePublishing = true; try library.enqueue(change) |
| 146 | #expect(try workspace.applyCompanionLibraryChange(change).error == nil) |
| 147 | #expect(try workspace.applyCompanionLibraryChange(change).error == nil) |
| 148 | var edited = article; edited["body"] = "A newer author edit."; _ = try workspace.save(edited) |
| 149 | var writes = 0 |
| 150 | await workspace.publishPendingXArticles(publisher: .init(workspace: workspace, transport: .init { _ in |
| 151 | writes += 1; throw URLError(.badURL) |
| 152 | }, authorize: { articleAccount() })) |
| 153 | #expect(writes == 0) |
| 154 | #expect(workspace.records.first { $0.id == article.id }?.body == "A newer author edit.") |
| 155 | } |
| 156 | |
| 157 | @Test @MainActor func linkedArticleResolvesOnlyForPublishedSameProjectAndPreservesThreadOrder() async throws { |
| 158 | let (workspace, article, folder) = try articleWorkspace() |
| 159 | defer { try? FileManager.default.removeItem(at: folder) } |
| 160 | let reference = try #require(article.referenceID) |
| 161 | let reply = XReplyArticle.attach(reference, to: "Read the manifesto.\n\nHere’s the full X article.") |
| 162 | let parts = ["Opening post", reply, "Newsletter: https://example.org/news", "Discord: https://example.org/join"] |
| 163 | var draft = WorkspaceRecord.new("draft", projectID: article.projectID) |
| 164 | draft["platform"] = "x" |
| 165 | draft["format"] = "thread" |
| 166 | draft["content"] = parts.joined(separator: XThreadText.separator) |
| 167 | draft = try workspace.save(draft) |
| 168 | var sent: [String] = [] |
| 169 | let publisher = SocialPublisher(workspace: workspace, transport: .init { request in |
| 170 | let payload = try #require(JSONSerialization.jsonObject(with: request.httpBody!) as? [String: Any]) |
| 171 | let previous = (payload["reply"] as? [String: String])?["in_reply_to_tweet_id"] |
| 172 | #expect(previous == (sent.isEmpty ? nil : String(sent.count))) |
| 173 | sent.append(try #require(payload["text"] as? String)) |
| 174 | return (Data("{\"data\":{\"id\":\"\(sent.count)\"}}".utf8), |
| 175 | HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)!) |
| 176 | }, authorize: { _ in articleAccount() }) |
| 177 | await #expect(throws: Error.self) { _ = try await publisher.review(draft) } |
| 178 | #expect(sent.isEmpty) |
| 179 | let articlePublisher = XArticlePublisher(workspace: workspace, transport: .init { request in |
| 180 | let payload = request.url!.path.hasSuffix("/publish") ? #"{"data":{"post_id":"789"}}"# : #"{"data":{"id":"456"}}"# |
| 181 | return (Data(payload.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) |
| 182 | }, authorize: { articleAccount() }) |
| 183 | _ = try await articlePublisher.publish(articlePublisher.review(article)) |
| 184 | let published = try #require(workspace.records.first { $0.id == article.id }) |
| 185 | let review = try await publisher.review(draft) |
| 186 | #expect(review.posts[0] == parts[0] + "\n" + published["articleURL"]) |
| 187 | #expect(review.posts[1] == XReplyArticle(reply).copy + "\n" + published["articleURL"]) |
| 188 | #expect(XThreadText.weight(reply) == XThreadText.weight(review.posts[1])) |
| 189 | #expect(review.posts[2...] == parts[2...]) |
| 190 | _ = try await publisher.publish(review) |
| 191 | #expect(sent == review.posts) |
| 192 | draft.fields["projectId"] = "another-project" |
| 193 | #expect(throws: Error.self) { |
| 194 | try SocialPublishPlan(draft: draft, account: articleAccount(), imageURL: nil, articles: [published]) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | @Test(arguments: [true, false], [true, false]) |
| 199 | @MainActor func xPostPublishesWithItsArticleAndRetriesWithoutRepublishingArticle(opening: Bool, failsFirstPost: Bool) async throws { |
| 200 | let (workspace, article, folder) = try articleWorkspace() |
| 201 | defer { try? FileManager.default.removeItem(at: folder) } |
| 202 | let reference = try #require(article.referenceID) |
| 203 | var draft = WorkspaceRecord.new("draft", projectID: article.projectID) |
| 204 | draft["platform"] = "x" |
| 205 | draft["format"] = "thread" |
| 206 | draft["title"] = "Our launch" |
| 207 | if opening { draft["xArticleID"] = article.id } |
| 208 | let reply = "Here's the full story." |
| 209 | draft["content"] = ["The opening post.", opening ? reply : XReplyArticle.attach(reference, to: reply)] |
| 210 | .joined(separator: XThreadText.separator) |
| 211 | draft = try workspace.save(draft) |
| 212 | |
| 213 | var requests: [String] = [] |
| 214 | var postedTexts: [String] = [] |
| 215 | let publisher = SocialPublisher(workspace: workspace, transport: .init { request in |
| 216 | let url = try #require(request.url) |
| 217 | requests.append(url.path) |
| 218 | let result: String |
| 219 | let status: Int |
| 220 | switch url.path { |
| 221 | case "/2/articles/draft": |
| 222 | result = #"{"data":{"id":"456"}}"#; status = 201 |
| 223 | case "/2/articles/456/publish": |
| 224 | result = #"{"data":{"post_id":"789"}}"#; status = 200 |
| 225 | case "/2/tweets": |
| 226 | let body = try #require(request.httpBody) |
| 227 | let payload = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any]) |
| 228 | let text = try #require(payload["text"] as? String) |
| 229 | #expect(!text.contains(XPostArticleLinks.pendingURL)) |
| 230 | if failsFirstPost && requests.count == 3 { |
| 231 | result = #"{"detail":"Please retry"}"#; status = 429 |
| 232 | } else { |
| 233 | postedTexts.append(text) |
| 234 | result = #"{"data":{"id":"\#(postedTexts.count + 100)"}}"#; status = 201 |
| 235 | } |
| 236 | default: throw WorkspaceError("Unexpected fixture URL.") |
| 237 | } |
| 238 | return (Data(result.utf8), try #require(HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil))) |
| 239 | }, authorize: { _ in articleAccount() }) |
| 240 | let pair = try #require(try await publisher.reviewXArticlePost(draft)) |
| 241 | #expect(pair.articles.map(\.articleID) == [article.id]) |
| 242 | #expect(requests.isEmpty) |
| 243 | #expect(throws: WorkspaceError.self) { |
| 244 | try workspace.scheduleDraft(draft, at: Date.now.addingTimeInterval(86400)) |
| 245 | } |
| 246 | if failsFirstPost { |
| 247 | await #expect(throws: WorkspaceError.self) { _ = try await publisher.publishXArticlePost(pair) } |
| 248 | #expect(requests == ["/2/articles/draft", "/2/articles/456/publish", "/2/tweets"]) |
| 249 | let retry = try #require(workspace.records.first { $0.id == draft.id }) |
| 250 | #expect(try await publisher.reviewXArticlePost(retry) == nil) |
| 251 | let revised = try await publisher.review(retry) |
| 252 | _ = try await publisher.publish(revised) |
| 253 | } else { |
| 254 | let receipt = try await publisher.publishXArticlePost(pair) |
| 255 | #expect(receipt["status"] == "published") |
| 256 | } |
| 257 | let url = "\nhttps://x.com/i/web/status/789" |
| 258 | #expect(postedTexts == ["The opening post." + url, reply + (opening ? "" : url)]) |
| 259 | #expect(requests == ["/2/articles/draft", "/2/articles/456/publish"] + |
| 260 | Array(repeating: "/2/tweets", count: failsFirstPost ? 3 : 2)) |
| 261 | } |