Branchwell

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

1import Foundation
2import Testing
3@testable import Inkspring
4
5@Test func writingAgentArgumentsForwardTheExactModel() throws {
6 for (agent, model) in [(StudioChatAgent.codex, "gpt-6.2-astra"), (.claude, "claude-fable-5-2")] {
7 let output = URL(fileURLWithPath: "/tmp/answer")
8 var baseline = try agent.arguments(server: "/tmp/inkspring", parameters: ["--mcp-write", "/tmp/input"],
9 output: output, workspaceOverride: nil)
10 var explicit = try agent.arguments(server: "/tmp/inkspring", parameters: ["--mcp-write", "/tmp/input"],
11 output: output, workspaceOverride: nil, model: model)
12 let modelFlag = try #require(explicit.firstIndex(of: "--model"))
13 #expect(explicit[modelFlag + 1] == model)
14 explicit.removeSubrange(modelFlag...modelFlag + 1)
15 if agent == .claude {
16 let index = try #require(baseline.firstIndex(of: "--mcp-config")) + 1
17 try #require(explicit.indices.contains(index))
18 let expected = try JSONSerialization.jsonObject(with: Data(baseline.remove(at: index).utf8)) as? NSDictionary
19 let actual = try JSONSerialization.jsonObject(with: Data(explicit.remove(at: index).utf8)) as? NSDictionary
20 #expect(try #require(actual) == #require(expected))
21 }
22 #expect(explicit == baseline)
23 }
24}
25
26@Test @MainActor func quickPromptsSendImmediatelyAndKeepUnsentText() async throws {
27 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
28 defer { try? FileManager.default.removeItem(at: folder) }
29 let workspace = Workspace(directory: folder)
30 let database = try #require(workspace.database)
31 let project = WorkspaceRecord.new("project")
32 let chat = StudioAgentChat { agent, projectID, prompt in
33 #expect(agent == .claude)
34 #expect(projectID == project.id)
35 #expect(prompt.contains("Which drafts are closest to ready?"))
36 #expect(!prompt.contains("Unsent text"))
37 return "One draft is ready for review."
38 }
39 chat.load(projectID: project.id, database: database)
40 chat.message = "Unsent text"
41 chat.send("Which drafts are closest to ready?", to: .claude, project: project)
42 #expect(chat.entries.map(\.text) == ["Which drafts are closest to ready?"])
43 #expect(chat.message == "Unsent text")
44 chat.send("Ignored while a response is pending", to: .claude, project: project)
45 await chat.task?.value
46 #expect(chat.entries.last?.text == "One draft is ready for review.")
47 #expect(chat.recentPrompts == ["Which drafts are closest to ready?"])
48}
49
50@Test @MainActor func recentPromptsPersistPerProjectAndPutRepeatedPromptsFirst() async throws {
51 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
52 defer { try? FileManager.default.removeItem(at: folder) }
53 let workspace = Workspace(directory: folder)
54 let database = try #require(workspace.database)
55 let project = WorkspaceRecord.new("project")
56 let chat = StudioAgentChat { _, _, _ in "Reply" }
57 chat.load(projectID: project.id, database: database)
58 for number in 1...6 {
59 chat.message = " Question \(number) "
60 chat.send(to: .codex, project: project)
61 await chat.task?.value
62 }
63 #expect(chat.message.isEmpty)
64 chat.open(nil)
65 let reopened = StudioAgentChat { _, _, _ in "Reply" }
66 let reopenedDatabase = try WorkspaceDatabase(url: folder.appending(path: "workspace.sqlite"))
67 reopened.load(projectID: project.id, database: reopenedDatabase)
68 #expect(reopened.recentPrompts == [
69 "Question 6", "Question 5", "Question 4", "Question 3", "Question 2"
70 ])
71 reopened.send("Question 3", to: .codex, project: project)
72 await reopened.task?.value
73 #expect(reopened.recentPrompts == [
74 "Question 3", "Question 6", "Question 5", "Question 4", "Question 2"
75 ])
76}
77
78@Test @MainActor func chatHistoryOpensAndDeletesIndividualChatsOrAllProjects() async throws {
79 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
80 defer { try? FileManager.default.removeItem(at: folder) }
81 let workspace = Workspace(directory: folder)
82 let database = try #require(workspace.database)
83 let project = WorkspaceRecord.new("project")
84 let otherProject = WorkspaceRecord.new("project")
85 let chat = StudioAgentChat { _, _, _ in "Reply" }
86 chat.load(projectID: project.id, database: database)
87 chat.send("First chat", to: .claude, project: project)
88 await chat.task?.value
89 let firstID = try #require(chat.currentID)
90 chat.open(nil)
91 #expect(chat.entries.isEmpty)
92 chat.send("Second chat", to: .codex, project: project)
93 await chat.task?.value
94 #expect(chat.history.count == 2)
95 chat.open(firstID)
96 #expect(chat.entries.map(\.text) == ["First chat", "Reply"])
97 #expect(chat.entries.last?.agent == .claude)
98 chat.delete(firstID)
99 #expect(chat.entries.isEmpty)
100 #expect(chat.recentPrompts == ["Second chat"])
101
102 let otherChat = StudioAgentChat { _, _, _ in "Reply" }
103 otherChat.load(projectID: otherProject.id, database: database)
104 #expect(otherChat.history.isEmpty)
105 #expect(otherChat.hasSavedChats)
106 otherChat.send("Other project chat", to: .codex, project: otherProject)
107 await otherChat.task?.value
108 chat.delete()
109 otherChat.load(projectID: otherProject.id, database: database)
110 #expect(otherChat.history.isEmpty)
111 #expect(!otherChat.hasSavedChats)
112 #expect(otherChat.recentPrompts.isEmpty)
113}
114
115@Test func geminiWritingSelectionKeepsChatIndependentAndUsesSupportedCLIModelIDs() throws {
116 let agent = StudioChatAgent.gemini
117 #expect(StudioChatAgent.writingAgent(settings: [:]) == .selected)
118 let settings = [StudioChatAgent.writingPreference: agent.rawValue, agent.modelPreferenceKey: "gemini-4-carbon-high"]
119 #expect(StudioChatAgent.writingAgent(settings: settings) == .gemini)
120 #expect(agent.preferredWritingModel(settings: settings) == "gemini-4-carbon-high")
121 #expect(agent.preferredWritingModel(settings: [agent.modelPreferenceKey: "retired"]) == GeminiWritingAgent.defaultModel)
122 for model in agent.writingModels {
123 let args = try GeminiWritingAgent.arguments(model: model.id)
124 let index = try #require(args.firstIndex(of: "--model"))
125 #expect(args[index + 1] == model.id)
126 #expect(args.contains("--sandbox"))
127 #expect(!args.contains("--dangerously-skip-permissions"))
128 }
129 #expect(throws: WorkspaceError.self) { try GeminiWritingAgent.arguments(model: "unsupported") }
130}
131
132@Test func geminiWritesWithAnIsolatedToolFreeProfileAndOnlyReadsTheFinalReply() throws {
133 let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
134 defer { try? FileManager.default.removeItem(at: folder) }
135 let context = Data(#"{"instructions":"Return JSON","writingContext":{"brief":"line one\nline two"}}"#.utf8)
136 let input = try GeminiWritingAgent.input(context: context, workingDirectory: folder)
137 let event = try #require(JSONSerialization.jsonObject(with: input) as? [String: Any])
138 #expect(event["event"] as? String == "user")
139 #expect((event["message"] as? [String: String])?["content"] == String(decoding: context, as: UTF8.self))
140 #expect(input.filter { $0 == 0x0a }.count == 1)
141 let profile = try String(contentsOf: folder.appending(path: ".agents/agents/inkspring-writer.md"), encoding: .utf8)
142 #expect(profile.contains("tools: []"))
143 #expect(profile.contains("mcpServers: []"))
144 #expect(profile.contains("subagent: false"))
145 #expect(!profile.contains("line one"))
146 let response = """
147 {"event":"step_update","step_update":{"text_delta":"unfinished"}}
148 {"event":"result","result":{"status":"SUCCESS","response":"OK"}}
149 """
150 #expect(try GeminiWritingAgent.response(from: Data(response.utf8)) == "OK")
151 #expect(throws: WorkspaceError.self) { try GeminiWritingAgent.response(from: Data(response.replacing("SUCCESS", with: "ERROR").utf8)) }
152 #expect(throws: WorkspaceError.self) { try GeminiWritingAgent.response(from: Data(response.prefix(30).utf8)) }
153}