Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / ContentPlanTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | @testable import InkspringSchedule |
| 5 | |
| 6 | @Test @MainActor func plansSurviveReopenTrashAndIndependentContentEdits() throws { |
| 7 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 8 | defer { try? FileManager.default.removeItem(at: folder) } |
| 9 | let mac = Workspace(directory: folder) |
| 10 | var letter = WorkspaceRecord.new("newsletter", projectID: mac.projectID) |
| 11 | letter["title"] = "Notes"; letter["body"] = "Original body" |
| 12 | letter = try mac.save(letter) |
| 13 | let plan = "# Plan 👋\n\n- [ ] Verify [source](https://example.com)\n\n```swift\nlet x = 1\n```\n" |
| 14 | let withPlan = try mac.savePlan(itemID: letter.id, markdown: plan, base: "") |
| 15 | #expect(withPlan.body == "Original body") |
| 16 | var oldEditor = letter; oldEditor["body"] = "Edited body" |
| 17 | let merged = try mac.saveNewsletterEditor(oldEditor, basedOn: letter) |
| 18 | #expect(merged["planMarkdown"] == plan) |
| 19 | #expect(throws: ContentPlanError.self) { try mac.savePlan(itemID: letter.id, markdown: "stale", base: "") } |
| 20 | let reopened = Workspace(directory: folder) |
| 21 | #expect(reopened.records.first { $0.id == letter.id }?["planMarkdown"] == plan) |
| 22 | var post = WorkspaceRecord.new("draft", projectID: mac.projectID) |
| 23 | post["title"] = "Draft"; post["content"] = "Content"; post["planMarkdown"] = plan |
| 24 | post = try mac.save(post) |
| 25 | try mac.trashLibraryItem(post) |
| 26 | let trashed = try #require(mac.trashedRecords.first { $0.id == post.id }) |
| 27 | #expect(trashed["planMarkdown"] == plan) |
| 28 | try mac.restoreLibraryItem(trashed) |
| 29 | #expect(mac.records.first { $0.id == post.id }?["planMarkdown"] == plan) |
| 30 | #expect(try ContentPlan.decode(Data(plan.utf8)) == plan) |
| 31 | #expect(ContentPlan.filename("pro-001") == "PRO-001-plan.md") |
| 32 | } |
| 33 | |
| 34 | @Test @MainActor func mobilePlansUseSeparateFullTextAndDocumentConflicts() throws { |
| 35 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 36 | defer { try? FileManager.default.removeItem(at: folder) } |
| 37 | let mac = Workspace(directory: folder) |
| 38 | var post = WorkspaceRecord.new("draft", projectID: mac.projectID) |
| 39 | post["title"] = "Draft"; post["content"] = "Post" |
| 40 | post = try mac.save(post) |
| 41 | var change = CompanionLibrary.Change(action: .editDraft, itemID: post.id, revision: post["updatedAt"], text: "# Plan\n\n- [ ] Test") |
| 42 | change.contentOperation = .savePlan; change.basePlan = "" |
| 43 | #expect(change.valid) |
| 44 | var oldMac = CompanionLibrary(workspaceID: UUID()); oldMac.supportsDraftEdits = true |
| 45 | #expect(throws: CompanionLibraryError.self) { try oldMac.enqueue(change) } |
| 46 | #expect(try mac.applyCompanionLibraryChange(change).error == nil) |
| 47 | #expect(try mac.applyCompanionLibraryChange(change).error == nil) |
| 48 | #expect(mac.records.first { $0.id == post.id }?.body == "Post") |
| 49 | var conflict = change |
| 50 | conflict = CompanionLibrary.Change(action: .editDraft, itemID: post.id, revision: post["updatedAt"], text: "Conflicting plan") |
| 51 | conflict.contentOperation = .savePlan; conflict.basePlan = "" |
| 52 | #expect(try mac.applyCompanionLibraryChange(conflict).error != nil) |
| 53 | var library = mac.makeCompanionLibrary(workspaceID: UUID()) |
| 54 | let expected = library.items.first { $0.id == post.id }?.planMarkdown |
| 55 | let separated = try library.separateFullText() |
| 56 | let fullText = try #require(separated) |
| 57 | #expect(library.items.first { $0.id == post.id }?.planMarkdown == nil) |
| 58 | try library.applyFullText(fullText) |
| 59 | #expect(library.items.first { $0.id == post.id }?.planMarkdown == expected) |
| 60 | var outbox = CompanionLibraryOutbox() |
| 61 | outbox.entries = [.init(id: change.id, action: .editDraft, itemID: post.id, revision: post["updatedAt"], title: "", text: change.text, |
| 62 | workspaceID: library.workspaceID, account: "owner", contentOperation: .savePlan, basePlan: "")] |
| 63 | #expect(try JSONDecoder().decode(CompanionLibraryOutbox.self, from: JSONEncoder().encode(outbox)) == outbox) |
| 64 | #expect(outbox.prepare(for: oldMac, account: "owner").isEmpty) |
| 65 | } |
| 66 | |
| 67 | @Test @MainActor func assistantOnlyConfirmsValidatedWritesAndRejectsAmbiguity() throws { |
| 68 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 69 | defer { try? FileManager.default.removeItem(at: folder) } |
| 70 | let mac = Workspace(directory: folder) |
| 71 | for title in ["Weekly notes one", "Weekly notes two"] { |
| 72 | var draft = WorkspaceRecord.new("draft", projectID: mac.projectID) |
| 73 | draft["title"] = title; draft["content"] = "Untouched" |
| 74 | try mac.save(draft) |
| 75 | } |
| 76 | let ambiguous = LocalContentCommand(operation: .title, target: "Weekly notes", value: "Changed") |
| 77 | #expect(throws: PlanAIError.self) { try mac.executeAssistant(ambiguous, request: "Rename Weekly notes to Changed") } |
| 78 | let item = try #require(mac.assistantContents.first { $0.title == "Weekly notes one" }) |
| 79 | let injected = LocalContentCommand(operation: .body, target: item.reference, value: "Bad") |
| 80 | #expect(throws: PlanAIError.self) { try mac.executeAssistant(injected, request: "Read the other item") } |
| 81 | #expect(throws: PlanAIError.self) { try mac.executeAssistant(injected, request: "Do not change \(item.reference)") } |
| 82 | let edit = LocalContentCommand(operation: .title, target: item.reference, value: "Better title") |
| 83 | let receipt = try mac.executeAssistant(edit, request: "Rename \(item.reference) to Better title") |
| 84 | #expect(receipt.itemID == item.id) |
| 85 | #expect(mac.records.first { $0.id == item.id }?.title == "Better title") |
| 86 | #expect(receipt.message.contains("Saved on this Mac")) |
| 87 | #expect(mac.records.filter { $0.kind == "draft" }.allSatisfy { $0.scheduleStatus != "posted" }) |
| 88 | } |
| 89 | |
| 90 | @Test @MainActor func planProofreadingCannotDropMarkdownPrefixesOrCode() async throws { |
| 91 | let original = "# We has a plan\n\n- [ ] Check this\n\n We has code\n\n~~~swift\nWe has code too\n~~~" |
| 92 | let review = try await ProofreadReview.check(.init(body: original), chunkSize: 500) { _ in |
| 93 | [.init(original: "# We has a plan", replacement: "We have a plan", reason: "Bad heading loss"), |
| 94 | .init(original: "- [ ] Check this", replacement: "Check this", reason: "Bad checklist loss"), |
| 95 | .init(original: "We has code too", replacement: "We have code too", reason: "Code"), |
| 96 | .init(original: "We has a plan", replacement: "We have a plan", reason: "Grammar")] |
| 97 | } |
| 98 | #expect(review.corrected.body == original.replacingOccurrences(of: "We has a plan", with: "We have a plan")) |
| 99 | } |
| 100 | |
| 101 | @Test(.enabled(if: ProcessInfo.processInfo.environment["INKSPRING_TEST_LOCAL_AI"] == "1")) @MainActor |
| 102 | func realAppleIntelligencePreservesMarkdownAndExecutesValidatedRename() async throws { |
| 103 | #expect(PlanIntelligence.unavailable == nil) |
| 104 | let original = "# Studio update\n\nWe has a plan.\n\n- [ ] Test the draft\n\n[Read](https://example.com/)\n\n```swift\nlet value = 1\n```" |
| 105 | let corrected = try await PlanIntelligence.proofread(original) |
| 106 | #expect(corrected.contains("# Studio update")) |
| 107 | #expect(corrected.contains("- [ ] Test the draft")) |
| 108 | #expect(corrected.contains("https://example.com/")) |
| 109 | #expect(corrected.contains("```swift\nlet value = 1\n```")) |
| 110 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 111 | defer { try? FileManager.default.removeItem(at: folder) } |
| 112 | let workspace = Workspace(directory: folder) |
| 113 | if let error = workspace.startupError { throw PlanAIError("Test workspace startup: " + error) } |
| 114 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 115 | draft["title"] = "Test newsletter angle"; draft["content"] = "Untouched body" |
| 116 | draft = try workspace.save(draft) |
| 117 | let request = "Rename \(draft.referenceID!) to A clearer title" |
| 118 | let command = try await OnDeviceContentAssistant.command(request, items: workspace.assistantContents) |
| 119 | #expect(command.operation == .title) |
| 120 | let result = try workspace.executeAssistant(command, request: request) |
| 121 | #expect(result.itemID == draft.id) |
| 122 | #expect(workspace.records.first { $0.id == draft.id }?.title == "A clearer title") |
| 123 | print("REAL ON-DEVICE AI: proofreading preserved Markdown; structured rename applied and read back from SQLite. \(result.message)") |
| 124 | } |
| 125 | |
| 126 | @Test @MainActor func fullBackupPreservesPlansAndPreviousRevision() throws { |
| 127 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 128 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 129 | defer { try? FileManager.default.removeItem(at: folder) } |
| 130 | let workspace = Workspace(directory: folder) |
| 131 | if let error = workspace.startupError { throw PlanAIError("Test workspace startup: " + error) } |
| 132 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 133 | draft["title"] = "Backup test"; draft["content"] = "Content" |
| 134 | draft = try workspace.save(draft) |
| 135 | try workspace.savePlan(itemID: draft.id, markdown: "# First plan", base: "") |
| 136 | try workspace.savePlan(itemID: draft.id, markdown: "# Second plan", base: "# First plan") |
| 137 | let archive = folder.appending(path: "backup.zip") |
| 138 | try WorkspaceBackup.export(records: workspace.records, preferences: workspace.settings, directory: folder, to: archive) |
| 139 | let (backup, _) = try WorkspaceBackup.stage(archive, in: folder) |
| 140 | let restored = try #require(backup.records.first { $0.id == draft.id }) |
| 141 | #expect(restored["planMarkdown"] == "# Second plan") |
| 142 | #expect(restored["previousPlanMarkdown"] == "# First plan") |
| 143 | } |
| 144 | |
| 145 | @Test @MainActor func proofreadingProtectsNestedShorterFencesAndIndentedCode() async throws { |
| 146 | let body = "~~~~text\nWe has fenced code\n~~~\nWe has more code\n~~~~\n\n We has indented code\n\nWe has prose." |
| 147 | let review = try await ProofreadReview.check(.init(body: body), chunkSize: 500) { _ in |
| 148 | ["We has fenced code", "We has more code", "We has indented code", "We has prose."].map { |
| 149 | ProofreadEdit(original: $0, replacement: $0.replacingOccurrences(of: "has", with: "have"), reason: "Grammar") |
| 150 | } |
| 151 | } |
| 152 | #expect(review.corrected.body == body.replacingOccurrences(of: "We has prose.", with: "We have prose.")) |
| 153 | } |
| 154 | |
| 155 | @Test @MainActor func createWithPlanPersistsItWithoutPublishing() throws { |
| 156 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 157 | defer { try? FileManager.default.removeItem(at: folder) } |
| 158 | let workspace = Workspace(directory: folder) |
| 159 | let command = LocalContentCommand(operation: .createDraft, value: "A first draft", title: "Studio notes") |
| 160 | let result = try workspace.executeAssistant(command, request: "Create a draft called Studio notes with a plan") |
| 161 | let draft = try #require(workspace.records.first { $0.id == result.itemID }) |
| 162 | #expect(draft["planMarkdown"].contains("# Studio notes")) |
| 163 | #expect(draft.scheduleStatus != "posted") |
| 164 | #expect(try ContentPlan.decode(Data(draft["planMarkdown"].utf8)) == draft["planMarkdown"]) |
| 165 | } |
| 166 | |
| 167 | @Test @MainActor func mcpPlansRequireExpectedTextAndRespectProjectScope() async throws { |
| 168 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 169 | defer { try? FileManager.default.removeItem(at: folder) } |
| 170 | let workspace = Workspace(directory: folder) |
| 171 | try workspace.set("mcpEnabled", to: true) |
| 172 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 173 | draft["title"] = "Plan via MCP"; draft = try workspace.save(draft) |
| 174 | let agent = AgentMCP(workspace: workspace) |
| 175 | func call(_ agent: AgentMCP, _ name: String, _ args: [String: Any]) async -> [String: Any] { |
| 176 | await agent.handle(["jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": ["name": name, "arguments": args]])?["result"] as? [String: Any] ?? [:] |
| 177 | } |
| 178 | let result = await call(agent, "save_plan", ["content_id": draft.referenceID!, "markdown": "# MCP Plan", "expected_markdown": ""]) |
| 179 | #expect(result["isError"] as? Bool != true) |
| 180 | let read = await call(agent, "get_plan", ["content_id": draft.referenceID!.lowercased()]) |
| 181 | #expect((read["structuredContent"] as? [String: Any])?["markdown"] as? String == "# MCP Plan") |
| 182 | let stale = await call(agent, "save_plan", ["content_id": draft.id, "markdown": "Old update", "expected_markdown": ""]) |
| 183 | #expect(stale["isError"] as? Bool == true) |
| 184 | let scoped = await call(AgentMCP(workspace: workspace, chatProjectID: "other-project"), "get_plan", ["content_id": draft.id]) |
| 185 | #expect(scoped["isError"] as? Bool == true) |
| 186 | } |
| 187 | |
| 188 | @Test(.enabled(if: ProcessInfo.processInfo.environment["INKSPRING_PLAN_REVIEW_WORKSPACE"] != nil)) @MainActor |
| 189 | func prepareLocalPlanReviewLibrary() throws { |
| 190 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["INKSPRING_PLAN_REVIEW_WORKSPACE"]!) |
| 191 | let workspace = Workspace(directory: folder) |
| 192 | if let error = workspace.startupError { throw PlanAIError(error) } |
| 193 | try workspace.set("autoPost", to: false) |
| 194 | try workspace.set("mcpEnabled", to: true) |
| 195 | var project = try #require(workspace.projects.first) |
| 196 | project["name"] = "Plan review" |
| 197 | project = try workspace.save(project) |
| 198 | workspace.selectProject(project.id) |
| 199 | if !workspace.records.contains(where: { $0.title == "Notes from the studio" }) { |
| 200 | var newsletter = WorkspaceRecord.new("newsletter", projectID: project.id) |
| 201 | newsletter["title"] = "Notes from the studio" |
| 202 | newsletter["body"] = "# A clearer opening\n\nWe use AI and automation to make more time for work that matters.\n\n[Visit Inkspring](https://inkspring.ai/)" |
| 203 | newsletter["planMarkdown"] = "# Newsletter plan\n\n## Goal\n\nWe has a plan to explain the workflow.\n\n- [ ] Write the opening\n- [ ] Check the links\n\n[Source](https://inkspring.ai/)\n\n```swift\nlet draft = \"Keep code unchanged\"\n```" |
| 204 | try workspace.save(newsletter) |
| 205 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 206 | draft["title"] = "A quieter way to draft"; draft["platform"] = "linkedin" |
| 207 | draft["content"] = "Start with the decision you made and why it mattered. One concrete example is enough." |
| 208 | draft["planMarkdown"] = "# Post plan\n\n- [ ] Open with one useful detail\n- [ ] Keep the claim specific\n- [ ] Review the final draft" |
| 209 | try workspace.save(draft) |
| 210 | } |
| 211 | print("Local review library ready: \(folder.path)") |
| 212 | } |
| 213 | |
| 214 | @Test func planOperationsCannotAlsoRequestPublishingOrWriting() { |
| 215 | var change = CompanionLibrary.Change(action: .editDraft, itemID: "article", revision: "revision", text: "# Plan", publishesXArticle: true, xArticleAccountKey: "account") |
| 216 | change.contentOperation = .savePlan; change.basePlan = "" |
| 217 | #expect(!change.valid) |
| 218 | var request = CompanionLibrary.Change(action: .editDraft, itemID: "post", revision: "revision", text: "# Plan", requestsWritingHelp: true) |
| 219 | request.contentOperation = .savePlan; request.basePlan = "" |
| 220 | #expect(!request.valid) |
| 221 | } |
| 222 | |
| 223 | @Test @MainActor func longFormPlansAndHistoryTravelTogether() throws { |
| 224 | let folder = URL(fileURLWithPath: ProcessInfo.processInfo.environment["TMPDIR"] ?? NSTemporaryDirectory()).appending(path: UUID().uuidString) |
| 225 | defer { try? FileManager.default.removeItem(at: folder) } |
| 226 | let mac = Workspace(directory: folder) |
| 227 | for kind in ["script", "article"] { |
| 228 | var record = WorkspaceRecord.new(kind, projectID: mac.projectID) |
| 229 | record["title"] = "Writing"; record["body"] = "Original full text" |
| 230 | record = try mac.save(record) |
| 231 | record = try mac.savePlan(itemID: record.id, markdown: "# Outline", base: "") |
| 232 | var library = mac.makeCompanionLibrary(workspaceID: UUID()) |
| 233 | let separated = try library.separateFullText() |
| 234 | let text = try #require(separated) |
| 235 | try library.applyFullText(text) |
| 236 | let item = try #require(((library.scripts ?? []) + (library.articles ?? [])).first { $0.id == record.id }) |
| 237 | #expect(item.body == "Original full text") |
| 238 | #expect(item.planMarkdown == "# Outline") |
| 239 | #expect(item.history?.isEmpty == false) |
| 240 | } |
| 241 | } |