Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / WritingAssistantTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | @testable import InkspringSchedule |
| 5 | |
| 6 | @Test(arguments: ["draft", "idea"]) @MainActor |
| 7 | func socialWritingRequestsApplyOnceAndRetainTheirComments(kind: String) async throws { |
| 8 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 9 | defer { try? FileManager.default.removeItem(at: folder) } |
| 10 | let workspace = Workspace(directory: folder) |
| 11 | try workspace.set("mcpEnabled", to: true) |
| 12 | var record = WorkspaceRecord.new(kind, projectID: workspace.projectID) |
| 13 | record[kind == "idea" ? "topic" : "title"] = "Useful tools" |
| 14 | let longIdea = String(repeating: "Preserve this context about our tools and the people who use them. ", count: 10) |
| 15 | record[kind == "idea" ? "text" : "content"] = kind == "idea" ? longIdea : "We build useful tools." |
| 16 | record["platform"] = "x" |
| 17 | record = try workspace.save(record) |
| 18 | let request = CompanionLibrary.Change(action: .note, itemID: record.id, revision: record["updatedAt"], |
| 19 | text: "Make this clearer.", requestsWritingHelp: true) |
| 20 | #expect(try workspace.applyCompanionLibraryChange(request).error == nil) |
| 21 | var calls = 0 |
| 22 | let expected = kind == "idea" ? String(longIdea.dropLast()) : "We build tools that save people time." |
| 23 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 24 | calls += 1 |
| 25 | return ["text": expected, "reply": "Clarified the goal."] |
| 26 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 27 | await workspace.runDraftRevisionComments(model: model) |
| 28 | await workspace.runDraftRevisionComments(model: model) |
| 29 | let revised = try #require(workspace.records.first { $0.id == record.id }) |
| 30 | #expect(calls == 1) |
| 31 | #expect(revised.body == expected) |
| 32 | #expect(revised.comments.count == 1) |
| 33 | #expect(revised.appliedRevisionCommentIDs == [request.id.uuidString.lowercased()]) |
| 34 | } |
| 35 | |
| 36 | @Test @MainActor func failedWritingRequestKeepsDraftAndRetriesSafely() async throws { |
| 37 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 38 | defer { try? FileManager.default.removeItem(at: folder) } |
| 39 | let workspace = Workspace(directory: folder) |
| 40 | try workspace.set("mcpEnabled", to: true) |
| 41 | var record = WorkspaceRecord.new("newsletter", projectID: workspace.projectID) |
| 42 | record["title"] = "Original"; record["body"] = "Original text." |
| 43 | record = try workspace.save(record) |
| 44 | try workspace.addComment(to: record, text: "Make it clearer.", revisionRequestID: "request") |
| 45 | let failed = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 46 | throw WorkspaceError("Internal provider detail") |
| 47 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 48 | await workspace.runDraftRevisionComments(model: failed) |
| 49 | let retained = try #require(workspace.records.first { $0.id == record.id }) |
| 50 | #expect(retained.body == "Original text." && retained.pendingRevisionComments.count == 1) |
| 51 | #expect(!retained["writingRequestError"].contains("Internal provider")) |
| 52 | #expect(retained["writingRequestError"].contains("The draft and requests are saved")) |
| 53 | let success = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 54 | ["body": "Clearer text."] |
| 55 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 56 | await workspace.runDraftRevisionComments(model: success) |
| 57 | let revised = try #require(workspace.records.first { $0.id == record.id }) |
| 58 | #expect(revised.body == "Clearer text." && revised.pendingRevisionComments.isEmpty) |
| 59 | #expect(revised["writingRequestError"].isEmpty) |
| 60 | } |
| 61 | |
| 62 | @Test @MainActor func multipleRequestsShareAnEditAndKeepTheFullSyncTrail() async throws { |
| 63 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 64 | defer { try? FileManager.default.removeItem(at: folder) } |
| 65 | let workspace = Workspace(directory: folder) |
| 66 | try workspace.set("mcpEnabled", to: true) |
| 67 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 68 | idea["topic"] = "A specific idea" |
| 69 | idea["text"] = "Original angle." |
| 70 | idea = try workspace.save(idea) |
| 71 | for index in 1...5 { |
| 72 | try workspace.addComment(to: idea, text: "Historical note \(index)", revisionRequestID: nil) |
| 73 | } |
| 74 | let requests = ["Add a concrete example.", "Keep the original angle."].map { |
| 75 | CompanionLibrary.Change(action: .note, itemID: idea.id, revision: idea["updatedAt"], |
| 76 | text: $0, requestsWritingHelp: true) |
| 77 | } |
| 78 | for request in requests { |
| 79 | #expect(try workspace.applyCompanionLibraryChange(request).error == nil) |
| 80 | } |
| 81 | var calls = 0 |
| 82 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, input in |
| 83 | calls += 1 |
| 84 | #expect(input["notes"] as? String == "Add a concrete example.\n\nKeep the original angle.") |
| 85 | return ["text": "Original angle with a concrete example."] |
| 86 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 87 | await workspace.runDraftRevisionComments(model: model) |
| 88 | #expect(calls == 1) |
| 89 | let workspaceID = UUID() |
| 90 | var library = workspace.makeCompanionLibrary(workspaceID: workspaceID) |
| 91 | let detached = try library.separateFullText() |
| 92 | let data = try #require(detached) |
| 93 | try library.applyFullText(data) |
| 94 | let history = try #require(library.items.first { $0.id == idea.id }?.revisionRequests) |
| 95 | #expect(history.count == 7) |
| 96 | #expect(Set(history.filter { $0.state == .actedOn }.map(\.id)) == Set(requests.map { $0.id.uuidString.lowercased() })) |
| 97 | } |
| 98 | |
| 99 | @Test(arguments: ["newsletter", "article", "script"]) @MainActor |
| 100 | func writingRequestCreatesBriefOnMacAndRetainsHistory(kind: String) async throws { |
| 101 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 102 | defer { try? FileManager.default.removeItem(at: folder) } |
| 103 | let workspace = Workspace(directory: folder) |
| 104 | try workspace.set("mcpEnabled", to: true) |
| 105 | let creation = CompanionLibrary.Change(action: .addIdea, itemID: workspace.projectID, |
| 106 | title: "A useful brief", createsScript: true, writingKind: kind) |
| 107 | #expect(creation.valid) |
| 108 | #expect(try workspace.applyCompanionLibraryChange(creation).error == nil) |
| 109 | let id = creation.id.uuidString.lowercased() |
| 110 | var record = try #require(workspace.records.first { $0.id == id }) |
| 111 | #expect(record.kind == kind && record.body.isEmpty) |
| 112 | let request = CompanionLibrary.Change(action: .note, itemID: id, revision: record["updatedAt"], |
| 113 | text: "Write a quick brief about local AI models.", requestsWritingHelp: true) |
| 114 | #expect(request.valid) |
| 115 | #expect(try workspace.applyCompanionLibraryChange(request).error == nil) |
| 116 | #expect(try workspace.applyCompanionLibraryChange(request).error == nil) |
| 117 | var calls = 0 |
| 118 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { instructions, input in |
| 119 | calls += 1 |
| 120 | #expect(instructions.contains("complete revised document")) |
| 121 | #expect((input["record"] as? [String: String])?["body"] == "") |
| 122 | return ["body": "# Local AI models\n\nA useful brief with two clear points.", "title": "Local AI models", "reply": "Wrote a concise brief."] |
| 123 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 124 | await workspace.runDraftRevisionComments(model: model) |
| 125 | await workspace.runDraftRevisionComments(model: model) |
| 126 | #expect(calls == 1) |
| 127 | record = try #require(workspace.records.first { $0.id == id }) |
| 128 | #expect(record.title == "Local AI models") |
| 129 | #expect(record.body.contains("two clear points")) |
| 130 | #expect(record.appliedRevisionCommentIDs == [request.id.uuidString.lowercased()]) |
| 131 | #expect(record.comments.count == 1) |
| 132 | #expect(try workspace.revisionHistory(for: record).contains { $0.text.isEmpty }) |
| 133 | let snapshot = workspace.makeCompanionLibrary(workspaceID: UUID()) |
| 134 | let synced = try #require(((snapshot.newsletters ?? []) + (snapshot.articles ?? []) + (snapshot.scripts ?? [])).first { $0.id == id }) |
| 135 | #expect(synced.noteStates == ["applied"] && synced.writingReply == "Wrote a concise brief.") |
| 136 | #expect(synced.body == record.body) |
| 137 | #expect(record.schedule.isEmpty) |
| 138 | } |
| 139 | |
| 140 | @Test func newWritingRequestsAndNewsletterCreationWaitForCompatibleMac() throws { |
| 141 | var library = CompanionLibrary(workspaceID: UUID()) |
| 142 | library.supportsScripts = true; library.supportsDraftEdits = true; library.supportsNewsletterEdits = true |
| 143 | let create = CompanionLibrary.Change(action: .addIdea, itemID: "project", title: "Newsletter", createsScript: true, writingKind: "newsletter") |
| 144 | let request = CompanionLibrary.Change(action: .note, itemID: "newsletter", revision: "1", text: "Write a brief.", requestsWritingHelp: true) |
| 145 | #expect(create.valid && request.valid) |
| 146 | #expect(throws: CompanionLibraryError.self) { try library.enqueue(create) } |
| 147 | #expect(throws: CompanionLibraryError.self) { try library.enqueue(request) } |
| 148 | library.supportsWritingTools = true |
| 149 | try library.enqueue(create) |
| 150 | #expect(throws: CompanionLibraryError.self) { try library.enqueue(request) } |
| 151 | library.supportsAgentFeatures = true |
| 152 | try library.enqueue(request) |
| 153 | #expect(library.pending.count == 2) |
| 154 | let malformed = CompanionLibrary.Change(action: .deleteItem, itemID: "draft", revision: "1", requestsWritingHelp: true) |
| 155 | #expect(!malformed.valid) |
| 156 | } |
| 157 | |
| 158 | @Test @MainActor func agentRewriteMergesIndependentChangesAndDoesNotOverwriteConcurrentWriting() async throws { |
| 159 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 160 | defer { try? FileManager.default.removeItem(at: folder) } |
| 161 | let workspace = Workspace(directory: folder) |
| 162 | var article = WorkspaceRecord.new("article", projectID: workspace.projectID) |
| 163 | article["title"] = "Article"; article["body"] = "Opening.\n\nMiddle.\n\nClosing." |
| 164 | article = try workspace.save(article) |
| 165 | let base = article |
| 166 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 167 | var current = try #require(workspace.records.first { $0.id == base.id }) |
| 168 | current["body"] = "Opening.\n\nMiddle.\n\nAuthor closing." |
| 169 | _ = try workspace.save(current) |
| 170 | return ["body": "Agent opening.\n\nMiddle.\n\nClosing."] |
| 171 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 172 | let revised = try await ContentStudio(workspace: workspace, model: model).rewrite(base, notes: "Improve the opening.") |
| 173 | #expect(revised.body == "Agent opening.\n\nMiddle.\n\nAuthor closing.") |
| 174 | let conflict = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 175 | var current = try #require(workspace.records.first { $0.id == revised.id }) |
| 176 | current["body"] = "Author replacement." |
| 177 | _ = try workspace.save(current) |
| 178 | return ["body": "Agent replacement."] |
| 179 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "fixture") |
| 180 | await #expect(throws: WorkspaceError.self) { _ = try await ContentStudio(workspace: workspace, model: conflict).rewrite(revised, notes: "Replace this.") } |
| 181 | #expect(workspace.records.first { $0.id == revised.id }?.body == "Author replacement.") |
| 182 | } |
| 183 | |
| 184 | @Test func newsletterTitleCoalescingKeepsTheOriginalMergeBase() throws { |
| 185 | let id = UUID() |
| 186 | var outbox = CompanionLibraryOutbox() |
| 187 | outbox.queueNewsletterEdit(.init(id: id, action: .editDraft, itemID: "newsletter", revision: "1", title: "New title", text: "Body.", baseScriptTitle: "Original title", editsNewsletter: true, newsletterPrepared: false, baseNewsletterText: "Body.")) |
| 188 | outbox.queueNewsletterEdit(.init(id: UUID(), action: .editDraft, itemID: "newsletter", revision: "1", title: "", text: "Edited body.", editsNewsletter: true, baseNewsletterText: "Body.")) |
| 189 | #expect(outbox.entries.count == 1) |
| 190 | #expect(outbox.entries[0].title == "New title") |
| 191 | #expect(outbox.entries[0].baseScriptTitle == "Original title") |
| 192 | var bodyFirst = CompanionLibraryOutbox() |
| 193 | bodyFirst.queueNewsletterEdit(.init(id: UUID(), action: .editDraft, itemID: "newsletter", revision: "1", title: "", text: "First body edit.", editsNewsletter: true, newsletterPrepared: false, baseNewsletterText: "Body.")) |
| 194 | bodyFirst.queueNewsletterEdit(.init(id: UUID(), action: .editDraft, itemID: "newsletter", revision: "1", title: "New title", text: "Second body edit.", baseScriptTitle: "Original title", editsNewsletter: true, baseNewsletterText: "First body edit.")) |
| 195 | #expect(bodyFirst.entries[0].baseScriptTitle == "Original title") |
| 196 | #expect(bodyFirst.entries[0].change?.needsWritingTools == true) |
| 197 | #expect(bodyFirst.entries[0].baseNewsletterText == "Body.") |
| 198 | } |