Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / AgentSettings.swift

Raw 7.0 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import AppKit
2import SwiftUI
3
4struct AgentSettings: View {
5 let workspace: Workspace
6 @State private var client = StudioChatAgent.claude
7 @State private var checking = false
8 @State private var result: AgentConnectionCheck.Result?
9 @State private var failure: String?
10
11 private var enabled: Bool { workspace.settings["mcpEnabled"] as? Bool == true }
12 private var command: String { Bundle.main.executableURL?.path ?? CommandLine.arguments[0] }
13
14 enum Section { case all, access, client, test }
15 var section: Section = .all
16 @State private var showsGuide = false
17
18 var body: some View {
19 VStack(alignment: .leading, spacing: 16) {
20 if section == .all {
21 Button("Open connection guide", systemImage: "book") { showsGuide = true }
22 SetupHelpLink("Writing agent setup and troubleshooting", topic: "writing-agent")
23 }
24 if section == .access || section == .all { accessControls }
25 if section == .client || section == .all { clientControls }
26 if section == .test || section == .all { testControls }
27 }
28 .frame(maxWidth: .infinity, alignment: .leading)
29 .sheet(isPresented: $showsGuide) { AgentConnectionGuide(workspace: workspace) }
30 .onChange(of: enabled) { _, _ in
31 result = nil
32 failure = nil
33 }
34 }
35
36 @ViewBuilder private var accessControls: some View {
37 Toggle("Let AI agents use Inkspring", isOn: Binding(get: { enabled }, set: { value in
38 workspace.perform { try workspace.set("mcpEnabled", to: value) }
39 }))
40 Text(enabled ? "Connected local agents can read and edit this workspace."
41 : "Turn on agent access to set permissions and test your connection.")
42 .foregroundStyle(.secondary)
43 Toggle("Let agents set API keys and R2 credentials", isOn: Binding(get: {
44 workspace.settings[AgentMCP.credentialPermission] as? Bool == true
45 }, set: { value in
46 workspace.perform { try workspace.set(AgentMCP.credentialPermission, to: value) }
47 }))
48 .disabled(!enabled)
49 Toggle("Let agents publish X and LinkedIn posts immediately", isOn: Binding(get: {
50 workspace.settings["mcpAllowPosting"] as? Bool == true
51 }, set: { value in
52 workspace.perform { try workspace.set("mcpAllowPosting", to: value) }
53 }))
54 .disabled(!enabled)
55 }
56
57 @ViewBuilder private var clientControls: some View {
58 StudioSegmentedControl(selection: $client, options: [.claude, .codex]) { StudioAgentLabel(agent: $0) }
59 .accessibilityLabel("Client")
60 if client == .claude {
61 StudioAgentLabel(agent: .claude, title: "Save the connection in the folder you use for your local Claude session.")
62 Button("Save project connection…", action: saveProjectConnection).disabled(!enabled)
63 } else {
64 StudioAgentLabel(agent: .codex, title: "In Codex Settings, add an STDIO MCP server named inkspring.")
65 field("Command", value: command)
66 field("Argument", value: "--mcp")
67 }
68 }
69
70 @ViewBuilder private var testControls: some View {
71 HStack {
72 Button("Test connection", systemImage: "checkmark.circle") {
73 Task { await testConnection() }
74 }
75 .disabled(!enabled || checking)
76 if checking { ProgressView().controlSize(.small).accessibilityLabel("Testing MCP connection") }
77 }
78 if enabled, let result {
79 Label("Inkspring answered. \(result.toolCount) tools available. Projects read: \(result.projectCount).",
80 systemImage: "checkmark.circle.fill")
81 .foregroundStyle(.secondary)
82 } else if enabled, let failure {
83 Label(failure, systemImage: "exclamationmark.triangle").foregroundStyle(.red)
84 }
85 }
86
87 private func testConnection() async {
88 guard enabled, !checking else { return }
89 checking = true
90 result = nil
91 failure = nil
92 defer { checking = false }
93 do {
94 let checked = try await workspace.verifyAgentConnection()
95 if enabled { result = checked }
96 } catch {
97 if enabled { failure = error.localizedDescription }
98 }
99 }
100
101 private func field(_ label: String, value: String) -> some View {
102 VStack(alignment: .leading, spacing: 4) {
103 Text(label).font(.caption).foregroundStyle(.secondary)
104 HStack {
105 Text(value)
106 .font(.system(.callout, design: .monospaced))
107 .lineLimit(1)
108 .truncationMode(.middle)
109 .help(value)
110 .textSelection(.enabled)
111 Spacer()
112 Button("Copy \(label.lowercased())") { copy(value) }
113 }
114 }
115 }
116
117 private func saveProjectConnection() {
118 let panel = NSOpenPanel()
119 panel.canChooseDirectories = true
120 panel.canChooseFiles = false
121 guard panel.runModal() == .OK, let directory = panel.url else { return }
122 workspace.perform {
123 let file = directory.appending(path: ".mcp.json")
124 var configuration: [String: Any] = [:]
125 if FileManager.default.fileExists(atPath: file.path) {
126 let data = try Data(contentsOf: file)
127 guard let existing = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
128 throw WorkspaceError("The existing .mcp.json is not a valid configuration.")
129 }
130 configuration = existing
131 }
132 let existing = configuration["mcpServers"]
133 guard existing == nil || existing is [String: Any] else {
134 throw WorkspaceError("The existing mcpServers entry is not a valid object.")
135 }
136 var servers = existing as? [String: Any] ?? [:]
137 let connection: [String: Any] = ["type": "stdio", "command": command, "args": ["--mcp"]]
138 if let previous = servers["inkspring"] {
139 if let previous = previous as? NSDictionary, previous.isEqual(to: connection) {
140 workspace.notice = "Project already connects to native Inkspring"
141 return
142 }
143 let alert = NSAlert()
144 alert.messageText = "Replace the Inkspring connection?"
145 alert.informativeText = "This project will use the native Inkspring workspace."
146 alert.addButton(withTitle: "Cancel")
147 alert.addButton(withTitle: "Replace connection")
148 guard alert.runModal() == .alertSecondButtonReturn else { return }
149 }
150 servers["inkspring"] = connection
151 configuration["mcpServers"] = servers
152 let data = try JSONSerialization.data(withJSONObject: configuration, options: [.prettyPrinted, .sortedKeys])
153 try data.write(to: file, options: .atomic)
154 workspace.notice = "Project connection saved"
155 }
156 }
157}