Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / XFormatTests.swift
| 1 | import Foundation |
| 2 | @testable import InkspringSchedule |
| 3 | import Testing |
| 4 | @testable import Inkspring |
| 5 | |
| 6 | @Test func mobileParagraphEditsWaitSafelyForACompatibleMac() throws { |
| 7 | let workspaceID = UUID() |
| 8 | var library = CompanionLibrary(workspaceID: workspaceID) |
| 9 | library.supportsDraftEdits = true |
| 10 | library.supportsXThreads = true |
| 11 | library.items = [.init(id: "draft", revision: "1", kind: .draft, projectID: "project", title: "Title", |
| 12 | body: "Legacy opening.\n\nLegacy reply.", shortened: false, platform: "x", status: "draft", notes: [])] |
| 13 | let text = ["Opening.\n\nA paragraph.", "Read more: https://example.com/"].joined(separator: XThreadText.separator) |
| 14 | let change = CompanionLibrary.Change(action: .editDraft, itemID: "draft", revision: "1", title: "Title", text: text, xFormat: "followup") |
| 15 | var outbox = CompanionLibraryOutbox() |
| 16 | outbox.entries = [.init(id: change.id, action: .editDraft, itemID: "draft", revision: "1", title: "Title", |
| 17 | text: text, workspaceID: workspaceID, account: "owner", xFormat: "followup")] |
| 18 | #expect(outbox.prepare(for: library, account: "owner").isEmpty) |
| 19 | #expect(outbox.entries.first?.text == text) |
| 20 | #expect(throws: CompanionLibraryError.self) { try library.enqueue(change) } |
| 21 | #expect(library.items.first?.body == "Legacy opening.\n\nLegacy reply.") |
| 22 | library.supportsXParagraphs = true |
| 23 | #expect(outbox.prepare(for: library, account: "owner") == [change]) |
| 24 | try library.enqueue(change) |
| 25 | #expect(library.pending.first?.text == text) |
| 26 | } |
| 27 | |
| 28 | @Test func xParagraphsAndEmptyEditingLinesAreNotReplyBoundaries() { |
| 29 | let posts = ["Opening.\n\nSecond paragraph.\n", "Newsletter: https://example.com/news\n\nRead it.", "Discord: https://example.com/join"] |
| 30 | let encoded = posts.joined(separator: XThreadText.separator) |
| 31 | #expect(XThreadText.parts(in: encoded) == posts) |
| 32 | #expect(XThreadText.posts(in: encoded).count == 3) |
| 33 | #expect(XThreadText.valid(encoded, format: "thread")) |
| 34 | #expect(XThreadText.singlePost(posts[1]) == posts[1]) |
| 35 | #expect(XThreadText.parts(in: encoded + XThreadText.separator).last == "") |
| 36 | #expect(XThreadText.posts(in: "Legacy opening.\n\nLegacy reply.") == ["Legacy opening.", "Legacy reply."]) |
| 37 | let adjacentMarkers = "<!-- inkspring:x-reply -->\n\n<!-- inkspring:x-reply -->" |
| 38 | let malformed = [posts[0], adjacentMarkers, posts[1], "", posts[2]].joined(separator: XThreadText.separator) |
| 39 | #expect(XThreadText.parts(in: malformed) == [posts[0], "", "", "", posts[1], "", posts[2]]) |
| 40 | #expect(XThreadText.posts(in: malformed) == posts.map(XThreadText.singlePost)) |
| 41 | } |
| 42 | |
| 43 | @Test @MainActor func xParagraphsSurviveMobileSaveReloadAndPublishPlanning() throws { |
| 44 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 45 | defer { try? FileManager.default.removeItem(at: folder) } |
| 46 | let workspace = Workspace(directory: folder) |
| 47 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 48 | draft["title"] = "Paragraphs and replies" |
| 49 | draft["format"] = "thread" |
| 50 | draft["content"] = "Opening.\n\nNewsletter.\n\nDiscord." |
| 51 | draft = try workspace.save(draft) |
| 52 | let posts = ["Opening.\n\nAnother line.", "Newsletter.\n\nhttps://example.com/news", "Discord.\nhttps://example.com/join"] |
| 53 | let edit = CompanionLibrary.Change(action: .editDraft, itemID: draft.id, revision: draft["updatedAt"], |
| 54 | title: draft.title, text: posts.joined(separator: XThreadText.separator), xFormat: "thread") |
| 55 | let restored = try JSONDecoder().decode(CompanionLibrary.Change.self, from: JSONEncoder().encode(edit)) |
| 56 | #expect(try workspace.applyCompanionLibraryChange(restored).error == nil) |
| 57 | try workspace.reload() |
| 58 | let saved = try #require(workspace.drafts.first { $0.id == draft.id }) |
| 59 | #expect(XThreadText.parts(in: saved.body) == posts) |
| 60 | let account = ManagedSocialAccount(session: .init(accessToken: "fixture", refreshToken: nil, managedTicket: nil, |
| 61 | expiresAt: 2_000_000_000_000, scopes: "tweet.write"), id: "user", name: "Test", username: "test") |
| 62 | let plan = try SocialPublishPlan(draft: saved, account: account, imageURL: nil) |
| 63 | #expect(plan.posts == posts) |
| 64 | #expect(!plan.posts.contains { $0.contains("inkspring:x-reply") }) |
| 65 | let mobile = workspace.makeCompanionLibrary(workspaceID: UUID()) |
| 66 | #expect(mobile.items.first { $0.id == draft.id }?.body == saved.body) |
| 67 | } |
| 68 | |
| 69 | @Test @MainActor func xRevisionCanSeparateLinksIntoTwoRepliesWithoutLosingParagraphs() async throws { |
| 70 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 71 | defer { try? FileManager.default.removeItem(at: folder) } |
| 72 | let workspace = Workspace(directory: folder) |
| 73 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 74 | draft["format"] = "followup" |
| 75 | draft["content"] = "Opening.\n\nRead: https://example.com/news\nJoin: https://example.com/join" |
| 76 | draft = try workspace.save(draft) |
| 77 | let posts = ["Opening.\n\nClosing.", "Read: https://example.com/news", "Join: https://example.com/join"] |
| 78 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { instructions, input in |
| 79 | #expect(instructions.contains("unless the author's notes request a change")) |
| 80 | #expect((input["record"] as? [String: Any])?["posts"] as? [String] == XThreadText.posts(in: draft.body)) |
| 81 | return ["posts": posts, "reply": "Separated the links into two replies."] |
| 82 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 83 | let saved = try await ContentStudio(workspace: workspace, model: model).rewrite(draft, notes: "Put each URL in its own reply.") |
| 84 | #expect(saved["format"] == "thread") |
| 85 | #expect(XThreadText.parts(in: saved.body) == posts) |
| 86 | } |
| 87 | |
| 88 | @Test @MainActor func xRevisionCannotSilentlyCombineExistingReplies() async throws { |
| 89 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 90 | defer { try? FileManager.default.removeItem(at: folder) } |
| 91 | let workspace = Workspace(directory: folder) |
| 92 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 93 | draft["format"] = "thread" |
| 94 | let posts = ["Opening.", "Read: https://example.com/news", "Join: https://example.com/join"] |
| 95 | draft["content"] = posts.joined(separator: XThreadText.separator) |
| 96 | draft = try workspace.save(draft) |
| 97 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 98 | ["posts": ["Opening.", "Read: https://example.com/news\nJoin: https://example.com/join"]] |
| 99 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 100 | await #expect(throws: WorkspaceError.self) { |
| 101 | _ = try await ContentStudio(workspace: workspace, model: model).rewrite(draft, notes: "Improve the wording.") |
| 102 | } |
| 103 | #expect(workspace.drafts.first { $0.id == draft.id }?.body == draft.body) |
| 104 | } |
| 105 | |
| 106 | @Test(arguments: [true, false]) @MainActor func xIdeaGenerationMovesURLsToTheReply(includesLinks: Bool) async throws { |
| 107 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 108 | defer { try? FileManager.default.removeItem(at: folder) } |
| 109 | let workspace = Workspace(directory: folder) |
| 110 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 111 | idea["topic"] = "A useful manifesto" |
| 112 | let sourceLink = "https://example.com/manifesto" |
| 113 | let additionalLink = "https://example.org/guide_(new)?ref=one#section" |
| 114 | idea["text"] = includesLinks ? "Read it at \(sourceLink), then [see the guide](\(additionalLink))." : "We build tools we use." |
| 115 | idea = try workspace.save(idea) |
| 116 | let originalText = idea.body |
| 117 | let opening = "We build tools we use.\n\nRead the manifesto." |
| 118 | let output = includesLinks ? "We build tools we use.\n\nRead the [manifesto](\(sourceLink))." : opening |
| 119 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, |
| 120 | object: { instructions, input in |
| 121 | #expect(instructions.contains("Write one opening post")) |
| 122 | #expect(instructions.contains("no URLs")) |
| 123 | #expect(instructions.contains("what they will find and what to do") == includesLinks) |
| 124 | #expect((input["ideaLinks"] as? [String]) == (includesLinks ? [sourceLink, additionalLink] : nil)) |
| 125 | return ["text": output, "linkCallsToAction": [ |
| 126 | ["url": sourceLink, "text": "Read our manifesto to learn why we build tools we use."], |
| 127 | ["url": additionalLink, "text": "Follow the guide to put that approach into practice."] |
| 128 | ]] |
| 129 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 130 | let (kept, posts) = try await ContentStudio(workspace: workspace, model: model).pick(idea, platforms: ["x"]) |
| 131 | #expect(kept.body == originalText) |
| 132 | #expect(kept["status"] == "draft") |
| 133 | let draft = try #require(posts.first) |
| 134 | #expect(draft["format"] == (includesLinks ? "followup" : "post")) |
| 135 | let expected = includesLinks ? [opening, "Read our manifesto to learn why we build tools we use.\n\(sourceLink)\n\nFollow the guide to put that approach into practice.\n\(additionalLink)"] : [opening] |
| 136 | #expect(draft.body == expected.joined(separator: XThreadText.separator)) |
| 137 | let account = ManagedSocialAccount(session: .init(accessToken: "fixture", refreshToken: nil, managedTicket: nil, |
| 138 | expiresAt: 2_000_000_000_000, scopes: "tweet.write"), id: "user", name: "Test", username: "test") |
| 139 | #expect(try SocialPublishPlan(draft: draft, account: account, imageURL: nil).posts == expected) |
| 140 | #expect(kept.draftVersions["x"] == posts.first?.id) |
| 141 | } |
| 142 | |
| 143 | @Test func xIdeaReplyRepairsBareRepliesAndKeepsTheExactLink() throws { |
| 144 | let link = "https://inkspring.ai/?ref=welcome" |
| 145 | let authored = "Read the release notes to see what changed.\nhttps://example.com/updates" |
| 146 | let result = try XIdeaDraft.separate("An opening.", replies: ["Links: \(link)", authored], suppliedLinks: [link], linkCopy: [ |
| 147 | ["url": link, "text": "Use https://wrong.example.com/ instead."], |
| 148 | ["url": "https://nowhere.example.com/", "text": "A link the author didn't give us."] |
| 149 | ]) |
| 150 | #expect(XThreadText.posts(in: result.text) == ["An opening.", authored, |
| 151 | "Download Inkspring for Mac and try it for yourself.\n\(link)"]) |
| 152 | } |
| 153 | |
| 154 | @Test func xIdeaReplyKeepsAllLinksAndSplitsOnlyAtTheXLimit() throws { |
| 155 | let links = (1...14).map { "https://example.com/\($0)" } |
| 156 | let opening = String(repeating: "Long copy. ", count: 30) + "Use (www.example.net/path)." |
| 157 | let result = try XIdeaDraft.separate(opening, suppliedLinks: links, long: true) |
| 158 | let posts = XThreadText.posts(in: result.text) |
| 159 | #expect(result.format == "thread") |
| 160 | #expect(posts.count == 3) |
| 161 | #expect(XIdeaDraft.links(in: posts[0]).isEmpty) |
| 162 | #expect(XThreadText.weight(posts[0]) > 280) |
| 163 | #expect(posts.dropFirst().flatMap { XIdeaDraft.links(in: $0) } == links + ["https://www.example.net/path"]) |
| 164 | #expect(posts.dropFirst().allSatisfy { XThreadText.weight($0) <= 280 }) |
| 165 | } |
| 166 | |
| 167 | @Test @MainActor func mobileXGenerationQueuesIdempotentlyAndThreadEditsRoundTrip() async throws { |
| 168 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 169 | defer { try? FileManager.default.removeItem(at: folder) } |
| 170 | let workspace = Workspace(directory: folder) |
| 171 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 172 | idea["topic"] = "A useful manifesto" |
| 173 | idea["text"] = "Our approach. https://example.org/approach" |
| 174 | idea = try workspace.save(idea) |
| 175 | let request = CompanionLibrary.Change(action: .addIdea, itemID: idea.id, revision: idea["updatedAt"], |
| 176 | title: idea.title, text: idea.body, xFormat: "thread", generatesXDraft: true) |
| 177 | #expect(request.valid) |
| 178 | #expect(try workspace.applyCompanionLibraryChange(request).error == nil) |
| 179 | #expect(try workspace.applyCompanionLibraryChange(request).error == nil) |
| 180 | let queued = workspace.records.filter { $0.fields["mobileGenerationPending"] as? Bool == true } |
| 181 | #expect(queued.count == 1) |
| 182 | #expect(workspace.ideas.contains { $0.id == idea.id && $0.body == idea.body }) |
| 183 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { input, format in |
| 184 | #expect(format == "thread") |
| 185 | #expect(input["brief"] as? String == idea.body) |
| 186 | #expect(input["ideaLinks"] as? [String] == ["https://example.org/approach"]) |
| 187 | return ["title": "A useful manifesto", "content": "First post. https://example.net/\n\nSecond post.\n\nLinks: https://example.com/", |
| 188 | "linkCallsToAction": [["url": "https://example.org/approach", "text": "See how we put this approach into practice."]]] |
| 189 | }, object: { _, _ in [:] }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 190 | await workspace.generateMobileXDraft(model: model) |
| 191 | let draft = try #require(workspace.drafts.first { $0.id == request.id.uuidString.lowercased() }) |
| 192 | #expect(draft.fields["mobileGenerationPending"] == nil) |
| 193 | #expect(draft["format"] == "thread") |
| 194 | #expect(XThreadText.posts(in: draft.body) == ["First post.", "Second post.", |
| 195 | "See how we put this approach into practice.\nhttps://example.org/approach\n\nFind more information here:\nhttps://example.net/\nhttps://example.com/"]) |
| 196 | let snapshot = workspace.makeCompanionLibrary(workspaceID: UUID()) |
| 197 | #expect(snapshot.supportsXThreads == true) |
| 198 | #expect(snapshot.items.first { $0.id == draft.id }?.format == "thread") |
| 199 | let edit = CompanionLibrary.Change(action: .editDraft, itemID: draft.id, revision: draft["updatedAt"], |
| 200 | title: draft.title, text: "Opening.\n\nUpdated reply.", xFormat: "followup") |
| 201 | #expect(try workspace.applyCompanionLibraryChange(edit).error == nil) |
| 202 | let saved = try #require(workspace.drafts.first { $0.id == draft.id }) |
| 203 | #expect(saved["format"] == "followup") |
| 204 | #expect(XThreadText.posts(in: saved.body) == ["Opening.", "Updated reply."]) |
| 205 | let encoded = try JSONEncoder().encode(CompanionLibraryOutbox.Entry(id: edit.id, action: .editDraft, |
| 206 | itemID: edit.itemID, revision: edit.revision, title: edit.title, text: edit.text, xFormat: edit.xFormat)) |
| 207 | let restored = try JSONDecoder().decode(CompanionLibraryOutbox.Entry.self, from: encoded) |
| 208 | #expect(restored.change?.xFormat == "followup") |
| 209 | } |