From d925b86ec3efc5a8e1168dd7823bd9c2d614496e Mon Sep 17 00:00:00 2001 From: Kazuki Nakashima <65545348+lynnswap@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:09:48 +0900 Subject: [PATCH 1/2] Split project inputs and destination selection out of NativePreviewBuild Co-Authored-By: Claude Opus 5.5 --- .../NativeObjCGetters.swift | 34 + .../NativePreviewBuild.swift | 1272 +---------------- .../NativePreviewDefinitions.swift | 8 +- .../NativePreviewDestinations.swift | 891 ++++++++++++ .../NativePreviewProjectInputs.swift | 300 ++++ .../NativePreviewSession.swift | 8 +- .../NativePreviewTool.swift | 67 +- .../NativePreviewBuildTests.swift | 46 +- 8 files changed, 1338 insertions(+), 1288 deletions(-) create mode 100644 Sources/XcodeMCPNativeRuntime/NativeObjCGetters.swift create mode 100644 Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift create mode 100644 Sources/XcodeMCPNativeRuntime/NativePreviewProjectInputs.swift diff --git a/Sources/XcodeMCPNativeRuntime/NativeObjCGetters.swift b/Sources/XcodeMCPNativeRuntime/NativeObjCGetters.swift new file mode 100644 index 00000000..7385a77b --- /dev/null +++ b/Sources/XcodeMCPNativeRuntime/NativeObjCGetters.swift @@ -0,0 +1,34 @@ +import ABIBridge +import ABIBridgeCore +import ABIBridgeCore.Backend +import Foundation + +/// Reads Objective-C properties of native Xcode objects through their getters. +@safe +@MainActor +enum NativeObjCGetters { + static func object(_ receiver: AnyObject, selector: String) throws -> AnyObject? { + let get = try ABIRuntime.shared.object(receiver).resolveAndWait(.objc(.method(selector, as: (() -> AnyObject?).self))) + return try unsafe get.unsafeInvoke() + } + + static func boolean(_ receiver: AnyObject, selector: String) throws -> Bool { + let get = try ABIRuntime.shared.object(receiver).resolveAndWait(.objc(.method(selector, as: (() -> Bool).self))) + return try unsafe get.unsafeInvoke() + } + + static func array(_ receiver: AnyObject, selector: String) throws -> [Value] { + guard let value = try Self.object(receiver, selector: selector) else { return [] } + guard let values = value as? [Value] else { + throw NativeRuntimeError.unsupportedContract("The native \(selector) value is not an array of \(Value.self)") + } + return values + } + + static func optionalString(_ receiver: AnyObject?, selector: String) throws -> String? { + guard let receiver, let object = receiver as? NSObject, + object.responds(to: NSSelectorFromString(selector)) else { return nil } + let get = try ABIRuntime.shared.object(receiver).resolveAndWait(.objc(.method(selector, as: (() -> String?).self))) + return try unsafe get.unsafeInvoke() + } +} diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift index 3613f5ad..fe58182f 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift @@ -143,161 +143,13 @@ final class NativePreviewBuild { private let runtime = ABIRuntime.shared private let installation: NativeXcodeInstallation - private var destinationPreparation: DestinationPreparation? private var clients: [UUID: Cancellation] = [:] private var performMethod: NativeSwiftMethod<@concurrent (AnyObject, AnyObject) async throws -> AnyObject>? - private var sourceSelections: [ObjectIdentifier: [SourceSelectionWaiter]] = [:] - private var synchronizedProjects: [ObjectIdentifier: ProjectSynchronization] = [:] - - private final class ProjectSynchronization { - weak var workspace: AnyObject? - let inputs: NativePreviewInputSnapshot - - init(workspace: AnyObject, inputs: NativePreviewInputSnapshot) { - self.workspace = workspace - self.inputs = inputs - } - } - - private struct SourceSelectionWaiter { - let identifier: UUID - let continuation: CheckedContinuation - } init(installation: NativeXcodeInstallation) { self.installation = installation } - func synchronizeProjectContainers(in workspace: AnyObject) async throws { - try Task.checkCancellation() - synchronizedProjects = synchronizedProjects.filter { $0.value.workspace != nil } - let identifier = ObjectIdentifier(workspace) - if let previous = synchronizedProjects[identifier], previous.workspace === workspace, - let current = try? projectConfigurationSnapshot(in: workspace), current == previous.inputs { - return - } - synchronizedProjects[identifier] = nil - let synchronizationStartedAt = Date() - guard let containers = try object(workspace, selector: "referencedContainers") as? NSSet else { - throw NativeRuntimeError.unsupportedContract("The native workspace has no referenced containers") - } - var updates: [(valid: NativeBoundObjCMethod, edited: NativeBoundObjCMethod, - invalidate: () throws -> Void, queue: OperationQueue)] = [] - var inputFiles: [(invalidate: NativeBoundObjCMethod, modificationDate: NativeBoundObjCMethod)] = [] - func addInputFile(_ filePath: AnyObject) throws { - let path = runtime.object(filePath) - inputFiles.append(( - try path.resolveAndWait(.objc(.method("invalidateFilePath", as: (() -> Void).self))), - try path.resolveAndWait(.objc(.method("modificationDate", as: (() -> AnyObject?).self))) - )) - } - for case let container as NSObject in containers.allObjects - where container !== workspace && container.responds(to: NSSelectorFromString("pbxProject")) { - let native = runtime.object(container) - let valid = try native.resolveAndWait(.objc(.method("isValid", as: (() -> Bool).self))) - guard try unsafe valid.unsafeInvoke() else { continue } - let edited = try native.resolveAndWait(.objc(.method("containerEditedByUserInUI", as: (() -> Bool).self))) - guard try unsafe !edited.unsafeInvoke() else { continue } - let invalidate: () throws -> Void - if container.responds(to: NSSelectorFromString("_invalidateContainerToDiscardInMemoryRepresentation:")) { - let method = try native.resolveAndWait(.objc(.method("_invalidateContainerToDiscardInMemoryRepresentation:", as: ((Bool) -> Void).self))) - invalidate = { try unsafe method.unsafeInvoke(true) } - } else { - let method = try native.resolveAndWait(.objc(.method("_invalidateContainerToDiscardInMemoryRepresentation", as: (() -> Void).self))) - invalidate = { try unsafe method.unsafeInvoke() } - } - guard let graph = try object(container, selector: "objectGraph"), - let queue = try object(graph, selector: "changeQueue") as? OperationQueue else { - throw NativeRuntimeError.unsupportedContract("A native project container has no model change queue") - } - let dataFiles = try native.resolveAndWait(.objc(.method("_containerDataFilePaths", as: (() -> NSArray).self))) - for filePath in try unsafe dataFiles.unsafeInvoke() { try addInputFile(filePath as AnyObject) } - updates.append((valid, edited, invalidate, queue)) - } - guard !updates.isEmpty else { return } - if let configurationPaths = try configurationFilePaths(in: containers) { - let paths = configurationPaths.bases.merging(configurationPaths.watched) { existing, _ in existing } - for filePath in paths.values { try addInputFile(filePath) } - } - guard let environment = try object(workspace, selector: "executionEnvironment") else { - throw NativeRuntimeError.unsupportedContract("The native workspace has no execution environment") - } - let disable = try runtime.object(environment).resolveAndWait( - .objc(.method("disableSubmissionOfBuildOperationsWithReason:", as: ((String) -> Void).self))) - let enable = try runtime.object(environment).resolveAndWait(.objc(.method("enableSubmissionOfBuildOperationsWithReason:", as: ((String) -> Void).self))) - typealias Completion = @convention(block) () -> Void - let cancel = try runtime.object(workspace).resolveAndWait( - .objc(.method("_cancelOngoingBuildWithCompletionBlockIfNeeded:", as: ((Completion?) -> Bool).self))) - let reason = "Synchronizing preview project inputs" - try Task.checkCancellation() - try unsafe disable.unsafeInvoke(reason) - let outcome: Swift.Result - do { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - let completed: Completion = { continuation.resume() } - do { - // A false result means no build was queued and the callback will not run. - if try unsafe !cancel.unsafeInvoke(completed) { continuation.resume() } - } catch { continuation.resume(throwing: error) } - } - try Task.checkCancellation() - // Replacement containers use these dates; configuration parsers also reuse the vnode's derived cache. - for file in inputFiles { - try unsafe file.invalidate.unsafeInvoke() - _ = try unsafe file.modificationDate.unsafeInvoke() - } - var queues: [OperationQueue] = [] - var seen: Set = [] - for update in updates { - if seen.insert(ObjectIdentifier(update.queue)).inserted { queues.append(update.queue) } - // Invalidating one container can also replace another referenced container. - guard try unsafe update.valid.unsafeInvoke(), try unsafe !update.edited.unsafeInvoke() else { continue } - try update.invalidate() - } - for queue in queues { - await withCheckedContinuation { continuation in - queue.addBarrierBlock { continuation.resume() } - } - } - try Task.checkCancellation() - outcome = .success(()) - } catch { outcome = .failure(error) } - do { try unsafe enable.unsafeInvoke(reason) } - catch { - let operation: String - switch outcome { - case .success: operation = "Native preview project synchronization completed" - case .failure(let failure): operation = String(describing: failure) - } - throw NativeRuntimeError.invocation("\(operation); failed to resume native build submissions: \(error)") - } - try outcome.get() - // A source edit or invalidated build certificate does not require replacing project models. - // Only certify settings that were already saved before those models were refreshed. - if let inputs = try? projectConfigurationSnapshot(in: workspace), inputs.predates(synchronizationStartedAt) { - synchronizedProjects[identifier] = ProjectSynchronization(workspace: workspace, inputs: inputs) - } - } - - private func projectConfigurationSnapshot(in workspace: AnyObject) throws -> NativePreviewInputSnapshot? { - guard let containers = try object(workspace, selector: "referencedContainers") as? NSSet, - let configurationPaths = try configurationFilePaths(in: containers), - let configurationFiles = trackableConfigurationFiles(configurationPaths) else { return nil } - var roots = configurationFiles - var missing: Set = [] - for case let container as NSObject in containers.allObjects - where container !== workspace && container.responds(to: NSSelectorFromString("pbxProject")) { - let dataFiles = try runtime.object(container).resolveAndWait(.objc(.method("_containerDataFilePaths", as: (() -> NSArray).self))) - for filePath in try unsafe dataFiles.unsafeInvoke() { - guard let url = try object(filePath as AnyObject, selector: "fileURL") as? URL, - url.isFileURL, url.path.hasPrefix("/") else { return nil } - if FileManager.default.fileExists(atPath: url.path) { roots.insert(url) } - else { missing.insert(url) } - } - } - return try NativePreviewInputSnapshot.capture(roots: Array(roots), missingInputs: missing) - } - func prepare(workspace: AnyObject) async throws -> NativeSwiftMethod<@concurrent (AnyObject, AnyObject) async throws -> AnyObject> { if let performMethod { return performMethod } let bound = try await runtime.object(workspace).resolve( @@ -310,9 +162,9 @@ final class NativePreviewBuild { } func runnableBuildable(in scheme: AnyObject) throws -> AnyObject? { - guard let action = try object(scheme, selector: "launchSchemeAction"), - let runnable = try object(action, selector: "runnable") else { return nil } - return try object(runnable, selector: "buildableProduct") + guard let action = try NativeObjCGetters.object(scheme, selector: "launchSchemeAction"), + let runnable = try NativeObjCGetters.object(action, selector: "runnable") else { return nil } + return try NativeObjCGetters.object(runnable, selector: "buildableProduct") } static func isRunnable(_ buildable: NSObject, runnable: AnyObject?) -> Bool { @@ -320,182 +172,7 @@ final class NativePreviewBuild { return buildable.isEqual(runnable) } - func planningContext(workspace: AnyObject, destination: DestinationSelection? = nil) throws -> PlanningContext { - guard let manager = try object(workspace, selector: "runContextManager"), - let scheme = try object(manager, selector: "activeRunContext"), - let environment = try object(workspace, selector: "executionEnvironment") else { - throw NativeRuntimeError.invalidRequest("The workspace has no active scheme, run destination, or execution environment") - } - return try PlanningContext(scheme: scheme, schemeIdentifier: object(scheme, selector: "schemeIdentifier") as? NSObject, - environment: environment, activeDestination: destinationContext(object(manager, selector: "activeRunDestination")), - destination: destinationContext(destination?.selected.value)) - } - - func workspaceBuilder(for destination: DestinationSelection) async throws -> AnyObject? { - guard let field = Mirror(reflecting: destination.resolution.host).children.first(where: { $0.label == "lastWorkspaceBuilder" }) else { - throw NativeRuntimeError.unsupportedContract("The native preview host has no cached workspace builder") - } - let mirror = Mirror(reflecting: field.value) - let value: Any - if mirror.displayStyle == .optional { - guard let payload = mirror.children.first else { return nil } - value = payload.value - } else { value = field.value } - guard Mirror(reflecting: value).displayStyle == .class else { - throw NativeRuntimeError.unsupportedContract("The native preview workspace builder is not a class") - } - // Creating a builder after restoring the agentic source would invalidate this native cache. - return value as AnyObject - } - - private func configurationFilePaths(in containers: NSSet) throws -> (bases: [URL: AnyObject], watched: [URL: AnyObject])? { - var baseFiles: [URL: AnyObject] = [:] - var watchedFiles: [URL: AnyObject] = [:] - for entry in containers.allObjects { - guard let container = entry as? NSObject else { return nil } - guard container.responds(to: NSSelectorFromString("pbxProject")) else { continue } - guard let project = try object(container, selector: "pbxProject"), - let targets = try object(project, selector: "targets") as? NSArray else { return nil } - for owner in [project] + targets.map({ $0 as AnyObject }) { - guard let list = try object(owner, selector: "buildConfigurationList"), - let configurations = try object(list, selector: "buildConfigurations") as? NSArray else { return nil } - for configuration in configurations { - let configuration = configuration as AnyObject - guard try object(configuration, selector: "baseConfigurationAnchoredReference") != nil else { continue } - guard let reference = try object(configuration, selector: "resolvedBaseConfigurationReference"), - let path = try object(reference, selector: "resolvedAbsolutePath") as? String, - path.hasPrefix("/"), - let filePath = try object(path as NSString, selector: "dvt_absoluteFilePath") else { return nil } - baseFiles[URL(filePath: path).standardizedFileURL] = filePath - let watched = try unsafe runtime.object(configuration).value(forObjCIvar: "_watchedBaseConfigurationFilePaths", as: NSSet?.self) - for filePath in watched?.allObjects ?? [] { - guard let url = try object(filePath as AnyObject, selector: "fileURL") as? URL, - url.isFileURL, url.path.hasPrefix("/") else { return nil } - watchedFiles[url.standardizedFileURL] = filePath as AnyObject - } - } - } - } - return (baseFiles, watchedFiles) - } - - private func trackableConfigurationFiles(_ configurationPaths: (bases: [URL: AnyObject], watched: [URL: AnyObject])) -> Set? { - let baseFiles = Set(configurationPaths.bases.keys) - let watchedFiles = Set(configurationPaths.watched.keys) - let configurationFiles = baseFiles.union(watchedFiles) - for file in configurationFiles { - // Optional includes can name paths absent from the native watched set. - guard let text = try? String(contentsOf: file, encoding: .utf8), !text.utf8.contains(0x3f) else { return nil } - if baseFiles.contains(file), text.utf8.contains(0x23), !watchedFiles.contains(file) { return nil } - } - return configurationFiles - } - - func inputRoots(workspace: AnyObject, build: Result, source: URL, excluding: Set = []) throws -> (roots: [URL], missing: Set)? { - guard let declaredInputFiles = build.declaredInputFiles, - let containers = try object(workspace, selector: "referencedContainers") as? NSSet, - let configurationPaths = try configurationFilePaths(in: containers), - let configurationFiles = trackableConfigurationFiles(configurationPaths) else { return nil } - guard let filePath = try object(workspace, selector: "representingFilePath"), - let workspaceURL = try object(filePath, selector: "fileURL") as? URL else { - throw NativeRuntimeError.unsupportedContract("The native workspace has no representing file URL") - } - // Native builder invalidation owns workspace configuration; these trees also detect disk edits synchronously. - var roots: Set = [workspaceURL] - var missing: Set = [] - for case let container as NSObject in containers.allObjects - where container.responds(to: NSSelectorFromString("pbxProject")) { - let dataFiles = try runtime.object(container).resolveAndWait(.objc(.method("_containerDataFilePaths", as: (() -> NSArray).self))) - for filePath in try unsafe dataFiles.unsafeInvoke() { - guard let url = try object(filePath as AnyObject, selector: "fileURL") as? URL, - url.isFileURL, url.path.hasPrefix("/") else { return nil } - // Native containers include alternate project formats that need not exist on disk. - if FileManager.default.fileExists(atPath: url.path) { roots.insert(url) } - else { missing.insert(url) } - } - } - roots.formUnion(configurationFiles) - roots.formUnion(declaredInputFiles) - var sources: Set = [source] - var pending = build.targets + build.previewRoots - while let target = pending.popLast() { - sources.formUnion(target.sourceFiles) - pending += target.dependencies - } - sources = NativePreviewBuildInputs.removingGeneratedPaths(from: sources, generatedPaths: build.generatedInputPaths) - let sourceDirectories = try Set(sources.map { source in - guard source.isFileURL, source.path.hasPrefix("/") else { - throw NativeRuntimeError.unsupportedContract("A native build source has no absolute file URL: \(source)") - } - return source.deletingLastPathComponent().standardizedFileURL - }) - var packageSearches: Set = [] - for sourceDirectory in sourceDirectories { - roots.insert(sourceDirectory) - var directory = sourceDirectory - while packageSearches.insert(directory.path).inserted { - if FileManager.default.fileExists(atPath: directory.appendingPathComponent("Package.swift").path) { - roots.insert(directory) - break - } - let parent = directory.deletingLastPathComponent().standardizedFileURL - if parent.path == directory.path { break } - directory = parent - } - } - struct RootFact { - let url: URL - let path: String - let components: [String] - } - let unique = Set(roots.map(\.standardizedFileURL)) - let facts: [RootFact] = unique.map { - RootFact(url: $0, path: $0.path, components: $0.pathComponents) - } - let normalized = facts.sorted { left, right in - if left.components.count == right.components.count { return left.path < right.path } - return left.components.count < right.components.count - } - var exclusionIDs: [[String]: Int] = [:] - for excluded in excluding.union(build.inputCaptureExclusions) { - for path in [excluded.standardizedFileURL.pathComponents, - excluded.resolvingSymlinksInPath().pathComponents] { - if exclusionIDs[path] == nil { exclusionIDs[path] = exclusionIDs.count } - } - } - var result: [URL] = [] - var retained: [[String]: [Set]] = [:] - for candidate in normalized { - var candidateExclusions: Set = [] - for path in [candidate.components, candidate.url.resolvingSymlinksInPath().pathComponents] { - var prefix: [String] = [] - prefix.reserveCapacity(path.count) - for component in path { - prefix.append(component) - if let id = exclusionIDs[prefix] { candidateExclusions.insert(id) } - } - } - var prefix: [String] = [] - prefix.reserveCapacity(candidate.components.count) - var covered = false - for component in candidate.components { - prefix.append(component) - if let parents = retained[prefix], parents.contains(where: { - candidateExclusions.isSubset(of: $0) - }) { - covered = true - break - } - } - if !covered { - result.append(candidate.url) - retained[candidate.components, default: []].append(candidateExclusions) - } - } - return (result, missing) - } - - func build(workspace: AnyObject, destination selection: DestinationSelection, source: URL) async throws -> Result { + func build(workspace: AnyObject, destination selection: NativePreviewDestinations.Selection, source: URL) async throws -> Result { try Task.checkCancellation() let info = selection.selected let destination = info.value @@ -516,12 +193,12 @@ final class NativePreviewBuild { defer { clients[identifier] = nil } let perform = try await prepare(workspace: workspace) - let workspaceBuilder = try? await self.workspaceBuilder(for: selection) + let workspaceBuilder = try? selection.workspaceBuilder() try Task.checkCancellation() // Match BuildSystem.buildScheme: capture the selection before the task can update the model. - guard let manager = try object(workspace, selector: "runContextManager"), - let scheme = try object(manager, selector: "activeRunContext"), - let environment = try object(workspace, selector: "executionEnvironment") else { + guard let manager = try NativeObjCGetters.object(workspace, selector: "runContextManager"), + let scheme = try NativeObjCGetters.object(manager, selector: "activeRunContext"), + let environment = try NativeObjCGetters.object(workspace, selector: "executionEnvironment") else { throw NativeRuntimeError.invalidRequest("The workspace has no active scheme, run destination, or execution environment") } let runnable = try runnableBuildable(in: scheme) @@ -623,7 +300,7 @@ final class NativePreviewBuild { // performTask finishes the operation without throwing compiler failures. // Xcode's BuildOperationErrorDetector treats native result 1 as success. guard value == 1 else { - let messages = try object(operation, selector: "buildLog").map { try buildErrors(in: $0) } ?? [] + let messages = try NativeObjCGetters.object(operation, selector: "buildLog").map { try buildErrors(in: $0) } ?? [] let details = messages.joined(separator: "\n") throw NativeRuntimeError.invocation(details.isEmpty ? "The native build failed with result \(value)" @@ -633,11 +310,11 @@ final class NativePreviewBuild { } private func buildErrors(in section: AnyObject) throws -> [String] { - if let text = try optionalString(section, selector: "text") { + if let text = try NativeObjCGetters.optionalString(section, selector: "text") { let errors = try runtime.object(section).resolveAndWait(.objc(.method("totalNumberOfErrors", as: (() -> UInt).self))) let failures = try runtime.object(section).resolveAndWait(.objc(.method("totalNumberOfTestFailures", as: (() -> UInt).self))) guard try unsafe errors.unsafeInvoke() > 0 || failures.unsafeInvoke() > 0 else { return [] } - let title = try optionalString(section, selector: "title") + let title = try NativeObjCGetters.optionalString(section, selector: "title") return [title.map { "\($0)\n\(text)" } ?? text] } let subsections = try runtime.object(section).resolveAndWait(.objc(.method("subsections", as: (() -> NSArray).self))) @@ -761,8 +438,8 @@ final class NativePreviewBuild { } private func canonicalBuildable(_ buildable: NSObject) throws -> NSObject { - guard let blueprint = try object(buildable, selector: "blueprint"), - let canonical = try object(blueprint, selector: "primaryBuildable") as? NSObject else { + guard let blueprint = try NativeObjCGetters.object(buildable, selector: "blueprint"), + let canonical = try NativeObjCGetters.object(blueprint, selector: "primaryBuildable") as? NSObject else { throw NativeRuntimeError.unsupportedContract("A native dependency buildable has no primary buildable") } return canonical @@ -777,7 +454,7 @@ final class NativePreviewBuild { let dependencies = try await runtime.object(graph).resolve( .swift(.method("dependencies(of: __C.IDEBuildable) -> [__C.IDEBuildable]", as: ((AnyObject) -> NativeSwiftValue).self))) let parameters = try runtime.object(priorBuild).resolveAndWait(.objc(.method("_buildParametersForBuildable:", as: ((AnyObject) -> AnyObject).self))) - guard let service = try object(workspace, selector: "buildSystemService"), + guard let service = try NativeObjCGetters.object(workspace, selector: "buildSystemService"), let levelClass = NSClassFromString("IDEMacroEvaluation_Level_Blueprint") else { throw NativeRuntimeError.unsupportedContract("The native build has no macro evaluation context") } @@ -800,7 +477,7 @@ final class NativePreviewBuild { guard seen.insert(ObjectIdentifier(buildable)).inserted else { continue } let values = try unsafe dependencies.unsafeInvoke(buildable) guard let children = try values.withCopy({ $0 as? [NSObject] }), - let blueprint = try object(buildable, selector: "blueprint") as? NSObject else { return nil } + let blueprint = try NativeObjCGetters.object(buildable, selector: "blueprint") as? NSObject else { return nil } pending.append(contentsOf: children) let buildParameters = try unsafe parameters.unsafeInvoke(buildable) let allocatedLevel = try unsafe allocateLevel.unsafeInvoke() @@ -838,14 +515,14 @@ final class NativePreviewBuild { responseFileSyntax: .swiftDriver)) } guard blueprint.responds(to: NSSelectorFromString("pbxTarget")) else { continue } - guard let target = try object(blueprint, selector: "pbxTarget") else { return nil } - let phases: [NSObject] = try array(target, selector: "buildPhases") - let groups: [NSObject] = try array(target, selector: "fileSystemSynchronizedGroupsArray") + guard let target = try NativeObjCGetters.object(blueprint, selector: "pbxTarget") else { return nil } + let phases: [NSObject] = try NativeObjCGetters.array(target, selector: "buildPhases") + let groups: [NSObject] = try NativeObjCGetters.array(target, selector: "fileSystemSynchronizedGroupsArray") var references: Set = [] func addReference(_ reference: NSObject) throws -> Bool { guard references.insert(ObjectIdentifier(reference)).inserted else { return true } if reference.responds(to: NSSelectorFromString("children")) { - let children: [NSObject] = try array(reference, selector: "children") + let children: [NSObject] = try NativeObjCGetters.array(reference, selector: "children") if !children.isEmpty { for child in children { guard try addReference(child) else { return false } @@ -857,8 +534,8 @@ final class NativePreviewBuild { .objc(.method("absolutePathForBuildParameters:", as: ((AnyObject) -> AnyObject?).self))) guard let path = try unsafe absolutePath.unsafeInvoke(buildParameters) as? String, path.hasPrefix("/") else { return false } let url = URL(filePath: path).standardizedFileURL - if try boolean(reference, selector: "isProductReference") - || optionalString(reference, selector: "sourceTree") == "BUILT_PRODUCTS_DIR" { + if try NativeObjCGetters.boolean(reference, selector: "isProductReference") + || NativeObjCGetters.optionalString(reference, selector: "sourceTree") == "BUILT_PRODUCTS_DIR" { products.insert(url) } else { files.insert(url) @@ -869,7 +546,7 @@ final class NativePreviewBuild { guard try addReference(group) else { return nil } } for phase in phases { - if try boolean(phase, selector: "runOnlyForDeploymentPostprocessing") { + if try NativeObjCGetters.boolean(phase, selector: "runOnlyForDeploymentPostprocessing") { let deployment = try await serviceType.resolve( .swift( .method( @@ -880,12 +557,12 @@ final class NativePreviewBuild { if !postprocessing { continue } } if phase.responds(to: NSSelectorFromString("inputPaths")) { - let inputs: [String] = try array(phase, selector: "inputPaths") - let inputLists: [String] = try array(phase, selector: "inputFileListPaths") - let outputs: [String] = try array(phase, selector: "outputPaths") - let outputLists: [String] = try array(phase, selector: "outputFileListPaths") + let inputs: [String] = try NativeObjCGetters.array(phase, selector: "inputPaths") + let inputLists: [String] = try NativeObjCGetters.array(phase, selector: "inputFileListPaths") + let outputs: [String] = try NativeObjCGetters.array(phase, selector: "outputPaths") + let outputLists: [String] = try NativeObjCGetters.array(phase, selector: "outputFileListPaths") guard inputLists.isEmpty, outputLists.isEmpty, - try !boolean(phase, selector: "alwaysOutOfDate") else { return nil } + try !NativeObjCGetters.boolean(phase, selector: "alwaysOutOfDate") else { return nil } let evaluate = try await serviceType.resolve( .swift( .method( @@ -906,11 +583,11 @@ final class NativePreviewBuild { files.insert(URL(filePath: path).standardizedFileURL) } } - let buildFiles: [NSObject] = try array(phase, selector: "buildFiles") + let buildFiles: [NSObject] = try NativeObjCGetters.array(phase, selector: "buildFiles") for file in buildFiles { - if let reference = try object(file, selector: "fileReference") as? NSObject { + if let reference = try NativeObjCGetters.object(file, selector: "fileReference") as? NSObject { guard try addReference(reference) else { return nil } - } else if try object(file, selector: "productReference") == nil { + } else if try NativeObjCGetters.object(file, selector: "productReference") == nil { return nil } } @@ -934,7 +611,7 @@ final class NativePreviewBuild { .swift(.getter("(extension in IDEXCBuildSupportCore):__C.IDEWorkspace.xcbuildDataCachePath.getter : __C.DVTFilePath?", as: (() -> AnyObject?).self)) ) guard let cachePath = try unsafe getCache.unsafeInvoke(), - let cacheURL = try object(cachePath, selector: "fileURL") as? URL, + let cacheURL = try NativeObjCGetters.object(cachePath, selector: "fileURL") as? URL, cacheURL.isFileURL, cacheURL.path.hasPrefix("/") else { return nil } let manifest = cacheURL.appendingPathComponent(identifier + ".xcbuilddata", isDirectory: true) .appendingPathComponent("manifest.json") @@ -947,8 +624,8 @@ final class NativePreviewBuild { private func dependencyGraph(for buildables: NativeSwiftValue, workspace: AnyObject, priorBuild: AnyObject) async throws -> (AnyObject, [NSObject]) { - guard let service = try object(workspace, selector: "buildSystemService"), - let parameters = try object(priorBuild, selector: "buildParameters") else { + guard let service = try NativeObjCGetters.object(workspace, selector: "buildSystemService"), + let parameters = try NativeObjCGetters.object(priorBuild, selector: "buildParameters") else { throw NativeRuntimeError.unsupportedContract("The native build has no dependency query context") } guard let selectedBuildables = try buildables.withCopy({ $0 as? [NSObject] }) else { @@ -1003,7 +680,7 @@ final class NativePreviewBuild { } edges[identifier] = dependencies pending.append(contentsOf: dependencies.reversed()) - guard let blueprint = try object(buildable, selector: "blueprint") as? NSObject else { + guard let blueprint = try NativeObjCGetters.object(buildable, selector: "blueprint") as? NSObject else { throw NativeRuntimeError.unsupportedContract("A native dependency buildable has no blueprint") } if let resourceClass, blueprint.isKind(of: resourceClass) { @@ -1173,11 +850,11 @@ final class NativePreviewBuild { let productType = try runtime.object(buildable).resolveAndWait(.objc(.method("productTypeIdentifier", as: (() -> String?).self))) guard let identifier = try unsafe productType.unsafeInvoke(), identifier == "com.apple.product-type.framework" || identifier == "com.apple.product-type.library.dynamic" else { return false } - guard let blueprint = try object(buildable, selector: "blueprint") as? NSObject, + guard let blueprint = try NativeObjCGetters.object(buildable, selector: "blueprint") as? NSObject, blueprint.responds(to: NSSelectorFromString("isValid")) else { return false } let valid = try runtime.object(blueprint).resolveAndWait(.objc(.method("isValid", as: (() -> Bool).self))) guard try unsafe valid.unsafeInvoke(), - let provider = try object(blueprint, selector: "blueprintProvider") as? NSObject else { return false } + let provider = try NativeObjCGetters.object(blueprint, selector: "blueprintProvider") as? NSObject else { return false } guard let package = NSProtocolFromString("IDESourcePackage") else { throw NativeRuntimeError.unsupportedContract("The native source package protocol is unavailable") } @@ -1228,7 +905,7 @@ final class NativePreviewBuild { private func sanitizerEnvironment(for buildable: AnyObject, priorBuild: AnyObject, scheme: AnyObject, destination: AnyObject) throws -> [String: String] { - guard let action = try object(scheme, selector: "launchSchemeAction") else { return [:] } + guard let action = try NativeObjCGetters.object(scheme, selector: "launchSchemeAction") else { return [:] } let address = try runtime.object(action).resolveAndWait(.objc(.method("enableAddressSanitizer", as: (() -> Bool).self))) let thread = try runtime.object(action).resolveAndWait(.objc(.method("enableThreadSanitizer", as: (() -> Bool).self))) var sanitizers: [String] = [] @@ -1267,8 +944,8 @@ final class NativePreviewBuild { private func compileCommandLine(for target: Target, buildable: AnyObject, buildVariant: String, priorBuild: AnyObject, workspace: AnyObject, source: URL) async throws -> [String] { - guard let service = try object(workspace, selector: "buildSystemService"), - let blueprint = try object(buildable, selector: "blueprint"), + guard let service = try NativeObjCGetters.object(workspace, selector: "buildSystemService"), + let blueprint = try NativeObjCGetters.object(buildable, selector: "blueprint"), let parametersClass = NSClassFromString("IDEBuildParameters"), let pathClass = NSClassFromString("DVTFilePath") else { throw NativeRuntimeError.unsupportedContract("The native build has no preview compilation context") @@ -1311,200 +988,6 @@ final class NativePreviewBuild { } } - private func object(_ receiver: AnyObject, selector: String) throws -> AnyObject? { - let get = try runtime.object(receiver).resolveAndWait(.objc(.method(selector, as: (() -> AnyObject?).self))) - return try unsafe get.unsafeInvoke() - } - - private func boolean(_ receiver: AnyObject, selector: String) throws -> Bool { - let get = try runtime.object(receiver).resolveAndWait(.objc(.method(selector, as: (() -> Bool).self))) - return try unsafe get.unsafeInvoke() - } - - private func array(_ receiver: AnyObject, selector: String) throws -> [Value] { - guard let value = try object(receiver, selector: selector) else { return [] } - guard let values = value as? [Value] else { - throw NativeRuntimeError.unsupportedContract("The native \(selector) value is not an array of \(Value.self)") - } - return values - } - - private func optionalString(_ receiver: AnyObject?, selector: String) throws -> String? { - guard let receiver, let object = receiver as? NSObject, - object.responds(to: NSSelectorFromString(selector)) else { return nil } - let get = try runtime.object(receiver).resolveAndWait(.objc(.method(selector, as: (() -> String?).self))) - return try unsafe get.unsafeInvoke() - } - - private func destinationContext(_ destination: AnyObject?) throws -> DestinationContext? { - guard let destination else { return nil } - let device = try object(destination, selector: "targetDevice") - let sdk = try object(destination, selector: "targetSDK") - let variant = try object(destination, selector: "targetSDKVariant") - let hostPlatform = try object(destination, selector: "hostTargetedPlatform") - let available: Bool? - if let device { - let get = try runtime.object(device).resolveAndWait(.objc(.method("isAvailable", as: (() -> Bool).self))) - available = try unsafe get.unsafeInvoke() - } else { available = nil } - return try DestinationContext(identifier: optionalString(device, selector: "identifier") - ?? optionalString(destination, selector: "targetIdentifier"), - architecture: optionalString(destination, selector: "targetArchitecture"), - sdk: optionalString(sdk, selector: "canonicalName"), variant: optionalString(variant, selector: "name"), - hostPlatform: optionalString(hostPlatform, selector: "identifier"), - runtimeVersion: optionalString(device, selector: "operatingSystemVersion"), available: available) - } - - @safe - private struct DestinationPreparation { - let properties: NativeSwiftMethod<() -> NativeSwiftValue> - let platform: NativeSwiftMethod<() -> NativeSwiftValue> - let identifier: NativeSwiftMethod<() -> NativeSwiftValue> - let version: NativeSwiftMethod<() -> NativeSwiftValue> - let platformName: NativeSwiftMethod<() -> String> - let identifierString: NativeSwiftMethod<() -> String> - let versionString: NativeSwiftMethod<() -> String> - let model: NativeSwiftMethod<() -> String?> - let name: NativeSwiftMethod<() -> String?> - let specifier: NativeSwiftMethod<() -> String?> - } - - private func prepareDestinationProperties() async throws -> DestinationPreparation { - if let destinationPreparation { return destinationPreparation } - let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) - let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) - let recipeType = try await runtime.resolve(.swift(.type("PreviewsPipeline.AnyRunDestinationRecipe")), in: pipeline) - let propertiesType = try await runtime.resolve(.swift(.type("PreviewsPipeline.RunDestinationProperties")), in: pipeline) - let platformType = try await runtime.resolve(.swift(.type("PreviewsPipeline.Platform")), in: pipeline) - let identifierType = try await runtime.resolve(.swift(.type("PreviewsPipeline.DeviceIdentifier")), in: pipeline) - let versionType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.VersionNumber")), in: foundation) - func getter(_ type: NativeSwiftType, _ declaration: String, _ value: Value.Type, - result: NativeSwiftType? = nil) async throws -> NativeSwiftMethod<() -> Value> { - try await type.resolve( - .swift( - .getter( - declaration, as: (() -> Value).self, valueABIs: try result.map { [$0: try NativeType.opaque(named: $0.name)] } ?? [:], - receiverABI: .opaque(named: type.name)))) - } - let preparation = try await DestinationPreparation( - properties: getter(recipeType, "properties.getter : PreviewsPipeline.RunDestinationProperties", NativeSwiftValue.self, result: propertiesType), - platform: getter(propertiesType, "platform.getter : PreviewsPipeline.Platform", NativeSwiftValue.self, result: platformType), - identifier: getter(propertiesType, "deviceIdentifier.getter : PreviewsPipeline.DeviceIdentifier", NativeSwiftValue.self, result: identifierType), - version: getter(propertiesType, "runtimeVersion.getter : PreviewsFoundationHost.VersionNumber", NativeSwiftValue.self, result: versionType), - platformName: getter(platformType, "name.getter : Swift.String", String.self), - identifierString: getter(identifierType, "stringValue.getter : Swift.String", String.self), - versionString: getter(versionType, "description.getter : Swift.String", String.self), - model: getter(propertiesType, "deviceModel.getter : Swift.String?", String?.self), - name: getter(propertiesType, "deviceName.getter : Swift.String?", String?.self), - specifier: getter(propertiesType, "deviceSpecifier.getter : Swift.String?", String?.self)) - destinationPreparation = preparation - return preparation - } - - private func destinationInfo(_ destination: AnyObject, recipe: NativeSwiftValue, prepared: DestinationPreparation) throws -> Destination { - let device = try object(destination, selector: "targetDevice") - let sdk = try object(destination, selector: "targetSDK") - let platform = try sdk.flatMap { try object($0, selector: "platform") } - let identifier = try optionalString(device, selector: "identifier") - ?? optionalString(destination, selector: "targetIdentifier") - guard let identifier else { - throw NativeRuntimeError.unsupportedContract("The native run destination has no identifier") - } - let platformIdentifier = try optionalString(platform, selector: "identifier") - let isMacCatalyst: Bool - if platformIdentifier == "com.apple.platform.macosx" { - let getter = try runtime.object(destination).resolveAndWait(.objc(.method("isMacCatalyst", as: (() -> Bool).self))) - isMacCatalyst = try unsafe getter.unsafeInvoke() - } else { isMacCatalyst = false } - let properties = try unsafe prepared.properties.unsafeInvoke(on: recipe) - let nativePlatform = try unsafe prepared.platform.unsafeInvoke(on: properties) - let nativeIdentifier = try unsafe prepared.identifier.unsafeInvoke(on: properties) - let version = try unsafe prepared.version.unsafeInvoke(on: properties) - let model = try unsafe prepared.model.unsafeInvoke(on: properties) - ?? prepared.name.unsafeInvoke(on: properties) ?? prepared.specifier.unsafeInvoke(on: properties) - let previewIdentifier = try unsafe prepared.identifierString.unsafeInvoke(on: nativeIdentifier) - let platformName = try unsafe prepared.platformName.unsafeInvoke(on: nativePlatform) - let systemVersion = try unsafe prepared.versionString.unsafeInvoke(on: version) - return Destination(value: destination, recipe: recipe, identifier: identifier, previewIdentifier: previewIdentifier, - platformIdentifier: platformIdentifier, - previewPlatform: NativePreviewPlatform(platformIdentifier: platformIdentifier, isMacCatalyst: isMacCatalyst), - platformName: platformName, - deviceModelName: model, systemVersion: systemVersion) - } - - struct PlanningContext { - fileprivate let scheme: AnyObject - fileprivate let schemeIdentifier: NSObject? - fileprivate let environment: AnyObject - fileprivate let activeDestination: DestinationContext? - fileprivate let destination: DestinationContext? - - func matches(_ other: PlanningContext) -> Bool { - let sameScheme: Bool - switch (schemeIdentifier, other.schemeIdentifier) { - case let (left?, right?): sameScheme = left.isEqual(right) - case (nil, nil): sameScheme = scheme === other.scheme - default: sameScheme = false - } - return sameScheme && environment === other.environment - && activeDestination == other.activeDestination && destination == other.destination - } - } - - fileprivate struct DestinationContext: Equatable { - let identifier: String? - let architecture: String? - let sdk: String? - let variant: String? - let hostPlatform: String? - let runtimeVersion: String? - let available: Bool? - } - - struct DestinationResolution { - fileprivate let host: AnyObject - fileprivate let preferences: NativeSwiftValue - let available: JSONValue? - let errors: [String] - } - - struct DestinationSelection { - let selected: Destination - let resolution: DestinationResolution - - var available: JSONValue? { resolution.available } - var errors: [String] { resolution.errors } - } - - struct Destination { - let value: AnyObject - let recipe: NativeSwiftValue - let identifier: String - let previewIdentifier: String - let platformIdentifier: String? - let previewPlatform: NativePreviewPlatform? - let platformName: String? - let deviceModelName: String? - let systemVersion: String? - } - - func frameworkAgent(for destination: DestinationSelection) async throws -> URL { - try Task.checkCancellation() - let recipe = destination.selected.recipe - let bundleType = try await runtime.resolve( - .swift(.type("PreviewsPipeline.PreviewAgentBundle")), in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) - let make = try await recipe.type.resolve( - .swift( - .method( - "makeFrameworkAgent() throws -> PreviewsPipeline.PreviewAgentBundle", as: (() throws -> NativeSwiftValue).self, - valueABIs: [bundleType: .opaque(named: bundleType.name)], receiverABI: .opaque(named: recipe.type.name)))) - let bundle = try unsafe make.unsafeInvoke(on: recipe) - let url = try await bundleType.resolve( - .swift(.getter("url.getter : Foundation.URL", as: (() -> NativePreviewBuildURL).self, receiverABI: .opaque(named: bundleType.name)))) - try Task.checkCancellation() - return try unsafe url.unsafeInvoke(on: bundle).value - } - @MainActor private final class Cancellation { private let action: () throws -> Void @@ -1533,7 +1016,7 @@ package func nativePreviewArray(_ values: [Any]) throws -> [Element] { } } -private struct NativePreviewBuildURL: ABIBridgeSwiftValue { +struct NativePreviewBuildURL: ABIBridgeSwiftValue { let value: URL static let swiftABIType: NativeType = try! .opaque(named: "Foundation.URL") } @@ -1549,680 +1032,7 @@ private struct NativePreviewMacroOverrides: ABIBridgeSwiftValue { } @MainActor -extension NativePreviewBuild { - struct Source { - let translationUnit: NativeSwiftValue - let definition: NativeSwiftValue - } - - private struct SourcePlan { - let value: NativeSwiftValue - let recordType: NativeSwiftType - let agentType: NativeSwiftType - let packRecordType: NativeSwiftType - let referenceType: NativeSwiftType - } - - func withSourceSelection(workspace: AnyObject, - operation: @MainActor () async throws -> Output) async throws -> Output { - let workspaceID = ObjectIdentifier(workspace) - try Task.checkCancellation() - if sourceSelections[workspaceID] == nil { - sourceSelections[workspaceID] = [] - } else { - let identifier = UUID() - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - if Task.isCancelled { continuation.resume(throwing: CancellationError()) } - else { sourceSelections[workspaceID, default: []].append(.init(identifier: identifier, continuation: continuation)) } - } - } onCancel: { - Task { @MainActor in - guard let index = self.sourceSelections[workspaceID]?.firstIndex(where: { $0.identifier == identifier }) else { return } - let waiter = self.sourceSelections[workspaceID]!.remove(at: index) - waiter.continuation.resume(throwing: CancellationError()) - } - } - } - defer { - if let waiter = sourceSelections[workspaceID]?.first { - sourceSelections[workspaceID]!.removeFirst() - waiter.continuation.resume() - } else { sourceSelections[workspaceID] = nil } - withExtendedLifetime(workspace) {} - } - try Task.checkCancellation() - return try await operation() - } - - func resolveDestination(workspace: AnyObject, input: NativeSwiftValue) async throws -> DestinationResolution { - try Task.checkCancellation() - let previews = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) - let createHost = try await runtime.object(workspace).resolve( - .swift( - .method( - "(extension in PreviewsXcode):__C.IDEWorkspace.sceneHost(isNewProjectFromTemplate: Swift.Bool) -> PreviewsXcode.XcodeWorkspaceSceneHost", - as: ((Bool) -> AnyObject).self))) - let host = try unsafe createHost.unsafeInvoke(false) - let resolutionType: NativeSwiftType - do { - resolutionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.DestinationResolution")), in: previews) - } catch is ABIResolutionError { - return try await currentDestinationResolution(host: host, input: input) - } - let actionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction")), in: previews) - let resolve = try await actionType.resolve( - .swift( - .staticMethod( - "static PreviewsXcode.RenderPreviewAction.resolveDestination(input: PreviewsXcode.RenderPreviewAction.Input, sceneHost: PreviewsXcode.XcodeWorkspaceSceneHost) async -> PreviewsXcode.RenderPreviewAction.DestinationResolution", - as: (@concurrent (NativeSwiftValue, AnyObject) async -> NativeSwiftValue).self, - valueABIs: [input.type: .opaque(named: input.type.name), resolutionType: .opaque(named: resolutionType.name)]))) - let resolution = try unsafe await resolve.unsafeInvoke(input, host) - try Task.checkCancellation() - let fields = try resolution.withCopy { Dictionary(uniqueKeysWithValues: Mirror(reflecting: $0).children.compactMap { - field in field.label.map { ($0, field.value) } - }) } - guard let rawPreferences = fields["preferences"] else { - throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no preferences") - } - let preferences = try await _openExistential(rawPreferences, do: nativePreviewOwnedValue) - let errors = (fields["errorMessage"] as? String? ?? nil).map { [$0] } ?? [] - guard let available = fields["availableRenderDestinations"] as? any Encodable else { - throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no encodable destinations") - } - let encodedAvailable = try JSONEncoder().encode(available) - guard let availableJSON = JSONValue(any: try JSONSerialization.jsonObject(with: encodedAvailable, options: .fragmentsAllowed)) else { - throw NativeRuntimeError.unsupportedContract("Native preview destinations have an unsupported JSON representation") - } - return DestinationResolution(host: host, preferences: preferences, - available: availableJSON == .null ? nil : availableJSON, errors: errors) - } - - private func currentDestinationResolution(host: AnyObject, input: NativeSwiftValue) async throws -> DestinationResolution { - let image = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) - let resolver = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.RenderDestinationResolver")), in: image) - let recipe = try await runtime.resolve(.swift(.type("PreviewsPipeline.AnyRunDestinationRecipe")), - in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) - let array = try await runtime.resolve(.swift(.type("Swift.Array", genericArguments: [.type(recipe)]))) - // The catalog wrappers have only optimizer-specialized entry points. - // Keep their native feature gate and use the scene host's callable API. - let offersChoice = UserDefaults.standard.object(forKey: "UVRenderPreviewOffersRenderDestinationChoice") as? Bool ?? true - guard offersChoice else { - let preferences = try await runtime.resolve(.swift(.type("PreviewsPipeline.DestinationPreferences")), - in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) - let empty = try await preferences.resolve(.swift(.staticGetter("empty", - as: (() -> NativeSwiftValue).self, valueABIs: [preferences: .opaque(named: preferences.name)]))) - return DestinationResolution(host: host, preferences: try unsafe empty.unsafeInvoke(), available: nil, errors: []) - } - let timeoutType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Timeout")), - in: .path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks"))) - let makeTimeout = try await timeoutType.resolve(.swift(.staticMethod("seconds(_:)", - as: ((Double) -> NativeSwiftValue).self, valueABIs: [timeoutType: .opaque(named: timeoutType.name)]))) - let timeout = try unsafe makeTimeout.unsafeInvoke(10) - let catalog = try await runtime.object(host).resolve(.swift(.method( - "(awaitAvailableRunDestinations in _8779CD8E26326606F5A569AC41E16EDA)(timeout: PreviewsFoundationHost.Timeout) async -> [PreviewsPipeline.AnyRunDestinationRecipe]", - as: (@concurrent (NativeSwiftValue) async -> NativeSwiftValue).self, - valueABIs: [timeoutType: .opaque(named: timeoutType.name), array: .pointer]))) - let nativeCatalog = try unsafe await catalog.unsafeInvoke(timeout) - let prepared = try await prepareDestinationProperties() - let platform = try await runtime.resolve(.swift(.type("PreviewsPipeline.Platform")), - in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) - let canonicalIdentifier = try await platform.resolve(.swift(.getter("canonicalIdentifier", - as: (() -> String).self, receiverABI: .opaque(named: platform.name)))) - func catalogValues(_ values: Recipes) async throws -> (NativeSwiftValue, JSONValue) { - var filtered: [Recipes.Element] = [] - var external: [JSONValue] = [] - for value in values { - let native = try await nativePreviewOwnedValue(value) - let properties = try unsafe prepared.properties.unsafeInvoke(on: native) - let nativePlatform = try unsafe prepared.platform.unsafeInvoke(on: properties) - let identifier = try unsafe canonicalIdentifier.unsafeInvoke(on: nativePlatform) - guard !["xros", "xrsimulator"].contains(identifier) else { continue } - filtered.append(value) - let nativeIdentifier = try unsafe prepared.identifier.unsafeInvoke(on: properties) - let version = try unsafe prepared.version.unsafeInvoke(on: properties) - var item: [String: JSONValue] = try unsafe [ - "identifier": .string(prepared.identifierString.unsafeInvoke(on: nativeIdentifier)), - "platformName": .string(prepared.platformName.unsafeInvoke(on: nativePlatform)), - "systemVersion": .string(prepared.versionString.unsafeInvoke(on: version)), - ] - if let model = try unsafe prepared.model.unsafeInvoke(on: properties) - ?? prepared.name.unsafeInvoke(on: properties) ?? prepared.specifier.unsafeInvoke(on: properties) { - item["deviceModelName"] = .string(model) - } - external.append(.object(item)) - } - return (try await nativePreviewOwnedValue(filtered), .array(external)) - } - let values = try nativeCatalog.withCopy { value in - guard let values = value as? any Collection else { - throw NativeRuntimeError.unsupportedContract("Native preview destination catalog is not a collection") - } - return values - } - let (recipes, available) = try await _openExistential(values, do: catalogValues) - let preferred = try input.withCopy { value in - guard let field = Mirror(reflecting: value).children.first(where: { $0.label == "preferredRenderDestination" }) else { - throw NativeRuntimeError.unsupportedContract("Native preview input has no render destination selection") - } - return field.value - } - let selection = try await _openExistential(preferred, do: nativePreviewOwnedValue) - let resolutionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.RenderDestinationResolver.Resolution")), in: image) - let resolve = try await resolver.resolve(.swift(.staticMethod("resolve(selection:catalog:)", - as: ((NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [selection.type: .opaque(named: selection.type.name), recipes.type: .pointer, - resolutionType: .opaque(named: resolutionType.name)]))) - let resolution = try unsafe resolve.unsafeInvoke(selection, recipes) - let fields = try resolution.withCopy { Dictionary(uniqueKeysWithValues: Mirror(reflecting: $0).children.compactMap { - field in field.label.map { ($0, field.value) } - }) } - guard let rawPreferences = fields["selection"] else { - throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no preferences") - } - let preferences = try await _openExistential(rawPreferences, do: nativePreviewOwnedValue) - guard let nativeErrors = fields["errors"] as? any Encodable else { - throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no encodable errors") - } - struct Message: Decodable { var message: String } - let errors = try JSONDecoder().decode([Message].self, from: JSONEncoder().encode(nativeErrors)).map(\.message) - return DestinationResolution(host: host, preferences: preferences, available: available, errors: errors) - } - - func destinationResolution(_ lhs: DestinationResolution, matches rhs: DestinationResolution) async throws -> Bool { - guard lhs.available == rhs.available, lhs.errors == rhs.errors else { return false } - let type = lhs.preferences.type - let equals = try await type.resolve( - .swift( - .staticMethod( - "== infix(PreviewsPipeline.DestinationPreferences, PreviewsPipeline.DestinationPreferences) -> Swift.Bool", - as: ((NativeSwiftValue, NativeSwiftValue) -> Bool).self, valueABIs: [type: .opaque(named: type.name)]))) - return try unsafe equals.unsafeInvoke(lhs.preferences, rhs.preferences) - } - - func selectDestination(workspace: AnyObject, source: Source, resolution: DestinationResolution, - metadata: Data? = nil, providerDescription: Data? = nil) async throws -> DestinationSelection { - let evaluatedMetadata: NativeSwiftValue? - if let metadata { evaluatedMetadata = try await decodePreviewValue(metadata, named: "PreviewMetadata") } - else { evaluatedMetadata = nil } - let evaluatedDescription: NativeSwiftValue? - if let providerDescription { evaluatedDescription = try await decodePreviewValue(providerDescription, named: "PreviewDescription") } - else { evaluatedDescription = nil } - return try await withSourceSelection(workspace: workspace) { - guard let pack = try await executionPointPack(source: source, preferences: resolution.preferences, - metadata: evaluatedMetadata, providerDescription: evaluatedDescription) else { throw NativePipelineRequired() } - let plan = try await sourcePlan(workspace: workspace, host: resolution.host, source: source, pack: pack) - let record = try await sourcePlanRecord(plan, pack: pack) - let prepared = try await prepareDestinationProperties() - let recipeType = try await runtime.resolve( - .swift(.type("PreviewsPipeline.AnyRunDestinationRecipe")), in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) - let recipe = try await sourceGetter(record, "destination.getter : PreviewsPipeline.AnyRunDestinationRecipe", resultType: recipeType) - let representation = try await sourceGetter(record, "destinationRepresentation.getter : C", resultType: plan.referenceType) - guard let destination = try representation.withCopy({ - Mirror(reflecting: $0).children.first { $0.label == "runDestination" }?.value as? NSObject - }) else { throw NativeRuntimeError.unsupportedContract("Native preview plan has no IDERunDestination representation") } - let selected = try destinationInfo(destination, recipe: recipe, prepared: prepared) - guard NativePreviewPlatform.supportsDestination(platformIdentifier: selected.platformIdentifier, identifier: selected.identifier) else { - throw NativePipelineRequired() - } - return DestinationSelection(selected: selected, resolution: resolution) - } - } - - private func sourceGetter(_ value: NativeSwiftValue, _ name: String, resultType: NativeSwiftType, - resultABI: NativeType? = nil) async throws -> NativeSwiftValue { - let getter = try await value.type.resolve( - .swift( - .getter( - name, as: (() -> NativeSwiftValue).self, valueABIs: [resultType: try resultABI ?? .opaque(named: resultType.name)], - receiverABI: .opaque(named: value.type.name)))) - return try unsafe getter.unsafeInvoke(on: value) - } - - func isWidgetPreview(metadata: Data) async throws -> Bool { - try await hasContentDomain("widget", metadata: metadata) - } - - func isComplicationPreview(metadata: Data) async throws -> Bool { - try await hasContentDomain("complication", metadata: metadata) - } - - private func hasContentDomain(_ name: String, metadata: Data) async throws -> Bool { - let metadata = try await decodePreviewValue(metadata, named: "PreviewMetadata") - let domainType = try await runtime.resolve( - .swift(.type("PreviewsMessagingHost.PreviewContentDomain")), in: .path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks"))) - let domain = try await sourceGetter(metadata, - "contentDomain.getter : PreviewsMessagingHost.PreviewContentDomain", resultType: domainType) - let expected = try domainType.makeEnumCase(named: name) - return try domain.withCopy { value in - guard let value = value as? any Equatable else { - throw NativeRuntimeError.unsupportedContract("The native preview content domain is not Equatable") - } - func compare(_ value: Value) throws -> Bool { - try expected.withCopy { $0 as? Value == value } - } - return try _openExistential(value, do: compare) - } - } - - func decodePreviewValue(_ data: Data, named name: String) async throws -> NativeSwiftValue { - guard let dictionary = try unsafe PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else { - throw NativeRuntimeError.invocation("The preview metadata is not a serializable dictionary") - } - let propertyListType = try await runtime.resolve( - .swift(.type("PreviewsFoundationHost.PropertyList")), in: .path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks"))) - let nativeDictionary = try await nativePreviewOwnedValue(dictionary) - let makePropertyList = try await propertyListType.resolve( - .swift( - .initializer( - "init(serializableDictionary:)", as: ((NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [nativeDictionary.type: .pointer, propertyListType: .opaque(named: propertyListType.name)]))) - let propertyList = try unsafe makePropertyList.unsafeInvoke(nativeDictionary) - let metadataType = try await runtime.resolve( - .swift(.type("PreviewsMessagingHost.\(name)")), in: .path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks"))) - let decode = try await metadataType.resolve( - .swift( - .initializer( - "init(propertyListValue: PreviewsFoundationHost.PropertyList) throws -> \(metadataType.name)", - as: ((NativeSwiftValue) throws -> NativeSwiftValue).self, - valueABIs: [propertyListType: .opaque(named: propertyListType.name), metadataType: .opaque(named: metadataType.name)]))) - return try unsafe decode.unsafeInvoke(propertyList) - } - - private func effectivePreferences(_ operation: NativeSwiftValue, instance: NativeSwiftValue) async throws -> NativeSwiftValue { - let type = operation.type - let emptyGetter = try await type.resolve( - .swift( - .staticGetter( - "empty.getter : PreviewsPipeline.DestinationPreferences", as: (() -> NativeSwiftValue).self, valueABIs: [type: .opaque(named: type.name)]))) - let empty = try unsafe emptyGetter.unsafeInvoke() - let equals = try await type.resolve( - .swift( - .staticMethod( - "== infix(PreviewsPipeline.DestinationPreferences, PreviewsPipeline.DestinationPreferences) -> Swift.Bool", - as: ((NativeSwiftValue, NativeSwiftValue) -> Bool).self, valueABIs: [type: .opaque(named: type.name)]))) - guard try unsafe equals.unsafeInvoke(operation, empty) else { return try operation.copy() } - let getter = try await instance.type.resolve( - .swift( - .getter( - "PreviewsPipeline.PreviewInstanceProtocol.destinationPreferences.getter : PreviewsPipeline.DestinationPreferences", - as: (() -> NativeSwiftValue).self, valueABIs: [type: .opaque(named: type.name)]))) - return try unsafe getter.unsafeInvoke(on: instance) - } - - private func executionPointPack(source: Source, preferences: NativeSwiftValue, - metadata: NativeSwiftValue?, providerDescription: NativeSwiftValue?) async throws -> NativeSwiftValue? { - let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) - let executionSource: NativeSwiftValue - let role: NativeSwiftValue - let effectivePreferences: NativeSwiftValue - if let definition = try await source.definition.copyEnumPayload(forCase: "registryPreview") { - let instanceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewInstance")), in: pipeline) - let makeInstance = try await instanceType.resolve( - .swift( - .staticMethod( - "registryPreview(definition: PreviewsModel.RegistryDefinition) -> PreviewsPipeline.PreviewInstance", - as: ((NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [definition.type: .opaque(named: definition.type.name), instanceType: .opaque(named: instanceType.name)]))) - let instance = try unsafe makeInstance.unsafeInvoke(definition.copy()) - let registryType = try await runtime.resolve(.swift(.type("PreviewsPipeline.RegistryPreviewInstance")), in: pipeline) - let optionalType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(registryType)]))) - let registryGetter = try await instanceType.resolve( - .swift( - .getter( - "registryInstance.getter : PreviewsPipeline.RegistryPreviewInstance?", as: (() -> NativeSwiftValue).self, - valueABIs: [optionalType: .opaque(named: optionalType.name)], receiverABI: .opaque(named: instanceType.name)))) - let optional = try unsafe registryGetter.unsafeInvoke(on: instance) - guard let registry = try await optional.copyEnumPayload(forCase: "some") else { - throw NativeRuntimeError.unsupportedContract("Native preview factory produced no registry instance") - } - func requirement(_ name: String, output: String) async throws -> NativeSwiftValue { - let type = try await runtime.resolve(.swift(.type(output))) - let get = try await registry.type.resolve( - .swift( - .getter( - "PreviewsPipeline.PreviewInstanceProtocol.\(name).getter : \(output)", as: (() -> NativeSwiftValue).self, - valueABIs: [type: .opaque(named: type.name)]))) - return try unsafe get.unsafeInvoke(on: registry) - } - executionSource = try await requirement("source", output: "PreviewsPipeline.ExecutionPointSource") - role = try await requirement("agentRole", output: "PreviewsMessagingHost.PreviewAgentRole") - if metadata != nil { effectivePreferences = try await self.effectivePreferences(preferences, instance: registry) } - else { effectivePreferences = preferences } - } else if let definition = try await source.definition.copyEnumPayload(forCase: "previewProvider") { - let identifierType = try await runtime.resolve(.swift(.type("PreviewsModel.SourceIdentifier"))) - let identifier = try await sourceGetter(definition, "sourceIdentifier.getter : PreviewsModel.SourceIdentifier", resultType: identifierType) - let sourceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointSource")), in: pipeline) - executionSource = try await sourceType.makeEnumCase(named: "sourceFile", payload: identifier) - let roleType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewAgentRole"))) - role = try roleType.makeEnumCase(named: "previews") - if metadata != nil { - guard let providerDescription else { - throw NativeRuntimeError.invocation("The evaluated provider returned no native preview description") - } - let providerSourceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ProviderSource")), in: pipeline) - let providerSource = try await providerSourceType.makeEnumCase(named: "provider", payload: definition.copy()) - let providerType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ProviderPreviewInstance")), in: pipeline) - let initialize = try await providerType.resolve( - .swift( - .initializer( - "init(providerSource: PreviewsPipeline.ProviderSource, previewDescription: PreviewsMessagingHost.PreviewDescription) -> PreviewsPipeline.ProviderPreviewInstance", - as: ((NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [ - providerSourceType: .opaque(named: providerSourceType.name), - providerDescription.type: .opaque(named: providerDescription.type.name), providerType: .opaque(named: providerType.name), - ]))) - let provider = try unsafe initialize.unsafeInvoke(providerSource, providerDescription.copy()) - effectivePreferences = try await self.effectivePreferences(preferences, instance: provider) - } else { effectivePreferences = preferences } - } else { return nil } - let requirementsType = try await runtime.resolve(.swift(.type("PreviewsPipeline.DestinationRequirements")), in: pipeline) - // Native preflight and RenderPreview's evaluated Location use none. - // The registry instance's requirements witness is unavailable. - let none = try await requirementsType.resolve( - .swift( - .staticGetter( - "none.getter : PreviewsPipeline.DestinationRequirements", as: (() -> NativeSwiftValue).self, - valueABIs: [requirementsType: .opaque(named: requirementsType.name)]))) - let requirements = try unsafe none.unsafeInvoke() - let domainType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewContentDomain"))) - let optionalDomainType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(domainType)]))) - let domain: NativeSwiftValue - if let metadata { - let contentDomain = try await sourceGetter(metadata, "contentDomain.getter : PreviewsMessagingHost.PreviewContentDomain", resultType: domainType) - let some = try await runtime.resolve( - .swift( - .function( - "XcodeMCPNativeRuntime.nativePreviewSome(A) -> A?", as: ((NativeSwiftValue) -> NativeSwiftValue).self, - genericArguments: [.type(domainType)], - valueABIs: [domainType: .opaque(named: domainType.name), optionalDomainType: .opaque(named: optionalDomainType.name)]))) - domain = try unsafe some.unsafeInvoke(contentDomain) - } else { - let propertiesType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointProperties")), in: pipeline) - let defaults = try await propertiesType.resolve( - .swift( - .staticGetter( - "default.getter : PreviewsPipeline.ExecutionPointProperties", as: (() -> NativeSwiftValue).self, - valueABIs: [propertiesType: .opaque(named: propertiesType.name)]))) - let properties = try unsafe defaults.unsafeInvoke() - let domainGetter = try await propertiesType.resolve( - .swift( - .getter( - "previewContentDomain.getter : PreviewsMessagingHost.PreviewContentDomain?", as: (() -> NativeSwiftValue).self, - valueABIs: [optionalDomainType: .opaque(named: optionalDomainType.name)], receiverABI: .opaque(named: propertiesType.name)))) - domain = try unsafe domainGetter.unsafeInvoke(on: properties) - } - let packType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointPack")), in: pipeline) - let create = try await packType.resolve( - .swift( - .initializer( - "init(executionPointSource: PreviewsPipeline.ExecutionPointSource, previewAgentRole: PreviewsMessagingHost.PreviewAgentRole, destinationPreferences: PreviewsPipeline.DestinationPreferences, destinationRequirements: PreviewsPipeline.DestinationRequirements, previewContentDomain: PreviewsMessagingHost.PreviewContentDomain?) -> PreviewsPipeline.ExecutionPointPack", - as: ((NativeSwiftValue, NativeSwiftValue, NativeSwiftValue, NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [ - executionSource.type: .opaque(named: executionSource.type.name), role.type: .opaque(named: role.type.name), - preferences.type: .opaque(named: preferences.type.name), requirementsType: .opaque(named: requirementsType.name), - optionalDomainType: .opaque(named: optionalDomainType.name), packType: .opaque(named: packType.name), - ]))) - return try unsafe create.unsafeInvoke(executionSource.copy(), role.copy(), effectivePreferences.copy(), requirements.copy(), domain.copy()) - } - - private func sourceArray(_ values: [NativeSwiftValue], elementType: NativeSwiftType) async throws -> NativeSwiftValue { - let cast = try await runtime.resolve( - .swift( - .function( - "XcodeMCPNativeRuntime.nativePreviewArray([Any]) throws -> [A]", as: (([Any]) throws -> NativeSwiftValue).self, - genericArguments: [.type(elementType)]))) - let copies = try values.map { try $0.withCopy { $0 } } - return try unsafe cast.unsafeInvoke(copies) - } - - private func sourcePlan(workspace: AnyObject, host: AnyObject, source: Source, pack: NativeSwiftValue) async throws -> SourcePlan { - let previews = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) - let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) - let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) - let hostType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeWorkspaceSceneHost")), in: previews) - let getScene = try await hostType.resolve( - .swift(.getter("workspaceScene.getter : PreviewsScenes.WorkspaceScene?", as: (() -> AnyObject?).self))) - guard let scene = try unsafe getScene.unsafeInvoke(on: host) else { - throw NativeRuntimeError.unsupportedContract("Native preview scene host has no workspace scene") - } - let fileType = try await runtime.resolve(.swift(.type("PreviewsPipeline.URLPreviewFileDescription")), in: pipeline) - let sceneType = try await runtime.resolve( - .swift(.type("PreviewsScenes.WorkspaceScene", genericArguments: [.type(fileType)])), - in: .path(installation.framework("PreviewsScenes", in: "SharedFrameworks"))) - let optionalUnitType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(source.translationUnit.type)]))) - let originalGetter = try await sceneType.resolve( - .swift( - .getter( - "agenticTranslationUnit.getter : PreviewsPipeline.PreviewTranslationUnit?", as: (() -> NativeSwiftValue).self, - valueABIs: [optionalUnitType: .opaque(named: optionalUnitType.name)]))) - let setter = try await sceneType.resolve( - .swift( - .setter( - "agenticTranslationUnit.setter : PreviewsPipeline.PreviewTranslationUnit?", as: ((NativeSwiftValue) -> Void).self, - valueABIs: [optionalUnitType: .opaque(named: optionalUnitType.name)], receiver: .borrowing))) - let original = try unsafe originalGetter.unsafeInvoke(on: scene) - let some = try await runtime.resolve( - .swift( - .function( - "XcodeMCPNativeRuntime.nativePreviewSome(A) -> A?", as: ((NativeSwiftValue) -> NativeSwiftValue).self, - genericArguments: [.type(source.translationUnit.type)]))) - let unit = try unsafe some.unsafeInvoke(source.translationUnit) - guard let field = Mirror(reflecting: host).children.first(where: { $0.label == "environmentCoalescer" }), - Mirror(reflecting: field.value).displayStyle == .class else { - throw NativeRuntimeError.unsupportedContract("Native preview environment coalescer is unavailable") - } - let coalescer = field.value as AnyObject - let coalescerType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeBuildEnvironmentCoalescer")), in: previews) - let invalidate = try await coalescerType.resolve(.swift(.method("setNeedsUpdate() -> ()", as: (() -> Void).self))) - let updateType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeBuildEnvironmentCoalescer.UpdateResult")), in: previews) - let refresh = try await coalescerType.resolve( - .swift( - .method( - "updated() -> PreviewsXcode.XcodeBuildEnvironmentCoalescer.UpdateResult", as: (() -> NativeSwiftValue).self, - valueABIs: [updateType: .opaque(named: updateType.name)]))) - let protocolSymbol = try await runtime.resolve( - .swift(.symbol("protocol descriptor for PreviewsIDEAPI.IDESchemeTaskExecutor", kind: .data)), - in: .path(installation.framework("PreviewsIDEAPI", in: "PlugIns"))) - let executorMetadata: Any.Type = try unsafe protocolSymbol.withUnsafeAddress { - guard let metadata = unsafe ABISwiftProtocolTypeMetadata($0) else { - throw NativeRuntimeError.unsupportedContract("Native scheme task executor protocol metadata is unavailable") - } - return unsafe unsafeBitCast(metadata, to: Any.Type.self) - } - let supplierFactory = try await runtime.resolve( - .swift( - .function( - "XcodeMCPNativeRuntime.nativePreviewExecutorProvider(Swift.AnyObject) throws -> @Swift.MainActor @Sendable () -> A?", - as: ((AnyObject) throws -> NativeSwiftValue).self, genericArguments: [.type(executorMetadata)]))) - let supplier = try unsafe supplierFactory.unsafeInvoke(workspace) - let callback = try await supplier.copyClosure(as: (@MainActor () -> NativeSwiftValue).self) - let callsiteType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Callsite")), in: foundation) - let makeCallsite = try await callsiteType.resolve( - .swift( - .initializer( - "init(Swift.StaticString, Swift.UInt, Swift.UInt, Swift.StaticString) -> PreviewsFoundationHost.Callsite", - as: ((NativePreviewStaticString, UInt, UInt, NativePreviewStaticString) -> NativeSwiftValue).self, - valueABIs: [callsiteType: .opaque(named: callsiteType.name)]))) - let callsite = try unsafe makeCallsite.unsafeInvoke(NativePreviewStaticString(value: #fileID), #line, #column, NativePreviewStaticString(value: #function)) - let tokenType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.CancellationToken")), in: foundation) - let cancel = try await tokenType.resolve( - .swift( - .method( - "cancel(callsite: PreviewsFoundationHost.Callsite) -> ()", as: ((NativeSwiftValue) -> Void).self, - valueABIs: [callsiteType: .opaque(named: callsiteType.name)], receiverABI: .opaque(named: tokenType.name)))) - let register = try await hostType.resolve( - .swift( - .method( - "registerSchemeTaskExecutorProvider(@Swift.MainActor () -> PreviewsIDEAPI.IDESchemeTaskExecutor?) -> PreviewsFoundationHost.CancellationToken", - as: ((NativeSwiftClosure<@MainActor () -> NativeSwiftValue>) -> NativeSwiftValue).self, - valueABIs: [tokenType: .opaque(named: tokenType.name)]))) - let token = try unsafe register.unsafeInvoke(on: host, callback) - let outcome: Swift.Result - do { - try unsafe setter.unsafeInvoke(on: scene, unit) - try unsafe invalidate.unsafeInvoke(on: coalescer) - outcome = .success(try await makeSourcePlan(host: host, source: source, pack: pack)) - } catch { outcome = .failure(error) } - var failures: [String] = [] - do { - try unsafe setter.unsafeInvoke(on: scene, original.copy()) - try unsafe invalidate.unsafeInvoke(on: coalescer) - _ = try unsafe refresh.unsafeInvoke(on: coalescer) - } catch { failures.append("source input restoration failed: \(error)") } - do { try unsafe cancel.unsafeInvoke(on: token, callsite.copy()) } - catch { failures.append("scheme executor provider cancellation failed: \(error)") } - withExtendedLifetime((protocolSymbol, supplier, callback)) {} - if !failures.isEmpty { - let operation = switch outcome { - case .success: "Native preview source destination selected" - case .failure(let error): String(describing: error) - } - throw NativeRuntimeError.invocation(([operation] + failures).joined(separator: "; ")) - } - return try outcome.get() - } - - private func makeSourcePlan(host: AnyObject, source: Source, pack: NativeSwiftValue) async throws -> SourcePlan { - let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) - let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) - let previews = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) - let executionSourceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointSource")), in: pipeline) - let executionSource = try await pack.type.resolve( - .swift( - .getter( - "executionPointSource.getter : PreviewsPipeline.ExecutionPointSource", as: (() -> NativeSwiftValue).self, - valueABIs: [executionSourceType: .opaque(named: executionSourceType.name)], receiverABI: .opaque(named: pack.type.name)))) - let sourceValue = try unsafe executionSource.unsafeInvoke(on: pack) - let sourceArray = try await sourceArray([sourceValue], elementType: sourceValue.type) - let orderedType = try await runtime.resolve( - .swift(.type("PreviewsFoundationHost.OrderedSet", genericArguments: [.type(sourceValue.type)])), in: foundation) - let initialize = try await orderedType.resolve( - .swift( - .initializer( - "init(A1) -> PreviewsFoundationHost.OrderedSet", - as: ((NativeSwiftValue) -> NativeSwiftValue).self, genericArguments: [.type(sourceArray.type)], - valueABIs: [orderedType: .opaque(named: orderedType.name)]))) - let sources = try unsafe initialize.unsafeInvoke(sourceArray.copy()) - let identifierType = try await runtime.resolve( - .swift(.type("PreviewsModel.SourceIdentifier")), in: .path(installation.framework("PreviewsModel", in: "SharedFrameworks"))) - let identifierGetter = try await source.translationUnit.type.resolve( - .swift( - .getter( - "sourceIdentifier.getter : PreviewsModel.SourceIdentifier", as: (() -> NativeSwiftValue).self, - valueABIs: [identifierType: .opaque(named: identifierType.name)], receiverABI: .opaque(named: source.translationUnit.type.name)))) - let identifier = try unsafe identifierGetter.unsafeInvoke(on: source.translationUnit) - let files = try await self.sourceArray([identifier], elementType: identifierType) - let hostType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeWorkspaceSceneHost")), in: previews) - let makeBuilder = try await hostType.resolve( - .swift(.method("makeBuilder() throws -> PreviewsXcode.XcodeWorkspaceBuilder", as: (() throws -> AnyObject).self))) - let builder = try unsafe makeBuilder.unsafeInvoke(on: host) - let builderType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeWorkspaceBuilder")), in: previews) - let makeGraph = try await builderType.resolve( - .swift( - .method( - "makeBuildGraph(for: PreviewsFoundationHost.OrderedSet, sourceFiles: [PreviewsModel.SourceIdentifier]) async throws -> PreviewsPipeline.WorkspaceGraph>", - as: (@concurrent (NativeSwiftValue, NativeSwiftValue) async throws -> AnyObject).self, - valueABIs: [orderedType: .opaque(named: orderedType.name)]))) - let graph = try unsafe await makeGraph.unsafeInvoke(on: builder, sources, files) - let graphSource = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeGraphSource")), in: previews) - let graphItem = try await runtime.resolve(.swift(.type("PreviewsPipeline.BuildGraphItem", genericArguments: [.type(graphSource)])), in: pipeline) - let graphType = try await runtime.resolve(.swift(.type("PreviewsPipeline.WorkspaceGraph", genericArguments: [.type(graphItem)])), in: pipeline) - let packs = try await self.sourceArray([pack], elementType: pack.type) - let update = try await graphType.resolve( - .swift( - .method( - "makeUpdateGraph, A1: PreviewsPipeline.WorkspaceGraphSource, B1: Swift.Collection, B1.Element == PreviewsPipeline.ExecutionPointPack>(for: B1) throws -> PreviewsPipeline.WorkspaceGraph>", - as: ((NativeSwiftValue) throws -> AnyObject).self, genericArguments: [.type(graphSource), .type(packs.type)]))) - let updateGraph = try unsafe update.unsafeInvoke(on: graph, packs) - let platform = try await runtime.resolve(.swift(.type("PreviewsPipeline.Platform")), in: pipeline) - let components = try await runtime.resolve(.swift(.type("PreviewsXcode.RunDestinationBuildComponents")), in: previews) - guard let destinationClass = NSClassFromString("IDERunDestination") else { - throw NativeRuntimeError.unsupportedContract("Native run destination class is unavailable") - } - let buildIdentifier = try await runtime.resolve( - .swift( - .type("PreviewsXcode.XcodeWorkspaceBuilder.BuildIdentifier", genericArguments: [.type(platform), .type(destinationClass), .type(components)])), - in: previews) - let reference = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeRunDestinationReference")), in: previews) - let arguments: [NativeSwiftGenericArgument] = [.type(graphSource), .type(buildIdentifier), .type(reference)] - let planType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewUpdatePlan", genericArguments: arguments)), in: pipeline) - let recordType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewUpdatePlan.UpdateRecord", genericArguments: arguments)), in: pipeline) - let agentType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewUpdatePlan.AgentRecord", genericArguments: arguments)), in: pipeline) - let packRecordType = try await runtime.resolve( - .swift(.type("PreviewsPipeline.PreviewUpdatePlan.AgentRecord.PackRecord", genericArguments: arguments)), in: pipeline) - let futureType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Future", genericArguments: [.type(planType)])), in: foundation) - let queryGetter = try await hostType.resolve(.swift(.getter("queryManager.getter : PreviewsFoundationHost.QueryManager", as: (() -> AnyObject).self))) - let query = try unsafe queryGetter.unsafeInvoke(on: host) - let graphValue = try await _openExistential(updateGraph as Any, do: nativePreviewOwnedValue) - let queryValue = try await _openExistential(query as Any, do: nativePreviewOwnedValue) - let builderValue = try await _openExistential(builder as Any, do: nativePreviewOwnedValue) - let plan = try await planType.resolve( - .swift( - .staticMethod( - "static PreviewsPipeline.PreviewUpdatePlan.planForUpdating(in: PreviewsPipeline.WorkspaceGraph>, queryManager: PreviewsFoundationHost.QueryManager, workspaceBuilder: A1) throws -> PreviewsFoundationHost.Future>", - as: ((NativeSwiftValue, NativeSwiftValue, NativeSwiftValue) throws -> NativeSwiftValue).self, genericArguments: [.type(builderType)]))) - let future = try unsafe plan.unsafeInvoke(graphValue, queryValue, builderValue) - let awaitValue = try await futureType.resolve( - .swift( - .getter( - "(extension in PreviewsFoundationHost):PreviewsFoundationHost.Future.value.getter : A", - as: (@concurrent () async throws -> NativeSwiftValue).self, declaredAs: "() async throws -> A", - valueABIs: [planType: .opaque(named: planType.name)]))) - return try unsafe await SourcePlan(value: awaitValue.unsafeInvoke(on: future), recordType: recordType, - agentType: agentType, packRecordType: packRecordType, referenceType: reference) - } - - private func sourcePlanRecord(_ plan: SourcePlan, pack: NativeSwiftValue) async throws -> NativeSwiftValue { - let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) - let setType = try await runtime.resolve( - .swift(.type("PreviewsFoundationHost.OrderedIdentifiedSet", genericArguments: [.type(plan.packRecordType)])), in: foundation) - let inhabitedType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Inhabited", genericArguments: [.type(setType)])), in: foundation) - let optionalType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(plan.packRecordType)]))) - let lookup = try await setType.resolve( - .swift( - .getter( - "PreviewsFoundationHost.OrderedIdentifiedSet.subscript.getter : (A.ID) -> A?", as: ((NativeSwiftValue) -> NativeSwiftValue).self, - valueABIs: [pack.type: .opaque(named: pack.type.name), optionalType: .opaque(named: optionalType.name)], - receiverABI: .opaque(named: setType.name)))) - for record in try await sourcePlanRecords(plan) { - let agent = try await sourceGetter(record, "agentRecord", resultType: plan.agentType) - let packs = try await sourceGetter(agent, "executionPointPacks", resultType: inhabitedType) - let values = try await sourceGetter(packs, - "(extension in PreviewsFoundationHost):PreviewsFoundationHost.PredicatedWrapper.value.getter : A.Predicate.Value", resultType: setType) - let match = try unsafe lookup.unsafeInvoke(on: values, pack.copy()) - if try await match.copyEnumPayload(forCase: "some", valueABIs: [plan.packRecordType: .opaque(named: plan.packRecordType.name)]) != nil { - return record - } - } - throw NativeRuntimeError.invocation("Could not find update record in native update plan for the selected execution point pack") - } - - private func sourcePlanRecords(_ plan: SourcePlan) async throws -> [NativeSwiftValue] { - let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) - let arrayType = try await runtime.resolve(.swift(.type("Swift.Array", genericArguments: [.type(plan.recordType)]))) - let inhabitedType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Inhabited", genericArguments: [.type(arrayType)])), in: foundation) - let headType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.HasHead", genericArguments: [.type(arrayType)])), in: foundation) - let predicatedType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Predicated", genericArguments: [.type(headType)])), in: foundation) - let records = try await sourceGetter(plan.value, "updateRecords", resultType: inhabitedType) - let predicated = try await sourceGetter(records, "predicated", resultType: predicatedType) - let values = try await sourceGetter(predicated, "value", resultType: arrayType, resultABI: .pointer) - guard let raw = try values.withCopy({ $0 as? [Any] }) else { - throw NativeRuntimeError.unsupportedContract("Native preview update plan records are not an array") - } - var result: [NativeSwiftValue] = [] - for value in raw { result.append(try await _openExistential(value, do: nativePreviewOwnedValue)) } - return result - } -} - -private struct NativePreviewStaticString: ABIBridgeSwiftValue { - let value: StaticString - static let swiftABIType: NativeType = try! .structure(named: "Swift.StaticString", fields: [.uint64, .uint64, .uint8]) -} - -@MainActor -private func nativePreviewOwnedValue(_ value: Value) async throws -> NativeSwiftValue { +func nativePreviewOwnedValue(_ value: Value) async throws -> NativeSwiftValue { let identity = try await ABIRuntime.shared.resolve( .swift(.function("XcodeMCPNativeRuntime.nativePreviewValue(A) -> A", as: ((Value) -> NativeSwiftValue).self, genericArguments: [.type(Value.self)]))) return try unsafe identity.unsafeInvoke(value) diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift index 35795839..b3969c7d 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewDefinitions.swift @@ -6,6 +6,12 @@ import Foundation struct NativePreviewDefinitions { let installation: NativeXcodeInstallation + /// A parsed preview definition and the translation unit it came from. + struct Source { + let translationUnit: NativeSwiftValue + let definition: NativeSwiftValue + } + func sourceURL(_ path: String, workspace: AnyObject) async throws -> URL { do { let action = try await ABIRuntime.shared.resolve( @@ -36,7 +42,7 @@ struct NativePreviewDefinitions { let displayName: String let providerPath: NativeSwiftValue? let registry: NativeSwiftValue? - let source: NativePreviewBuild.Source + let source: NativePreviewDefinitions.Source } func definition(in source: URL, at index: Int) async throws -> Definition { diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift new file mode 100644 index 00000000..124a9762 --- /dev/null +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift @@ -0,0 +1,891 @@ +import ABIBridge +import ABIBridgeCore +import ABIBridgeCore.Backend +import Foundation +import XcodeMCPWire + +/// Resolves and selects a preview's render destination, and captures the planning context that a reused build must still match. +@safe +@MainActor +final class NativePreviewDestinations { + private let runtime = ABIRuntime.shared + private let installation: NativeXcodeInstallation + + init(installation: NativeXcodeInstallation) { + self.installation = installation + } + + private var destinationPreparation: DestinationPreparation? + + private var sourceSelections: [ObjectIdentifier: [SourceSelectionWaiter]] = [:] + + private struct SourceSelectionWaiter { + let identifier: UUID + let continuation: CheckedContinuation + } + + func planningContext(workspace: AnyObject, destination: Selection? = nil) throws -> PlanningContext { + guard let manager = try NativeObjCGetters.object(workspace, selector: "runContextManager"), + let scheme = try NativeObjCGetters.object(manager, selector: "activeRunContext"), + let environment = try NativeObjCGetters.object(workspace, selector: "executionEnvironment") else { + throw NativeRuntimeError.invalidRequest("The workspace has no active scheme, run destination, or execution environment") + } + return try PlanningContext(scheme: scheme, schemeIdentifier: NativeObjCGetters.object(scheme, selector: "schemeIdentifier") as? NSObject, + environment: environment, activeDestination: destinationContext(NativeObjCGetters.object(manager, selector: "activeRunDestination")), + destination: destinationContext(destination?.selected.value)) + } + + + + private func destinationContext(_ destination: AnyObject?) throws -> DestinationContext? { + guard let destination else { return nil } + let device = try NativeObjCGetters.object(destination, selector: "targetDevice") + let sdk = try NativeObjCGetters.object(destination, selector: "targetSDK") + let variant = try NativeObjCGetters.object(destination, selector: "targetSDKVariant") + let hostPlatform = try NativeObjCGetters.object(destination, selector: "hostTargetedPlatform") + let available: Bool? + if let device { + let get = try runtime.object(device).resolveAndWait(.objc(.method("isAvailable", as: (() -> Bool).self))) + available = try unsafe get.unsafeInvoke() + } else { available = nil } + return try DestinationContext(identifier: NativeObjCGetters.optionalString(device, selector: "identifier") + ?? NativeObjCGetters.optionalString(destination, selector: "targetIdentifier"), + architecture: NativeObjCGetters.optionalString(destination, selector: "targetArchitecture"), + sdk: NativeObjCGetters.optionalString(sdk, selector: "canonicalName"), variant: NativeObjCGetters.optionalString(variant, selector: "name"), + hostPlatform: NativeObjCGetters.optionalString(hostPlatform, selector: "identifier"), + runtimeVersion: NativeObjCGetters.optionalString(device, selector: "operatingSystemVersion"), available: available) + } + + @safe + private struct DestinationPreparation { + let properties: NativeSwiftMethod<() -> NativeSwiftValue> + let platform: NativeSwiftMethod<() -> NativeSwiftValue> + let identifier: NativeSwiftMethod<() -> NativeSwiftValue> + let version: NativeSwiftMethod<() -> NativeSwiftValue> + let platformName: NativeSwiftMethod<() -> String> + let identifierString: NativeSwiftMethod<() -> String> + let versionString: NativeSwiftMethod<() -> String> + let model: NativeSwiftMethod<() -> String?> + let name: NativeSwiftMethod<() -> String?> + let specifier: NativeSwiftMethod<() -> String?> + } + + private func prepareDestinationProperties() async throws -> DestinationPreparation { + if let destinationPreparation { return destinationPreparation } + let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) + let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) + let recipeType = try await runtime.resolve(.swift(.type("PreviewsPipeline.AnyRunDestinationRecipe")), in: pipeline) + let propertiesType = try await runtime.resolve(.swift(.type("PreviewsPipeline.RunDestinationProperties")), in: pipeline) + let platformType = try await runtime.resolve(.swift(.type("PreviewsPipeline.Platform")), in: pipeline) + let identifierType = try await runtime.resolve(.swift(.type("PreviewsPipeline.DeviceIdentifier")), in: pipeline) + let versionType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.VersionNumber")), in: foundation) + func getter(_ type: NativeSwiftType, _ declaration: String, _ value: Value.Type, + result: NativeSwiftType? = nil) async throws -> NativeSwiftMethod<() -> Value> { + try await type.resolve( + .swift( + .getter( + declaration, as: (() -> Value).self, valueABIs: try result.map { [$0: try NativeType.opaque(named: $0.name)] } ?? [:], + receiverABI: .opaque(named: type.name)))) + } + let preparation = try await DestinationPreparation( + properties: getter(recipeType, "properties.getter : PreviewsPipeline.RunDestinationProperties", NativeSwiftValue.self, result: propertiesType), + platform: getter(propertiesType, "platform.getter : PreviewsPipeline.Platform", NativeSwiftValue.self, result: platformType), + identifier: getter(propertiesType, "deviceIdentifier.getter : PreviewsPipeline.DeviceIdentifier", NativeSwiftValue.self, result: identifierType), + version: getter(propertiesType, "runtimeVersion.getter : PreviewsFoundationHost.VersionNumber", NativeSwiftValue.self, result: versionType), + platformName: getter(platformType, "name.getter : Swift.String", String.self), + identifierString: getter(identifierType, "stringValue.getter : Swift.String", String.self), + versionString: getter(versionType, "description.getter : Swift.String", String.self), + model: getter(propertiesType, "deviceModel.getter : Swift.String?", String?.self), + name: getter(propertiesType, "deviceName.getter : Swift.String?", String?.self), + specifier: getter(propertiesType, "deviceSpecifier.getter : Swift.String?", String?.self)) + destinationPreparation = preparation + return preparation + } + + private func destinationInfo(_ destination: AnyObject, recipe: NativeSwiftValue, prepared: DestinationPreparation) throws -> Destination { + let device = try NativeObjCGetters.object(destination, selector: "targetDevice") + let sdk = try NativeObjCGetters.object(destination, selector: "targetSDK") + let platform = try sdk.flatMap { try NativeObjCGetters.object($0, selector: "platform") } + let identifier = try NativeObjCGetters.optionalString(device, selector: "identifier") + ?? NativeObjCGetters.optionalString(destination, selector: "targetIdentifier") + guard let identifier else { + throw NativeRuntimeError.unsupportedContract("The native run destination has no identifier") + } + let platformIdentifier = try NativeObjCGetters.optionalString(platform, selector: "identifier") + let isMacCatalyst: Bool + if platformIdentifier == "com.apple.platform.macosx" { + let getter = try runtime.object(destination).resolveAndWait(.objc(.method("isMacCatalyst", as: (() -> Bool).self))) + isMacCatalyst = try unsafe getter.unsafeInvoke() + } else { isMacCatalyst = false } + let properties = try unsafe prepared.properties.unsafeInvoke(on: recipe) + let nativePlatform = try unsafe prepared.platform.unsafeInvoke(on: properties) + let nativeIdentifier = try unsafe prepared.identifier.unsafeInvoke(on: properties) + let version = try unsafe prepared.version.unsafeInvoke(on: properties) + let model = try unsafe prepared.model.unsafeInvoke(on: properties) + ?? prepared.name.unsafeInvoke(on: properties) ?? prepared.specifier.unsafeInvoke(on: properties) + let previewIdentifier = try unsafe prepared.identifierString.unsafeInvoke(on: nativeIdentifier) + let platformName = try unsafe prepared.platformName.unsafeInvoke(on: nativePlatform) + let systemVersion = try unsafe prepared.versionString.unsafeInvoke(on: version) + return Destination(value: destination, recipe: recipe, identifier: identifier, previewIdentifier: previewIdentifier, + platformIdentifier: platformIdentifier, + previewPlatform: NativePreviewPlatform(platformIdentifier: platformIdentifier, isMacCatalyst: isMacCatalyst), + platformName: platformName, + deviceModelName: model, systemVersion: systemVersion) + } + + struct PlanningContext { + fileprivate let scheme: AnyObject + fileprivate let schemeIdentifier: NSObject? + fileprivate let environment: AnyObject + fileprivate let activeDestination: DestinationContext? + fileprivate let destination: DestinationContext? + + func matches(_ other: PlanningContext) -> Bool { + let sameScheme: Bool + switch (schemeIdentifier, other.schemeIdentifier) { + case let (left?, right?): sameScheme = left.isEqual(right) + case (nil, nil): sameScheme = scheme === other.scheme + default: sameScheme = false + } + return sameScheme && environment === other.environment + && activeDestination == other.activeDestination && destination == other.destination + } + } + + fileprivate struct DestinationContext: Equatable { + let identifier: String? + let architecture: String? + let sdk: String? + let variant: String? + let hostPlatform: String? + let runtimeVersion: String? + let available: Bool? + } + + struct Resolution { + fileprivate let host: AnyObject + fileprivate let preferences: NativeSwiftValue + let available: JSONValue? + let errors: [String] + } + + struct Selection { + let selected: Destination + let resolution: Resolution + + var available: JSONValue? { resolution.available } + var errors: [String] { resolution.errors } + + /// The workspace builder that Xcode cached on the preview host for this selection. + func workspaceBuilder() throws -> AnyObject? { + guard let field = Mirror(reflecting: resolution.host).children.first(where: { $0.label == "lastWorkspaceBuilder" }) else { + throw NativeRuntimeError.unsupportedContract("The native preview host has no cached workspace builder") + } + let mirror = Mirror(reflecting: field.value) + let value: Any + if mirror.displayStyle == .optional { + guard let payload = mirror.children.first else { return nil } + value = payload.value + } else { value = field.value } + guard Mirror(reflecting: value).displayStyle == .class else { + throw NativeRuntimeError.unsupportedContract("The native preview workspace builder is not a class") + } + // Creating a builder after restoring the agentic source would invalidate this native cache. + return value as AnyObject + } + } + + struct Destination { + let value: AnyObject + let recipe: NativeSwiftValue + let identifier: String + let previewIdentifier: String + let platformIdentifier: String? + let previewPlatform: NativePreviewPlatform? + let platformName: String? + let deviceModelName: String? + let systemVersion: String? + } + + func frameworkAgent(for destination: Selection) async throws -> URL { + try Task.checkCancellation() + let recipe = destination.selected.recipe + let bundleType = try await runtime.resolve( + .swift(.type("PreviewsPipeline.PreviewAgentBundle")), in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) + let make = try await recipe.type.resolve( + .swift( + .method( + "makeFrameworkAgent() throws -> PreviewsPipeline.PreviewAgentBundle", as: (() throws -> NativeSwiftValue).self, + valueABIs: [bundleType: .opaque(named: bundleType.name)], receiverABI: .opaque(named: recipe.type.name)))) + let bundle = try unsafe make.unsafeInvoke(on: recipe) + let url = try await bundleType.resolve( + .swift(.getter("url.getter : Foundation.URL", as: (() -> NativePreviewBuildURL).self, receiverABI: .opaque(named: bundleType.name)))) + try Task.checkCancellation() + return try unsafe url.unsafeInvoke(on: bundle).value + } + + private struct SourcePlan { + let value: NativeSwiftValue + let recordType: NativeSwiftType + let agentType: NativeSwiftType + let packRecordType: NativeSwiftType + let referenceType: NativeSwiftType + } + + func withSourceSelection(workspace: AnyObject, + operation: @MainActor () async throws -> Output) async throws -> Output { + let workspaceID = ObjectIdentifier(workspace) + try Task.checkCancellation() + if sourceSelections[workspaceID] == nil { + sourceSelections[workspaceID] = [] + } else { + let identifier = UUID() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + if Task.isCancelled { continuation.resume(throwing: CancellationError()) } + else { sourceSelections[workspaceID, default: []].append(.init(identifier: identifier, continuation: continuation)) } + } + } onCancel: { + Task { @MainActor in + guard let index = self.sourceSelections[workspaceID]?.firstIndex(where: { $0.identifier == identifier }) else { return } + let waiter = self.sourceSelections[workspaceID]!.remove(at: index) + waiter.continuation.resume(throwing: CancellationError()) + } + } + } + defer { + if let waiter = sourceSelections[workspaceID]?.first { + sourceSelections[workspaceID]!.removeFirst() + waiter.continuation.resume() + } else { sourceSelections[workspaceID] = nil } + withExtendedLifetime(workspace) {} + } + try Task.checkCancellation() + return try await operation() + } + + func resolveDestination(workspace: AnyObject, input: NativeSwiftValue) async throws -> Resolution { + try Task.checkCancellation() + let previews = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) + let createHost = try await runtime.object(workspace).resolve( + .swift( + .method( + "(extension in PreviewsXcode):__C.IDEWorkspace.sceneHost(isNewProjectFromTemplate: Swift.Bool) -> PreviewsXcode.XcodeWorkspaceSceneHost", + as: ((Bool) -> AnyObject).self))) + let host = try unsafe createHost.unsafeInvoke(false) + let resolutionType: NativeSwiftType + do { + resolutionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.Resolution")), in: previews) + } catch is ABIResolutionError { + return try await currentDestinationResolution(host: host, input: input) + } + let actionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction")), in: previews) + let resolve = try await actionType.resolve( + .swift( + .staticMethod( + "static PreviewsXcode.RenderPreviewAction.resolveDestination(input: PreviewsXcode.RenderPreviewAction.Input, sceneHost: PreviewsXcode.XcodeWorkspaceSceneHost) async -> PreviewsXcode.RenderPreviewAction.Resolution", + as: (@concurrent (NativeSwiftValue, AnyObject) async -> NativeSwiftValue).self, + valueABIs: [input.type: .opaque(named: input.type.name), resolutionType: .opaque(named: resolutionType.name)]))) + let resolution = try unsafe await resolve.unsafeInvoke(input, host) + try Task.checkCancellation() + let fields = try resolution.withCopy { Dictionary(uniqueKeysWithValues: Mirror(reflecting: $0).children.compactMap { + field in field.label.map { ($0, field.value) } + }) } + guard let rawPreferences = fields["preferences"] else { + throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no preferences") + } + let preferences = try await _openExistential(rawPreferences, do: nativePreviewOwnedValue) + let errors = (fields["errorMessage"] as? String? ?? nil).map { [$0] } ?? [] + guard let available = fields["availableRenderDestinations"] as? any Encodable else { + throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no encodable destinations") + } + let encodedAvailable = try JSONEncoder().encode(available) + guard let availableJSON = JSONValue(any: try JSONSerialization.jsonObject(with: encodedAvailable, options: .fragmentsAllowed)) else { + throw NativeRuntimeError.unsupportedContract("Native preview destinations have an unsupported JSON representation") + } + return Resolution(host: host, preferences: preferences, + available: availableJSON == .null ? nil : availableJSON, errors: errors) + } + + private func currentDestinationResolution(host: AnyObject, input: NativeSwiftValue) async throws -> Resolution { + let image = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) + let resolver = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.RenderDestinationResolver")), in: image) + let recipe = try await runtime.resolve(.swift(.type("PreviewsPipeline.AnyRunDestinationRecipe")), + in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) + let array = try await runtime.resolve(.swift(.type("Swift.Array", genericArguments: [.type(recipe)]))) + // The catalog wrappers have only optimizer-specialized entry points. + // Keep their native feature gate and use the scene host's callable API. + let offersChoice = UserDefaults.standard.object(forKey: "UVRenderPreviewOffersRenderDestinationChoice") as? Bool ?? true + guard offersChoice else { + let preferences = try await runtime.resolve(.swift(.type("PreviewsPipeline.DestinationPreferences")), + in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) + let empty = try await preferences.resolve(.swift(.staticGetter("empty", + as: (() -> NativeSwiftValue).self, valueABIs: [preferences: .opaque(named: preferences.name)]))) + return Resolution(host: host, preferences: try unsafe empty.unsafeInvoke(), available: nil, errors: []) + } + let timeoutType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Timeout")), + in: .path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks"))) + let makeTimeout = try await timeoutType.resolve(.swift(.staticMethod("seconds(_:)", + as: ((Double) -> NativeSwiftValue).self, valueABIs: [timeoutType: .opaque(named: timeoutType.name)]))) + let timeout = try unsafe makeTimeout.unsafeInvoke(10) + let catalog = try await runtime.object(host).resolve(.swift(.method( + "(awaitAvailableRunDestinations in _8779CD8E26326606F5A569AC41E16EDA)(timeout: PreviewsFoundationHost.Timeout) async -> [PreviewsPipeline.AnyRunDestinationRecipe]", + as: (@concurrent (NativeSwiftValue) async -> NativeSwiftValue).self, + valueABIs: [timeoutType: .opaque(named: timeoutType.name), array: .pointer]))) + let nativeCatalog = try unsafe await catalog.unsafeInvoke(timeout) + let prepared = try await prepareDestinationProperties() + let platform = try await runtime.resolve(.swift(.type("PreviewsPipeline.Platform")), + in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) + let canonicalIdentifier = try await platform.resolve(.swift(.getter("canonicalIdentifier", + as: (() -> String).self, receiverABI: .opaque(named: platform.name)))) + func catalogValues(_ values: Recipes) async throws -> (NativeSwiftValue, JSONValue) { + var filtered: [Recipes.Element] = [] + var external: [JSONValue] = [] + for value in values { + let native = try await nativePreviewOwnedValue(value) + let properties = try unsafe prepared.properties.unsafeInvoke(on: native) + let nativePlatform = try unsafe prepared.platform.unsafeInvoke(on: properties) + let identifier = try unsafe canonicalIdentifier.unsafeInvoke(on: nativePlatform) + guard !["xros", "xrsimulator"].contains(identifier) else { continue } + filtered.append(value) + let nativeIdentifier = try unsafe prepared.identifier.unsafeInvoke(on: properties) + let version = try unsafe prepared.version.unsafeInvoke(on: properties) + var item: [String: JSONValue] = try unsafe [ + "identifier": .string(prepared.identifierString.unsafeInvoke(on: nativeIdentifier)), + "platformName": .string(prepared.platformName.unsafeInvoke(on: nativePlatform)), + "systemVersion": .string(prepared.versionString.unsafeInvoke(on: version)), + ] + if let model = try unsafe prepared.model.unsafeInvoke(on: properties) + ?? prepared.name.unsafeInvoke(on: properties) ?? prepared.specifier.unsafeInvoke(on: properties) { + item["deviceModelName"] = .string(model) + } + external.append(.object(item)) + } + return (try await nativePreviewOwnedValue(filtered), .array(external)) + } + let values = try nativeCatalog.withCopy { value in + guard let values = value as? any Collection else { + throw NativeRuntimeError.unsupportedContract("Native preview destination catalog is not a collection") + } + return values + } + let (recipes, available) = try await _openExistential(values, do: catalogValues) + let preferred = try input.withCopy { value in + guard let field = Mirror(reflecting: value).children.first(where: { $0.label == "preferredRenderDestination" }) else { + throw NativeRuntimeError.unsupportedContract("Native preview input has no render destination selection") + } + return field.value + } + let selection = try await _openExistential(preferred, do: nativePreviewOwnedValue) + let resolutionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.RenderDestinationResolver.Resolution")), in: image) + let resolve = try await resolver.resolve(.swift(.staticMethod("resolve(selection:catalog:)", + as: ((NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [selection.type: .opaque(named: selection.type.name), recipes.type: .pointer, + resolutionType: .opaque(named: resolutionType.name)]))) + let resolution = try unsafe resolve.unsafeInvoke(selection, recipes) + let fields = try resolution.withCopy { Dictionary(uniqueKeysWithValues: Mirror(reflecting: $0).children.compactMap { + field in field.label.map { ($0, field.value) } + }) } + guard let rawPreferences = fields["selection"] else { + throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no preferences") + } + let preferences = try await _openExistential(rawPreferences, do: nativePreviewOwnedValue) + guard let nativeErrors = fields["errors"] as? any Encodable else { + throw NativeRuntimeError.unsupportedContract("Native preview destination resolution has no encodable errors") + } + struct Message: Decodable { var message: String } + let errors = try JSONDecoder().decode([Message].self, from: JSONEncoder().encode(nativeErrors)).map(\.message) + return Resolution(host: host, preferences: preferences, available: available, errors: errors) + } + + func destinationResolution(_ lhs: Resolution, matches rhs: Resolution) async throws -> Bool { + guard lhs.available == rhs.available, lhs.errors == rhs.errors else { return false } + let type = lhs.preferences.type + let equals = try await type.resolve( + .swift( + .staticMethod( + "== infix(PreviewsPipeline.DestinationPreferences, PreviewsPipeline.DestinationPreferences) -> Swift.Bool", + as: ((NativeSwiftValue, NativeSwiftValue) -> Bool).self, valueABIs: [type: .opaque(named: type.name)]))) + return try unsafe equals.unsafeInvoke(lhs.preferences, rhs.preferences) + } + + func selectDestination(workspace: AnyObject, source: NativePreviewDefinitions.Source, resolution: Resolution, + metadata: Data? = nil, providerDescription: Data? = nil) async throws -> Selection { + let evaluatedMetadata: NativeSwiftValue? + if let metadata { evaluatedMetadata = try await decodePreviewValue(metadata, named: "PreviewMetadata") } + else { evaluatedMetadata = nil } + let evaluatedDescription: NativeSwiftValue? + if let providerDescription { evaluatedDescription = try await decodePreviewValue(providerDescription, named: "PreviewDescription") } + else { evaluatedDescription = nil } + return try await withSourceSelection(workspace: workspace) { + guard let pack = try await executionPointPack(source: source, preferences: resolution.preferences, + metadata: evaluatedMetadata, providerDescription: evaluatedDescription) else { throw NativePipelineRequired() } + let plan = try await sourcePlan(workspace: workspace, host: resolution.host, source: source, pack: pack) + let record = try await sourcePlanRecord(plan, pack: pack) + let prepared = try await prepareDestinationProperties() + let recipeType = try await runtime.resolve( + .swift(.type("PreviewsPipeline.AnyRunDestinationRecipe")), in: .path(installation.framework("PreviewsPipeline", in: "SharedFrameworks"))) + let recipe = try await sourceGetter(record, "destination.getter : PreviewsPipeline.AnyRunDestinationRecipe", resultType: recipeType) + let representation = try await sourceGetter(record, "destinationRepresentation.getter : C", resultType: plan.referenceType) + guard let destination = try representation.withCopy({ + Mirror(reflecting: $0).children.first { $0.label == "runDestination" }?.value as? NSObject + }) else { throw NativeRuntimeError.unsupportedContract("Native preview plan has no IDERunDestination representation") } + let selected = try destinationInfo(destination, recipe: recipe, prepared: prepared) + guard NativePreviewPlatform.supportsDestination(platformIdentifier: selected.platformIdentifier, identifier: selected.identifier) else { + throw NativePipelineRequired() + } + return Selection(selected: selected, resolution: resolution) + } + } + + private func sourceGetter(_ value: NativeSwiftValue, _ name: String, resultType: NativeSwiftType, + resultABI: NativeType? = nil) async throws -> NativeSwiftValue { + let getter = try await value.type.resolve( + .swift( + .getter( + name, as: (() -> NativeSwiftValue).self, valueABIs: [resultType: try resultABI ?? .opaque(named: resultType.name)], + receiverABI: .opaque(named: value.type.name)))) + return try unsafe getter.unsafeInvoke(on: value) + } + + func isWidgetPreview(metadata: Data) async throws -> Bool { + try await hasContentDomain("widget", metadata: metadata) + } + + func isComplicationPreview(metadata: Data) async throws -> Bool { + try await hasContentDomain("complication", metadata: metadata) + } + + private func hasContentDomain(_ name: String, metadata: Data) async throws -> Bool { + let metadata = try await decodePreviewValue(metadata, named: "PreviewMetadata") + let domainType = try await runtime.resolve( + .swift(.type("PreviewsMessagingHost.PreviewContentDomain")), in: .path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks"))) + let domain = try await sourceGetter(metadata, + "contentDomain.getter : PreviewsMessagingHost.PreviewContentDomain", resultType: domainType) + let expected = try domainType.makeEnumCase(named: name) + return try domain.withCopy { value in + guard let value = value as? any Equatable else { + throw NativeRuntimeError.unsupportedContract("The native preview content domain is not Equatable") + } + func compare(_ value: Value) throws -> Bool { + try expected.withCopy { $0 as? Value == value } + } + return try _openExistential(value, do: compare) + } + } + + func decodePreviewValue(_ data: Data, named name: String) async throws -> NativeSwiftValue { + guard let dictionary = try unsafe PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else { + throw NativeRuntimeError.invocation("The preview metadata is not a serializable dictionary") + } + let propertyListType = try await runtime.resolve( + .swift(.type("PreviewsFoundationHost.PropertyList")), in: .path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks"))) + let nativeDictionary = try await nativePreviewOwnedValue(dictionary) + let makePropertyList = try await propertyListType.resolve( + .swift( + .initializer( + "init(serializableDictionary:)", as: ((NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [nativeDictionary.type: .pointer, propertyListType: .opaque(named: propertyListType.name)]))) + let propertyList = try unsafe makePropertyList.unsafeInvoke(nativeDictionary) + let metadataType = try await runtime.resolve( + .swift(.type("PreviewsMessagingHost.\(name)")), in: .path(installation.framework("PreviewsMessagingHost", in: "SharedFrameworks"))) + let decode = try await metadataType.resolve( + .swift( + .initializer( + "init(propertyListValue: PreviewsFoundationHost.PropertyList) throws -> \(metadataType.name)", + as: ((NativeSwiftValue) throws -> NativeSwiftValue).self, + valueABIs: [propertyListType: .opaque(named: propertyListType.name), metadataType: .opaque(named: metadataType.name)]))) + return try unsafe decode.unsafeInvoke(propertyList) + } + + private func effectivePreferences(_ operation: NativeSwiftValue, instance: NativeSwiftValue) async throws -> NativeSwiftValue { + let type = operation.type + let emptyGetter = try await type.resolve( + .swift( + .staticGetter( + "empty.getter : PreviewsPipeline.DestinationPreferences", as: (() -> NativeSwiftValue).self, valueABIs: [type: .opaque(named: type.name)]))) + let empty = try unsafe emptyGetter.unsafeInvoke() + let equals = try await type.resolve( + .swift( + .staticMethod( + "== infix(PreviewsPipeline.DestinationPreferences, PreviewsPipeline.DestinationPreferences) -> Swift.Bool", + as: ((NativeSwiftValue, NativeSwiftValue) -> Bool).self, valueABIs: [type: .opaque(named: type.name)]))) + guard try unsafe equals.unsafeInvoke(operation, empty) else { return try operation.copy() } + let getter = try await instance.type.resolve( + .swift( + .getter( + "PreviewsPipeline.PreviewInstanceProtocol.destinationPreferences.getter : PreviewsPipeline.DestinationPreferences", + as: (() -> NativeSwiftValue).self, valueABIs: [type: .opaque(named: type.name)]))) + return try unsafe getter.unsafeInvoke(on: instance) + } + + private func executionPointPack(source: NativePreviewDefinitions.Source, preferences: NativeSwiftValue, + metadata: NativeSwiftValue?, providerDescription: NativeSwiftValue?) async throws -> NativeSwiftValue? { + let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) + let executionSource: NativeSwiftValue + let role: NativeSwiftValue + let effectivePreferences: NativeSwiftValue + if let definition = try await source.definition.copyEnumPayload(forCase: "registryPreview") { + let instanceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewInstance")), in: pipeline) + let makeInstance = try await instanceType.resolve( + .swift( + .staticMethod( + "registryPreview(definition: PreviewsModel.RegistryDefinition) -> PreviewsPipeline.PreviewInstance", + as: ((NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [definition.type: .opaque(named: definition.type.name), instanceType: .opaque(named: instanceType.name)]))) + let instance = try unsafe makeInstance.unsafeInvoke(definition.copy()) + let registryType = try await runtime.resolve(.swift(.type("PreviewsPipeline.RegistryPreviewInstance")), in: pipeline) + let optionalType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(registryType)]))) + let registryGetter = try await instanceType.resolve( + .swift( + .getter( + "registryInstance.getter : PreviewsPipeline.RegistryPreviewInstance?", as: (() -> NativeSwiftValue).self, + valueABIs: [optionalType: .opaque(named: optionalType.name)], receiverABI: .opaque(named: instanceType.name)))) + let optional = try unsafe registryGetter.unsafeInvoke(on: instance) + guard let registry = try await optional.copyEnumPayload(forCase: "some") else { + throw NativeRuntimeError.unsupportedContract("Native preview factory produced no registry instance") + } + func requirement(_ name: String, output: String) async throws -> NativeSwiftValue { + let type = try await runtime.resolve(.swift(.type(output))) + let get = try await registry.type.resolve( + .swift( + .getter( + "PreviewsPipeline.PreviewInstanceProtocol.\(name).getter : \(output)", as: (() -> NativeSwiftValue).self, + valueABIs: [type: .opaque(named: type.name)]))) + return try unsafe get.unsafeInvoke(on: registry) + } + executionSource = try await requirement("source", output: "PreviewsPipeline.ExecutionPointSource") + role = try await requirement("agentRole", output: "PreviewsMessagingHost.PreviewAgentRole") + if metadata != nil { effectivePreferences = try await self.effectivePreferences(preferences, instance: registry) } + else { effectivePreferences = preferences } + } else if let definition = try await source.definition.copyEnumPayload(forCase: "previewProvider") { + let identifierType = try await runtime.resolve(.swift(.type("PreviewsModel.SourceIdentifier"))) + let identifier = try await sourceGetter(definition, "sourceIdentifier.getter : PreviewsModel.SourceIdentifier", resultType: identifierType) + let sourceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointSource")), in: pipeline) + executionSource = try await sourceType.makeEnumCase(named: "sourceFile", payload: identifier) + let roleType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewAgentRole"))) + role = try roleType.makeEnumCase(named: "previews") + if metadata != nil { + guard let providerDescription else { + throw NativeRuntimeError.invocation("The evaluated provider returned no native preview description") + } + let providerSourceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ProviderSource")), in: pipeline) + let providerSource = try await providerSourceType.makeEnumCase(named: "provider", payload: definition.copy()) + let providerType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ProviderPreviewInstance")), in: pipeline) + let initialize = try await providerType.resolve( + .swift( + .initializer( + "init(providerSource: PreviewsPipeline.ProviderSource, previewDescription: PreviewsMessagingHost.PreviewDescription) -> PreviewsPipeline.ProviderPreviewInstance", + as: ((NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [ + providerSourceType: .opaque(named: providerSourceType.name), + providerDescription.type: .opaque(named: providerDescription.type.name), providerType: .opaque(named: providerType.name), + ]))) + let provider = try unsafe initialize.unsafeInvoke(providerSource, providerDescription.copy()) + effectivePreferences = try await self.effectivePreferences(preferences, instance: provider) + } else { effectivePreferences = preferences } + } else { return nil } + let requirementsType = try await runtime.resolve(.swift(.type("PreviewsPipeline.DestinationRequirements")), in: pipeline) + // Native preflight and RenderPreview's evaluated Location use none. + // The registry instance's requirements witness is unavailable. + let none = try await requirementsType.resolve( + .swift( + .staticGetter( + "none.getter : PreviewsPipeline.DestinationRequirements", as: (() -> NativeSwiftValue).self, + valueABIs: [requirementsType: .opaque(named: requirementsType.name)]))) + let requirements = try unsafe none.unsafeInvoke() + let domainType = try await runtime.resolve(.swift(.type("PreviewsMessagingHost.PreviewContentDomain"))) + let optionalDomainType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(domainType)]))) + let domain: NativeSwiftValue + if let metadata { + let contentDomain = try await sourceGetter(metadata, "contentDomain.getter : PreviewsMessagingHost.PreviewContentDomain", resultType: domainType) + let some = try await runtime.resolve( + .swift( + .function( + "XcodeMCPNativeRuntime.nativePreviewSome(A) -> A?", as: ((NativeSwiftValue) -> NativeSwiftValue).self, + genericArguments: [.type(domainType)], + valueABIs: [domainType: .opaque(named: domainType.name), optionalDomainType: .opaque(named: optionalDomainType.name)]))) + domain = try unsafe some.unsafeInvoke(contentDomain) + } else { + let propertiesType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointProperties")), in: pipeline) + let defaults = try await propertiesType.resolve( + .swift( + .staticGetter( + "default.getter : PreviewsPipeline.ExecutionPointProperties", as: (() -> NativeSwiftValue).self, + valueABIs: [propertiesType: .opaque(named: propertiesType.name)]))) + let properties = try unsafe defaults.unsafeInvoke() + let domainGetter = try await propertiesType.resolve( + .swift( + .getter( + "previewContentDomain.getter : PreviewsMessagingHost.PreviewContentDomain?", as: (() -> NativeSwiftValue).self, + valueABIs: [optionalDomainType: .opaque(named: optionalDomainType.name)], receiverABI: .opaque(named: propertiesType.name)))) + domain = try unsafe domainGetter.unsafeInvoke(on: properties) + } + let packType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointPack")), in: pipeline) + let create = try await packType.resolve( + .swift( + .initializer( + "init(executionPointSource: PreviewsPipeline.ExecutionPointSource, previewAgentRole: PreviewsMessagingHost.PreviewAgentRole, destinationPreferences: PreviewsPipeline.DestinationPreferences, destinationRequirements: PreviewsPipeline.DestinationRequirements, previewContentDomain: PreviewsMessagingHost.PreviewContentDomain?) -> PreviewsPipeline.ExecutionPointPack", + as: ((NativeSwiftValue, NativeSwiftValue, NativeSwiftValue, NativeSwiftValue, NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [ + executionSource.type: .opaque(named: executionSource.type.name), role.type: .opaque(named: role.type.name), + preferences.type: .opaque(named: preferences.type.name), requirementsType: .opaque(named: requirementsType.name), + optionalDomainType: .opaque(named: optionalDomainType.name), packType: .opaque(named: packType.name), + ]))) + return try unsafe create.unsafeInvoke(executionSource.copy(), role.copy(), effectivePreferences.copy(), requirements.copy(), domain.copy()) + } + + private func sourceArray(_ values: [NativeSwiftValue], elementType: NativeSwiftType) async throws -> NativeSwiftValue { + let cast = try await runtime.resolve( + .swift( + .function( + "XcodeMCPNativeRuntime.nativePreviewArray([Any]) throws -> [A]", as: (([Any]) throws -> NativeSwiftValue).self, + genericArguments: [.type(elementType)]))) + let copies = try values.map { try $0.withCopy { $0 } } + return try unsafe cast.unsafeInvoke(copies) + } + + private func sourcePlan(workspace: AnyObject, host: AnyObject, source: NativePreviewDefinitions.Source, pack: NativeSwiftValue) async throws -> SourcePlan { + let previews = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) + let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) + let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) + let hostType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeWorkspaceSceneHost")), in: previews) + let getScene = try await hostType.resolve( + .swift(.getter("workspaceScene.getter : PreviewsScenes.WorkspaceScene?", as: (() -> AnyObject?).self))) + guard let scene = try unsafe getScene.unsafeInvoke(on: host) else { + throw NativeRuntimeError.unsupportedContract("Native preview scene host has no workspace scene") + } + let fileType = try await runtime.resolve(.swift(.type("PreviewsPipeline.URLPreviewFileDescription")), in: pipeline) + let sceneType = try await runtime.resolve( + .swift(.type("PreviewsScenes.WorkspaceScene", genericArguments: [.type(fileType)])), + in: .path(installation.framework("PreviewsScenes", in: "SharedFrameworks"))) + let optionalUnitType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(source.translationUnit.type)]))) + let originalGetter = try await sceneType.resolve( + .swift( + .getter( + "agenticTranslationUnit.getter : PreviewsPipeline.PreviewTranslationUnit?", as: (() -> NativeSwiftValue).self, + valueABIs: [optionalUnitType: .opaque(named: optionalUnitType.name)]))) + let setter = try await sceneType.resolve( + .swift( + .setter( + "agenticTranslationUnit.setter : PreviewsPipeline.PreviewTranslationUnit?", as: ((NativeSwiftValue) -> Void).self, + valueABIs: [optionalUnitType: .opaque(named: optionalUnitType.name)], receiver: .borrowing))) + let original = try unsafe originalGetter.unsafeInvoke(on: scene) + let some = try await runtime.resolve( + .swift( + .function( + "XcodeMCPNativeRuntime.nativePreviewSome(A) -> A?", as: ((NativeSwiftValue) -> NativeSwiftValue).self, + genericArguments: [.type(source.translationUnit.type)]))) + let unit = try unsafe some.unsafeInvoke(source.translationUnit) + guard let field = Mirror(reflecting: host).children.first(where: { $0.label == "environmentCoalescer" }), + Mirror(reflecting: field.value).displayStyle == .class else { + throw NativeRuntimeError.unsupportedContract("Native preview environment coalescer is unavailable") + } + let coalescer = field.value as AnyObject + let coalescerType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeBuildEnvironmentCoalescer")), in: previews) + let invalidate = try await coalescerType.resolve(.swift(.method("setNeedsUpdate() -> ()", as: (() -> Void).self))) + let updateType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeBuildEnvironmentCoalescer.UpdateResult")), in: previews) + let refresh = try await coalescerType.resolve( + .swift( + .method( + "updated() -> PreviewsXcode.XcodeBuildEnvironmentCoalescer.UpdateResult", as: (() -> NativeSwiftValue).self, + valueABIs: [updateType: .opaque(named: updateType.name)]))) + let protocolSymbol = try await runtime.resolve( + .swift(.symbol("protocol descriptor for PreviewsIDEAPI.IDESchemeTaskExecutor", kind: .data)), + in: .path(installation.framework("PreviewsIDEAPI", in: "PlugIns"))) + let executorMetadata: Any.Type = try unsafe protocolSymbol.withUnsafeAddress { + guard let metadata = unsafe ABISwiftProtocolTypeMetadata($0) else { + throw NativeRuntimeError.unsupportedContract("Native scheme task executor protocol metadata is unavailable") + } + return unsafe unsafeBitCast(metadata, to: Any.Type.self) + } + let supplierFactory = try await runtime.resolve( + .swift( + .function( + "XcodeMCPNativeRuntime.nativePreviewExecutorProvider(Swift.AnyObject) throws -> @Swift.MainActor @Sendable () -> A?", + as: ((AnyObject) throws -> NativeSwiftValue).self, genericArguments: [.type(executorMetadata)]))) + let supplier = try unsafe supplierFactory.unsafeInvoke(workspace) + let callback = try await supplier.copyClosure(as: (@MainActor () -> NativeSwiftValue).self) + let callsiteType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Callsite")), in: foundation) + let makeCallsite = try await callsiteType.resolve( + .swift( + .initializer( + "init(Swift.StaticString, Swift.UInt, Swift.UInt, Swift.StaticString) -> PreviewsFoundationHost.Callsite", + as: ((NativePreviewStaticString, UInt, UInt, NativePreviewStaticString) -> NativeSwiftValue).self, + valueABIs: [callsiteType: .opaque(named: callsiteType.name)]))) + let callsite = try unsafe makeCallsite.unsafeInvoke(NativePreviewStaticString(value: #fileID), #line, #column, NativePreviewStaticString(value: #function)) + let tokenType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.CancellationToken")), in: foundation) + let cancel = try await tokenType.resolve( + .swift( + .method( + "cancel(callsite: PreviewsFoundationHost.Callsite) -> ()", as: ((NativeSwiftValue) -> Void).self, + valueABIs: [callsiteType: .opaque(named: callsiteType.name)], receiverABI: .opaque(named: tokenType.name)))) + let register = try await hostType.resolve( + .swift( + .method( + "registerSchemeTaskExecutorProvider(@Swift.MainActor () -> PreviewsIDEAPI.IDESchemeTaskExecutor?) -> PreviewsFoundationHost.CancellationToken", + as: ((NativeSwiftClosure<@MainActor () -> NativeSwiftValue>) -> NativeSwiftValue).self, + valueABIs: [tokenType: .opaque(named: tokenType.name)]))) + let token = try unsafe register.unsafeInvoke(on: host, callback) + let outcome: Swift.Result + do { + try unsafe setter.unsafeInvoke(on: scene, unit) + try unsafe invalidate.unsafeInvoke(on: coalescer) + outcome = .success(try await makeSourcePlan(host: host, source: source, pack: pack)) + } catch { outcome = .failure(error) } + var failures: [String] = [] + do { + try unsafe setter.unsafeInvoke(on: scene, original.copy()) + try unsafe invalidate.unsafeInvoke(on: coalescer) + _ = try unsafe refresh.unsafeInvoke(on: coalescer) + } catch { failures.append("source input restoration failed: \(error)") } + do { try unsafe cancel.unsafeInvoke(on: token, callsite.copy()) } + catch { failures.append("scheme executor provider cancellation failed: \(error)") } + withExtendedLifetime((protocolSymbol, supplier, callback)) {} + if !failures.isEmpty { + let operation = switch outcome { + case .success: "Native preview source destination selected" + case .failure(let error): String(describing: error) + } + throw NativeRuntimeError.invocation(([operation] + failures).joined(separator: "; ")) + } + return try outcome.get() + } + + private func makeSourcePlan(host: AnyObject, source: NativePreviewDefinitions.Source, pack: NativeSwiftValue) async throws -> SourcePlan { + let pipeline = ImageSelector.path(installation.framework("PreviewsPipeline", in: "SharedFrameworks")) + let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) + let previews = ImageSelector.path(installation.framework("PreviewsXcode", in: "PlugIns")) + let executionSourceType = try await runtime.resolve(.swift(.type("PreviewsPipeline.ExecutionPointSource")), in: pipeline) + let executionSource = try await pack.type.resolve( + .swift( + .getter( + "executionPointSource.getter : PreviewsPipeline.ExecutionPointSource", as: (() -> NativeSwiftValue).self, + valueABIs: [executionSourceType: .opaque(named: executionSourceType.name)], receiverABI: .opaque(named: pack.type.name)))) + let sourceValue = try unsafe executionSource.unsafeInvoke(on: pack) + let sourceArray = try await sourceArray([sourceValue], elementType: sourceValue.type) + let orderedType = try await runtime.resolve( + .swift(.type("PreviewsFoundationHost.OrderedSet", genericArguments: [.type(sourceValue.type)])), in: foundation) + let initialize = try await orderedType.resolve( + .swift( + .initializer( + "init(A1) -> PreviewsFoundationHost.OrderedSet", + as: ((NativeSwiftValue) -> NativeSwiftValue).self, genericArguments: [.type(sourceArray.type)], + valueABIs: [orderedType: .opaque(named: orderedType.name)]))) + let sources = try unsafe initialize.unsafeInvoke(sourceArray.copy()) + let identifierType = try await runtime.resolve( + .swift(.type("PreviewsModel.SourceIdentifier")), in: .path(installation.framework("PreviewsModel", in: "SharedFrameworks"))) + let identifierGetter = try await source.translationUnit.type.resolve( + .swift( + .getter( + "sourceIdentifier.getter : PreviewsModel.SourceIdentifier", as: (() -> NativeSwiftValue).self, + valueABIs: [identifierType: .opaque(named: identifierType.name)], receiverABI: .opaque(named: source.translationUnit.type.name)))) + let identifier = try unsafe identifierGetter.unsafeInvoke(on: source.translationUnit) + let files = try await self.sourceArray([identifier], elementType: identifierType) + let hostType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeWorkspaceSceneHost")), in: previews) + let makeBuilder = try await hostType.resolve( + .swift(.method("makeBuilder() throws -> PreviewsXcode.XcodeWorkspaceBuilder", as: (() throws -> AnyObject).self))) + let builder = try unsafe makeBuilder.unsafeInvoke(on: host) + let builderType = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeWorkspaceBuilder")), in: previews) + let makeGraph = try await builderType.resolve( + .swift( + .method( + "makeBuildGraph(for: PreviewsFoundationHost.OrderedSet, sourceFiles: [PreviewsModel.SourceIdentifier]) async throws -> PreviewsPipeline.WorkspaceGraph>", + as: (@concurrent (NativeSwiftValue, NativeSwiftValue) async throws -> AnyObject).self, + valueABIs: [orderedType: .opaque(named: orderedType.name)]))) + let graph = try unsafe await makeGraph.unsafeInvoke(on: builder, sources, files) + let graphSource = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeGraphSource")), in: previews) + let graphItem = try await runtime.resolve(.swift(.type("PreviewsPipeline.BuildGraphItem", genericArguments: [.type(graphSource)])), in: pipeline) + let graphType = try await runtime.resolve(.swift(.type("PreviewsPipeline.WorkspaceGraph", genericArguments: [.type(graphItem)])), in: pipeline) + let packs = try await self.sourceArray([pack], elementType: pack.type) + let update = try await graphType.resolve( + .swift( + .method( + "makeUpdateGraph, A1: PreviewsPipeline.WorkspaceGraphSource, B1: Swift.Collection, B1.Element == PreviewsPipeline.ExecutionPointPack>(for: B1) throws -> PreviewsPipeline.WorkspaceGraph>", + as: ((NativeSwiftValue) throws -> AnyObject).self, genericArguments: [.type(graphSource), .type(packs.type)]))) + let updateGraph = try unsafe update.unsafeInvoke(on: graph, packs) + let platform = try await runtime.resolve(.swift(.type("PreviewsPipeline.Platform")), in: pipeline) + let components = try await runtime.resolve(.swift(.type("PreviewsXcode.RunDestinationBuildComponents")), in: previews) + guard let destinationClass = NSClassFromString("IDERunDestination") else { + throw NativeRuntimeError.unsupportedContract("Native run destination class is unavailable") + } + let buildIdentifier = try await runtime.resolve( + .swift( + .type("PreviewsXcode.XcodeWorkspaceBuilder.BuildIdentifier", genericArguments: [.type(platform), .type(destinationClass), .type(components)])), + in: previews) + let reference = try await runtime.resolve(.swift(.type("PreviewsXcode.XcodeRunDestinationReference")), in: previews) + let arguments: [NativeSwiftGenericArgument] = [.type(graphSource), .type(buildIdentifier), .type(reference)] + let planType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewUpdatePlan", genericArguments: arguments)), in: pipeline) + let recordType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewUpdatePlan.UpdateRecord", genericArguments: arguments)), in: pipeline) + let agentType = try await runtime.resolve(.swift(.type("PreviewsPipeline.PreviewUpdatePlan.AgentRecord", genericArguments: arguments)), in: pipeline) + let packRecordType = try await runtime.resolve( + .swift(.type("PreviewsPipeline.PreviewUpdatePlan.AgentRecord.PackRecord", genericArguments: arguments)), in: pipeline) + let futureType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Future", genericArguments: [.type(planType)])), in: foundation) + let queryGetter = try await hostType.resolve(.swift(.getter("queryManager.getter : PreviewsFoundationHost.QueryManager", as: (() -> AnyObject).self))) + let query = try unsafe queryGetter.unsafeInvoke(on: host) + let graphValue = try await _openExistential(updateGraph as Any, do: nativePreviewOwnedValue) + let queryValue = try await _openExistential(query as Any, do: nativePreviewOwnedValue) + let builderValue = try await _openExistential(builder as Any, do: nativePreviewOwnedValue) + let plan = try await planType.resolve( + .swift( + .staticMethod( + "static PreviewsPipeline.PreviewUpdatePlan.planForUpdating(in: PreviewsPipeline.WorkspaceGraph>, queryManager: PreviewsFoundationHost.QueryManager, workspaceBuilder: A1) throws -> PreviewsFoundationHost.Future>", + as: ((NativeSwiftValue, NativeSwiftValue, NativeSwiftValue) throws -> NativeSwiftValue).self, genericArguments: [.type(builderType)]))) + let future = try unsafe plan.unsafeInvoke(graphValue, queryValue, builderValue) + let awaitValue = try await futureType.resolve( + .swift( + .getter( + "(extension in PreviewsFoundationHost):PreviewsFoundationHost.Future.value.getter : A", + as: (@concurrent () async throws -> NativeSwiftValue).self, declaredAs: "() async throws -> A", + valueABIs: [planType: .opaque(named: planType.name)]))) + return try unsafe await SourcePlan(value: awaitValue.unsafeInvoke(on: future), recordType: recordType, + agentType: agentType, packRecordType: packRecordType, referenceType: reference) + } + + private func sourcePlanRecord(_ plan: SourcePlan, pack: NativeSwiftValue) async throws -> NativeSwiftValue { + let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) + let setType = try await runtime.resolve( + .swift(.type("PreviewsFoundationHost.OrderedIdentifiedSet", genericArguments: [.type(plan.packRecordType)])), in: foundation) + let inhabitedType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Inhabited", genericArguments: [.type(setType)])), in: foundation) + let optionalType = try await runtime.resolve(.swift(.type("Swift.Optional", genericArguments: [.type(plan.packRecordType)]))) + let lookup = try await setType.resolve( + .swift( + .getter( + "PreviewsFoundationHost.OrderedIdentifiedSet.subscript.getter : (A.ID) -> A?", as: ((NativeSwiftValue) -> NativeSwiftValue).self, + valueABIs: [pack.type: .opaque(named: pack.type.name), optionalType: .opaque(named: optionalType.name)], + receiverABI: .opaque(named: setType.name)))) + for record in try await sourcePlanRecords(plan) { + let agent = try await sourceGetter(record, "agentRecord", resultType: plan.agentType) + let packs = try await sourceGetter(agent, "executionPointPacks", resultType: inhabitedType) + let values = try await sourceGetter(packs, + "(extension in PreviewsFoundationHost):PreviewsFoundationHost.PredicatedWrapper.value.getter : A.Predicate.Value", resultType: setType) + let match = try unsafe lookup.unsafeInvoke(on: values, pack.copy()) + if try await match.copyEnumPayload(forCase: "some", valueABIs: [plan.packRecordType: .opaque(named: plan.packRecordType.name)]) != nil { + return record + } + } + throw NativeRuntimeError.invocation("Could not find update record in native update plan for the selected execution point pack") + } + + private func sourcePlanRecords(_ plan: SourcePlan) async throws -> [NativeSwiftValue] { + let foundation = ImageSelector.path(installation.framework("PreviewsFoundationHost", in: "SharedFrameworks")) + let arrayType = try await runtime.resolve(.swift(.type("Swift.Array", genericArguments: [.type(plan.recordType)]))) + let inhabitedType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Inhabited", genericArguments: [.type(arrayType)])), in: foundation) + let headType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.HasHead", genericArguments: [.type(arrayType)])), in: foundation) + let predicatedType = try await runtime.resolve(.swift(.type("PreviewsFoundationHost.Predicated", genericArguments: [.type(headType)])), in: foundation) + let records = try await sourceGetter(plan.value, "updateRecords", resultType: inhabitedType) + let predicated = try await sourceGetter(records, "predicated", resultType: predicatedType) + let values = try await sourceGetter(predicated, "value", resultType: arrayType, resultABI: .pointer) + guard let raw = try values.withCopy({ $0 as? [Any] }) else { + throw NativeRuntimeError.unsupportedContract("Native preview update plan records are not an array") + } + var result: [NativeSwiftValue] = [] + for value in raw { result.append(try await _openExistential(value, do: nativePreviewOwnedValue)) } + return result + } +} + +private struct NativePreviewStaticString: ABIBridgeSwiftValue { + let value: StaticString + static let swiftABIType: NativeType = try! .structure(named: "Swift.StaticString", fields: [.uint64, .uint64, .uint8]) +} diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewProjectInputs.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewProjectInputs.swift new file mode 100644 index 00000000..9d9a1d3c --- /dev/null +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewProjectInputs.swift @@ -0,0 +1,300 @@ +import ABIBridge +import ABIBridgeCore +import ABIBridgeCore.Backend +import Foundation + +/// Synchronizes a workspace's project containers before a preview build and collects the inputs that certify a reusable build. +@safe +@MainActor +final class NativePreviewProjectInputs { + private let runtime = ABIRuntime.shared + + private var synchronizedProjects: [ObjectIdentifier: ProjectSynchronization] = [:] + + private final class ProjectSynchronization { + weak var workspace: AnyObject? + let inputs: NativePreviewInputSnapshot + + init(workspace: AnyObject, inputs: NativePreviewInputSnapshot) { + self.workspace = workspace + self.inputs = inputs + } + } + + func synchronizeProjectContainers(in workspace: AnyObject) async throws { + try Task.checkCancellation() + synchronizedProjects = synchronizedProjects.filter { $0.value.workspace != nil } + let identifier = ObjectIdentifier(workspace) + if let previous = synchronizedProjects[identifier], previous.workspace === workspace, + let current = try? projectConfigurationSnapshot(in: workspace), current == previous.inputs { + return + } + synchronizedProjects[identifier] = nil + let synchronizationStartedAt = Date() + guard let containers = try NativeObjCGetters.object(workspace, selector: "referencedContainers") as? NSSet else { + throw NativeRuntimeError.unsupportedContract("The native workspace has no referenced containers") + } + var updates: [(valid: NativeBoundObjCMethod, edited: NativeBoundObjCMethod, + invalidate: () throws -> Void, queue: OperationQueue)] = [] + var inputFiles: [(invalidate: NativeBoundObjCMethod, modificationDate: NativeBoundObjCMethod)] = [] + func addInputFile(_ filePath: AnyObject) throws { + let path = runtime.object(filePath) + inputFiles.append(( + try path.resolveAndWait(.objc(.method("invalidateFilePath", as: (() -> Void).self))), + try path.resolveAndWait(.objc(.method("modificationDate", as: (() -> AnyObject?).self))) + )) + } + for case let container as NSObject in containers.allObjects + where container !== workspace && container.responds(to: NSSelectorFromString("pbxProject")) { + let native = runtime.object(container) + let valid = try native.resolveAndWait(.objc(.method("isValid", as: (() -> Bool).self))) + guard try unsafe valid.unsafeInvoke() else { continue } + let edited = try native.resolveAndWait(.objc(.method("containerEditedByUserInUI", as: (() -> Bool).self))) + guard try unsafe !edited.unsafeInvoke() else { continue } + let invalidate: () throws -> Void + if container.responds(to: NSSelectorFromString("_invalidateContainerToDiscardInMemoryRepresentation:")) { + let method = try native.resolveAndWait(.objc(.method("_invalidateContainerToDiscardInMemoryRepresentation:", as: ((Bool) -> Void).self))) + invalidate = { try unsafe method.unsafeInvoke(true) } + } else { + let method = try native.resolveAndWait(.objc(.method("_invalidateContainerToDiscardInMemoryRepresentation", as: (() -> Void).self))) + invalidate = { try unsafe method.unsafeInvoke() } + } + guard let graph = try NativeObjCGetters.object(container, selector: "objectGraph"), + let queue = try NativeObjCGetters.object(graph, selector: "changeQueue") as? OperationQueue else { + throw NativeRuntimeError.unsupportedContract("A native project container has no model change queue") + } + let dataFiles = try native.resolveAndWait(.objc(.method("_containerDataFilePaths", as: (() -> NSArray).self))) + for filePath in try unsafe dataFiles.unsafeInvoke() { try addInputFile(filePath as AnyObject) } + updates.append((valid, edited, invalidate, queue)) + } + guard !updates.isEmpty else { return } + if let configurationPaths = try configurationFilePaths(in: containers) { + let paths = configurationPaths.bases.merging(configurationPaths.watched) { existing, _ in existing } + for filePath in paths.values { try addInputFile(filePath) } + } + guard let environment = try NativeObjCGetters.object(workspace, selector: "executionEnvironment") else { + throw NativeRuntimeError.unsupportedContract("The native workspace has no execution environment") + } + let disable = try runtime.object(environment).resolveAndWait( + .objc(.method("disableSubmissionOfBuildOperationsWithReason:", as: ((String) -> Void).self))) + let enable = try runtime.object(environment).resolveAndWait(.objc(.method("enableSubmissionOfBuildOperationsWithReason:", as: ((String) -> Void).self))) + typealias Completion = @convention(block) () -> Void + let cancel = try runtime.object(workspace).resolveAndWait( + .objc(.method("_cancelOngoingBuildWithCompletionBlockIfNeeded:", as: ((Completion?) -> Bool).self))) + let reason = "Synchronizing preview project inputs" + try Task.checkCancellation() + try unsafe disable.unsafeInvoke(reason) + let outcome: Swift.Result + do { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let completed: Completion = { continuation.resume() } + do { + // A false result means no build was queued and the callback will not run. + if try unsafe !cancel.unsafeInvoke(completed) { continuation.resume() } + } catch { continuation.resume(throwing: error) } + } + try Task.checkCancellation() + // Replacement containers use these dates; configuration parsers also reuse the vnode's derived cache. + for file in inputFiles { + try unsafe file.invalidate.unsafeInvoke() + _ = try unsafe file.modificationDate.unsafeInvoke() + } + var queues: [OperationQueue] = [] + var seen: Set = [] + for update in updates { + if seen.insert(ObjectIdentifier(update.queue)).inserted { queues.append(update.queue) } + // Invalidating one container can also replace another referenced container. + guard try unsafe update.valid.unsafeInvoke(), try unsafe !update.edited.unsafeInvoke() else { continue } + try update.invalidate() + } + for queue in queues { + await withCheckedContinuation { continuation in + queue.addBarrierBlock { continuation.resume() } + } + } + try Task.checkCancellation() + outcome = .success(()) + } catch { outcome = .failure(error) } + do { try unsafe enable.unsafeInvoke(reason) } + catch { + let operation: String + switch outcome { + case .success: operation = "Native preview project synchronization completed" + case .failure(let failure): operation = String(describing: failure) + } + throw NativeRuntimeError.invocation("\(operation); failed to resume native build submissions: \(error)") + } + try outcome.get() + // A source edit or invalidated build certificate does not require replacing project models. + // Only certify settings that were already saved before those models were refreshed. + if let inputs = try? projectConfigurationSnapshot(in: workspace), inputs.predates(synchronizationStartedAt) { + synchronizedProjects[identifier] = ProjectSynchronization(workspace: workspace, inputs: inputs) + } + } + + private func projectConfigurationSnapshot(in workspace: AnyObject) throws -> NativePreviewInputSnapshot? { + guard let containers = try NativeObjCGetters.object(workspace, selector: "referencedContainers") as? NSSet, + let configurationPaths = try configurationFilePaths(in: containers), + let configurationFiles = trackableConfigurationFiles(configurationPaths) else { return nil } + var roots = configurationFiles + var missing: Set = [] + for case let container as NSObject in containers.allObjects + where container !== workspace && container.responds(to: NSSelectorFromString("pbxProject")) { + let dataFiles = try runtime.object(container).resolveAndWait(.objc(.method("_containerDataFilePaths", as: (() -> NSArray).self))) + for filePath in try unsafe dataFiles.unsafeInvoke() { + guard let url = try NativeObjCGetters.object(filePath as AnyObject, selector: "fileURL") as? URL, + url.isFileURL, url.path.hasPrefix("/") else { return nil } + if FileManager.default.fileExists(atPath: url.path) { roots.insert(url) } + else { missing.insert(url) } + } + } + return try NativePreviewInputSnapshot.capture(roots: Array(roots), missingInputs: missing) + } + + private func configurationFilePaths(in containers: NSSet) throws -> (bases: [URL: AnyObject], watched: [URL: AnyObject])? { + var baseFiles: [URL: AnyObject] = [:] + var watchedFiles: [URL: AnyObject] = [:] + for entry in containers.allObjects { + guard let container = entry as? NSObject else { return nil } + guard container.responds(to: NSSelectorFromString("pbxProject")) else { continue } + guard let project = try NativeObjCGetters.object(container, selector: "pbxProject"), + let targets = try NativeObjCGetters.object(project, selector: "targets") as? NSArray else { return nil } + for owner in [project] + targets.map({ $0 as AnyObject }) { + guard let list = try NativeObjCGetters.object(owner, selector: "buildConfigurationList"), + let configurations = try NativeObjCGetters.object(list, selector: "buildConfigurations") as? NSArray else { return nil } + for configuration in configurations { + let configuration = configuration as AnyObject + guard try NativeObjCGetters.object(configuration, selector: "baseConfigurationAnchoredReference") != nil else { continue } + guard let reference = try NativeObjCGetters.object(configuration, selector: "resolvedBaseConfigurationReference"), + let path = try NativeObjCGetters.object(reference, selector: "resolvedAbsolutePath") as? String, + path.hasPrefix("/"), + let filePath = try NativeObjCGetters.object(path as NSString, selector: "dvt_absoluteFilePath") else { return nil } + baseFiles[URL(filePath: path).standardizedFileURL] = filePath + let watched = try unsafe runtime.object(configuration).value(forObjCIvar: "_watchedBaseConfigurationFilePaths", as: NSSet?.self) + for filePath in watched?.allObjects ?? [] { + guard let url = try NativeObjCGetters.object(filePath as AnyObject, selector: "fileURL") as? URL, + url.isFileURL, url.path.hasPrefix("/") else { return nil } + watchedFiles[url.standardizedFileURL] = filePath as AnyObject + } + } + } + } + return (baseFiles, watchedFiles) + } + + private func trackableConfigurationFiles(_ configurationPaths: (bases: [URL: AnyObject], watched: [URL: AnyObject])) -> Set? { + let baseFiles = Set(configurationPaths.bases.keys) + let watchedFiles = Set(configurationPaths.watched.keys) + let configurationFiles = baseFiles.union(watchedFiles) + for file in configurationFiles { + // Optional includes can name paths absent from the native watched set. + guard let text = try? String(contentsOf: file, encoding: .utf8), !text.utf8.contains(0x3f) else { return nil } + if baseFiles.contains(file), text.utf8.contains(0x23), !watchedFiles.contains(file) { return nil } + } + return configurationFiles + } + + func inputRoots(workspace: AnyObject, build: NativePreviewBuild.Result, source: URL, excluding: Set = []) throws -> (roots: [URL], missing: Set)? { + guard let declaredInputFiles = build.declaredInputFiles, + let containers = try NativeObjCGetters.object(workspace, selector: "referencedContainers") as? NSSet, + let configurationPaths = try configurationFilePaths(in: containers), + let configurationFiles = trackableConfigurationFiles(configurationPaths) else { return nil } + guard let filePath = try NativeObjCGetters.object(workspace, selector: "representingFilePath"), + let workspaceURL = try NativeObjCGetters.object(filePath, selector: "fileURL") as? URL else { + throw NativeRuntimeError.unsupportedContract("The native workspace has no representing file URL") + } + // Native builder invalidation owns workspace configuration; these trees also detect disk edits synchronously. + var roots: Set = [workspaceURL] + var missing: Set = [] + for case let container as NSObject in containers.allObjects + where container.responds(to: NSSelectorFromString("pbxProject")) { + let dataFiles = try runtime.object(container).resolveAndWait(.objc(.method("_containerDataFilePaths", as: (() -> NSArray).self))) + for filePath in try unsafe dataFiles.unsafeInvoke() { + guard let url = try NativeObjCGetters.object(filePath as AnyObject, selector: "fileURL") as? URL, + url.isFileURL, url.path.hasPrefix("/") else { return nil } + // Native containers include alternate project formats that need not exist on disk. + if FileManager.default.fileExists(atPath: url.path) { roots.insert(url) } + else { missing.insert(url) } + } + } + roots.formUnion(configurationFiles) + roots.formUnion(declaredInputFiles) + var sources: Set = [source] + var pending = build.targets + build.previewRoots + while let target = pending.popLast() { + sources.formUnion(target.sourceFiles) + pending += target.dependencies + } + sources = NativePreviewBuildInputs.removingGeneratedPaths(from: sources, generatedPaths: build.generatedInputPaths) + let sourceDirectories = try Set(sources.map { source in + guard source.isFileURL, source.path.hasPrefix("/") else { + throw NativeRuntimeError.unsupportedContract("A native build source has no absolute file URL: \(source)") + } + return source.deletingLastPathComponent().standardizedFileURL + }) + var packageSearches: Set = [] + for sourceDirectory in sourceDirectories { + roots.insert(sourceDirectory) + var directory = sourceDirectory + while packageSearches.insert(directory.path).inserted { + if FileManager.default.fileExists(atPath: directory.appendingPathComponent("Package.swift").path) { + roots.insert(directory) + break + } + let parent = directory.deletingLastPathComponent().standardizedFileURL + if parent.path == directory.path { break } + directory = parent + } + } + struct RootFact { + let url: URL + let path: String + let components: [String] + } + let unique = Set(roots.map(\.standardizedFileURL)) + let facts: [RootFact] = unique.map { + RootFact(url: $0, path: $0.path, components: $0.pathComponents) + } + let normalized = facts.sorted { left, right in + if left.components.count == right.components.count { return left.path < right.path } + return left.components.count < right.components.count + } + var exclusionIDs: [[String]: Int] = [:] + for excluded in excluding.union(build.inputCaptureExclusions) { + for path in [excluded.standardizedFileURL.pathComponents, + excluded.resolvingSymlinksInPath().pathComponents] { + if exclusionIDs[path] == nil { exclusionIDs[path] = exclusionIDs.count } + } + } + var result: [URL] = [] + var retained: [[String]: [Set]] = [:] + for candidate in normalized { + var candidateExclusions: Set = [] + for path in [candidate.components, candidate.url.resolvingSymlinksInPath().pathComponents] { + var prefix: [String] = [] + prefix.reserveCapacity(path.count) + for component in path { + prefix.append(component) + if let id = exclusionIDs[prefix] { candidateExclusions.insert(id) } + } + } + var prefix: [String] = [] + prefix.reserveCapacity(candidate.components.count) + var covered = false + for component in candidate.components { + prefix.append(component) + if let parents = retained[prefix], parents.contains(where: { + candidateExclusions.isSubset(of: $0) + }) { + covered = true + break + } + } + if !covered { + result.append(candidate.url) + retained[candidate.components, default: []].append(candidateExclusions) + } + } + return (result, missing) + } +} diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewSession.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewSession.swift index 8d01b537..e32bd1f5 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewSession.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewSession.swift @@ -30,7 +30,7 @@ final class NativePreviewSession { systemVersion = build.systemVersion } - init(_ destination: NativePreviewBuild.Destination) { + init(_ destination: NativePreviewDestinations.Destination) { identifier = destination.identifier systemVersion = destination.systemVersion } @@ -43,8 +43,8 @@ final class NativePreviewSession { let location: NativePreviewDefinitions.Definition let index: Int let localization: String? - let context: NativePreviewBuild.PlanningContext - let destination: NativePreviewBuild.DestinationSelection + let context: NativePreviewDestinations.PlanningContext + let destination: NativePreviewDestinations.Selection var certificate: BuildCertificate? } @@ -234,7 +234,7 @@ final class NativePreviewSession { } } - func prepareSimulator(destination: NativePreviewBuild.Destination, + func prepareSimulator(destination: NativePreviewDestinations.Destination, process: NativePreviewProcess) async throws { guard destination.previewPlatform?.isSimulator == true else { return } try await prepareSimulator(destination: SimulatorDestination(destination), diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift index ab455035..18543bb1 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift @@ -10,6 +10,8 @@ final class NativePreviewTool { private let installation: NativeXcodeInstallation private let builder: NativePreviewBuild private let definitions: NativePreviewDefinitions + private let destinations: NativePreviewDestinations + private let projectInputs = NativePreviewProjectInputs() private var operations: [UUID: (request: URL?, task: Task)] = [:] private var sessions: [String: NativePreviewSession] = [:] private let renderQueue = NativePreviewRenderQueue() @@ -20,6 +22,7 @@ final class NativePreviewTool { self.installation = installation builder = NativePreviewBuild(installation: installation) definitions = NativePreviewDefinitions(installation: installation) + destinations = NativePreviewDestinations(installation: installation) } static func handles(_ action: NativeActionClass) -> Bool { @@ -249,8 +252,8 @@ final class NativePreviewTool { let workspace: AnyObject let source: URL let location: NativePreviewDefinitions.Definition - let destination: NativePreviewBuild.DestinationSelection - let context: NativePreviewBuild.PlanningContext + let destination: NativePreviewDestinations.Selection + let context: NativePreviewDestinations.PlanningContext let retainedBuild: (build: NativePreviewBuild.Result, signature: NativePreviewProductSignature)? let reusesDestination: Bool let inputRevision: UInt64 @@ -262,12 +265,12 @@ final class NativePreviewTool { let inputRevision = session.inputRevision let workspace = try await workspace(input.workspaceIdentifier) try await NativeWorkspaceRegistry.waitForSourcePackages(in: workspace) - let currentContext = try builder.planningContext(workspace: workspace) + let currentContext = try destinations.planningContext(workspace: workspace) var inputsAreCurrent = false if let plan = session.plan, let certificate = plan.certificate, - plan.context.matches(try builder.planningContext(workspace: workspace, destination: plan.destination)) { + plan.context.matches(try destinations.planningContext(workspace: workspace, destination: plan.destination)) { do { - let currentBuilder = try await builder.workspaceBuilder(for: plan.destination) + let currentBuilder = try plan.destination.workspaceBuilder() if currentBuilder === certificate.workspaceBuilder, try await NativePreviewInputSnapshot.matchesCurrentFiles( source: certificate.inputs, generated: certificate.generatedInputs), @@ -275,11 +278,11 @@ final class NativePreviewTool { inputsAreCurrent = true if plan.requestKey == input.requestKey, plan.sourcePath == input.sourcePath, certificate.build.previewPlatform != nil, let signature = session.signature { - let resolution = try await builder.resolveDestination(workspace: workspace, input: input.nativeValue) - if try await builder.destinationResolution(resolution, matches: plan.destination.resolution), + let resolution = try await destinations.resolveDestination(workspace: workspace, input: input.nativeValue) + if try await destinations.destinationResolution(resolution, matches: plan.destination.resolution), try await signature.matchesCurrentFiles(digestCache: session.productDigests), inputRevision == session.inputRevision, - plan.context.matches(try builder.planningContext(workspace: workspace, destination: plan.destination)) { - let destination = NativePreviewBuild.DestinationSelection(selected: plan.destination.selected, resolution: resolution) + plan.context.matches(try destinations.planningContext(workspace: workspace, destination: plan.destination)) { + let destination = NativePreviewDestinations.Selection(selected: plan.destination.selected, resolution: resolution) return Prepared(workspace: workspace, source: plan.source, location: plan.location, destination: destination, context: currentContext, retainedBuild: (certificate.build, signature), reusesDestination: true, @@ -294,21 +297,21 @@ final class NativePreviewTool { } if !inputsAreCurrent { session.plan = nil - try await builder.synchronizeProjectContainers(in: workspace) + try await projectInputs.synchronizeProjectContainers(in: workspace) try await NativeWorkspaceRegistry.waitForSourcePackages(in: workspace) } session.plan?.certificate = nil let source = try await definitions.sourceURL(input.sourcePath, workspace: workspace) let location = try await definitions.definition(in: source, at: input.index) - let context = try builder.planningContext(workspace: workspace) - let resolution = try await builder.resolveDestination(workspace: workspace, input: input.nativeValue) + let context = try destinations.planningContext(workspace: workspace) + let resolution = try await destinations.resolveDestination(workspace: workspace, input: input.nativeValue) if let plan = session.plan, plan.source == source, plan.index == input.index, plan.localization == input.localization, - plan.context.matches(try builder.planningContext(workspace: workspace, destination: plan.destination)), - try await builder.destinationResolution(resolution, matches: plan.destination.resolution) { + plan.context.matches(try destinations.planningContext(workspace: workspace, destination: plan.destination)), + try await destinations.destinationResolution(resolution, matches: plan.destination.resolution) { do { // The current build certifies a retained plan; stale plans return to native selection below. - let destination = NativePreviewBuild.DestinationSelection(selected: plan.destination.selected, resolution: resolution) + let destination = NativePreviewDestinations.Selection(selected: plan.destination.selected, resolution: resolution) let build = try await builder.build(workspace: workspace, destination: destination, source: source) if let platform = build.previewPlatform { let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/PreviewRenderer/\(platform.helperDirectory)") @@ -316,7 +319,7 @@ final class NativePreviewTool { digestCache: session.productDigests, additionalProducts: session.additionalProducts) if signature == session.signature, - plan.context.matches(try builder.planningContext(workspace: workspace, destination: plan.destination)) { + plan.context.matches(try destinations.planningContext(workspace: workspace, destination: plan.destination)) { return Prepared(workspace: workspace, source: source, location: location, destination: destination, context: context, retainedBuild: (build, signature), reusesDestination: true, inputRevision: inputRevision, reusedCertificate: nil) @@ -328,7 +331,7 @@ final class NativePreviewTool { } } session.plan = nil - let destination = try await builder.selectDestination(workspace: workspace, source: location.source, resolution: resolution) + let destination = try await destinations.selectDestination(workspace: workspace, source: location.source, resolution: resolution) _ = try await builder.prepare(workspace: workspace) try Task.checkCancellation() return Prepared(workspace: workspace, source: source, location: location, destination: destination, @@ -337,12 +340,12 @@ final class NativePreviewTool { } private func certifyBuild(_ build: NativePreviewBuild.Result, workspace: AnyObject, - destination: NativePreviewBuild.DestinationSelection, source: URL, + destination: NativePreviewDestinations.Selection, source: URL, session: NativePreviewSession, inputRevision: UInt64) async throws -> NativePreviewSession.BuildCertificate? { guard let buildStartedAt = build.buildStartedAt, let buildCompletedAt = build.buildCompletedAt, let workspaceBuilder = build.workspaceBuilder else { return nil } let outputPaths = build.inputCaptureExclusions.union([session.artifactsRoot]) - guard let inputsToCapture = try builder.inputRoots(workspace: workspace, build: build, source: source, excluding: outputPaths) else { return nil } + guard let inputsToCapture = try projectInputs.inputRoots(workspace: workspace, build: build, source: source, excluding: outputPaths) else { return nil } let exclusions = NativePreviewInputSnapshot.coalescedExclusions(outputPaths, roots: inputsToCapture.roots) let inputs = try await NativePreviewInputSnapshot.capture(roots: inputsToCapture.roots, excluding: exclusions, missingInputs: build.missingInputFiles.union(inputsToCapture.missing)) @@ -353,7 +356,7 @@ final class NativePreviewTool { excluding: build.generatedInputExclusions, missingInputs: build.generatedMissingInputFiles) // Generated inputs may be written by this build, but never after its native operation completed. guard generatedInputs.predates(buildCompletedAt) else { return nil } - let currentBuilder = try await builder.workspaceBuilder(for: destination) + let currentBuilder = try destination.workspaceBuilder() guard currentBuilder === workspaceBuilder, inputRevision == session.inputRevision else { return nil } return NativePreviewSession.BuildCertificate(build: build, workspaceBuilder: workspaceBuilder, inputs: inputs, generatedInputs: generatedInputs) @@ -430,7 +433,7 @@ final class NativePreviewTool { } private func prepareStage(_ input: Input, prepared: Prepared, session: NativePreviewSession, - build: NativePreviewBuild.Result, destination: NativePreviewBuild.DestinationSelection, + build: NativePreviewBuild.Result, destination: NativePreviewDestinations.Selection, platform: NativePreviewPlatform, process: NativePreviewProcess, metadataOnly: Bool? = nil, isLegacyComplication: Bool? = nil, nativeWidget: Bool = false) async throws -> NativePreviewSession.RendererStage { @@ -480,7 +483,7 @@ final class NativePreviewTool { } private func prepareRenderer(_ input: Input, prepared: Prepared, directory: URL, build: NativePreviewBuild.Result, - destination: NativePreviewBuild.DestinationSelection, + destination: NativePreviewDestinations.Selection, platform: NativePreviewPlatform, process: NativePreviewProcess, digestCache: NativePreviewProductSignature.DigestCache, metadataOnly: Bool? = nil, isLegacyComplication: Bool? = nil, @@ -503,7 +506,7 @@ final class NativePreviewTool { product = appProduct sourceProduct = nil } else { - product = try await builder.frameworkAgent(for: destination) + product = try await destinations.frameworkAgent(for: destination) sourceProduct = NativePreviewStaging.frameworkBundle(containing: output) ?? output } let app = directory.appendingPathComponent(sourceProduct == nil ? "Preview.app" : product.lastPathComponent, isDirectory: true) @@ -691,12 +694,12 @@ final class NativePreviewTool { guard let metadata = metadataResponse.nativeMetadata else { throw NativeRuntimeError.invocation("The preview process returned no native metadata") } - let evaluated: NativePreviewBuild.DestinationSelection + let evaluated: NativePreviewDestinations.Selection if prepared.reusesDestination, session.plan != nil { evaluated = destination } else { - let resolution = try await builder.resolveDestination(workspace: workspace, input: input.nativeValue) - evaluated = try await builder.selectDestination(workspace: workspace, source: location.source, + let resolution = try await destinations.resolveDestination(workspace: workspace, input: input.nativeValue) + evaluated = try await destinations.selectDestination(workspace: workspace, source: location.source, resolution: resolution, metadata: metadata, providerDescription: metadataResponse.nativeProviderPreviewDescription) } @@ -708,13 +711,13 @@ final class NativePreviewTool { platform = selectedPlatform try await session.update(build: build, source: prepared.source, platform: platform, process: process) } - let planContext = try builder.planningContext(workspace: workspace, destination: destination) + let planContext = try destinations.planningContext(workspace: workspace, destination: destination) let isLegacyComplication: Bool? if platform == .watchOS, location.providerPath != nil { let complication: Bool if let cached = metadataEntry.isComplicationPreview { complication = cached } else { - complication = try await builder.isComplicationPreview(metadata: metadata) + complication = try await destinations.isComplicationPreview(metadata: metadata) metadataEntry.isComplicationPreview = complication } isLegacyComplication = complication ? true : nil @@ -723,7 +726,7 @@ final class NativePreviewTool { if platform == .iOS || platform == .watchOS { if let cached = metadataEntry.isWidgetPreview { nativeWidget = cached } else { - nativeWidget = try await builder.isWidgetPreview(metadata: metadata) + nativeWidget = try await destinations.isWidgetPreview(metadata: metadata) metadataEntry.isWidgetPreview = nativeWidget } } else { nativeWidget = false } @@ -745,7 +748,7 @@ final class NativePreviewTool { specification = try await definitions.registrySpecification(registry: registry, moduleName: moduleName) } else if let providerName = renderer.request.providerTypeName, let description = metadataResponse.nativeProviderPreviewDescription { specification = try await definitions.providerSpecification(name: providerName, - description: builder.decodePreviewValue(description, named: "PreviewDescription")) + description: destinations.decodePreviewValue(description, named: "PreviewDescription")) } else { throw NativePipelineRequired() } if !stage.nativeWidgetPrepared { let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/PreviewRenderer/\(platform.helperDirectory)") @@ -848,8 +851,8 @@ final class NativePreviewTool { } } } - if prepared.context.matches(try builder.planningContext(workspace: workspace)), - planContext.matches(try builder.planningContext(workspace: workspace, destination: destination)) { + if prepared.context.matches(try destinations.planningContext(workspace: workspace)), + planContext.matches(try destinations.planningContext(workspace: workspace, destination: destination)) { session.plan = NativePreviewSession.RetainedPlan(requestKey: input.requestKey, sourcePath: input.sourcePath, source: prepared.source, location: prepared.location, index: input.index, localization: input.localization, context: planContext, destination: destination, certificate: certificate) diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewBuildTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewBuildTests.swift index 9a48ba0d..547aedd8 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewBuildTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewBuildTests.swift @@ -6,7 +6,7 @@ import Testing @MainActor struct NativePreviewBuildTests { @Test func sourceSelectionsWaitForRestorationAndCancelQueuedOperations() async throws { - let (builder, root) = try sourceSelectionBuilder() + let (destinations, root) = try sourceSelectionDestinations() defer { try? FileManager.default.removeItem(at: root) } let workspace = NSObject() let entered = AsyncStream.makeStream() @@ -15,7 +15,7 @@ struct NativePreviewBuildTests { var input = "original" var observed: [String] = [] let first = Task { @MainActor in - try await builder.withSourceSelection(workspace: workspace) { + try await destinations.withSourceSelection(workspace: workspace) { input = "first" entered.continuation.yield(()) defer { input = "original"; observed.append("restored") } @@ -27,7 +27,7 @@ struct NativePreviewBuildTests { _ = await ready.next() let second = Task { @MainActor in attempted.continuation.yield(()) - return try await builder.withSourceSelection(workspace: workspace) { + return try await destinations.withSourceSelection(workspace: workspace) { observed.append(input) return input } @@ -35,7 +35,7 @@ struct NativePreviewBuildTests { var pending = attempted.stream.makeAsyncIterator() _ = await pending.next() let cancelled = Task { @MainActor in - try await builder.withSourceSelection(workspace: workspace) { + try await destinations.withSourceSelection(workspace: workspace) { observed.append("cancelled operation ran") } } @@ -52,7 +52,7 @@ struct NativePreviewBuildTests { } @Test func sourceSelectionDoesNotBlockAnotherWorkspace() async throws { - let (builder, root) = try sourceSelectionBuilder() + let (destinations, root) = try sourceSelectionDestinations() defer { try? FileManager.default.removeItem(at: root) } let firstWorkspace = NSObject() let secondWorkspace = NSObject() @@ -61,7 +61,7 @@ struct NativePreviewBuildTests { let attempted = AsyncStream.makeStream() var secondEntered = false let first = Task { @MainActor in - try await builder.withSourceSelection(workspace: firstWorkspace) { + try await destinations.withSourceSelection(workspace: firstWorkspace) { entered.continuation.yield(()) for await _ in release.stream { break } } @@ -70,7 +70,7 @@ struct NativePreviewBuildTests { _ = await ready.next() let second = Task { @MainActor in attempted.continuation.yield(()) - try await builder.withSourceSelection(workspace: secondWorkspace) { secondEntered = true } + try await destinations.withSourceSelection(workspace: secondWorkspace) { secondEntered = true } } var pending = attempted.stream.makeAsyncIterator() _ = await pending.next() @@ -81,16 +81,22 @@ struct NativePreviewBuildTests { try await second.value } - private func sourceSelectionBuilder() throws -> (NativePreviewBuild, URL) { + private func sourceSelectionDestinations() throws -> (NativePreviewDestinations, URL) { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) let app = root.appendingPathComponent("Xcode.app") try FileManager.default.createDirectory(at: app.appendingPathComponent("Contents/Frameworks/IDEFoundation.framework"), withIntermediateDirectories: true) - return (NativePreviewBuild(installation: try NativeXcodeInstallation(developerDirectory: app)), root) + return (NativePreviewDestinations(installation: try NativeXcodeInstallation(developerDirectory: app)), root) + } + + private func projectInputs() throws -> (NativePreviewProjectInputs, URL) { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + return (NativePreviewProjectInputs(), root) } @Test func inputRootsDetectReferencedProjectConfigurationChangesOutsideWorkspace() throws { - let (builder, root) = try sourceSelectionBuilder() + let (inputs, root) = try projectInputs() defer { try? FileManager.default.removeItem(at: root) } let workspaceURL = root.appendingPathComponent("Workspace/Fixture.xcworkspace") let projectFile = root.appendingPathComponent("Project/Fixture.xcodeproj/project.pbxproj") @@ -106,7 +112,7 @@ struct NativePreviewBuildTests { let build = NativePreviewBuild.Result(targets: [], previewRoots: [], destinationIdentifier: "destination", previewDestinationIdentifier: "preview", platformIdentifier: nil, previewPlatform: nil, platformName: nil, deviceModelName: nil, systemVersion: nil, declaredInputFiles: []) - let roots = try #require(try builder.inputRoots(workspace: workspace, build: build, source: source)) + let roots = try #require(try inputs.inputRoots(workspace: workspace, build: build, source: source)) #expect(roots.missing == [alternateProjectFile]) let before = try NativePreviewInputSnapshot.capture(roots: roots.roots, missingInputs: roots.missing) #expect(try before.matchesCurrentFiles()) @@ -124,7 +130,7 @@ struct NativePreviewBuildTests { @Test(arguments: [false, true]) func projectSynchronizationSkipsSourceChangesButRefreshesSavedProjects(legacy: Bool) async throws { - let (builder, root) = try sourceSelectionBuilder() + let (inputs, root) = try projectInputs() defer { try? FileManager.default.removeItem(at: root) } let projectFile = root.appendingPathComponent("Fixture.xcodeproj/project.pbxproj") let alternate = projectFile.deletingLastPathComponent().appendingPathComponent("project.xcproj") @@ -137,27 +143,27 @@ struct NativePreviewBuildTests { ? LegacyPreviewBuildProjectContainer(dataFiles: files) : PreviewBuildProjectContainer(dataFiles: files) let workspace = PreviewBuildWorkspace(url: root.appendingPathComponent("Fixture.xcworkspace"), containers: [container]) - try await builder.synchronizeProjectContainers(in: workspace) + try await inputs.synchronizeProjectContainers(in: workspace) #expect(container.synchronizationCount == 1) try Data("edited view".utf8).write(to: source) - try await builder.synchronizeProjectContainers(in: workspace) + try await inputs.synchronizeProjectContainers(in: workspace) #expect(container.synchronizationCount == 1) try Data("edited project".utf8).write(to: projectFile) - try await builder.synchronizeProjectContainers(in: workspace) + try await inputs.synchronizeProjectContainers(in: workspace) #expect(container.synchronizationCount == 2) try Data("alternate project".utf8).write(to: alternate) - try await builder.synchronizeProjectContainers(in: workspace) + try await inputs.synchronizeProjectContainers(in: workspace) #expect(container.synchronizationCount == 3) // A new workspace must refresh even when it opens the same files. let replacement = PreviewBuildWorkspace(url: workspace.representingFilePath.fileURL, containers: [container]) - try await builder.synchronizeProjectContainers(in: replacement) + try await inputs.synchronizeProjectContainers(in: replacement) #expect(container.synchronizationCount == 4) } @Test func untrackableProjectSettingsContinueRefreshing() async throws { - let (builder, root) = try sourceSelectionBuilder() + let (inputs, root) = try projectInputs() defer { try? FileManager.default.removeItem(at: root) } let projectFile = root.appendingPathComponent("project.pbxproj") try Data("project".utf8).write(to: projectFile) @@ -165,8 +171,8 @@ struct NativePreviewBuildTests { container.pbxProject.targets = nil let workspace = PreviewBuildWorkspace(url: root.appendingPathComponent("Fixture.xcworkspace"), containers: [container]) - try await builder.synchronizeProjectContainers(in: workspace) - try await builder.synchronizeProjectContainers(in: workspace) + try await inputs.synchronizeProjectContainers(in: workspace) + try await inputs.synchronizeProjectContainers(in: workspace) #expect(container.synchronizationCount == 2) } From 668bba82e6661aebe3403843f2fa7c81523f82c6 Mon Sep 17 00:00:00 2001 From: Kazuki Nakashima <65545348+lynnswap@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:11:58 +0900 Subject: [PATCH 2/2] Keep the native DestinationResolution name in ABI lookups Co-Authored-By: Claude Opus 5.5 --- Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift index 124a9762..af42f4e2 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewDestinations.swift @@ -275,7 +275,7 @@ final class NativePreviewDestinations { let host = try unsafe createHost.unsafeInvoke(false) let resolutionType: NativeSwiftType do { - resolutionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.Resolution")), in: previews) + resolutionType = try await runtime.resolve(.swift(.type("PreviewsXcode.RenderPreviewAction.DestinationResolution")), in: previews) } catch is ABIResolutionError { return try await currentDestinationResolution(host: host, input: input) } @@ -283,7 +283,7 @@ final class NativePreviewDestinations { let resolve = try await actionType.resolve( .swift( .staticMethod( - "static PreviewsXcode.RenderPreviewAction.resolveDestination(input: PreviewsXcode.RenderPreviewAction.Input, sceneHost: PreviewsXcode.XcodeWorkspaceSceneHost) async -> PreviewsXcode.RenderPreviewAction.Resolution", + "static PreviewsXcode.RenderPreviewAction.resolveDestination(input: PreviewsXcode.RenderPreviewAction.Input, sceneHost: PreviewsXcode.XcodeWorkspaceSceneHost) async -> PreviewsXcode.RenderPreviewAction.DestinationResolution", as: (@concurrent (NativeSwiftValue, AnyObject) async -> NativeSwiftValue).self, valueABIs: [input.type: .opaque(named: input.type.name), resolutionType: .opaque(named: resolutionType.name)]))) let resolution = try unsafe await resolve.unsafeInvoke(input, host)