Branchwell

Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / IdeaSaveMCPTests.swift

Raw 8.2 KB on 8f75dd7d901e2186ca9d9e1cf2f061105c02ae42
1import Foundation
2import ImageIO
3import InkspringSchedule
4import Testing
5@testable import Inkspring
6
7@MainActor
8private func ideaTool(_ agent: AgentMCP, _ name: String, _ arguments: [String: Any]) async -> [String: Any] {
9 let request: [String: Any] = ["jsonrpc": "2.0", "id": 1, "method": "tools/call",
10 "params": ["name": name, "arguments": arguments]]
11 let result = await agent.handle(request)?["result"] as? [String: Any] ?? [:]
12 return result["structuredContent"] as? [String: Any] ?? result
13}
14
15@Test @MainActor func suppliedIdeaSavesOnceAndReadsBackInFull() async throws {
16 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
17 defer { try? FileManager.default.removeItem(at: folder) }
18 let workspace = Workspace(directory: folder)
19 let projectID = workspace.projectID
20 let body = String(repeating: "Keep the exact paragraph.\n\n", count: 35) + "https://example.com/source\n"
21 let args: [String: Any] = ["project_id": projectID, "title": "An exact idea", "text": body,
22 "request_key": "test-exact-idea"]
23 let agent = AgentMCP(workspace: workspace, credentialEnvironment: [:])
24 #expect(await ideaTool(agent, "save_idea", args)["isError"] as? Bool == true)
25 try workspace.set("mcpEnabled", to: true)
26 try workspace.set("writingConnection", to: "api")
27
28 let saved = await ideaTool(agent, "save_idea", args)
29 let id = try #require(saved["id"] as? String)
30 #expect(saved["status"] as? String == "draft")
31 #expect(saved["projectId"] as? String == projectID)
32 #expect(saved["topic"] as? String == "An exact idea")
33 #expect(saved["text"] as? String == body)
34 for key in ["platform", "format", "suggestedPlatforms", "platforms", "kind"] {
35 #expect(saved[key] == nil)
36 }
37
38 let reopened = Workspace(directory: folder)
39 let freshAgent = AgentMCP(workspace: reopened, credentialEnvironment: [:])
40 let retry = await ideaTool(freshAgent, "save_idea", args)
41 #expect(retry["id"] as? String == id)
42 #expect(retry["updatedAt"] as? String == saved["updatedAt"] as? String)
43 #expect(reopened.ideas.filter { $0.id == id && $0.isPendingPostIdea }.count == 1)
44 let list = await ideaTool(freshAgent, "list_ideas", ["project_id": projectID, "status": "draft"])
45 #expect((list["items"] as? [[String: Any]])?.contains { $0["id"] as? String == id } == true)
46 let readback = await ideaTool(freshAgent, "get_idea", ["idea_id": id])
47 #expect(readback["text"] as? String == body)
48 #expect(readback["suggestedPlatforms"] == nil)
49
50 var changed = args
51 changed["text"] = "Different copy for the same key."
52 #expect(await ideaTool(freshAgent, "save_idea", changed)["isError"] as? Bool == true)
53 let chat = AgentMCP(workspace: reopened, chatProjectID: projectID)
54 #expect(await ideaTool(chat, "save_idea", args)["isError"] as? Bool == true)
55 #expect(await ideaTool(chat, "get_idea", ["idea_id": id])["text"] as? String == body)
56 let otherChat = AgentMCP(workspace: reopened, chatProjectID: "other-project")
57 #expect(await ideaTool(otherChat, "get_idea", ["idea_id": id])["isError"] as? Bool == true)
58
59 let listing = try #require(AgentMCP.tools.first { $0.name == "save_idea" })
60 #expect(listing.writes)
61 #expect(!listing.usesNetwork)
62}
63
64@Test @MainActor func suppliedIdeaRejectsInvalidInputWithoutCreatingRecords() async throws {
65 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
66 defer { try? FileManager.default.removeItem(at: folder) }
67 let workspace = Workspace(directory: folder)
68 try workspace.set("mcpEnabled", to: true)
69 let agent = AgentMCP(workspace: workspace)
70 let recordCount = workspace.records.count
71 let invalid: [[String: Any]] = [
72 ["title": " ", "text": "Text"],
73 ["title": "Title", "text": "\n"],
74 ["title": "Title", "text": "Bad\0text"],
75 ["title": String(repeating: "x", count: 141), "text": "Text"],
76 ["title": "Title", "text": String(repeating: "x", count: 2_001)],
77 ["title": "Title", "text": "Text", "request_key": ""],
78 ["title": "Title", "text": "Text", "project_id": "missing-project"]
79 ]
80 for input in invalid {
81 let args = ["project_id": workspace.projectID as Any].merging(input) { _, supplied in supplied }
82 #expect(await ideaTool(agent, "save_idea", args)["isError"] as? Bool == true)
83 }
84 #expect(workspace.records.count == recordCount)
85}
86
87@Test @MainActor func ideaArtworkCarriesIntoDraftsAndMobilePreview() async throws {
88 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
89 defer { try? FileManager.default.removeItem(at: folder) }
90 let workspace = Workspace(directory: folder)
91 try workspace.set("mcpEnabled", to: true)
92 let bytes = try #require(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGNgAAAAAgABSK+kcQAAAABJRU5ErkJggg=="))
93 let source = folder.appending(path: "artwork.png")
94 try bytes.write(to: source)
95 var imageCalls = 0
96 let model = ContentStudio.Model(provider: "fixture", name: "fixture", draft: { _, _ in [:] }, object: { _, _ in
97 ["text": "The artwork travels with the draft."]
98 }, prompt: { _ in "Fixture image" }, image: { _ in imageCalls += 1; return (bytes, "png") }, imageProvider: "Fixture")
99 let agent = AgentMCP(workspace: workspace, model: model)
100 let saved = await ideaTool(agent, "save_idea", ["title": "Artwork test", "text": "An idea with its own image."])
101 let id = try #require(saved["id"] as? String)
102 let originalRevision = try #require(saved["updatedAt"] as? String)
103 let generated = await ideaTool(agent, "make_image", ["idea_id": id, "prompt": "A test image", "expected_updated_at": originalRevision])
104 #expect((generated["image"] as? [String: String])?["origin"] == "Fixture")
105 #expect(generated["platform"] == nil && generated["format"] == nil)
106 let stale = await ideaTool(agent, "attach_image", ["idea_id": id, "file_path": source.path, "expected_updated_at": originalRevision])
107 #expect(stale["isError"] as? Bool == true)
108
109 let idea = try #require(workspace.ideas.first { $0.id == id })
110 var request = CompanionLibrary.Change(action: .note, itemID: id, revision: idea["updatedAt"])
111 request.ideaImagePrompt = "A second test image"
112 #expect(await workspace.generateMobileIdeaImage(request, model: model).error == nil)
113 #expect(await workspace.generateMobileIdeaImage(request, model: model).error == nil)
114 #expect(imageCalls == 2)
115 let attached = await ideaTool(agent, "attach_image", ["idea_id": id, "file_path": source.path])
116 let readback = await ideaTool(agent, "get_idea", ["idea_id": id])
117 #expect((attached["image"] as? [String: String])?["origin"] == "Attached")
118 #expect(readback["text"] as? String == "An idea with its own image.")
119
120 let latest = try #require(workspace.ideas.first { $0.id == id })
121 let studio = ContentStudio(workspace: workspace, model: model)
122 let (_, drafts) = try await studio.pick(latest, platforms: ["x", "linkedin", "reddit", "instagram", "tiktok"])
123 let expectedHeights = ["x": 900, "linkedin": 1080, "reddit": 1080, "instagram": 1350, "tiktok": 1920]
124 #expect(drafts.count == expectedHeights.count)
125 for draft in drafts {
126 let file = try #require(workspace.imageURL(draft))
127 let image = try #require(CGImageSourceCreateWithURL(file as CFURL, nil))
128 let properties = try #require(CGImageSourceCopyPropertiesAtIndex(image, 0, nil) as? [String: Any])
129 #expect(properties[kCGImagePropertyPixelHeight as String] as? Int == expectedHeights[draft["platform"]])
130 }
131 var snapshot = workspace.makeCompanionLibrary(workspaceID: UUID())
132 let separated = try snapshot.separateFullText()
133 let body = try #require(separated)
134 #expect(snapshot.items.allSatisfy { $0.imagePreview == nil })
135 try snapshot.applyFullText(body)
136 #expect(snapshot.items.first { $0.id == id }?.imagePreview != nil)
137 #expect(snapshot.items.filter { $0.kind == .draft && $0.imagePreview != nil }.count == drafts.count)
138
139 let backup = folder.appending(path: "backup.zip")
140 try workspace.exportBackup(to: backup)
141 let staged = try WorkspaceBackup.stage(backup, in: folder)
142 #expect(staged.backup.media.count >= drafts.count + 1)
143}