Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasMCPJobs.swift

Raw 24.6 KB on 87dd19288bbd69b69b6ac6e250fb5d18bfebb877
1#if os(macOS) && DIRECT_BUILD && !STORE_BUILD
2@preconcurrency import AVFoundation
3import Foundation
4
5@MainActor
6final class PulseMCPJobs {
7 static let maxPending = 3
8 private static let historyLimit = 200
9
10 struct Format: Codable {
11 let aspect: String
12 let resolution: Int
13 let fps: Int
14 }
15
16 struct Job: Codable, Identifiable {
17 let id: String
18 let signature: String
19 let requestKey: String
20 let destination: String
21 let projectPath: String?
22 let sourcePath: String
23 let sourceBytes: Int
24 let sourceModified: Date
25 let settings: Format
26 let previewSeconds: Double?
27 let overwrite: Bool
28 let project: CreatorProject
29 let timeline: [PulseMCPScene]
30 let duration: Double
31 let usedFallback: Bool
32 var phase = "queued"
33 var artifact: Artifact?
34 var errorCode: String?
35 var errorMessage: String?
36 var manifestPath: String?
37 var pending: Bool { ["queued", "preparing", "rendering", "muxing", "validating"].contains(phase) }
38 }
39
40 struct Artifact: Codable {
41 var path: String
42 let durationSeconds: Double
43 let width: Int
44 let height: Int
45 let fps: Double
46 let expectedFrames: Int
47 let videoCodec: String
48 let audioCodec: String
49 let bytes: Int
50 }
51
52 struct SaveReceipt: Codable {
53 let key: String
54 let signature: String
55 let path: String
56 let project: CreatorProject
57 let duration: Double
58 }
59
60 struct Ledger: Codable {
61 var jobs: [Job] = []
62 var saves: [SaveReceipt] = []
63 }
64
65 private let access: PulseMCPAccess
66 private let exporter: SocialExportController
67 private let url: URL
68 private var ledger = Ledger()
69 private var loadError: Error?
70 private var worker: Task<Void, Never>?
71 private var active: String?
72 private(set) var pendingCount = 0
73
74 init(access: PulseMCPAccess, exporter: SocialExportController) {
75 self.access = access
76 self.exporter = exporter
77 url = PulseMCPMailbox.configuredRoot.appendingPathComponent("jobs.json")
78 do {
79 _ = try PulseMCPMailbox.root()
80 if FileManager.default.fileExists(atPath: url.path) {
81 ledger = try JSONDecoder().decode(Ledger.self, from: Data(contentsOf: url))
82 var recovered = ledger
83 for index in recovered.jobs.indices where recovered.jobs[index].pending {
84 cleanupInterrupted(recovered.jobs[index])
85 recovered.jobs[index].phase = "failed"
86 recovered.jobs[index].errorCode = "EXPORT_INTERRUPTED"
87 recovered.jobs[index].errorMessage = "PulseCanvas closed before this export completed. Start a new export with a new request key."
88 }
89 try write(recovered)
90 }
91 } catch { loadError = error }
92 }
93
94 private func cleanupInterrupted(_ job: Job) {
95 guard UUID(uuidString: job.id) != nil,
96 let output = try? access.authorize(job.destination, in: [.output], writing: true) else { return }
97 defer { withExtendedLifetime(output.scope) {} }
98 let folder = workDirectory(destination: output.url, id: job.id)
99 let marker = folder.appendingPathComponent("owner")
100 guard let properties = try? folder.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
101 properties.isDirectory == true, properties.isSymbolicLink != true,
102 (try? marker.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])).map({
103 $0.isRegularFile == true && $0.isSymbolicLink != true && $0.fileSize == job.id.utf8.count
104 }) == true,
105 (try? Data(contentsOf: marker)) == Data(job.id.utf8) else { return }
106 try? FileManager.default.removeItem(at: folder)
107 }
108
109 private func workDirectory(destination: URL, id: String) -> URL {
110 destination.deletingLastPathComponent().appendingPathComponent(".PulseCanvas-" + id, isDirectory: true)
111 }
112
113 func requireStorage() throws {
114 if loadError != nil {
115 throw PulseMCPError("JOB_STORAGE_UNAVAILABLE", "PulseCanvas could not read or save its job history. Check the AgentConnection folder before retrying.")
116 }
117 }
118
119 func job(_ id: String) throws -> Job {
120 try requireStorage()
121 guard let job = ledger.jobs.first(where: { $0.id == id }) else {
122 throw PulseMCPError("JOB_NOT_FOUND", "Read list_exports to find the retained ID.")
123 }
124 return job
125 }
126
127 func recent(_ limit: Int) throws -> [Job] {
128 try requireStorage()
129 return Array(ledger.jobs.suffix(limit).reversed())
130 }
131
132 func repeatJob(key: String, signature: String) throws -> Job? {
133 try requireStorage()
134 if ledger.saves.contains(where: { $0.key == key }) { throw keyConflict() }
135 guard let previous = ledger.jobs.first(where: { $0.requestKey == key }) else { return nil }
136 guard previous.signature == signature else { throw keyConflict() }
137 return previous
138 }
139
140 func repeatSave(key: String, signature: String) throws -> SaveReceipt? {
141 try requireStorage()
142 if ledger.jobs.contains(where: { $0.requestKey == key }) { throw keyConflict() }
143 guard let receipt = ledger.saves.first(where: { $0.key == key }) else { return nil }
144 guard receipt.signature == signature else { throw keyConflict() }
145 return receipt
146 }
147
148 func rememberSave(_ receipt: SaveReceipt) throws {
149 var next = ledger
150 next.saves.append(receipt)
151 if next.saves.count > Self.historyLimit { next.saves.removeFirst() }
152 try write(next)
153 }
154
155 private func keyConflict() -> PulseMCPError {
156 PulseMCPError("REQUEST_KEY_CONFLICT", "Use a new request key for a different operation or different arguments.")
157 }
158
159 func checkCapacity(destination: URL) throws {
160 try requireStorage()
161 guard pendingCount < Self.maxPending,
162 !ledger.jobs.contains(where: { $0.pending && $0.destination == destination.path }) else {
163 throw PulseMCPError("EXPORT_BUSY", "Wait for a pending export or choose an unused destination.")
164 }
165 }
166
167 func checkOutput(_ destination: URL, overwrite: Bool) throws {
168 let manifest = Self.manifestURL(destination)
169 try Self.checkDestination(destination, overwrite: overwrite)
170 try Self.checkDestination(manifest, overwrite: overwrite)
171 let fm = FileManager.default
172 guard overwrite && (fm.fileExists(atPath: destination.path) || fm.fileExists(atPath: manifest.path)) else { return }
173 let known = ledger.jobs.last { $0.phase == "completed" && $0.destination == destination.path }
174 guard let known, let artifact = known.artifact, known.manifestPath == manifest.path,
175 let size = try? destination.resourceValues(forKeys: [.fileSizeKey]).fileSize, size == artifact.bytes,
176 let manifestSize = try? manifest.resourceValues(forKeys: [.fileSizeKey]).fileSize, manifestSize <= 2_000_000,
177 let data = try? Data(contentsOf: manifest),
178 let metadata = try? JSONSerialization.jsonObject(with: data) as? PulseMCP.Object,
179 metadata["jobId"] as? String == known.id
180 else {
181 throw PulseMCPError("OUTPUT_EXISTS", "Use a new name. PulseCanvas can replace only an export it previously recorded at this path.")
182 }
183 }
184
185 func submit(_ job: Job) throws {
186 var next = ledger
187 next.jobs.append(job)
188 if next.jobs.count > Self.historyLimit, let index = next.jobs.firstIndex(where: { !$0.pending }) {
189 next.jobs.remove(at: index)
190 }
191 try write(next)
192 kick()
193 }
194
195 func failPreparation(_ queued: Job, error: Error) {
196 var job = queued
197 job.phase = "failed"
198 let failure = Self.error(error, defaultCode: "PROJECT_SAVE_FAILED")
199 job.errorCode = failure.code
200 job.errorMessage = failure.message
201 try? record(job)
202 }
203
204 private func write(_ next: Ledger) throws {
205 let data = try JSONEncoder().encode(next)
206 try data.write(to: url, options: .atomic)
207 ledger = next
208 pendingCount = ledger.jobs.filter(\.pending).count
209 }
210
211 private func record(_ job: Job) throws {
212 guard let index = ledger.jobs.firstIndex(where: { $0.id == job.id }) else { return }
213 var next = ledger
214 next.jobs[index] = job
215 do { try write(next) }
216 catch {
217 // Never report an unpersisted completion. Stop accepting further work
218 // until the storage problem is resolved and the app restarts.
219 loadError = error
220 throw error
221 }
222 }
223
224 private func kick() {
225 guard worker == nil else { return }
226 worker = Task { [weak self] in await self?.drain() }
227 }
228
229 private func drain() async {
230 defer { active = nil; worker = nil }
231 while let job = ledger.jobs.first(where: { $0.phase == "queued" }), loadError == nil, !Task.isCancelled {
232 if exporter.isExporting {
233 try? await Task.sleep(for: .milliseconds(150))
234 continue
235 }
236 active = job.id
237 let task = Task { await run(job) }
238 activeTask = task
239 await task.value
240 activeTask = nil
241 active = nil
242 }
243 }
244
245 private var activeTask: Task<Void, Never>?
246
247 func cancel(_ id: String) throws -> Job {
248 var job = try self.job(id)
249 guard job.pending else { return job }
250 if id == active {
251 activeTask?.cancel()
252 exporter.cancel()
253 } else {
254 job.phase = "cancelled"
255 try record(job)
256 }
257 return job
258 }
259
260 func details(_ job: Job) -> PulseMCP.Object {
261 let live = active == job.id && job.pending
262 var result: PulseMCP.Object = [
263 "id": job.id, "phase": live && exporter.isExporting ? exporter.phase.rawValue : job.phase,
264 "progress": job.phase == "completed" ? 1.0 : live ? min(exporter.progress, 0.99) : 0.0,
265 "framesRendered": live ? exporter.renderedFrames : job.artifact?.expectedFrames ?? 0,
266 "totalFrames": live ? exporter.totalFrames : job.artifact?.expectedFrames ?? 0,
267 "destination": job.destination, "previewOnly": job.previewSeconds != nil
268 ]
269 result["projectPath"] = job.projectPath
270 result["manifestPath"] = job.manifestPath
271 if let eta = live ? exporter.estimatedSecondsRemaining : nil { result["etaSeconds"] = eta }
272 if let artifact = job.artifact, let data = try? JSONEncoder().encode(artifact) {
273 result["artifact"] = try? JSONSerialization.jsonObject(with: data)
274 }
275 if let code = job.errorCode, let message = job.errorMessage {
276 result["error"] = ["code": code, "message": message]
277 }
278 return result
279 }
280
281 private func run(_ queued: Job) async {
282 var job = queued
283 do {
284 try Task.checkCancellation()
285 guard access.enabled, access.rendering else { throw revoked() }
286 let source = try access.authorize(job.sourcePath, in: [.input])
287 let output = try access.authorize(job.destination, in: [.output], writing: true)
288 defer { withExtendedLifetime((source.scope, output.scope)) {} }
289 let identity = try Self.sourceIdentity(source.url)
290 guard identity.bytes == job.sourceBytes, identity.modified == job.sourceModified else {
291 throw PulseMCPError("AUDIO_CHANGED", "The source file changed since submission. Reload it and start a new export.")
292 }
293 let destination = output.url
294 let manifestPath = Self.manifestURL(destination)
295 try checkOutput(destination, overwrite: job.overwrite)
296 let work = workDirectory(destination: destination, id: job.id)
297 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
298 defer { try? FileManager.default.removeItem(at: work) }
299 try Data(job.id.utf8).write(to: work.appendingPathComponent("owner"), options: .withoutOverwriting)
300 let staged = work.appendingPathComponent("video.mp4")
301 let manifest = work.appendingPathComponent("manifest.json")
302 let snapshot: CreatorProject
303 do {
304 snapshot = try job.project.remapped(using: .shared)
305 let allScenes = Set((snapshot.timeline ?? []).map(\.scene)).union([snapshot.scene])
306 guard allScenes.isSubset(of: Set(ProjectMPresets.shared.availableScenes)),
307 job.project.effectIdentities?[job.project.scene] == ProjectMPresets.shared.identity(for: snapshot.scene),
308 job.timeline.count == (snapshot.timeline ?? []).count,
309 zip(job.timeline, snapshot.timeline ?? []).allSatisfy({ $0.visualizerId == ProjectMPresets.shared.identity(for: $1.scene) })
310 else { throw CocoaError(.fileReadCorruptFile) }
311 } catch { throw PulseMCPError("UNSUPPORTED_EFFECT", "An effect used by the saved export is no longer installed. Restore it and submit another job.") }
312 guard let aspect = SocialAspect.allCases.first(where: { $0.agentName == job.settings.aspect }) else {
313 throw PulseMCPError("UNSUPPORTED_FORMAT", "Read the current export capabilities.")
314 }
315 job.phase = "preparing"
316 try record(job)
317 let state = RenderState()
318 state.scene = snapshot.scene
319 snapshot.appearance.apply(to: state)
320 await exporter.export(audioURL: source.url, render: state, to: staged,
321 segments: snapshot.studioEnabled == true ? (snapshot.timeline ?? []) : [],
322 appearances: snapshot.visualPresets ?? [:],
323 offline: .init(aspect: aspect, resolution: job.settings.resolution, fps: job.settings.fps,
324 scratchDirectory: work, previewSeconds: job.previewSeconds))
325 try Task.checkCancellation()
326 if let error = exporter.error { throw error }
327 guard exporter.exportedURL == staged else { throw CancellationError() }
328 job.phase = "validating"
329 try record(job)
330 let duration = min(job.previewSeconds ?? job.duration, job.duration)
331 let dimensions = aspect.dimensions(resolution: job.settings.resolution)
332 var artifact = try await Self.validate(staged, dimensions: dimensions, fps: job.settings.fps, duration: duration)
333 try Task.checkCancellation()
334 guard access.enabled, access.rendering else { throw revoked() }
335 let liveGrant = try access.authorize(job.destination, in: [.output], writing: true)
336 let liveInput = try access.authorize(job.sourcePath, in: [.input])
337 defer { withExtendedLifetime((liveGrant.scope, liveInput.scope)) {} }
338 let finalSource = try Self.sourceIdentity(liveInput.url)
339 guard finalSource.bytes == job.sourceBytes, finalSource.modified == job.sourceModified else {
340 throw PulseMCPError("AUDIO_CHANGED", "The source file changed during the render. Reload it and start a new export.")
341 }
342 artifact.path = destination.path
343 let details: PulseMCP.Object = ["jobId": job.id, "appVersion": PulseMCPAccess.version,
344 "appEdition": PulseMCPAccess.edition, "sourcePath": job.sourcePath, "sourceBytes": job.sourceBytes,
345 "sourceModified": ISO8601DateFormatter().string(from: job.sourceModified), "projectPath": job.projectPath as Any? ?? NSNull(),
346 "seed": job.project.generationSeed as Any? ?? NSNull(), "timeline": job.timeline.map(\.payload),
347 "settings": ["aspect": job.settings.aspect, "resolution": job.settings.resolution, "fps": job.settings.fps],
348 "artifact": try JSONSerialization.jsonObject(with: JSONEncoder().encode(artifact))]
349 try JSONSerialization.data(withJSONObject: details, options: [.prettyPrinted, .sortedKeys]).write(to: manifest)
350 try checkOutput(destination, overwrite: job.overwrite)
351 try Self.publish(staged, to: destination, overwrite: job.overwrite)
352 do { try Self.publish(manifest, to: manifestPath, overwrite: job.overwrite) }
353 catch {
354 if !job.overwrite { try? FileManager.default.removeItem(at: destination) }
355 throw error
356 }
357 job.phase = "completed"
358 job.artifact = artifact
359 job.manifestPath = manifestPath.path
360 try record(job)
361 } catch is CancellationError {
362 job.phase = "cancelled"
363 try? record(job)
364 } catch {
365 job.phase = "failed"
366 job.artifact = nil
367 job.manifestPath = nil
368 let failure = Self.error(error)
369 job.errorCode = failure.code
370 job.errorMessage = failure.message
371 try? record(job)
372 }
373 }
374
375 private func revoked() -> PulseMCPError {
376 PulseMCPError("PERMISSION_REQUIRED", "Rendering access was disabled. Review Settings → Agent access before submitting another export.")
377 }
378
379 static func error(_ error: Error, defaultCode: String = "EXPORT_FAILED") -> PulseMCPError {
380 if let error = error as? PulseMCPError { return error }
381 var underlying: NSError? = error as NSError
382 while let current = underlying {
383 if (current.domain == NSPOSIXErrorDomain && current.code == Int(ENOSPC)) ||
384 (current.domain == NSCocoaErrorDomain && current.code == NSFileWriteOutOfSpaceError) {
385 return PulseMCPError("DISK_FULL", "Free space on the authorized output drive or choose another output folder.")
386 }
387 if (current.domain == NSPOSIXErrorDomain && current.code == Int(EEXIST)) ||
388 (current.domain == NSCocoaErrorDomain && current.code == NSFileWriteFileExistsError) {
389 return PulseMCPError("OUTPUT_EXISTS", "Choose a new output path.")
390 }
391 underlying = current.userInfo[NSUnderlyingErrorKey] as? NSError
392 }
393 return PulseMCPError(defaultCode, "\(error.localizedDescription) Check the source, authorized folder and available storage before retrying.")
394 }
395
396 static func sourceIdentity(_ url: URL) throws -> (bytes: Int, modified: Date) {
397 let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey])
398 guard let bytes = values.fileSize, let modified = values.contentModificationDate else {
399 throw PulseMCPError("AUDIO_UNAVAILABLE", "Choose a readable audio file in the authorized input folder.")
400 }
401 return (bytes, modified)
402 }
403
404 static func manifestURL(_ video: URL) -> URL { video.deletingPathExtension().appendingPathExtension("render.json") }
405
406 static func checkDestination(_ url: URL, overwrite: Bool) throws {
407 var isDirectory: ObjCBool = false
408 let exists = FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory)
409 let symbol = try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)
410 guard symbol == nil, !isDirectory.boolValue, !exists || overwrite else {
411 throw PulseMCPError("OUTPUT_EXISTS", "Choose a new destination; directories and symbolic links are never overwritten.")
412 }
413 }
414
415 static func publish(_ staged: URL, to destination: URL, overwrite: Bool) throws {
416 try checkDestination(destination, overwrite: overwrite)
417 if overwrite {
418 guard rename(staged.path, destination.path) == 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
419 } else {
420 guard renamex_np(staged.path, destination.path, UInt32(RENAME_EXCL)) == 0 else {
421 throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno))
422 }
423 }
424 }
425
426 private static func validate(_ url: URL, dimensions: (width: Int, height: Int), fps: Int, duration: Double) async throws -> Artifact {
427 let asset = AVURLAsset(url: url)
428 let videoTracks = try await asset.loadTracks(withMediaType: .video)
429 let audioTracks = try await asset.loadTracks(withMediaType: .audio)
430 let failure = PulseMCPError("MEDIA_VALIDATION_FAILED", "The MP4 did not match the requested audio and video format.")
431 guard videoTracks.count == 1, audioTracks.count == 1,
432 let video = videoTracks.first, let audio = audioTracks.first else { throw failure }
433 let actual = try await asset.load(.duration).seconds
434 let size = try await video.load(.naturalSize)
435 let rate = try await video.load(.nominalFrameRate)
436 let videoRange = try await video.load(.timeRange)
437 let audioRange = try await audio.load(.timeRange)
438 let videoCodec = try await video.load(.formatDescriptions).first.map(CMFormatDescriptionGetMediaSubType)
439 let audioCodec = try await audio.load(.formatDescriptions).first.map(CMFormatDescriptionGetMediaSubType)
440 let tolerance = max(2 / Double(fps), 0.06)
441 let bytes = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
442 guard bytes > 0, abs(actual - duration) <= tolerance, Int(size.width) == dimensions.width,
443 Int(size.height) == dimensions.height, abs(Double(rate) - Double(fps)) < 0.5,
444 videoCodec == kCMVideoCodecType_H264, audioCodec == kAudioFormatMPEG4AAC,
445 abs(videoRange.start.seconds - audioRange.start.seconds) <= tolerance,
446 abs(videoRange.duration.seconds - audioRange.duration.seconds) <= tolerance else { throw failure }
447 let frames = Int(ceil(duration * Double(fps) - 0.00000001))
448 let scan = Task.detached {
449 try await Self.checkVideoSamples(url, fps: fps, expected: frames)
450 }
451 try await withTaskCancellationHandler { try await scan.value } onCancel: { scan.cancel() }
452 return Artifact(path: url.path, durationSeconds: actual, width: dimensions.width, height: dimensions.height,
453 fps: Double(rate), expectedFrames: frames, videoCodec: "h264", audioCodec: "aac", bytes: bytes)
454 }
455
456 nonisolated private static func checkVideoSamples(_ url: URL, fps: Int, expected: Int) async throws {
457 let asset = AVURLAsset(url: url)
458 guard let track = try await asset.loadTracks(withMediaType: .video).first else {
459 throw PulseMCPError("MEDIA_VALIDATION_FAILED", "The video track could not be opened for decoding.")
460 }
461 let reader = try AVAssetReader(asset: asset)
462 let output = AVAssetReaderTrackOutput(track: track, outputSettings: [
463 kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
464 ])
465 output.alwaysCopiesSampleData = false
466 guard reader.canAdd(output) else {
467 throw PulseMCPError("MEDIA_VALIDATION_FAILED", "The decoder rejected the encoded video track.")
468 }
469 reader.add(output)
470 guard reader.startReading() else {
471 throw reader.error ?? PulseMCPError("MEDIA_VALIDATION_FAILED", "The decoder could not start.")
472 }
473 var frames = 0
474 var mediaStart: Double?
475 defer { if reader.status == .reading { reader.cancelReading() } }
476 while let sample = output.copyNextSampleBuffer() {
477 try Task.checkCancellation()
478 guard CMSampleBufferGetImageBuffer(sample) != nil else { continue }
479 let timestamp = CMSampleBufferGetPresentationTimeStamp(sample).seconds
480 if mediaStart == nil { mediaStart = timestamp }
481 let elapsed = timestamp - (mediaStart ?? timestamp)
482 guard timestamp.isFinite, abs(elapsed - Double(frames) / Double(fps)) < 0.001 else {
483 throw PulseMCPError("MEDIA_VALIDATION_FAILED", "Decoded frame \(frames + 1) does not match the requested frame cadence.")
484 }
485 frames += 1
486 }
487 guard reader.status == .completed, frames == expected else {
488 throw reader.error ?? PulseMCPError("MEDIA_VALIDATION_FAILED", "The decoder found \(frames) frames. Expected \(expected).")
489 }
490 }
491
492}
493
494struct PulseMCPScene: Codable {
495 let visualizerId: String
496 let startSeconds: Double
497 let endSeconds: Double
498 let bars: Int?
499 var payload: PulseMCP.Object {
500 var object: PulseMCP.Object = ["visualizerId": visualizerId, "startSeconds": startSeconds, "endSeconds": endSeconds]
501 object["bars"] = bars.flatMap { (1...128).contains($0) ? $0 : nil }
502 return object
503 }
504}
505
506extension SocialAspect {
507 var agentName: String { PulseMCP.aspectNames[Self.allCases.firstIndex(of: self)!] }
508}
509#endif