Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / ContentWorkflowTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | |
| 5 | @Test @MainActor func mcpSettingsProbeUsesTheRealStdioServerAndReadsWithoutEditing() throws { |
| 6 | guard let command = ProcessInfo.processInfo.environment["INKSPRING_MCP_TEST_COMMAND"] else { return } |
| 7 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 8 | defer { try? FileManager.default.removeItem(at: folder) } |
| 9 | let workspace = Workspace(directory: folder) |
| 10 | let records = workspace.records.map(\.id) |
| 11 | try workspace.set("mcpEnabled", to: false) |
| 12 | #expect(throws: WorkspaceError.self) { try AgentConnectionCheck.run(command: command, workspaceOverride: folder.path) } |
| 13 | try workspace.set("mcpEnabled", to: true) |
| 14 | let check = try AgentConnectionCheck.run(command: command, workspaceOverride: folder.path) |
| 15 | #expect(check.toolCount == AgentMCP.tools.count) |
| 16 | #expect(check.projectCount == workspace.projects.count) |
| 17 | try workspace.reload() |
| 18 | #expect(workspace.records.map(\.id) == records) |
| 19 | #expect(workspace.settings["autoPost"] as? Bool != true) |
| 20 | #expect(workspace.settings["mcpAllowPosting"] as? Bool != true) |
| 21 | } |
| 22 | |
| 23 | @Test @MainActor func workspaceQuickEditKeepsAttachmentsAndScheduleReview() throws { |
| 24 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 25 | defer { try? FileManager.default.removeItem(at: folder) } |
| 26 | let workspace = Workspace(directory: folder) |
| 27 | var post = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 28 | post["title"] = "Test title" |
| 29 | post["content"] = "Original post" |
| 30 | post["format"] = "image" |
| 31 | post.fields["image"] = ["file": "fixture.png"] |
| 32 | post = try workspace.save(post) |
| 33 | #expect(PostBrowserFilter.draft.matches(post, platform: "x", search: " original ")) |
| 34 | let scheduled = try workspace.scheduleDraft(post, at: .now.addingTimeInterval(3_600)) |
| 35 | #expect(!PostBrowserFilter.draft.matches(scheduled, platform: nil, search: "")) |
| 36 | #expect(!PostBrowserFilter.scheduling.matches(scheduled, platform: "x", search: "")) |
| 37 | try workspace.addComment(to: scheduled, text: "Keep this review comment.") |
| 38 | try workspace.updatePostText(scheduled, title: "Updated title", text: "Edited post") |
| 39 | let edited = try #require(workspace.drafts.first { $0.id == post.id }) |
| 40 | #expect(edited.title == "Updated title") |
| 41 | #expect(edited.body == "Edited post") |
| 42 | #expect(edited.comments.first?["text"] as? String == "Keep this review comment.") |
| 43 | #expect((edited.fields["image"] as? [String: String])?["file"] == "fixture.png") |
| 44 | #expect(PostBrowserFilter.draft.matches(edited, platform: "x", search: "edited")) |
| 45 | #expect(PostBrowserFilter.scheduling.matches(edited, platform: "x", search: "edited")) |
| 46 | #expect(!PostBrowserFilter.scheduling.matches(edited, platform: "linkedin", search: "")) |
| 47 | #expect(throws: WorkspaceError.self) { try workspace.updatePostText(scheduled, title: "Stale title", text: "Stale post") } |
| 48 | let otherWindow = Workspace(directory: folder) |
| 49 | try otherWindow.updatePostText(edited, title: edited.title, text: "Edited in another window") |
| 50 | try workspace.addComment(to: edited, text: "Comment from an older preview.") |
| 51 | let latest = try #require(workspace.drafts.first { $0.id == post.id }) |
| 52 | #expect(latest.body == "Edited in another window") |
| 53 | #expect(latest.comments.count == 2) |
| 54 | |
| 55 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 56 | idea["topic"] = "Legacy idea" |
| 57 | idea["text"] = "An old angle" |
| 58 | idea.fields["suggestedPlatforms"] = ["x"] |
| 59 | idea = try workspace.save(idea) |
| 60 | let reopenedIdea = try #require(Workspace(directory: folder).ideas.first { $0.id == idea.id }) |
| 61 | #expect(reopenedIdea.fields["suggestedPlatforms"] == nil) |
| 62 | #expect(PostBrowserFilter.ideas.matches(reopenedIdea, platform: "linkedin", search: "legacy")) |
| 63 | #expect(!PostBrowserFilter.ideas.matches(reopenedIdea, platform: nil, search: "LinkedIn")) |
| 64 | try workspace.updatePostText(idea, title: idea.title, text: "A better angle") |
| 65 | let updatedIdea = try #require(workspace.ideas.first { $0.id == idea.id }) |
| 66 | #expect(updatedIdea.body == "A better angle") |
| 67 | #expect(updatedIdea["previousText"] == "An old angle") |
| 68 | } |
| 69 | |
| 70 | @Test @MainActor func workspaceBrowsesAllDraftFormatsByProjectAndChannel() throws { |
| 71 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 72 | defer { try? FileManager.default.removeItem(at: folder) } |
| 73 | let workspace = Workspace(directory: folder) |
| 74 | var other = WorkspaceRecord.new("project") |
| 75 | other["name"] = "Other project" |
| 76 | try workspace.save(other) |
| 77 | for format in WorkspaceDraftType.allCases { |
| 78 | var record = format.makeRecord(projectID: workspace.projectID) |
| 79 | record["title"] = "Shared title" |
| 80 | record[record.isLongForm ? "body" : "content"] = "Find this paragraph" |
| 81 | let saved = try workspace.save(record) |
| 82 | #expect(workspace.workspaceDrafts.contains { $0.id == saved.id }) |
| 83 | let channel = format == .newsletter ? "substack" : record["platform"] |
| 84 | #expect(WorkspaceDraftType(record: saved) == format) |
| 85 | #expect(PostBrowserFilter.all.matches(saved, platform: channel, search: "paragraph")) |
| 86 | #expect(!PostBrowserFilter.all.matches(saved, platform: "instagram", search: "")) |
| 87 | #expect(PostBrowserFilter.draft.matches(saved, platform: nil, search: format.name)) |
| 88 | #expect(PostBrowserFilter.scheduling.matches(saved, platform: nil, search: "") == (format == .newsletter)) |
| 89 | } |
| 90 | workspace.selectProject(other.id) |
| 91 | #expect(workspace.workspaceDrafts.isEmpty) |
| 92 | } |
| 93 | |
| 94 | @Test @MainActor func scheduleRevisionKeepsTheDraftAndRequiresANewPostingTime() async throws { |
| 95 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 96 | defer { try? FileManager.default.removeItem(at: folder) } |
| 97 | let workspace = Workspace(directory: folder) |
| 98 | var project = WorkspaceRecord.new("project") |
| 99 | project["name"] = "Another project" |
| 100 | try workspace.save(project) |
| 101 | #expect(workspace.projectID != project.id) |
| 102 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 103 | draft["title"] = "Scheduled draft" |
| 104 | draft["content"] = "Original wording." |
| 105 | draft["format"] = "image" |
| 106 | draft["imagePrompt"] = "Earlier direction" |
| 107 | draft.fields["image"] = ["file": "fixture.png", "prompt": "Earlier direction"] |
| 108 | draft = try workspace.save(draft) |
| 109 | let queued = try workspace.scheduleDraft(draft, at: .now.addingTimeInterval(3_600)) |
| 110 | |
| 111 | let notes = "Start with the result." |
| 112 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, |
| 113 | object: { _, input in |
| 114 | #expect(input["notes"] as? String == notes) |
| 115 | return ["text": "Revised wording.", "reply": "Moved the result up.", "imagePrompt": "Updated direction"] |
| 116 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 117 | let studio = ContentStudio(workspace: workspace, model: model) |
| 118 | let revised = try await studio.rewrite(queued, notes: notes) |
| 119 | #expect(revised.id == queued.id) |
| 120 | #expect(revised.body == "Revised wording.") |
| 121 | #expect(revised["notesReply"] == "Moved the result up.") |
| 122 | #expect(revised["imagePrompt"] == "Updated direction") |
| 123 | #expect(revised.fields["image"] as? [String: String] == queued.fields["image"] as? [String: String]) |
| 124 | #expect(!revised["mediaError"].isEmpty) |
| 125 | #expect(ScheduleListing.section(for: revised) == .ready) |
| 126 | #expect(revised.schedule["slotAt"] as? String == "") |
| 127 | let restored = try studio.undoRewrite(revised) |
| 128 | #expect(restored.body == queued.body) |
| 129 | #expect(restored["previousContent"] == revised.body) |
| 130 | #expect(restored.scheduleStatus == "ready") |
| 131 | |
| 132 | let database = try WorkspaceDatabase(url: folder.appending(path: "workspace.sqlite")) |
| 133 | let deletingModel = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, |
| 134 | object: { _, _ in |
| 135 | try database.remove(restored.id, kind: "draft") |
| 136 | return ["text": "Late rewrite."] |
| 137 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 138 | let deletingStudio = ContentStudio(workspace: workspace, model: deletingModel) |
| 139 | await #expect(throws: WorkspaceError.self) { _ = try await deletingStudio.rewrite(restored, notes: notes) } |
| 140 | #expect(throws: WorkspaceError.self) { _ = try studio.undoRewrite(restored) } |
| 141 | #expect(!workspace.records.contains { $0.id == restored.id }) |
| 142 | } |
| 143 | |
| 144 | @Test @MainActor func learningWritingStyleUsesSelectedPublishedExamplesAndRequiresSave() async throws { |
| 145 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 146 | defer { try? FileManager.default.removeItem(at: folder) } |
| 147 | let workspace = Workspace(directory: folder) |
| 148 | let active = ["voice": "Existing voice", "imageStyle": "Soft pencil"] |
| 149 | try workspace.set("personalProfile", to: active) |
| 150 | var published = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 151 | published["title"] = "A published example" |
| 152 | published["content"] = "This was shared publicly." |
| 153 | try workspace.save(published) |
| 154 | var receipt = WorkspaceRecord.new("publication", projectID: workspace.projectID) |
| 155 | receipt["title"] = published.title |
| 156 | receipt["draftId"] = published.id |
| 157 | receipt["status"] = "published" |
| 158 | try workspace.save(receipt) |
| 159 | var sample = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 160 | sample["title"] = "Template example" |
| 161 | sample["content"] = "Do not include sample templates." |
| 162 | sample.fields["sample"] = true |
| 163 | sample.fields["schedule"] = ["status": "posted"] |
| 164 | try workspace.save(sample) |
| 165 | let candidates = PersonalProfile.publishedDrafts(in: workspace.records) |
| 166 | #expect(candidates.map(\.id) == [published.id]) |
| 167 | let samples = try PersonalProfile.samples(appending: candidates, to: "A pasted example.") |
| 168 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, input in |
| 169 | #expect(input.keys.sorted() == ["samples"]) |
| 170 | #expect(input["samples"] as? String == "A pasted example.\n\nThis was shared publicly.") |
| 171 | return ["voice": "Short sentences", "interests": "Engineering", "avoid": "Jargon"] |
| 172 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 173 | let suggestion = try await ContentStudio(workspace: workspace, model: model).learnWritingStyle(from: samples) |
| 174 | #expect((workspace.settings["personalProfile"] as? [String: String]) == active) |
| 175 | var reviewed: [String: Any] = active.merging(suggestion) { _, suggested in suggested } |
| 176 | reviewed["samples"] = samples |
| 177 | try workspace.savePersonalProfile(reviewed, replacing: active) |
| 178 | let saved = try #require(workspace.settings["personalProfile"] as? [String: Any]) |
| 179 | #expect(saved["voice"] as? String == "Short sentences") |
| 180 | #expect(saved["imageStyle"] as? String == "Soft pencil") |
| 181 | #expect(throws: WorkspaceError.self) { try workspace.savePersonalProfile(reviewed, replacing: active) } |
| 182 | } |
| 183 | |
| 184 | @Test @MainActor func savingReviewedProfileAppliesEditsAndResolvesTheSuggestion() throws { |
| 185 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 186 | defer { try? FileManager.default.removeItem(at: folder) } |
| 187 | let workspace = Workspace(directory: folder) |
| 188 | let active = workspace.settings["personalProfile"] as? [String: Any] ?? [:] |
| 189 | let suggestion = try workspace.suggestProfile(["voice": "Proposed voice"]) |
| 190 | var reviewed = try #require(suggestion.fields["profile"] as? [String: Any]) |
| 191 | reviewed["voice"] = "Reviewed voice" |
| 192 | try workspace.savePersonalProfile(reviewed, replacing: active, suggestionID: suggestion.id) |
| 193 | #expect((workspace.settings["personalProfile"] as? [String: Any])?["voice"] as? String == "Reviewed voice") |
| 194 | #expect(workspace.records.first { $0.id == suggestion.id }?["status"] == "accepted") |
| 195 | } |
| 196 | |
| 197 | @Test @MainActor func agentWritesAndPicksDraftsInTheUIWorkspace() async throws { |
| 198 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 199 | defer { try? FileManager.default.removeItem(at: folder) } |
| 200 | let workspace = Workspace(directory: folder) |
| 201 | try workspace.set("mcpEnabled", to: true) |
| 202 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in |
| 203 | ["title": "Fixture draft", "content": "An original local post."] |
| 204 | }, object: { instructions, _ in |
| 205 | if instructions.contains("Generate up to") { |
| 206 | return ["ideas": [ |
| 207 | ["slot": 2, "kind": "work", "topic": "Draft stewardship", |
| 208 | "text": "Open with the cost of replacing a useful draft.", "sourceId": "s1"] |
| 209 | ]] |
| 210 | } |
| 211 | return ["text": "A finished draft about stewardship."] |
| 212 | }, prompt: { _ in "An illustration" }, image: { _ in (Data([1, 2, 3]), "png") }, imageProvider: "Fixture") |
| 213 | let agent = AgentMCP(workspace: workspace, model: model) |
| 214 | let created = await tool(agent, "write_post", ["platform": "x", "idea": "Writing care"]) |
| 215 | let draft = try #require(created["draft"] as? [String: Any]) |
| 216 | #expect(draft["content"] as? String == "An original local post.") |
| 217 | #expect(workspace.drafts.contains { $0.id == draft["id"] as? String }) |
| 218 | let refreshed = await tool(agent, "refresh_ideas", ["research": false]) |
| 219 | #expect(refreshed["written"] as? Int == 1) |
| 220 | let idea = try #require(workspace.ideas.first) |
| 221 | let selected = await tool(agent, "pick_idea", ["idea_id": idea.id, "platforms": ["x", "linkedin"]]) |
| 222 | let versions = try #require(selected["versions"] as? [[String: Any]]) |
| 223 | #expect(versions.count == 2) |
| 224 | #expect(workspace.ideas.first?["status"] == "draft") |
| 225 | #expect(workspace.ideas.first?.body == idea.body) |
| 226 | #expect(workspace.ideas.first?.draftVersions.count == 2) |
| 227 | #expect(workspace.ideas.first?.isPendingPostIdea == false) |
| 228 | #expect(!workspace.trashedRecords.contains { $0.id == idea.id }) |
| 229 | let duplicate = await tool(agent, "pick_idea", ["idea_id": idea.id, "platforms": ["x"]]) |
| 230 | #expect(duplicate["isError"] as? Bool == true) |
| 231 | #expect(workspace.drafts.filter { $0.scheduleStatus == "ready" }.count == 2) |
| 232 | #expect(workspace.drafts.filter { $0["ideaId"] == idea.id }.allSatisfy { $0.fields["image"] == nil }) |
| 233 | let reopened = Workspace(directory: folder) |
| 234 | #expect(reopened.drafts.count == workspace.drafts.count) |
| 235 | #expect(reopened.ideas.first?["status"] == "draft") |
| 236 | |
| 237 | let posted = await tool(agent, "post_now", ["draft_id": draft["id"] ?? ""]) |
| 238 | #expect(posted["isError"] as? Bool == true) |
| 239 | #expect(workspace.records.filter { $0.kind == "publication" }.isEmpty) |
| 240 | } |
| 241 | |
| 242 | @Test @MainActor func writingStudioKeepsItsSavedTextAndPreviousImageWhenImageGenerationFails() async throws { |
| 243 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 244 | defer { try? FileManager.default.removeItem(at: folder) } |
| 245 | let workspace = Workspace(directory: folder) |
| 246 | var reference = WorkspaceRecord.new("source", projectID: workspace.projectID) |
| 247 | reference["title"] = "A selected reference" |
| 248 | reference["text"] = "Fixture evidence for the writing request." |
| 249 | try workspace.save(reference) |
| 250 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 251 | draft["title"] = "Earlier draft" |
| 252 | draft["content"] = "Earlier wording" |
| 253 | draft["brief"] = "Use the selected evidence." |
| 254 | draft["format"] = "image" |
| 255 | draft.fields["sourceIds"] = [reference.id, "missing"] |
| 256 | let previous = try workspace.writeGeneratedImage(Data("previous fixture image".utf8), fileExtension: "png") |
| 257 | draft.fields["image"] = ["file": previous] |
| 258 | draft = try workspace.save(draft) |
| 259 | let draftID = draft.id |
| 260 | |
| 261 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { input, format in |
| 262 | #expect(format == "image") |
| 263 | #expect((input["evidence"] as? [[String: String]])?.map { $0["title"] } == ["A selected reference"]) |
| 264 | return ["title": "Revised draft", "content": "New wording.", "imagePrompt": "A line drawing"] |
| 265 | }, object: { _, _ in [:] }, prompt: { _ in "" }, image: { prompt in |
| 266 | #expect(prompt == "A line drawing") |
| 267 | let disk = try WorkspaceDatabase(url: folder.appending(path: "workspace.sqlite")) |
| 268 | #expect(try disk.records().first { $0.id == draftID }?.body == "New wording.") |
| 269 | throw WorkspaceError("The image provider is unavailable.") |
| 270 | }, imageProvider: "Fixture") |
| 271 | let (saved, imageError) = try await ContentStudio(workspace: workspace, model: model).compose(draft, withImage: true) { textDraft in |
| 272 | #expect(textDraft.id == draftID) |
| 273 | #expect(textDraft.body == "New wording.") |
| 274 | } |
| 275 | #expect(imageError == "The image provider is unavailable.") |
| 276 | #expect(saved.id == draftID) |
| 277 | #expect(saved["imagePrompt"] == "A line drawing") |
| 278 | #expect(saved.fields["sourceIds"] as? [String] == [reference.id]) |
| 279 | #expect(workspace.mediaURL(saved)?.lastPathComponent == previous) |
| 280 | #expect(workspace.drafts.first { $0.id == draftID }?.body == "New wording.") |
| 281 | } |
| 282 | |
| 283 | @Test(arguments: [false, true]) |
| 284 | @MainActor func generatedImageDoesNotOverwriteAnEditOrSendClaim(mimicSendClaim: Bool) async throws { |
| 285 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 286 | defer { try? FileManager.default.removeItem(at: folder) } |
| 287 | let workspace = Workspace(directory: folder) |
| 288 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 289 | draft["title"] = "An image draft" |
| 290 | draft["brief"] = "Describe this image." |
| 291 | draft["format"] = "image" |
| 292 | let draftID = draft.id |
| 293 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in |
| 294 | ["title": "An image draft", "content": "New text", "imagePrompt": "A diagram"] |
| 295 | }, object: { _, _ in [:] }, prompt: { _ in "" }, image: { _ in |
| 296 | let concurrent = Workspace(directory: folder) |
| 297 | var latest = try #require(concurrent.drafts.first { $0.id == draftID }) |
| 298 | if mimicSendClaim { |
| 299 | latest.fields["schedule"] = ["status": "posting"] |
| 300 | let disk = try WorkspaceDatabase(url: folder.appending(path: "workspace.sqlite")) |
| 301 | try disk.put(latest) |
| 302 | } else { |
| 303 | latest["content"] = "Concurrent edit" |
| 304 | try concurrent.save(latest) |
| 305 | } |
| 306 | return (Data("new fixture image".utf8), "png") |
| 307 | }, imageProvider: "Fixture") |
| 308 | let (_, imageError) = try await ContentStudio(workspace: workspace, model: model).compose(draft, withImage: true) |
| 309 | #expect(imageError?.contains("draft changed") == true) |
| 310 | let latest = try #require(workspace.drafts.first { $0.id == draftID }) |
| 311 | #expect(latest.body == (mimicSendClaim ? "New text" : "Concurrent edit")) |
| 312 | #expect(latest.scheduleStatus == (mimicSendClaim ? "posting" : "")) |
| 313 | #expect(latest.fields["image"] == nil) |
| 314 | #expect(!FileManager.default.fileExists(atPath: folder.appending(path: "images").path)) |
| 315 | } |
| 316 | |
| 317 | @Test @MainActor func vaultRejectsLinksAndRequiresReviewBeforeSavingSuggestions() async throws { |
| 318 | let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 319 | defer { try? FileManager.default.removeItem(at: root) } |
| 320 | let workspace = Workspace(directory: root.appending(path: "workspace")) |
| 321 | let folder = root.appending(path: "vault") |
| 322 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 323 | let note = folder.appending(path: "Project.md") |
| 324 | try Data("---\nprivate: fixture\n---\nProject notes.\n".utf8).write(to: note) |
| 325 | try FileManager.default.createSymbolicLink(at: folder.appending(path: "Linked.md"), withDestinationURL: note) |
| 326 | let vault = try ObsidianVault(folder.path) |
| 327 | let listing = try vault.list(query: "") |
| 328 | #expect(listing.notes.compactMap { $0["id"] as? String } == ["Project.md"]) |
| 329 | #expect(throws: WorkspaceError.self) { try vault.preview(["Linked.md"]) } |
| 330 | #expect(throws: WorkspaceError.self) { try vault.preview(["../Project.md"]) } |
| 331 | let selected = try vault.preview(["Project.md"]).notes |
| 332 | #expect(selected.first?["text"] == "Project notes.") |
| 333 | try workspace.set("obsidianVault", to: ["path": folder.path, "allowAgents": false]) |
| 334 | try workspace.set("mcpEnabled", to: true) |
| 335 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, context in |
| 336 | let notes = try #require(context["notes"] as? [[String: String]]) |
| 337 | #expect(notes.first?["text"] == "Project notes.") |
| 338 | return ["ideas": [["title": "Public angle", "summary": "A reviewable suggestion.", "noteIds": ["Project.md"]]]] |
| 339 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 340 | let agent = AgentMCP(workspace: workspace, model: model) |
| 341 | let denied = await tool(agent, "preview_vault_notes", ["note_ids": ["Project.md"]]) |
| 342 | #expect(denied["isError"] as? Bool == true) |
| 343 | try workspace.set("obsidianVault", to: ["path": folder.path, "allowAgents": true]) |
| 344 | let generated = await tool(agent, "suggest_vault_ideas", ["notes": selected]) |
| 345 | #expect(generated["count"] as? Int == 1) |
| 346 | let suggestion = try #require(workspace.records.first { $0.kind == "personal-inbox" }) |
| 347 | #expect(suggestion["status"] == "pending") |
| 348 | #expect(!workspace.sources.contains { $0.title == "Public angle" }) |
| 349 | try workspace.reviewSuggestion(suggestion.id, accept: true) |
| 350 | #expect(workspace.sources.contains { $0.title == "Public angle" }) |
| 351 | try Data("Changed".utf8).write(to: note) |
| 352 | let changed = await tool(agent, "suggest_vault_ideas", ["notes": selected]) |
| 353 | #expect(changed["isError"] as? Bool == true) |
| 354 | } |
| 355 | |
| 356 | @Test @MainActor func discoverySavesEvidenceAndKeepsDismissalsAcrossRefreshes() async throws { |
| 357 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 358 | defer { try? FileManager.default.removeItem(at: folder) } |
| 359 | let workspace = Workspace(directory: folder) |
| 360 | let now = Date.now |
| 361 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { instructions, _ in |
| 362 | if instructions.contains("Choose three") { |
| 363 | return ["focus": "Writing tools", "topics": [["topic": "Drafts", "query": "writing drafts"]]] |
| 364 | } |
| 365 | return ["items": [["id": "0", "headline": "Draft care", "relevance": 95, "angle": "Make drafts easy to reopen."]]] |
| 366 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 367 | let discovery = ResearchDiscovery(studio: ContentStudio(workspace: workspace, model: model)) { _, _, topic in |
| 368 | [["url": "https://news.google.com/rss/articles/fixture", "title": "Public headline", "text": "A public headline with enough context", |
| 369 | "postedAt": workspaceTimestamp(now), "topic": topic, "author": "Fixture publisher"]] |
| 370 | } |
| 371 | let feed = try await discovery.discover(.news, projectID: workspace.projectID, now: now) |
| 372 | let item = try #require((feed.fields["items"] as? [[String: Any]])?.first) |
| 373 | let source = try #require(item["source"] as? [String: Any]) |
| 374 | let first = try workspace.saveResearchReference(source, projectID: workspace.projectID) |
| 375 | let second = try workspace.saveResearchReference(source, projectID: workspace.projectID) |
| 376 | #expect(first.id == second.id) |
| 377 | try workspace.dismissResearch(try #require(item["id"] as? String), from: feed.id) |
| 378 | let refreshed = try await discovery.discover(.news, projectID: workspace.projectID, now: now) |
| 379 | #expect((refreshed.fields["items"] as? [[String: Any]])?.isEmpty == true) |
| 380 | #expect(workspace.sources.contains { $0.id == first.id }) |
| 381 | } |
| 382 | |
| 383 | @Test @MainActor func researchCanBrowseWithoutWritingAndKeepsTheFeedOnSearchFailure() async throws { |
| 384 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 385 | defer { try? FileManager.default.removeItem(at: folder) } |
| 386 | let workspace = Workspace(directory: folder) |
| 387 | let now = Date.now |
| 388 | let studio = ContentStudio(workspace: workspace) |
| 389 | let referencesBeforeBrowse = workspace.sources.map(\.id) |
| 390 | let topic = RecentResearch.topic(in: "Apple platforms, AI models and developer tools") |
| 391 | #expect(topic == "Apple platforms") |
| 392 | #expect(RecentResearch.topic(in: "") == "Technology") |
| 393 | var shouldFail = false |
| 394 | let discovery = ResearchDiscovery(studio: studio) { platform, query, title in |
| 395 | #expect(platform == .news) |
| 396 | #expect(query == "Apple platforms") |
| 397 | if shouldFail { throw WorkspaceError("The provider is offline.") } |
| 398 | return [ |
| 399 | ["url": "https://example.test/news", "title": "A fresh headline", "text": "A fresh headline", |
| 400 | "topic": title, "postedAt": workspaceTimestamp(now.addingTimeInterval(-60)), |
| 401 | "origin": "News · Google News RSS"] |
| 402 | ] |
| 403 | } |
| 404 | let feed = try await discovery.browse(.news, projectID: workspace.projectID, topic: topic, now: now) |
| 405 | let items = try #require(feed.fields["items"] as? [[String: Any]]) |
| 406 | #expect(items.first?["headline"] as? String == "A fresh headline") |
| 407 | #expect(items.first?["angle"] == nil) |
| 408 | #expect(workspace.sources.map(\.id) == referencesBeforeBrowse) |
| 409 | #expect(RecentResearch.fresh(feed, now: now.addingTimeInterval(60))) |
| 410 | #expect(!RecentResearch.fresh(feed, now: now.addingTimeInterval(3601))) |
| 411 | |
| 412 | shouldFail = true |
| 413 | await #expect(throws: WorkspaceError.self) { |
| 414 | _ = try await discovery.browse(.news, projectID: workspace.projectID, topic: topic, now: now.addingTimeInterval(60)) |
| 415 | } |
| 416 | let retained = try #require(workspace.items("discovery").first) |
| 417 | #expect(retained["searchedAt"] == feed["searchedAt"]) |
| 418 | #expect((retained.fields["items"] as? [[String: Any]])?.first?["headline"] as? String == "A fresh headline") |
| 419 | } |
| 420 | |
| 421 | @Test @MainActor func researchRanksFreshEvidenceAndLimitsRepeatAuthors() async throws { |
| 422 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 423 | defer { try? FileManager.default.removeItem(at: folder) } |
| 424 | let workspace = Workspace(directory: folder) |
| 425 | let now = Date.now |
| 426 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { instructions, context in |
| 427 | if instructions.contains("Choose three") { |
| 428 | return ["topics": [["topic": "Draft care", "query": "draft care"]]] |
| 429 | } |
| 430 | let candidates = try #require(context["candidates"] as? [[String: Any]]) |
| 431 | #expect(candidates.count == 4) |
| 432 | #expect((candidates.first?["text"] as? String)?.hasPrefix("Fresh") == true) |
| 433 | return ["items": candidates.map { |
| 434 | ["id": $0["id"] as? String ?? "", "relevance": 85, "headline": "Draft care", "angle": "Keep the source handy."] |
| 435 | }] |
| 436 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 437 | let discovery = ResearchDiscovery(studio: ContentStudio(workspace: workspace, model: model)) { _, _, topic in |
| 438 | func post(_ id: Int, text: String, age: TimeInterval, author: String, likes: String = "200") -> [String: Any] { |
| 439 | ["url": "https://x.com/i/web/status/\(id)", "title": text, "text": text, "postedAt": workspaceTimestamp(now.addingTimeInterval(-age)), |
| 440 | "author": author, "topic": topic, "likes": likes] |
| 441 | } |
| 442 | return [ |
| 443 | post(1, text: "Older results with enough detail to compare engagement.", age: 5 * 86_400, author: "example"), |
| 444 | post(2, text: "Fresh results with enough detail to compare engagement. https://example.test/first", age: 60, author: "example"), |
| 445 | post(3, text: "Fresh results with enough detail to compare engagement. https://example.test/copy", age: 120, author: "other"), |
| 446 | post(4, text: "Another useful account of the same writing project.", age: 3600, author: "@EXAMPLE"), |
| 447 | post(5, text: "A distinct author's example of careful writing and editing.", age: 7200, author: "different"), |
| 448 | post(6, text: "A third author with only a small amount of engagement.", age: 120, author: "third", likes: "2"), |
| 449 | post(7, text: "A previously useful example from outside the research window.", age: 8 * 86_400, author: "fourth") |
| 450 | ] |
| 451 | } |
| 452 | let feed = try await discovery.discover(.x, projectID: workspace.projectID, now: now) |
| 453 | let items = try #require(feed.fields["items"] as? [[String: Any]]) |
| 454 | #expect(items.compactMap { $0["id"] as? String } == [2, 4, 5].map { "https://x.com/i/web/status/\($0)" }) |
| 455 | } |
| 456 | |
| 457 | @Test @MainActor func instagramResearchRotatesFollowedHashtagsAcrossRefreshes() async throws { |
| 458 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 459 | defer { try? FileManager.default.removeItem(at: folder) } |
| 460 | let workspace = Workspace(directory: folder) |
| 461 | try workspace.set("personalProfile", to: ["hashtags": ["drafts", "writing", "editing", "publishing"]]) |
| 462 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 463 | ["topics": [["topic": "Draft care", "query": "draft care", "hashtag": "draftcare"]]] |
| 464 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 465 | var searched: [String] = [] |
| 466 | let discovery = ResearchDiscovery(studio: ContentStudio(workspace: workspace, model: model)) { _, query, _ in |
| 467 | searched.append(query) |
| 468 | return [] |
| 469 | } |
| 470 | let now = Date.now |
| 471 | _ = try await discovery.discover(.instagram, projectID: workspace.projectID, now: now) |
| 472 | #expect(searched == ["drafts", "writing", "editing"]) |
| 473 | searched.removeAll() |
| 474 | _ = try await discovery.discover(.instagram, projectID: workspace.projectID, now: now.addingTimeInterval(60)) |
| 475 | #expect(searched == ["publishing", "drafts", "writing"]) |
| 476 | } |
| 477 | |
| 478 | @Test @MainActor func researchOpensDraftsWithTheDestinationAndOriginalEvidence() throws { |
| 479 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 480 | defer { try? FileManager.default.removeItem(at: folder) } |
| 481 | let workspace = Workspace(directory: folder) |
| 482 | let evidence: [String: Any] = [ |
| 483 | "title": "A public example", "text": "Original evidence.", "author": "fixture", |
| 484 | "url": "https://twitter.com/fixture/status/123456?source=fixture", "likes": 10, "reposts": 3 |
| 485 | ] |
| 486 | let source = try workspace.saveResearchReference(evidence, projectID: workspace.projectID) |
| 487 | let instagram = try workspace.save(ResearchDraft.post(from: source, platform: "instagram", hook: "Open here.", angle: "Explore the result.")) |
| 488 | #expect(instagram["platform"] == "instagram") |
| 489 | #expect(instagram["format"] == "image") |
| 490 | #expect(instagram["brief"] == "Original hook: Open here.\nExplore the result.") |
| 491 | #expect(instagram.fields["sourceIds"] as? [String] == [source.id]) |
| 492 | #expect(source.fields["reposts"] as? Int == 3) |
| 493 | let reply = try workspace.save(ResearchDraft.reply(to: evidence, projectID: workspace.projectID)) |
| 494 | #expect(reply["platform"] == "x") |
| 495 | #expect(reply["format"] == "reply") |
| 496 | #expect(reply.fields["replyTo"] as? [String: String] == [ |
| 497 | "text": "Original evidence.", "author": "fixture", "url": "https://x.com/i/web/status/123456" |
| 498 | ]) |
| 499 | #expect(throws: WorkspaceError.self) { |
| 500 | _ = try ResearchDraft.reply(to: ["text": "A copied link.", "url": "https://example.test/status/123456"], projectID: workspace.projectID) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | @Test @MainActor func ideaRefillReplacesTheMissingKindAndRejectsUnsupportedNumbers() async throws { |
| 505 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 506 | defer { try? FileManager.default.removeItem(at: folder) } |
| 507 | let workspace = Workspace(directory: folder) |
| 508 | try workspace.set("ideaQueueTarget", to: 10) |
| 509 | for (index, kind) in (Array(repeating: "trend", count: 4) + Array(repeating: "work", count: 4) + ["data"]).enumerated() { |
| 510 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 511 | idea["topic"] = "Existing topic \(index)" |
| 512 | idea["text"] = "Existing concept \(index)" |
| 513 | idea["kind"] = kind |
| 514 | try workspace.save(idea) |
| 515 | } |
| 516 | var source = WorkspaceRecord.new("source", projectID: workspace.projectID) |
| 517 | source["title"] = "Project measurement" |
| 518 | source["text"] = "The measured export took 12 seconds." |
| 519 | try workspace.save(source) |
| 520 | func studio(number: String) -> ContentStudio { |
| 521 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, context in |
| 522 | let slots = try #require(context["slots"] as? [[String: Any]]) |
| 523 | #expect(slots.count == 1) |
| 524 | #expect(slots.first?["kind"] as? String == "data") |
| 525 | #expect(slots.first?["long"] as? Bool == false) |
| 526 | let materials = try #require(context["materials"] as? [[String: Any]]) |
| 527 | let material = try #require(materials.first { $0["title"] as? String == "Project measurement" }) |
| 528 | let id = try #require(material["id"] as? String) |
| 529 | return ["ideas": [["slot": 1, "kind": "data", "topic": "Measured export speed", |
| 530 | "text": "Explain why a \(number)-second export matters for this workflow.", "sourceId": id]]] |
| 531 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 532 | return ContentStudio(workspace: workspace, model: model) |
| 533 | } |
| 534 | let rejected = try await studio(number: "95").refresh(projectID: workspace.projectID) |
| 535 | #expect(rejected.written == 0) |
| 536 | #expect(!rejected.warnings.isEmpty) |
| 537 | let accepted = try await studio(number: "12").refresh(projectID: workspace.projectID) |
| 538 | #expect(accepted.written == 1) |
| 539 | #expect(accepted.full) |
| 540 | let saved = try #require(workspace.ideas.first { $0.title == "Measured export speed" }) |
| 541 | #expect((saved.fields["source"] as? [String: String])?["referenceId"] == source.id) |
| 542 | #expect(saved.fields["suggestedPlatforms"] == nil) |
| 543 | } |
| 544 | |
| 545 | @Test @MainActor func automaticIdeaChecksStopAtTheTargetWithoutLimitingManualIdeas() async throws { |
| 546 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 547 | defer { try? FileManager.default.removeItem(at: folder) } |
| 548 | let workspace = Workspace(directory: folder) |
| 549 | #expect(IdeaQueuePlan.target(nil) == 20) |
| 550 | #expect(IdeaQueuePlan.target(51) == 20) |
| 551 | try workspace.set("ideaQueueTarget", to: 50) |
| 552 | try workspace.set("ideaQueueAutomatic", to: true) |
| 553 | for index in 1...51 { |
| 554 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 555 | idea["topic"] = "Manual idea \(index)" |
| 556 | idea["text"] = "A distinct topic, number \(index)." |
| 557 | try workspace.save(idea) |
| 558 | } |
| 559 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 560 | throw WorkspaceError("A full queue should not call the model.") |
| 561 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 562 | let result = try await ResearchDiscovery(studio: ContentStudio(workspace: workspace, model: model)) |
| 563 | .refreshIdeas(projectID: workspace.projectID, withResearch: true, automatic: true) |
| 564 | #expect(result.full) |
| 565 | #expect(result.written == 0) |
| 566 | #expect(result.warnings.isEmpty) |
| 567 | #expect(result.open.count == 51) |
| 568 | } |
| 569 | |
| 570 | @Test @MainActor func agentCanWriteDraftTextWithoutAProviderAndRejectsAStaleRevision() async throws { |
| 571 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 572 | defer { try? FileManager.default.removeItem(at: folder) } |
| 573 | let workspace = Workspace(directory: folder) |
| 574 | try workspace.set("mcpEnabled", to: true) |
| 575 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 576 | draft["brief"] = "Draft a post about quiet writing tools." |
| 577 | draft["title"] = "Draft for AI agent" |
| 578 | draft = try workspace.save(draft) |
| 579 | let agent = AgentMCP(workspace: workspace) |
| 580 | let read = await tool(agent, "get_draft", ["draft_id": draft.id]) |
| 581 | #expect(read["brief"] as? String == draft["brief"]) |
| 582 | let written = await tool(agent, "edit_draft", [ |
| 583 | "draft_id": draft.id, "expected_updated_at": draft["updatedAt"], "content": "A draft for review." |
| 584 | ]) |
| 585 | #expect(written["content"] as? String == "A draft for review.") |
| 586 | let stale = await tool(agent, "edit_draft", [ |
| 587 | "draft_id": draft.id, "expected_updated_at": draft["updatedAt"], "content": "An outdated overwrite." |
| 588 | ]) |
| 589 | #expect(stale["isError"] as? Bool == true) |
| 590 | let current = try #require(workspace.drafts.first { $0.id == draft.id }) |
| 591 | #expect(current.body == "A draft for review.") |
| 592 | #expect(current.scheduleStatus.isEmpty) |
| 593 | } |
| 594 | |
| 595 | @Test @MainActor func disablingAutomaticIdeaRefillDuringGenerationDiscardsItsOutput() async throws { |
| 596 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 597 | defer { try? FileManager.default.removeItem(at: folder) } |
| 598 | let workspace = Workspace(directory: folder) |
| 599 | try workspace.set("ideaQueueAutomatic", to: true) |
| 600 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in |
| 601 | try workspace.set("ideaQueueAutomatic", to: false) |
| 602 | return ["ideas": [["slot": 2, "kind": "work", "topic": "Late suggestion", |
| 603 | "text": "A model result returned after refill was disabled.", "sourceId": "s1"]]] |
| 604 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 605 | let result = try await ContentStudio(workspace: workspace, model: model) |
| 606 | .refresh(projectID: workspace.projectID, automatic: true) |
| 607 | #expect(result.written == 0) |
| 608 | #expect(workspace.ideas.isEmpty) |
| 609 | } |
| 610 | |
| 611 | @MainActor |
| 612 | private func tool(_ agent: AgentMCP, _ name: String, _ arguments: [String: Any]) async -> [String: Any] { |
| 613 | let request: [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": ["name": name, "arguments": arguments]] |
| 614 | let response = await agent.handle(request)?["result"] as? [String: Any] ?? [:] |
| 615 | return response["structuredContent"] as? [String: Any] ?? response |
| 616 | } |
| 617 | |
| 618 | @Test @MainActor func recentResearchImportsCitedSourcesAndRejectsInvalidUpdates() async throws { |
| 619 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 620 | defer { try? FileManager.default.removeItem(at: folder) } |
| 621 | let workspace = Workspace(directory: folder) |
| 622 | try workspace.set("mcpEnabled", to: true) |
| 623 | let agent = AgentMCP(workspace: workspace) |
| 624 | let published = workspaceTimestamp(Date.now.addingTimeInterval(-14 * 86_400)) |
| 625 | let reddit = "https://www.reddit.com/r/swift/comments/abc123/" |
| 626 | let github = "https://github.com/apple/swift/issues/1" |
| 627 | let finding: [String: Any] = ["title": "A shared concern", "text": "Both sources discuss the migration cost.", "source_ids": ["r", "g", "copy"]] |
| 628 | let sources: [[String: Any]] = [ |
| 629 | ["id": "r", "url": reddit + "thread/?utm_source=test", "title": "Discussion", "platform": "Reddit", "published_at": published, "likes": 35], |
| 630 | ["id": "g", "url": github, "title": "Issue", "platform": "GitHub", "published_at": published], |
| 631 | ["id": "copy", "url": reddit, "title": "Duplicate", "platform": "Reddit", "published_at": published] |
| 632 | ] |
| 633 | var input: [String: Any] = ["topic": "Swift migration", "sources": sources, "findings": [finding], |
| 634 | "angles": [["source_id": "copy", "angle": "Explain how to estimate the migration effort."]]] |
| 635 | let saved = await tool(agent, "save_research_brief", input) |
| 636 | let id = try #require(saved["id"] as? String) |
| 637 | #expect(saved["platform"] as? String == "last30days") |
| 638 | let items = try #require(saved["items"] as? [[String: Any]]) |
| 639 | #expect(items.count == 2) |
| 640 | #expect(items.first?["id"] as? String == reddit) |
| 641 | #expect(items.first?["angle"] as? String == "Explain how to estimate the migration effort.") |
| 642 | #expect((items.first?["source"] as? [String: Any])?["likes"] as? Int == 35) |
| 643 | #expect((items.last?["source"] as? [String: Any])?["likes"] == nil) |
| 644 | #expect((saved["findings"] as? [[String: Any]])?.first?["sourceURLs"] as? [String] == [reddit, github]) |
| 645 | |
| 646 | input["topic"] = " SWIFT migration " |
| 647 | let repeated = await tool(agent, "save_research_brief", input) |
| 648 | #expect(repeated["id"] as? String == id) |
| 649 | var invalidFinding = finding |
| 650 | invalidFinding["source_ids"] = ["r", "unknown"] |
| 651 | input["findings"] = [invalidFinding] |
| 652 | #expect((await tool(agent, "save_research_brief", input))["isError"] as? Bool == true) |
| 653 | input["findings"] = [finding] |
| 654 | for age in [-86_400.0, 31 * 86_400.0] { |
| 655 | var invalid = sources |
| 656 | invalid[0]["published_at"] = workspaceTimestamp(Date.now.addingTimeInterval(-age)) |
| 657 | input["sources"] = invalid |
| 658 | #expect((await tool(agent, "save_research_brief", input))["isError"] as? Bool == true) |
| 659 | } |
| 660 | |
| 661 | let reopened = AgentMCP(workspace: Workspace(directory: folder)) |
| 662 | let readback = await tool(reopened, "list_research", ["platform": "last30days"]) |
| 663 | let briefs = try #require(readback["items"] as? [[String: Any]]) |
| 664 | #expect(briefs.count == 1) |
| 665 | #expect(briefs.first?["id"] as? String == id) |
| 666 | #expect((briefs.first?["findings"] as? [[String: Any]])?.first?["sourceURLs"] as? [String] == [reddit, github]) |
| 667 | } |
| 668 | |
| 669 | @Test @MainActor func writingDefaultsToAgentAndAPIWritingRequiresAnExplicitSelection() async throws { |
| 670 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 671 | defer { try? FileManager.default.removeItem(at: folder) } |
| 672 | let workspace = Workspace(directory: folder) |
| 673 | try workspace.set("provider", to: "anthropic") |
| 674 | try workspace.set("imageProvider", to: "gemini") |
| 675 | let studio = ContentStudio(workspace: workspace) |
| 676 | #expect(studio.model.provider == "agent") |
| 677 | #expect(studio.model.imageProvider == ProviderKey.gemini.name) |
| 678 | await #expect(throws: WorkspaceError.self) { |
| 679 | try await studio.model.object("Return an empty JSON object.", [:]) |
| 680 | } |
| 681 | |
| 682 | try workspace.set("mcpEnabled", to: true) |
| 683 | try workspace.set(StudioWritingConnection.preferenceKey, to: StudioWritingConnection.api.rawValue) |
| 684 | #expect(ContentStudio(workspace: workspace).model.provider == "anthropic") |
| 685 | } |
| 686 | |
| 687 | @Test @MainActor func mcpCredentialSetupRequiresPermissionAndUsesOnlyTheLocalEnvironment() async throws { |
| 688 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 689 | defer { try? FileManager.default.removeItem(at: folder) } |
| 690 | let workspace = Workspace(directory: folder) |
| 691 | try workspace.set("mcpEnabled", to: true) |
| 692 | let agent = AgentMCP(workspace: workspace, credentialEnvironment: [:]) |
| 693 | let provider = ["provider": "x"] |
| 694 | |
| 695 | let denied = await tool(agent, "set_provider_key", provider) |
| 696 | #expect(denied["isError"] as? Bool == true) |
| 697 | #expect(String(describing: denied["content"]).contains("Enable credential setup")) |
| 698 | |
| 699 | try workspace.set(AgentMCP.credentialPermission, to: true) |
| 700 | let missing = await tool(agent, "set_provider_key", ["provider": "x", "value": "fixture-value"]) |
| 701 | #expect(missing["isError"] as? Bool == true) |
| 702 | #expect(String(describing: missing["content"]).contains("INKSPRING_X_BEARER_TOKEN")) |
| 703 | #expect(!String(describing: missing).contains("fixture-value")) |
| 704 | |
| 705 | let r2 = await tool(agent, "set_r2_credentials", ["account_id": String(repeating: "a", count: 32), "bucket": "example"]) |
| 706 | #expect(r2["isError"] as? Bool == true) |
| 707 | #expect(String(describing: r2["content"]).contains("INKSPRING_R2_ACCESS_KEY_ID")) |
| 708 | |
| 709 | let chat = AgentMCP(workspace: workspace, chatProjectID: workspace.projectID, credentialEnvironment: [:]) |
| 710 | let blocked = await tool(chat, "set_provider_key", provider) |
| 711 | #expect(blocked["isError"] as? Bool == true) |
| 712 | #expect(String(describing: blocked["content"]).contains("Unknown tool")) |
| 713 | } |
| 714 | |
| 715 | @Test @MainActor func inAppChatToolsAreReadOnlyAndLimitedToTheOpenProject() async throws { |
| 716 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 717 | defer { try? FileManager.default.removeItem(at: folder) } |
| 718 | let workspace = Workspace(directory: folder) |
| 719 | try workspace.set("mcpEnabled", to: true) |
| 720 | let projectID = workspace.projectID |
| 721 | var other = WorkspaceRecord.new("project") |
| 722 | other["name"] = "Other project" |
| 723 | other = try workspace.save(other) |
| 724 | var first = WorkspaceRecord.new("draft", projectID: projectID) |
| 725 | first["title"] = "Open project draft" |
| 726 | first = try workspace.save(first) |
| 727 | var second = WorkspaceRecord.new("draft", projectID: other.id) |
| 728 | second["title"] = "Other project draft" |
| 729 | second = try workspace.save(second) |
| 730 | let agent = AgentMCP(workspace: workspace, chatProjectID: projectID) |
| 731 | let listed = await tool(agent, "list_drafts", ["project_id": other.id]) |
| 732 | let ids = (listed["items"] as? [[String: Any]])?.compactMap { $0["id"] as? String } ?? [] |
| 733 | #expect(ids.contains(first.id)) |
| 734 | #expect(!ids.contains(second.id)) |
| 735 | let otherRead = await tool(agent, "get_draft", ["draft_id": second.id]) |
| 736 | #expect(otherRead["isError"] as? Bool == true) |
| 737 | let edit = await tool(agent, "edit_draft", ["draft_id": first.id, "content": "Should be blocked."]) |
| 738 | #expect(edit["isError"] as? Bool == true) |
| 739 | } |
| 740 | |
| 741 | @Test @MainActor func contentIDsAreSharedByPostsAndNewslettersAndResolveInMCP() async throws { |
| 742 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 743 | defer { try? FileManager.default.removeItem(at: folder) } |
| 744 | let workspace = Workspace(directory: folder) |
| 745 | try workspace.set("mcpEnabled", to: true) |
| 746 | var project = WorkspaceRecord.new("project") |
| 747 | project["name"] = "Protomota" |
| 748 | project = try workspace.save(project) |
| 749 | var other = WorkspaceRecord.new("project") |
| 750 | other["name"] = "Production" |
| 751 | other = try workspace.save(other) |
| 752 | #expect(project["projectKey"] == "PRO") |
| 753 | #expect(other["projectKey"] != project["projectKey"]) |
| 754 | |
| 755 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 756 | draft["title"] = "First post" |
| 757 | draft["content"] = "Post content" |
| 758 | draft = try workspace.save(draft) |
| 759 | var newsletter = WorkspaceRecord.new("newsletter", projectID: project.id) |
| 760 | newsletter["title"] = "First newsletter" |
| 761 | newsletter["body"] = "Newsletter content" |
| 762 | newsletter = try workspace.save(newsletter) |
| 763 | #expect(draft.referenceID == "PRO-001") |
| 764 | #expect(newsletter.referenceID == "PRO-002") |
| 765 | |
| 766 | project["name"] = "Studio" |
| 767 | _ = try workspace.save(project) |
| 768 | let external = AgentMCP(workspace: workspace) |
| 769 | let readPost = await tool(external, "get_content", ["id": " pro-001 "]) |
| 770 | #expect(readPost["kind"] as? String == "post") |
| 771 | #expect((readPost["item"] as? [String: Any])?["id"] as? String == draft.id) |
| 772 | let readNewsletter = await tool(external, "get_newsletter", ["newsletter_id": "PRO-002"]) |
| 773 | #expect(readNewsletter["id"] as? String == newsletter.id) |
| 774 | #expect(readNewsletter["body"] as? String == "Newsletter content") |
| 775 | let chat = AgentMCP(workspace: workspace, chatProjectID: other.id) |
| 776 | let scoped = await tool(chat, "get_content", ["id": "PRO-001"]) |
| 777 | #expect(scoped["isError"] as? Bool == true) |
| 778 | |
| 779 | let snapshot = workspace.makeCompanionLibrary(workspaceID: UUID()) |
| 780 | #expect(snapshot.items.first { $0.id == draft.id }?.referenceID == draft.referenceID) |
| 781 | #expect(snapshot.newsletters?.first { $0.id == newsletter.id }?.referenceID == newsletter.referenceID) |
| 782 | |
| 783 | let secondConnection = try WorkspaceDatabase(url: folder.appending(path: "workspace.sqlite")) |
| 784 | try secondConnection.remove(draft.id, kind: draft.kind) |
| 785 | var replacement = WorkspaceRecord.new("draft", projectID: project.id) |
| 786 | replacement["title"] = "Another post" |
| 787 | replacement = try workspace.save(replacement) |
| 788 | #expect(replacement.referenceID == "PRO-003") |
| 789 | let removed = await tool(external, "get_content", ["id": "PRO-001"]) |
| 790 | #expect(removed["isError"] as? Bool == true) |
| 791 | } |
| 792 | |
| 793 | @Test @MainActor func repliesPageWithoutDroppingCursorAndReuseDraft() async throws { |
| 794 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 795 | defer { try? FileManager.default.removeItem(at: folder) } |
| 796 | let workspace = Workspace(directory: folder) |
| 797 | let account = ManagedSocialAccount( |
| 798 | session: ManagedSocialSession(accessToken: "fixture", refreshToken: nil, managedTicket: nil, |
| 799 | expiresAt: 2_000_000_000_000, scopes: "tweet.read"), |
| 800 | id: "100", name: "Fixture", username: "fixture", connectedAt: "fixture" |
| 801 | ) |
| 802 | let transport = SocialTransport { request in |
| 803 | let url = try #require(request.url) |
| 804 | let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] |
| 805 | let older = query.contains { $0.name == "pagination_token" && $0.value == "old" } |
| 806 | if older { #expect(!query.contains { $0.name == "since_id" }) } |
| 807 | let rows = [["id": older ? "101" : "103", "author_id": "200", "text": "Reply to the fixture."]] |
| 808 | let meta: [String: Any] = older ? ["result_count": 1] : ["result_count": 1, "newest_id": "103", "next_token": "old"] |
| 809 | let fields: [String: Any] = ["data": rows, "meta": meta] |
| 810 | let data = try JSONSerialization.data(withJSONObject: fields) |
| 811 | let response = try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)) |
| 812 | return (data, response) |
| 813 | } |
| 814 | let inbox = ReplyInbox(workspace: workspace, transport: transport, accountOverride: account) |
| 815 | #expect(try await inbox.refresh() == 1) |
| 816 | #expect(inbox.hasOlder) |
| 817 | let reply = try #require(inbox.rows.first) |
| 818 | let draft = try workspace.makeReplyDraft(reply.id, projectID: workspace.projectID) |
| 819 | #expect(try workspace.makeReplyDraft(reply.id, projectID: workspace.projectID).id == draft.id) |
| 820 | #expect(try await inbox.refresh(older: true) == 1) |
| 821 | #expect(!inbox.hasOlder) |
| 822 | #expect(inbox.rows.count == 2) |
| 823 | #expect(inbox.rows.first { $0.id == reply.id }?["status"] == "drafted") |
| 824 | try inbox.setMonitoring(true) |
| 825 | #expect(inbox.monitoring) |
| 826 | var newAccount = account |
| 827 | newAccount.connectedAt = "different session" |
| 828 | #expect(!ReplyInbox(workspace: workspace, accountOverride: newAccount).monitoring) |
| 829 | } |
| 830 | |
| 831 | @Test @MainActor func analyticsKeepsDailyBaselineAndUpdatesCurrentMetrics() async throws { |
| 832 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 833 | defer { try? FileManager.default.removeItem(at: folder) } |
| 834 | let workspace = Workspace(directory: folder) |
| 835 | let account = ManagedSocialAccount( |
| 836 | session: ManagedSocialSession(accessToken: "fixture", refreshToken: nil, managedTicket: nil, |
| 837 | expiresAt: 2_000_000_000_000, scopes: "users.read tweet.read"), |
| 838 | id: "100", name: "Fixture", username: "fixture" |
| 839 | ) |
| 840 | var count = 0 |
| 841 | let transport = SocialTransport { request in |
| 842 | let url = try #require(request.url) |
| 843 | let fields: [String: Any] |
| 844 | if url.path.hasSuffix("/tweets") { |
| 845 | let post: [String: Any] = ["id": "20", "text": "Sample post", "created_at": "2027-01-01T09:00:00Z", |
| 846 | "public_metrics": ["like_count": 5]] |
| 847 | fields = ["data": [post], "meta": ["next_token": "older"]] |
| 848 | } else { |
| 849 | count += 1 |
| 850 | let profile: [String: Any] = ["id": "100", "public_metrics": ["followers_count": 50 + count]] |
| 851 | fields = ["data": profile] |
| 852 | } |
| 853 | let response = try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)) |
| 854 | return (try JSONSerialization.data(withJSONObject: fields), response) |
| 855 | } |
| 856 | let analytics = AccountAnalytics(workspace: workspace, transport: transport, accountOverride: account) |
| 857 | let now = try #require(scheduleDate("2027-01-01T10:00:00Z")) |
| 858 | #expect(try await analytics.refresh(.x, now: now).isEmpty) |
| 859 | #expect(try await analytics.refresh(.x, now: now.addingTimeInterval(120)).isEmpty) |
| 860 | let rows = workspace.records.filter { $0.kind == "analytics-day" } |
| 861 | #expect(rows.count == 1) |
| 862 | #expect((rows.first?.fields["first"] as? [String: Any])?["followers"] as? Int == 51) |
| 863 | #expect((rows.first?.fields["last"] as? [String: Any])?["followers"] as? Int == 52) |
| 864 | #expect(workspace.records.filter { $0.kind == "analytics-post" }.count == 1) |
| 865 | #expect(analytics.state(.x, account: account)?["cursor"] == "older") |
| 866 | } |
| 867 | |
| 868 | @Test @MainActor func restoringEarlierWordingReturnsQueuedPostToReview() throws { |
| 869 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 870 | defer { try? FileManager.default.removeItem(at: folder) } |
| 871 | let workspace = Workspace(directory: folder) |
| 872 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 873 | draft["title"] = "Local draft" |
| 874 | draft["content"] = "Revised wording" |
| 875 | draft["previousContent"] = "Earlier wording" |
| 876 | draft.fields["schedule"] = ["status": "queued", "slotAt": "2027-01-01T12:00:00Z"] |
| 877 | draft = try workspace.save(draft) |
| 878 | let studio = ContentStudio(workspace: workspace) |
| 879 | let restored = try studio.undoRewrite(draft) |
| 880 | #expect(restored.body == "Earlier wording") |
| 881 | #expect(restored["previousContent"] == "Revised wording") |
| 882 | #expect(restored.scheduleStatus == "ready") |
| 883 | #expect(restored.schedule["slotAt"] as? String == "") |
| 884 | #expect(throws: WorkspaceError.self) { _ = try studio.undoRewrite(draft) } |
| 885 | let reverted = try studio.undoRewrite(restored) |
| 886 | #expect(reverted.body == "Revised wording") |
| 887 | } |
| 888 | |
| 889 | @Test @MainActor func reopeningAnIdeaKeepsDraftsAndPublishingHistory() async throws { |
| 890 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 891 | defer { try? FileManager.default.removeItem(at: folder) } |
| 892 | let workspace = Workspace(directory: folder) |
| 893 | var idea = WorkspaceRecord.new("idea", projectID: workspace.projectID) |
| 894 | idea["topic"] = "Project update" |
| 895 | idea["text"] = "An update on the project." |
| 896 | idea["status"] = "picked" |
| 897 | var discarded = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 898 | discarded["title"] = "Unpublished draft" |
| 899 | discarded["ideaId"] = idea.id |
| 900 | discarded = try workspace.save(discarded) |
| 901 | var kept = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 902 | kept["title"] = "Previously attempted draft" |
| 903 | kept["platform"] = "linkedin" |
| 904 | kept["ideaId"] = idea.id |
| 905 | kept.fields["schedule"] = ["status": "failed"] |
| 906 | kept = try workspace.save(kept) |
| 907 | var receipt = WorkspaceRecord.new("publication", projectID: workspace.projectID) |
| 908 | receipt["title"] = kept.title |
| 909 | receipt["draftId"] = kept.id |
| 910 | receipt["status"] = "uncertain" |
| 911 | try workspace.save(receipt) |
| 912 | idea.fields["versions"] = ["x": discarded.id, "linkedin": kept.id] |
| 913 | idea = try workspace.save(idea) |
| 914 | |
| 915 | let preview = try workspace.reviewIdeaReturn(for: discarded) |
| 916 | idea["text"] = "Changed after review." |
| 917 | idea = try workspace.save(idea) |
| 918 | #expect(throws: WorkspaceError.self) { try workspace.returnToIdeas(preview) } |
| 919 | #expect(workspace.ideas.first?["status"] == "picked") |
| 920 | #expect(workspace.drafts.filter { $0["ideaId"] == idea.id }.count == 2) |
| 921 | try workspace.returnToIdeas(workspace.reviewIdeaReturn(for: discarded)) |
| 922 | let reopened = try #require(workspace.ideas.first { $0.id == idea.id }) |
| 923 | #expect(reopened["status"] == "draft") |
| 924 | #expect(Set(workspace.drafts.filter { $0["ideaId"] == idea.id }.map(\.id)) == [kept.id, discarded.id]) |
| 925 | #expect(workspace.records.contains { $0.id == receipt.id }) |
| 926 | |
| 927 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, |
| 928 | object: { _, _ in ["text": "The new platform version."] }, |
| 929 | prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 930 | let studio = ContentStudio(workspace: workspace, model: model) |
| 931 | await #expect(throws: WorkspaceError.self) { _ = try await studio.pick(reopened, platforms: ["linkedin"]) } |
| 932 | let (picked, versions) = try await studio.pick(reopened, platforms: ["instagram"]) |
| 933 | let replacement = try #require(versions.first) |
| 934 | #expect(picked["status"] == "draft") |
| 935 | #expect(picked.draftVersions == ["linkedin": kept.id, "x": discarded.id, "instagram": replacement.id]) |
| 936 | } |
| 937 | |
| 938 | @Test @MainActor func anXQuoteUsesItsCitedResearchAndLeavesThePostingQueue() async throws { |
| 939 | let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) |
| 940 | defer { try? FileManager.default.removeItem(at: folder) } |
| 941 | let workspace = Workspace(directory: folder) |
| 942 | let address = "https://twitter.com/example/status/123456?source=fixture" |
| 943 | let body = "A + B & C #writing" |
| 944 | var feed = WorkspaceRecord.new("discovery", projectID: workspace.projectID) |
| 945 | feed["title"] = "Fixture research" |
| 946 | feed["platform"] = "x" |
| 947 | feed["searchedAt"] = WorkspaceRecord.timestamp |
| 948 | feed.fields["items"] = [["id": address, "headline": "Example post", |
| 949 | "source": ["url": address, "author": "example", "text": "Cited evidence"]]] |
| 950 | try workspace.save(feed) |
| 951 | let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, |
| 952 | object: { instructions, context in |
| 953 | if instructions.contains("Generate up to") { |
| 954 | return ["ideas": [["slot": 1, "kind": "trend", "topic": "Quote angle", "text": "Explain the cited example.", |
| 955 | "sourceId": "r1", "mediaPlan": "A diagram"]]] |
| 956 | } |
| 957 | let evidence = try #require(context["evidence"] as? [[String: Any]]) |
| 958 | #expect(evidence.first?["text"] as? String == "Cited evidence") |
| 959 | return ["text": body] |
| 960 | }, prompt: { _ in "" }, image: { _ in (Data(), "") }, imageProvider: "Fixture") |
| 961 | let studio = ContentStudio(workspace: workspace, model: model) |
| 962 | _ = try await studio.refresh(projectID: workspace.projectID) |
| 963 | let idea = try #require(workspace.ideas.first) |
| 964 | #expect(XQuoteComposer.source(in: idea)?.absoluteString == "https://x.com/i/web/status/123456") |
| 965 | #expect(XQuoteComposer.postURL("https://x.com.evil.test/example/status/123456") == nil) |
| 966 | #expect(XQuoteComposer.postURL("https://name@x.com/example/status/123456") == nil) |
| 967 | let (_, drafts) = try await studio.pick(idea, platforms: ["x"]) |
| 968 | let draft = try #require(drafts.first) |
| 969 | #expect(draft["mediaPlan"] == "A diagram") |
| 970 | let scheduled = try workspace.scheduleDraft(draft, at: .now.addingTimeInterval(3600)) |
| 971 | #expect(scheduled.scheduleStatus == "queued") |
| 972 | let url = try workspace.prepareManualQuote(scheduled) |
| 973 | let query = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems) |
| 974 | #expect(query.first { $0.name == "text" }?.value == body) |
| 975 | #expect(query.first { $0.name == "url" }?.value == "https://x.com/i/web/status/123456") |
| 976 | #expect(url.absoluteString.contains("%2B")) |
| 977 | let manual = try #require(workspace.drafts.first { $0.id == scheduled.id }) |
| 978 | #expect(manual.scheduleStatus == "manual") |
| 979 | #expect(manual.schedule["slotAt"] as? String == "") |
| 980 | #expect(throws: WorkspaceError.self) { try workspace.scheduleDraft(manual, at: .now.addingTimeInterval(7200)) } |
| 981 | } |
| 982 | |
| 983 | @Test @MainActor func savedAndQueuedAnthropicFableSelectionsUse52() { |
| 984 | let saved: [String: Any] = ["provider": "anthropic", "anthropicModel": "claude-fable-5-1"] |
| 985 | #expect(WritingProviders(settings: saved).writingModel == "claude-fable-5-2") |
| 986 | #expect(WritingProviders(settings: saved, modelOverride: "claude-fable-5-1").writingModel == "claude-fable-5-2") |
| 987 | #expect(WritingProviders(settings: saved, modelOverride: "claude-sonnet-5-5").writingModel == "claude-sonnet-5-5") |
| 988 | } |
| 989 | |
| 990 | @Test @MainActor func geminiFourUsesAStatelessInteractionAndTheCompletedModelOutput() throws { |
| 991 | let request = WritingProviders.geminiInteraction(model: "gemini-4-neon", instructions: "Write JSON", input: "Brief") |
| 992 | #expect(request["store"] as? Bool == false) |
| 993 | #expect(request["model"] as? String == "gemini-4-neon") |
| 994 | #expect((request["response_format"] as? [String: String])?["mime_type"] == "application/json") |
| 995 | let steps = [ |
| 996 | ["type": "user_input", "content": [["type": "text", "text": "untrusted"]]], |
| 997 | ["type": "thought", "content": [["type": "text", "text": "reasoning"]]], |
| 998 | ["type": "model_output", "content": [["type": "text", "text": "{\"ok\":"], ["type": "text", "text": "true}"]]] |
| 999 | ] |
| 1000 | #expect(try WritingProviders.geminiInteractionText(["status": "completed", "steps": steps]) == "{\"ok\":true}") |
| 1001 | #expect(throws: WorkspaceError.self) { try WritingProviders.geminiInteractionText(["status": "incomplete", "steps": steps]) } |
| 1002 | } |