PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasAgentAccess.swift
| 1 | #if os(macOS) && DIRECT_BUILD && !STORE_BUILD |
| 2 | import AppKit |
| 3 | import SwiftUI |
| 4 | |
| 5 | @MainActor |
| 6 | final class PulseMCPAccess: ObservableObject { |
| 7 | @AppStorage("PulseCanvas.agent.enabled") var enabled = false |
| 8 | @AppStorage("PulseCanvas.agent.playback") var playback = false |
| 9 | @AppStorage("PulseCanvas.agent.editing") var editing = false |
| 10 | @AppStorage("PulseCanvas.agent.rendering") var rendering = false |
| 11 | @AppStorage("PulseCanvas.agent.inputBookmark") private var inputBookmark = Data() |
| 12 | @AppStorage("PulseCanvas.agent.outputBookmark") private var outputBookmark = Data() |
| 13 | |
| 14 | @Published private(set) var lastConnection: Date? |
| 15 | @Published private(set) var hostRunning = false |
| 16 | let host = PulseMCPMailbox.Host() |
| 17 | |
| 18 | nonisolated static var edition: String { |
| 19 | #if STORE_BUILD |
| 20 | "app-store" |
| 21 | #elseif LOCAL_BUILD |
| 22 | "direct-local" |
| 23 | #else |
| 24 | "direct" |
| 25 | #endif |
| 26 | } |
| 27 | nonisolated static var version: String { |
| 28 | Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "development" |
| 29 | } |
| 30 | nonisolated static var offlineStatus: PulseMCP.Object { |
| 31 | ["running": false, "enabled": false, "edition": edition, "version": version, |
| 32 | "playback": false, "editing": false, "rendering": false, "pendingExports": 0] |
| 33 | } |
| 34 | |
| 35 | func host(_ service: PulseMCPService) { |
| 36 | host.start { [weak self, weak service] name, arguments in |
| 37 | guard let self, let service else { return ["error": PulseMCPError("APP_UNAVAILABLE", "Open Pulse Canvas.").payload] } |
| 38 | if name == "get_app_status" || enabled { lastConnection = Date() } |
| 39 | return await service.call(name, arguments) |
| 40 | } |
| 41 | hostRunning = host.isRunning |
| 42 | } |
| 43 | |
| 44 | func permits(_ permission: String) -> Bool { |
| 45 | switch permission { |
| 46 | case "playback": playback |
| 47 | case "editing": editing |
| 48 | case "rendering": rendering |
| 49 | default: false |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | enum Folder: String { case input, output } |
| 54 | |
| 55 | func grant(_ folder: Folder, url: URL) throws { |
| 56 | let options: URL.BookmarkCreationOptions = folder == .input |
| 57 | ? [.withSecurityScope, .securityScopeAllowOnlyReadAccess] : [.withSecurityScope] |
| 58 | let bookmark = try url.bookmarkData(options: options, includingResourceValuesForKeys: nil, relativeTo: nil) |
| 59 | switch folder { |
| 60 | case .input: inputBookmark = bookmark |
| 61 | case .output: outputBookmark = bookmark |
| 62 | } |
| 63 | objectWillChange.send() |
| 64 | } |
| 65 | |
| 66 | func revoke(_ folder: Folder) { |
| 67 | switch folder { |
| 68 | case .input: inputBookmark = Data() |
| 69 | case .output: outputBookmark = Data() |
| 70 | } |
| 71 | objectWillChange.send() |
| 72 | } |
| 73 | |
| 74 | func scope(_ folder: Folder) -> SecurityScopedAccess? { |
| 75 | let data = folder == .input ? inputBookmark : outputBookmark |
| 76 | guard !data.isEmpty else { return nil } |
| 77 | var stale = false |
| 78 | guard let url = try? URL(resolvingBookmarkData: data, options: [.withSecurityScope, .withoutUI, .withoutMounting], |
| 79 | relativeTo: nil, bookmarkDataIsStale: &stale), !stale else { return nil } |
| 80 | let access = SecurityScopedAccess(url: url) |
| 81 | guard (try? access.url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true else { return nil } |
| 82 | return access |
| 83 | } |
| 84 | |
| 85 | struct AuthorizedPath { |
| 86 | let url: URL |
| 87 | let scope: SecurityScopedAccess |
| 88 | } |
| 89 | |
| 90 | func authorize(_ path: String, in folders: [Folder], writing: Bool = false) throws -> AuthorizedPath { |
| 91 | guard path.hasPrefix("/"), !path.utf8.contains(0) else { |
| 92 | throw PulseMCPError("INVALID_PATH", "Use an absolute local file path.") |
| 93 | } |
| 94 | let url = URL(fileURLWithPath: path).standardizedFileURL |
| 95 | for folder in folders { |
| 96 | guard let grant = scope(folder) else { continue } |
| 97 | let root = grant.url.resolvingSymlinksInPath().path |
| 98 | let parent = url.deletingLastPathComponent().resolvingSymlinksInPath() |
| 99 | let prefix = root == "/" ? "/" : root + "/" |
| 100 | guard parent.path == root || parent.path.hasPrefix(prefix) else { continue } |
| 101 | let candidate = parent.appendingPathComponent(url.lastPathComponent, isDirectory: false) |
| 102 | let resolved = candidate.resolvingSymlinksInPath() |
| 103 | guard resolved.path.hasPrefix(prefix), !writing || candidate.path == resolved.path else { continue } |
| 104 | if writing { |
| 105 | guard (try? parent.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true else { |
| 106 | throw PulseMCPError("OUTPUT_UNAVAILABLE", "Choose an existing directory in the authorized output folder.") |
| 107 | } |
| 108 | } else if let properties = try? resolved.resourceValues(forKeys: [.isRegularFileKey, .isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]) { |
| 109 | guard properties.isRegularFile == true else { |
| 110 | throw PulseMCPError("FILE_UNAVAILABLE", "Choose an existing regular file in the authorized folder.") |
| 111 | } |
| 112 | if properties.isUbiquitousItem == true, |
| 113 | properties.ubiquitousItemDownloadingStatus != .current && properties.ubiquitousItemDownloadingStatus != .downloaded { |
| 114 | throw PulseMCPError("FILE_UNAVAILABLE", "Download the file locally before using it in PulseCanvas.") |
| 115 | } |
| 116 | } else { |
| 117 | throw PulseMCPError("FILE_UNAVAILABLE", "The file could not be read. Check that it exists and is downloaded.") |
| 118 | } |
| 119 | return AuthorizedPath(url: writing ? candidate : resolved, scope: grant) |
| 120 | } |
| 121 | throw PulseMCPError("PERMISSION_REQUIRED", "Authorize the containing folder under Pulse Canvas → Settings → Agent access.") |
| 122 | } |
| 123 | |
| 124 | static var command: String { |
| 125 | Bundle.main.executableURL?.path ?? "/Applications/PulseCanvas Studio.app/Contents/MacOS/PulseCanvas" |
| 126 | } |
| 127 | |
| 128 | static func saveClaudeConnection(in directory: URL) throws { |
| 129 | let config = directory.appendingPathComponent(".mcp.json", isDirectory: false) |
| 130 | let fileManager = FileManager.default |
| 131 | let exists = fileManager.fileExists(atPath: config.path) |
| 132 | let original: Data? |
| 133 | var contents: PulseMCP.Object |
| 134 | if exists { |
| 135 | let info = try config.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) |
| 136 | guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= PulseMCP.maxMessage else { |
| 137 | throw PulseMCPError("INVALID_CONFIG", "Choose a project with a regular .mcp.json file smaller than 2 MB.") |
| 138 | } |
| 139 | let data = try Data(contentsOf: config) |
| 140 | guard let object = try JSONSerialization.jsonObject(with: data) as? PulseMCP.Object else { |
| 141 | throw PulseMCPError("INVALID_CONFIG", "The existing .mcp.json must contain a JSON object.") |
| 142 | } |
| 143 | contents = object |
| 144 | original = data |
| 145 | } else { |
| 146 | contents = [:] |
| 147 | original = nil |
| 148 | } |
| 149 | guard contents["mcpServers"] == nil || contents["mcpServers"] is PulseMCP.Object else { |
| 150 | throw PulseMCPError("INVALID_CONFIG", "Correct the existing mcpServers object before adding PulseCanvas.") |
| 151 | } |
| 152 | var servers = contents["mcpServers"] as? PulseMCP.Object ?? [:] |
| 153 | let entry: PulseMCP.Object = ["type": "stdio", "command": command, "args": [PulseMCP.argument]] |
| 154 | if let existing = servers["pulsecanvas"] { |
| 155 | guard let existing = existing as? PulseMCP.Object, existing["command"] as? String == command, |
| 156 | existing["args"] as? [String] == [PulseMCP.argument] else { |
| 157 | throw PulseMCPError("CONFIG_CONFLICT", "This project already has a different pulsecanvas entry. Edit that entry explicitly.") |
| 158 | } |
| 159 | return |
| 160 | } |
| 161 | servers["pulsecanvas"] = entry |
| 162 | contents["mcpServers"] = servers |
| 163 | let data = try JSONSerialization.data(withJSONObject: contents, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) |
| 164 | if let original { |
| 165 | guard try Data(contentsOf: config) == original else { |
| 166 | throw PulseMCPError("CONFIG_CONFLICT", "The project configuration changed. Check the existing file and try again.") |
| 167 | } |
| 168 | try (data + Data([10])).write(to: config, options: .atomic) |
| 169 | } else { |
| 170 | try (data + Data([10])).write(to: config, options: .withoutOverwriting) |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | struct PulseMCPSettings: View { |
| 176 | @ObservedObject var access: PulseMCPAccess |
| 177 | @State private var client = "Claude Code" |
| 178 | @State private var feedback = "" |
| 179 | @State private var testing = false |
| 180 | |
| 181 | var body: some View { |
| 182 | Section("Agent access") { |
| 183 | Toggle("Allow local agents to connect", isOn: $access.enabled) |
| 184 | VStack(alignment: .leading, spacing: 10) { |
| 185 | Text(access.lastConnection.map { "Last local request: \($0.formatted())" } |
| 186 | ?? (access.hostRunning ? "Ready for a local connection" : "Connection unavailable")) |
| 187 | .foregroundStyle(.secondary) |
| 188 | Toggle("Allow song loading and playback control", isOn: $access.playback) |
| 189 | Toggle("Allow favorites and project edits", isOn: $access.editing) |
| 190 | Toggle("Allow previews and video exports", isOn: $access.rendering) |
| 191 | folderRow("Input folder", .input) |
| 192 | folderRow("Project and export folder", .output) |
| 193 | Picker("Client", selection: $client) { |
| 194 | Text("Claude Code").tag("Claude Code") |
| 195 | Text("Codex").tag("Codex") |
| 196 | }.pickerStyle(.segmented) |
| 197 | if client == "Claude Code" { |
| 198 | Button("Save project connection…") { saveProjectConnection() } |
| 199 | Text("Open Claude → Code and start a new local session in that folder. Approve the project connection and check Connectors for PulseCanvas.") |
| 200 | } else { |
| 201 | Text("In Codex, open Settings → MCP servers → Add server → STDIO. Name the server pulsecanvas. Save, restart, and enter /mcp in a local chat.") |
| 202 | copyRow("Command", PulseMCPAccess.command) |
| 203 | copyRow("Argument", PulseMCP.argument) |
| 204 | } |
| 205 | DisclosureGroup("Advanced") { |
| 206 | Text(PulseMCP.jsonText(["mcpServers": ["pulsecanvas": ["type": "stdio", "command": PulseMCPAccess.command, "args": [PulseMCP.argument]]]])) |
| 207 | .font(.system(.caption, design: .monospaced)).textSelection(.enabled) |
| 208 | } |
| 209 | Button("Test connection") { testConnection() }.disabled(testing) |
| 210 | if !feedback.isEmpty { Text(feedback).textSelection(.enabled) } |
| 211 | }.font(.callout).disabled(!access.enabled) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | private func folderRow(_ title: String, _ folder: PulseMCPAccess.Folder) -> some View { |
| 216 | HStack { |
| 217 | Text(title) |
| 218 | Spacer() |
| 219 | if let scope = access.scope(folder) { |
| 220 | Text(scope.url.path).lineLimit(1).truncationMode(.middle).help(scope.url.path) |
| 221 | Button("Remove") { access.revoke(folder) } |
| 222 | } |
| 223 | Button("Choose…") { |
| 224 | let panel = folderPicker() |
| 225 | panel.begin { response in |
| 226 | guard response == .OK, let url = panel.url else { return } |
| 227 | do { try access.grant(folder, url: url); feedback = "Folder authorized." } |
| 228 | catch { feedback = error.localizedDescription } |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | private func copyRow(_ label: String, _ value: String) -> some View { |
| 235 | HStack { |
| 236 | Text(label) |
| 237 | Text(value).lineLimit(1).truncationMode(.middle).textSelection(.enabled) |
| 238 | Spacer() |
| 239 | Button("Copy \(label.lowercased())") { |
| 240 | NSPasteboard.general.clearContents() |
| 241 | NSPasteboard.general.setString(value, forType: .string) |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | private func folderPicker() -> NSOpenPanel { |
| 247 | let panel = NSOpenPanel() |
| 248 | panel.canChooseDirectories = true |
| 249 | panel.canChooseFiles = false |
| 250 | panel.allowsMultipleSelection = false |
| 251 | return panel |
| 252 | } |
| 253 | |
| 254 | private func saveProjectConnection() { |
| 255 | let panel = folderPicker() |
| 256 | panel.message = "Choose the folder you open in Claude Code." |
| 257 | panel.begin { response in |
| 258 | guard response == .OK, let url = panel.url else { return } |
| 259 | let scope = SecurityScopedAccess(url: url) |
| 260 | defer { withExtendedLifetime(scope) {} } |
| 261 | do { |
| 262 | try PulseMCPAccess.saveClaudeConnection(in: scope.url) |
| 263 | feedback = "Project connection saved in \(scope.url.lastPathComponent)/.mcp.json." |
| 264 | } catch { feedback = error.localizedDescription } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | private func testConnection() { |
| 269 | testing = true |
| 270 | Task { |
| 271 | let connected = await Task.detached { |
| 272 | let response = PulseMCPMailbox.call("get_app_status", [:])["value"] as? PulseMCP.Object |
| 273 | return response?["enabled"] as? Bool == true |
| 274 | }.value |
| 275 | testing = false |
| 276 | feedback = connected ? "Local connection passed." : "Connection failed. Reopen Pulse Canvas and try again." |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | #endif |