From 24cb74e6c9f7b9613b0daa8627ef99e64a12294d Mon Sep 17 00:00:00 2001 From: Kazuki Nakashima <65545348+lynnswap@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:55:18 +0900 Subject: [PATCH] Rename the native Correction classes after what they do Co-Authored-By: Claude Opus 5.5 --- .../NativeCrashData.swift | 4 +- ...orrection.swift => NativeCrashTools.swift} | 2 +- .../NativeExecutionOperations.swift | 4 +- .../NativePreviewBuild.swift | 4 +- .../NativePreviewProductSignature.swift | 4 +- .../NativePreviewSnapshot.swift | 4 +- ...rrection.swift => NativePreviewTool.swift} | 2 +- ...ift => NativeSimulatorLaunchTracker.swift} | 2 +- ...t => NativeTestableStateNoticeGuard.swift} | 2 +- .../NativeToolBackend.swift | 64 +++---- .../NativeCrashDataTests.swift | 4 +- ...ests.swift => NativeCrashToolsTests.swift} | 94 +++++----- .../NativePreviewDiscoveryTests.swift | 16 +- .../NativePreviewLocationTests.swift | 4 +- .../NativePreviewOptionsTests.swift | 24 +-- .../NativePreviewProcessTests.swift | 2 +- .../NativePreviewSnapshotTests.swift | 16 +- ...sts.swift => NativePreviewToolTests.swift} | 170 +++++++++--------- 18 files changed, 211 insertions(+), 211 deletions(-) rename Sources/XcodeMCPNativeRuntime/{NativeCrashToolCorrection.swift => NativeCrashTools.swift} (99%) rename Sources/XcodeMCPNativeRuntime/{NativePreviewCorrection.swift => NativePreviewTool.swift} (99%) rename Sources/XcodeMCPNativeRuntime/{NativeSimulatorLaunchCorrection.swift => NativeSimulatorLaunchTracker.swift} (97%) rename Sources/XcodeMCPNativeRuntime/{NativeTestableStateCorrection.swift => NativeTestableStateNoticeGuard.swift} (98%) rename Tests/XcodeMCPNativeRuntimeTests/{NativeCrashToolCorrectionTests.swift => NativeCrashToolsTests.swift} (88%) rename Tests/XcodeMCPNativeRuntimeTests/{NativePreviewCorrectionTests.swift => NativePreviewToolTests.swift} (93%) diff --git a/Sources/XcodeMCPNativeRuntime/NativeCrashData.swift b/Sources/XcodeMCPNativeRuntime/NativeCrashData.swift index 2b34eb02..b9f04654 100644 --- a/Sources/XcodeMCPNativeRuntime/NativeCrashData.swift +++ b/Sources/XcodeMCPNativeRuntime/NativeCrashData.swift @@ -153,7 +153,7 @@ struct NativeCrashReadRequest: Decodable, Sendable { } enum NativeCrashContract { - static func describe(_ kind: NativeCrashToolCorrection.Kind) -> NativeTool { + static func describe(_ kind: NativeCrashTools.Kind) -> NativeTool { func property(_ type: String, _ description: String) -> JSONValue { .object(["type": .string(type), "description": .string(description)]) } @@ -262,7 +262,7 @@ enum NativeCrashContract { ]), workspaceScoped: kind == .sync) } - private static func describeJob(_ kind: NativeCrashToolCorrection.Kind, description: String, inputs: [String: JSONValue], + private static func describeJob(_ kind: NativeCrashTools.Kind, description: String, inputs: [String: JSONValue], required: [String]) -> NativeTool { let outputs: [String: JSONValue] = [ "jobId": .object(["type": .string("string"), "description": .string("Persistent crash sync job identifier.")]), diff --git a/Sources/XcodeMCPNativeRuntime/NativeCrashToolCorrection.swift b/Sources/XcodeMCPNativeRuntime/NativeCrashTools.swift similarity index 99% rename from Sources/XcodeMCPNativeRuntime/NativeCrashToolCorrection.swift rename to Sources/XcodeMCPNativeRuntime/NativeCrashTools.swift index 41209aea..c8a4611a 100644 --- a/Sources/XcodeMCPNativeRuntime/NativeCrashToolCorrection.swift +++ b/Sources/XcodeMCPNativeRuntime/NativeCrashTools.swift @@ -5,7 +5,7 @@ import XcodeMCPWire @safe @MainActor -final class NativeCrashToolCorrection { +final class NativeCrashTools { enum Kind: String, CaseIterable { case sync = "SyncOrganizerCrashReports" case read = "ReadOrganizerCrashChanges" diff --git a/Sources/XcodeMCPNativeRuntime/NativeExecutionOperations.swift b/Sources/XcodeMCPNativeRuntime/NativeExecutionOperations.swift index ae0ca766..586fa8f5 100644 --- a/Sources/XcodeMCPNativeRuntime/NativeExecutionOperations.swift +++ b/Sources/XcodeMCPNativeRuntime/NativeExecutionOperations.swift @@ -9,7 +9,7 @@ final class NativeExecutionOperations { private let callback: Callback private let hook: NativeObjCMethodHook private let launchSessionHook: NativeObjCMethodHook - private let simulatorLaunchCorrection: NativeSimulatorLaunchCorrection + private let simulatorLaunchTracker: NativeSimulatorLaunchTracker @MainActor init() throws { let ownership = NativeLaunchOwnership() @@ -19,7 +19,7 @@ final class NativeExecutionOperations { let runtime = ABIRuntime.shared let callback = Callback(operation: try runtime.resolveAndWait(.objc(.method("operation", as: (() -> AnyObject?).self)), on: trackerClass)) self.callback = callback - simulatorLaunchCorrection = try NativeSimulatorLaunchCorrection(ownership: ownership, + simulatorLaunchTracker = try NativeSimulatorLaunchTracker(ownership: ownership, onFailure: { callback.recordFailure($0) }) launchSessionHook = try unsafe runtime.hookCalls( .objc(.method("setLaunchSession:", as: ((AnyObject?) -> Void).self)), on: trackerClass, diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift index 9789f29b..9c67067b 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewBuild.swift @@ -664,7 +664,7 @@ final class NativePreviewBuild { var result = records.map(\.target) var previewRoots: [Target] = [] if let platform { - let selection = try NativePreviewCorrection.selectTarget(result, source: source, platform: platform) + let selection = try NativePreviewTool.selectTarget(result, source: source, platform: platform) if let index = result.firstIndex(where: { $0.outputURL == selection.host.outputURL && $0.sdkRoot == selection.host.sdkRoot && $0.sdkVariant == selection.host.sdkVariant && $0.architecture == selection.host.architecture @@ -681,7 +681,7 @@ final class NativePreviewBuild { result[index].compileCommandLine = try await compileCommandLine(for: records[index], priorBuild: priorBuild, workspace: workspace, source: source, image: image) } - if let hostOutput = selection.host.outputURL, NativePreviewCorrection.productBundle(containing: hostOutput) == nil { + if let hostOutput = selection.host.outputURL, NativePreviewTool.productBundle(containing: hostOutput) == nil { let sourceRecord = (buildable: records[index].buildable, native: records[index].native, target: result[index]) let dependencies = try await dependencies(for: sourceRecord, records: records, buildables: buildables, image: image, priorBuild: priorBuild, workspace: workspace, scheme: scheme, destination: destination) diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewProductSignature.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewProductSignature.swift index 44f65dcf..23e92b44 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewProductSignature.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewProductSignature.swift @@ -91,8 +91,8 @@ struct NativePreviewProductSignature: Equatable, Sendable { var pending = build.targets + build.previewRoots while let target = pending.popLast() { if let output = target.outputURL { - products.insert(NativePreviewCorrection.productBundle(containing: output) - ?? NativePreviewCorrection.frameworkBundle(containing: output) ?? output) + products.insert(NativePreviewTool.productBundle(containing: output) + ?? NativePreviewTool.frameworkBundle(containing: output) ?? output) } products.formUnion(target.resourceURLs) pending += target.dependencies diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewSnapshot.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewSnapshot.swift index 31e3b5e0..77e054b8 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewSnapshot.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewSnapshot.swift @@ -4,7 +4,7 @@ import CoreGraphics import Foundation import ImageIO -extension NativePreviewCorrection { +extension NativePreviewTool { func writeSnapshot(from source: Data, to destination: URL, deviceType: URL?, usesDeviceLayout: Bool, orientation: String?, exclusion: Data? = nil) async throws { guard let imageSource = CGImageSourceCreateWithData(source as CFData, nil), @@ -44,7 +44,7 @@ extension NativePreviewCorrection { return snapshot.png } let data = NSMutableData() - guard let thumbnail = NativePreviewCorrection.thumbnail(from: image, maximumDimension: 1500, + guard let thumbnail = NativePreviewTool.thumbnail(from: image, maximumDimension: 1500, framebufferMask: framebufferMask, rotationDegrees: rotationDegrees, swapsAxes: swapsAxes, exclusionImage: exclusionImage), let output = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else { diff --git a/Sources/XcodeMCPNativeRuntime/NativePreviewCorrection.swift b/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift similarity index 99% rename from Sources/XcodeMCPNativeRuntime/NativePreviewCorrection.swift rename to Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift index 99edf566..9bc37f69 100644 --- a/Sources/XcodeMCPNativeRuntime/NativePreviewCorrection.swift +++ b/Sources/XcodeMCPNativeRuntime/NativePreviewTool.swift @@ -5,7 +5,7 @@ import Foundation import XcodeMCPWire @MainActor -final class NativePreviewCorrection { +final class NativePreviewTool { private static let defaultTimeout: Int64 = 300 private let installation: NativeXcodeInstallation private let builder: NativePreviewBuild diff --git a/Sources/XcodeMCPNativeRuntime/NativeSimulatorLaunchCorrection.swift b/Sources/XcodeMCPNativeRuntime/NativeSimulatorLaunchTracker.swift similarity index 97% rename from Sources/XcodeMCPNativeRuntime/NativeSimulatorLaunchCorrection.swift rename to Sources/XcodeMCPNativeRuntime/NativeSimulatorLaunchTracker.swift index 4346c531..659668a4 100644 --- a/Sources/XcodeMCPNativeRuntime/NativeSimulatorLaunchCorrection.swift +++ b/Sources/XcodeMCPNativeRuntime/NativeSimulatorLaunchTracker.swift @@ -2,7 +2,7 @@ import ABIBridge import Foundation @safe -final class NativeSimulatorLaunchCorrection { +final class NativeSimulatorLaunchTracker { private let initialization: NativeObjCMethodHook? private let completion: NativeObjCMethodHook? diff --git a/Sources/XcodeMCPNativeRuntime/NativeTestableStateCorrection.swift b/Sources/XcodeMCPNativeRuntime/NativeTestableStateNoticeGuard.swift similarity index 98% rename from Sources/XcodeMCPNativeRuntime/NativeTestableStateCorrection.swift rename to Sources/XcodeMCPNativeRuntime/NativeTestableStateNoticeGuard.swift index caedd497..4227f1fc 100644 --- a/Sources/XcodeMCPNativeRuntime/NativeTestableStateCorrection.swift +++ b/Sources/XcodeMCPNativeRuntime/NativeTestableStateNoticeGuard.swift @@ -4,7 +4,7 @@ import Synchronization @safe @MainActor -final class NativeTestableStateCorrection { +final class NativeTestableStateNoticeGuard { private let callback: NativeTestableStateCallback private let hook: NativeObjCMethodHook diff --git a/Sources/XcodeMCPNativeRuntime/NativeToolBackend.swift b/Sources/XcodeMCPNativeRuntime/NativeToolBackend.swift index e6245ca5..f53a9a96 100644 --- a/Sources/XcodeMCPNativeRuntime/NativeToolBackend.swift +++ b/Sources/XcodeMCPNativeRuntime/NativeToolBackend.swift @@ -63,14 +63,14 @@ extension NativeToolBackend { package final class NativeXcodeBackend: NativeToolBackend { private let installation: NativeXcodeInstallation private let includesGUIBridgeTools: Bool - private let testableStateCorrection: NativeTestableStateCorrection + private let testableStateNoticeGuard: NativeTestableStateNoticeGuard private var executionOperations: NativeExecutionOperations? private let bridge: NativeActionBridge private let selection: NativeToolSelection private let scope: NativeWorkspaceScope private let workspaces: NativeWorkspaceRegistry - private let crashCorrection: NativeCrashToolCorrection - private let previewCorrection: NativePreviewCorrection + private let crashTools: NativeCrashTools + private let previewTool: NativePreviewTool private let selections = NativeWorkspaceSelections() /// The headless workspace of each running request, by its artifacts directory. private var requestWorkspaces: [URL: (identifier: String, tool: String, reportsSelection: Bool, finished: Bool)] = [:] @@ -81,22 +81,22 @@ package final class NativeXcodeBackend: NativeToolBackend { package init(installation: NativeXcodeInstallation, includesGUIBridgeTools: Bool = false) async throws { self.includesGUIBridgeTools = includesGUIBridgeTools - testableStateCorrection = try NativeTestableStateCorrection() + testableStateNoticeGuard = try NativeTestableStateNoticeGuard() self.installation = installation bridge = NativeActionBridge(installation: installation) selection = try await NativeToolSelection(installation: installation) scope = try await NativeWorkspaceScope(installation: installation) workspaces = try await NativeWorkspaceRegistry(installation: installation) - crashCorrection = NativeCrashToolCorrection(installation: installation) - previewCorrection = NativePreviewCorrection(installation: installation) - try testableStateCorrection.checkFailure() + crashTools = NativeCrashTools(installation: installation) + previewTool = NativePreviewTool(installation: installation) + try testableStateNoticeGuard.checkFailure() } package var origin: [String: JSONValue]? { installation.origin(kind: "nativeHost", processID: getpid(), toolCancellation: "task") } - package var processFailure: (any Error)? { testableStateCorrection.failure } + package var processFailure: (any Error)? { testableStateNoticeGuard.failure } package func listTools() async throws -> [NativeTool] { if let catalogTask { return try await catalogTask.value } @@ -123,9 +123,9 @@ package final class NativeXcodeBackend: NativeToolBackend { let tool = try NativeSchemaConverter.tool(from: schema, workspaceScoped: workspaceScoped) // The broker executes GUI tools through Apple's bridge; the host supplies only their schemas. if !gui { unsafe (nextActions[name] = action) } - nextTools[name] = unsafe NativePreviewCorrection.handles(action) ? NativePreviewCorrection.describe(tool) : tool + nextTools[name] = unsafe NativePreviewTool.handles(action) ? NativePreviewTool.describe(tool) : tool } - for kind in NativeCrashToolCorrection.Kind.allCases { + for kind in NativeCrashTools.Kind.allCases { nextTools[kind.toolName] = NativeCrashContract.describe(kind) } unsafe (actions = nextActions) @@ -153,16 +153,16 @@ package final class NativeXcodeBackend: NativeToolBackend { package func execute(_ name: String, arguments: [String: JSONValue], context: NativeToolContext) async throws -> AsyncStream { try workspaces.beginExecution(request: context.artifactsDirectory, workspace: context.executionResource.workspace) - try testableStateCorrection.checkFailure() + try testableStateNoticeGuard.checkFailure() if tools[name] == nil { _ = try await listTools() } try Task.checkCancellation() guard let tool = tools[name] else { throw NativeRuntimeError.invalidRequest("Unknown native tool '\(name)'") } if Self.bypassesCrashWorkspace(name, arguments: arguments), - let kind = NativeCrashToolCorrection.Kind(rawValue: name) { + let kind = NativeCrashTools.Kind(rawValue: name) { let input = try JSONSerialization.data(withJSONObject: arguments.mapValues(\.foundationObject)) - return try crashCorrection.execute(kind, input: input, context: context) + return try crashTools.execute(kind, input: input, context: context) } if ["BuildProject", "RunProject", "RunAllTests", "RunSomeTests"].contains(name), executionOperations == nil { executionOperations = try NativeExecutionOperations() @@ -174,7 +174,7 @@ package final class NativeXcodeBackend: NativeToolBackend { do { try await workspaces.closeRemovedWorkspaces(request: context.artifactsDirectory) let registered = try workspaces.registeredIdentifiers() - try await previewCorrection.retainWorkspaces(registered) + try await previewTool.retainWorkspaces(registered) selections.retain(registered) } catch { NativeErrorPresentation.reportBackground("Native workspace cleanup failed: \(error)") } @@ -182,12 +182,12 @@ package final class NativeXcodeBackend: NativeToolBackend { } var arguments = arguments let isPreview: Bool - if let action = unsafe actions[name] { isPreview = unsafe NativePreviewCorrection.handles(action) } + if let action = unsafe actions[name] { isPreview = unsafe NativePreviewTool.handles(action) } else { isPreview = false } let invalidatesPreviewBuild = !isPreview && tool.requiresPreviewBuildInvalidation if invalidatesPreviewBuild, !tool.workspaceScoped { previewBuildInvalidations.updateValue(nil, forKey: context.artifactsDirectory) - previewCorrection.invalidateReusableBuild(workspaceIdentifier: nil) + previewTool.invalidateReusableBuild(workspaceIdentifier: nil) } if name == "XcodeOpenWorkspace", case .string(let path) = arguments["path"] { arguments["path"] = .string(NativeWorkspaceRegistry.workspacePath(for: path)) @@ -203,7 +203,7 @@ package final class NativeXcodeBackend: NativeToolBackend { if case .string(let value) = arguments["workspaceIdentifier"] { identifier = value } else { identifier = nil } previewBuildInvalidations.updateValue(identifier, forKey: context.artifactsDirectory) - previewCorrection.invalidateReusableBuild(workspaceIdentifier: identifier) + previewTool.invalidateReusableBuild(workspaceIdentifier: identifier) } if tool.workspaceScoped, case .string(let identifier) = arguments["workspaceIdentifier"] { try await workspaces.prepareDebugger(for: identifier) @@ -220,10 +220,10 @@ package final class NativeXcodeBackend: NativeToolBackend { try Task.checkCancellation() arguments["temporaryArtifactsPath"] = .string(context.artifactsDirectory.path) arguments["conversationID"] = .string(context.conversationID) - if isPreview { arguments = NativePreviewCorrection.prepareArguments(arguments) } + if isPreview { arguments = NativePreviewTool.prepareArguments(arguments) } let input = try JSONSerialization.data(withJSONObject: arguments.mapValues(\.foundationObject)) - if let kind = NativeCrashToolCorrection.Kind(rawValue: name) { - return try crashCorrection.execute(kind, input: input, context: context) + if let kind = NativeCrashTools.Kind(rawValue: name) { + return try crashTools.execute(kind, input: input, context: context) } guard let action = unsafe actions[name] else { throw NativeRuntimeError.invalidRequest("Unknown native tool '\(name)'") @@ -232,7 +232,7 @@ package final class NativeXcodeBackend: NativeToolBackend { let outputSchema: JSONValue? if case .object(let descriptor) = tools[name]?.descriptor { outputSchema = descriptor["outputSchema"] } else { outputSchema = nil } - return try unsafe await previewCorrection.execute(inputType: scope.inputType(for: action), input: input, + return try unsafe await previewTool.execute(inputType: scope.inputType(for: action), input: input, artifactsRoot: context.artifactsRoot, request: context.artifactsDirectory, outputSchema: outputSchema) { [self] in guard let action = unsafe actions[name] else { throw NativeRuntimeError.invalidRequest("Unknown native tool '\(name)'") @@ -244,7 +244,7 @@ package final class NativeXcodeBackend: NativeToolBackend { } private static func bypassesCrashWorkspace(_ name: String, arguments: [String: JSONValue]) -> Bool { - guard let kind = NativeCrashToolCorrection.Kind(rawValue: name) else { return false } + guard let kind = NativeCrashTools.Kind(rawValue: name) else { return false } switch kind { case .read, .start, .wait, .cancel, .resume: return true @@ -332,8 +332,8 @@ package final class NativeXcodeBackend: NativeToolBackend { package func beginShutdown() { catalogTask?.cancel() - crashCorrection.cancelPendingOperations() - previewCorrection.cancelPendingOperations() + crashTools.cancelPendingOperations() + previewTool.cancelPendingOperations() } package func finishExecution(context: NativeToolContext, outcome: NativeToolOutcome) async throws { @@ -346,8 +346,8 @@ package final class NativeXcodeBackend: NativeToolBackend { } if Task.isCancelled { context.executionScope.cancel() } await context.executionScope.finishCancellation() - await previewCorrection.finishExecution(request: context.artifactsDirectory) - await crashCorrection.finishExecution(request: context.artifactsDirectory) + await previewTool.finishExecution(request: context.artifactsDirectory) + await crashTools.finishExecution(request: context.artifactsDirectory) await bridge.finishExecution(request: context.artifactsDirectory) var failures: [String] = [] let launchedPID = requestWorkspaces[context.artifactsDirectory]?.tool == "RunProject" @@ -358,13 +358,13 @@ package final class NativeXcodeBackend: NativeToolBackend { catch { failures.append(String(describing: error)) } if let identifier = previewBuildInvalidations.removeValue(forKey: context.artifactsDirectory) { // A native action's stream can overlap rendering before its mutation finishes. - previewCorrection.invalidateReusableBuild(workspaceIdentifier: identifier) + previewTool.invalidateReusableBuild(workspaceIdentifier: identifier) } do { try workspaces.finishOpen(request: context.artifactsDirectory) - try await previewCorrection.retainWorkspaces(workspaces.registeredIdentifiers()) + try await previewTool.retainWorkspaces(workspaces.registeredIdentifiers()) } catch { failures.append(String(describing: error)) } - do { try testableStateCorrection.checkFailure() } + do { try testableStateNoticeGuard.checkFailure() } catch { failures.append(String(describing: error)) } if !failures.isEmpty { throw NativeRuntimeError.invocation(failures.joined(separator: "; ")) } } @@ -373,11 +373,11 @@ package final class NativeXcodeBackend: NativeToolBackend { catalogTask?.cancel() if let catalogTask { _ = try? await catalogTask.value } var failures: [String] = [] - do { try await crashCorrection.shutdown() } catch { failures.append(String(describing: error)) } - do { try await previewCorrection.shutdown() } catch { failures.append(String(describing: error)) } + do { try await crashTools.shutdown() } catch { failures.append(String(describing: error)) } + do { try await previewTool.shutdown() } catch { failures.append(String(describing: error)) } await bridge.shutdown() do { try await workspaces.closeAllWorkspaces() } catch { failures.append(String(describing: error)) } - do { try testableStateCorrection.checkFailure() } catch { failures.append(String(describing: error)) } + do { try testableStateNoticeGuard.checkFailure() } catch { failures.append(String(describing: error)) } if !failures.isEmpty { throw NativeRuntimeError.invocation(failures.joined(separator: "; ")) } } } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativeCrashDataTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativeCrashDataTests.swift index b0384a3e..d5b20a60 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativeCrashDataTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativeCrashDataTests.swift @@ -132,7 +132,7 @@ struct NativeCrashDataTests { let query = NativeCrashQuery(bundleIdentifier: "com.example.app", platformIdentifier: "com.apple.platform.iphoneos", uploadPlatformIdentifier: "com.apple.platform.iphoneos", appVersion: nil, isBeta: nil, timePeriod: "last14Days", pageIndex: 0, pageSize: 25, collectsAllPages: true) - let snapshot = try NativeCrashToolCorrection.snapshot(collection: .issues, query: query, + let snapshot = try NativeCrashTools.snapshot(collection: .issues, query: query, issueID: nil, loaded: uncachedPage) #expect(!snapshot.sourceAvailable) #expect(!snapshot.isComplete) @@ -400,7 +400,7 @@ struct NativeCrashDataTests { #expect(request.cursor == nil) #expect(request.source == .network) - for kind in [NativeCrashToolCorrection.Kind.start, .wait, .cancel, .resume] { + for kind in [NativeCrashTools.Kind.start, .wait, .cancel, .resume] { let tool = NativeCrashContract.describe(kind) #expect(!tool.workspaceScoped) #expect(try nativeTestField(tool.descriptor, "annotations", "readOnlyHint") == .bool(kind == .wait)) diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativeCrashToolCorrectionTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativeCrashToolsTests.swift similarity index 88% rename from Tests/XcodeMCPNativeRuntimeTests/NativeCrashToolCorrectionTests.swift rename to Tests/XcodeMCPNativeRuntimeTests/NativeCrashToolsTests.swift index f4681585..8b767cdf 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativeCrashToolCorrectionTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativeCrashToolsTests.swift @@ -5,7 +5,7 @@ import XcodeMCPWire @Suite @MainActor -struct NativeCrashToolCorrectionTests { +struct NativeCrashToolsTests { @Test(arguments: ["cache", "networkWithCacheFallback"]) func explicitCachedQueryDoesNotRequireTheProductInventory(source: String) async throws { try #require(NSClassFromString("IDEProductManager") == nil) @@ -30,8 +30,8 @@ struct NativeCrashToolCorrectionTests { "workspaceIdentifier": .string("unavailable-workspace"), "bundle_id": .string("example.App"), "platform": .string("macOS"), "upload_platform": .string("iOS"), "source": .string(source), ]) - let correction = NativeCrashToolCorrection(installation: installation) - let result = try await execute(.sync, input: input, correction: correction, context: context) + let tools = NativeCrashTools(installation: installation) + let result = try await execute(.sync, input: input, tools: tools, context: context) guard case .string(let metadataPath) = result["metadataPath"] else { Issue.record("Sync must retain its source metadata without returning all records") return @@ -56,7 +56,7 @@ struct NativeCrashToolCorrectionTests { let read = try await execute(.read, input: .object(["bundle_id": .string("example.App"), "platform": .string("macOS"), "upload_platform": .string("iOS")]), - correction: correction, context: context) + tools: tools, context: context) #expect(read["changes"] == .array([])) guard case .string = read["checkpoint"] else { Issue.record("A locally completed empty read must issue a checkpoint") @@ -75,10 +75,10 @@ struct NativeCrashToolCorrectionTests { let installation = try NativeXcodeInstallation(developerDirectory: contents.appending(component: "Developer")) let context = NativeToolContext(artifactsDirectory: root.appending(component: "request"), artifactsRoot: root, conversationID: "missing-crash-source") - let correction = NativeCrashToolCorrection(installation: installation) + let tools = NativeCrashTools(installation: installation) let result = try await execute(.sync, input: .object([ "bundle_id": .string("example.App"), "platform": .string("iOS"), "source": .string("cache"), - ]), correction: correction, context: context, expectedEventType: "error") + ]), tools: tools, context: context, expectedEventType: "error") #expect(result["status"] == .string("failed")) #expect(try nativeTestField(.object(result), "cacheInfo", "sourceAvailable") == .bool(false)) @@ -110,14 +110,14 @@ struct NativeCrashToolCorrectionTests { fetchedAt: "2024-01-01T00:00:00Z") let input: JSONValue = .object(["bundle_id": .string("example.App"), "platform": .string("iOS"), "source": .string(source), "max_records": .number(.int(1))]) - let owner = NativeCrashToolCorrection(installation: installation) - let observer = NativeCrashToolCorrection(installation: installation) + let owner = NativeCrashTools(installation: installation) + let observer = NativeCrashTools(installation: installation) // The Start response stream has fully ended before the separate request waits. - let started = try await execute(.start, input: input, correction: owner, context: startContext) + let started = try await execute(.start, input: input, tools: owner, context: startContext) #expect(started["state"] == .string("queued")) await owner.finishExecution(request: startContext.artifactsDirectory) - let finished = try await finishedJob(started, correction: observer, context: observerContext) + let finished = try await finishedJob(started, tools: observer, context: observerContext) let expectedState = source == "cache" ? "completed" : "failed" #expect(finished["state"] == .string(expectedState)) let result = try nativeTestObject(try nativeTestField(.object(finished), "result")) @@ -127,7 +127,7 @@ struct NativeCrashToolCorrectionTests { #expect(try NativeCrashStore.object(Data(contentsOf: URL(fileURLWithPath: responsePath))) == result) let read = try await execute(.read, input: .object(["bundle_id": .string("example.App"), "platform": .string("iOS")]), - correction: observer, context: observerContext) + tools: observer, context: observerContext) guard case .array(let changes) = read["changes"], case .string(let checkpoint) = read["checkpoint"] else { throw FixtureError.missingField } @@ -137,11 +137,11 @@ struct NativeCrashToolCorrectionTests { } #expect(readIdentifiers.sorted() == identifiers.sorted()) - let repeated = try await execute(.start, input: input, correction: owner, context: startContext) - let repeatedResult = try await finishedJob(repeated, correction: observer, context: observerContext) + let repeated = try await execute(.start, input: input, tools: owner, context: startContext) + let repeatedResult = try await finishedJob(repeated, tools: observer, context: observerContext) #expect(repeatedResult["state"] == .string(expectedState)) let unchanged = try await execute(.read, input: .object(["checkpoint": .string(checkpoint)]), - correction: observer, context: observerContext) + tools: observer, context: observerContext) #expect(unchanged["changes"] == .array([])) try await owner.shutdown() try await observer.shutdown() @@ -151,19 +151,19 @@ struct NativeCrashToolCorrectionTests { try #require(NSClassFromString("IDEProductManager") == nil) let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: root) } - let correction = NativeCrashToolCorrection(installation: try jobInstallation(at: root)) + let tools = NativeCrashTools(installation: try jobInstallation(at: root)) let context = NativeToolContext(artifactsDirectory: root.appending(component: "request"), artifactsRoot: root, conversationID: "missing-crash-job-source") let started = try await execute(.start, input: .object(["bundle_id": .string("example.App"), - "platform": .string("iOS"), "source": .string("cache")]), correction: correction, context: context) - let finished = try await finishedJob(started, correction: correction, context: context) + "platform": .string("iOS"), "source": .string("cache")]), tools: tools, context: context) + let finished = try await finishedJob(started, tools: tools, context: context) #expect(finished["state"] == .string("failed")) #expect(try nativeTestField(.object(finished), "result", "status") == .string("failed")) guard case .array(let errors) = try nativeTestField(.object(finished), "result", "errors") else { throw FixtureError.missingField } #expect(try nativeTestField(try #require(errors.first), "operation") == .string("cacheRead")) - try await correction.shutdown() + try await tools.shutdown() } @Test func anUnreadableSampleStopsTheJobAndRetainsOneImportResponseForExplicitRetry() async throws { @@ -182,7 +182,7 @@ struct NativeCrashToolCorrectionTests { // A native filename supplies the date, so import reaches the body read after metadata capture succeeds. #expect(try NativeCrashLogSource.inspect(rawURL: sample, includeHeaderDate: false).nativeID == sample.deletingPathExtension().lastPathComponent) - let correction = NativeCrashToolCorrection(installation: try jobInstallation(at: root)) + let tools = NativeCrashTools(installation: try jobInstallation(at: root)) let context = NativeToolContext(artifactsDirectory: root.appending(component: "request"), artifactsRoot: root, conversationID: "unreadable-crash-job-sample") let query = NativeCrashQuery(bundleIdentifier: "example.App", platformIdentifier: "com.apple.platform.iphoneos", @@ -193,8 +193,8 @@ struct NativeCrashToolCorrectionTests { fetchedAt: "2024-01-01T00:00:00Z") let started = try await execute(.start, input: .object(["bundle_id": .string("example.App"), "platform": .string("iOS"), "issue_id": .string("stable-issue"), "source": .string("cache")]), - correction: correction, context: context) - let finished = try await finishedJob(started, correction: correction, context: context) + tools: tools, context: context) + let finished = try await finishedJob(started, tools: tools, context: context) #expect(finished["state"] == .string("failed")) let result = try nativeTestField(.object(finished), "result") #expect(try nativeTestField(result, "status") == .string("partial")) @@ -207,14 +207,14 @@ struct NativeCrashToolCorrectionTests { #expect(responses.count == 1) let failedResume = try await execute(.resume, input: .object(["job_id": try nativeTestField(.object(finished), "jobId")]), - correction: correction, context: context) - let failedRetry = try await finishedJob(failedResume, correction: correction, context: context) + tools: tools, context: context) + let failedRetry = try await finishedJob(failedResume, tools: tools, context: context) #expect(failedRetry["state"] == .string("failed")) let failedRetryResult = try nativeTestField(.object(failedRetry), "result") try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: sample.path) let resumed = try await execute(.resume, input: .object(["job_id": try nativeTestField(.object(failedRetry), "jobId")]), - correction: correction, context: context) - let retriedJob = try await finishedJob(resumed, correction: correction, context: context) + tools: tools, context: context) + let retriedJob = try await finishedJob(resumed, tools: tools, context: context) #expect(retriedJob["state"] == .string("completed")) #expect(retriedJob["previousJobId"] == failedRetry["jobId"]) let retried = try nativeTestField(.object(retriedJob), "result") @@ -222,9 +222,9 @@ struct NativeCrashToolCorrectionTests { #expect(try nativeTestField(retried, "cacheInfo", "processedCount") == .number(.int(1))) // The original continuation remains replayable after Resume used it. let originalContinuation = try await execute(.sync, input: .object(["cursor": .string(cursor)]), - correction: correction, context: context) + tools: tools, context: context) #expect(.object(originalContinuation) == failedRetryResult) - try await correction.shutdown() + try await tools.shutdown() } @Test(arguments: ["cache", "network", "missing-page"]) @@ -241,7 +241,7 @@ struct NativeCrashToolCorrectionTests { let retained = point("retained", name: "Previously captured") let before = point("changed", name: "Unsymbolicated") let importer = try NativeCrashSyncStore(root: context.crashCacheRoot) - let partialSnapshot = try NativeCrashToolCorrection.snapshot(collection: .issues, query: query, issueID: nil, + let partialSnapshot = try NativeCrashTools.snapshot(collection: .issues, query: query, issueID: nil, loaded: .init(value: .object(["points": .array([before, retained])]), source: "organizer", fetchedAt: "2024-01-01T00:00:00Z", isComplete: false)) let partial = try await importer.synchronize(partialSnapshot, maxRecords: 1, maxBytes: 1024 * 1024) @@ -261,8 +261,8 @@ struct NativeCrashToolCorrectionTests { try job.updateProgress(["pages": .array([.object(["query": pageQuery])])]) return partial } - let correction = NativeCrashToolCorrection(installation: try jobInstallation(at: root)) - let previous = try await finishedJob(try nativeTestObject(started), correction: correction, context: context) + let tools = NativeCrashTools(installation: try jobInstallation(at: root)) + let previous = try await finishedJob(try nativeTestObject(started), tools: tools, context: context) #expect(previous["state"] == .string("failed")) guard case .string(let oldID) = previous["jobId"] else { throw FixtureError.missingField } let ledger = context.crashCacheRoot.appending(path: "Jobs/\(oldID)/job.json") @@ -272,8 +272,8 @@ struct NativeCrashToolCorrectionTests { point("new", name: "New issue")])]), key: query.json(issueID: nil), fetchedAt: "2024-01-02T00:00:00Z") let resumed = try await execute(.resume, input: .object(["job_id": .string(oldID)]), - correction: correction, context: context) - let finished = try await finishedJob(resumed, correction: correction, context: context) + tools: tools, context: context) + let finished = try await finishedJob(resumed, tools: tools, context: context) #expect(finished["state"] == .string(sourceMode != "network" ? "completed" : "failed")) #expect(finished["previousJobId"] == .string(oldID)) #expect(finished["jobId"] != previous["jobId"]) @@ -294,7 +294,7 @@ struct NativeCrashToolCorrectionTests { #expect(try NativeCrashStore.object(Data(contentsOf: URL(filePath: recoveryPath)))["cacheInfo"] == nativeTestField(imported, "cacheInfo")) let changes = try await execute(.read, input: .object(["checkpoint": checkpoint]), - correction: correction, context: context) + tools: tools, context: context) guard case .array(let records) = changes["changes"] else { throw FixtureError.missingField } let names = try records.map { try nativeTestField($0, "name") } #expect(names.contains(.string("Previously captured"))) @@ -302,13 +302,13 @@ struct NativeCrashToolCorrectionTests { #expect(names.contains(.string("New issue")) == (sourceMode != "network")) let secondCheckpoint = try #require(changes["checkpoint"]) let unchanged = try await execute(.read, input: .object(["checkpoint": secondCheckpoint]), - correction: correction, context: context) + tools: tools, context: context) #expect(unchanged["changes"] == .array([])) guard case .string(let token) = cursor else { throw FixtureError.missingField } let replay = try await importer.resumeSync(token) #expect(try nativeTestField(replay, "cacheInfo", "processedCount") == .number(.int(2))) await jobs.shutdown() - try await correction.shutdown() + try await tools.shutdown() } @Test(arguments: [false, true]) @@ -327,11 +327,11 @@ struct NativeCrashToolCorrectionTests { if incompleteIdentity { try job.updateProgress(["organizer": .object(["processId": .number(.int(123))])]) } return partial } - let correction = NativeCrashToolCorrection(installation: try jobInstallation(at: root)) - let previous = try await finishedJob(try nativeTestObject(started), correction: correction, context: context) + let tools = NativeCrashTools(installation: try jobInstallation(at: root)) + let previous = try await finishedJob(try nativeTestObject(started), tools: tools, context: context) let resumed = try await execute(.resume, input: .object(["job_id": try #require(previous["jobId"])]), - correction: correction, context: context) - let finished = try await finishedJob(resumed, correction: correction, context: context) + tools: tools, context: context) + let finished = try await finishedJob(resumed, tools: tools, context: context) #expect(finished["state"] == .string("failed")) if incompleteIdentity { #expect(finished["result"] == partial) @@ -352,7 +352,7 @@ struct NativeCrashToolCorrectionTests { == .string("Xcode's product manager is unavailable")) } await owner.shutdown() - try await correction.shutdown() + try await tools.shutdown() } private func point(_ id: String, name: String) -> JSONValue { @@ -379,13 +379,13 @@ struct NativeCrashToolCorrectionTests { let originalTime = "2024-01-01T00:00:00.125Z" var loaded = NativeCrashData.Loaded(value: .object(["distribution": distribution, "logDirectory": .string(primaryLogs.path)]), source: "cache", fetchedAt: originalTime, isComplete: true) - let primary = try NativeCrashToolCorrection.snapshot(collection: .logs, query: query, issueID: "stable-issue", loaded: loaded) + let primary = try NativeCrashTools.snapshot(collection: .logs, query: query, issueID: "stable-issue", loaded: loaded) #expect(primary.sourceObservedAt == Date(timeIntervalSince1970: 1_704_067_200.125)) loaded.recovery = NativeCrashData.Fetched(value: .object(["cachedDistribution": distribution, "sampleFreshness": .string("unverifiedSavedSamples"), "logDirectory": .string(recoveredLogs.path)]), fetchedAt: nil, source: "organizerCache", errors: [failure], isComplete: false) loaded.errors = [failure] - let snapshot = try NativeCrashToolCorrection.snapshot(collection: .logs, query: query, issueID: "stable-issue", loaded: loaded) + let snapshot = try NativeCrashTools.snapshot(collection: .logs, query: query, issueID: "stable-issue", loaded: loaded) #expect(try nativeTestField(snapshot.metadata, "provenance", "source") == .string("cache")) #expect(try nativeTestField(snapshot.metadata, "provenance", "fetchedAt") == .string(originalTime)) #expect(try nativeTestField(snapshot.metadata, "timeSeries", "uniqueDeviceCountForTimePeriod") == .number(.int(9))) @@ -410,10 +410,10 @@ struct NativeCrashToolCorrectionTests { #expect(try String(contentsOfFile: path, encoding: .utf8) == text) } - private func execute(_ kind: NativeCrashToolCorrection.Kind, input: JSONValue, - correction: NativeCrashToolCorrection, context: NativeToolContext, + private func execute(_ kind: NativeCrashTools.Kind, input: JSONValue, + tools: NativeCrashTools, context: NativeToolContext, expectedEventType: String = "completed") async throws -> [String: JSONValue] { - let stream = try correction.execute(kind, input: NativeCrashStore.encode(input), context: context) + let stream = try tools.execute(kind, input: NativeCrashStore.encode(input), context: context) var events: [[String: JSONValue]] = [] for await event in stream { events.append(try NativeCrashStore.object(event)) } let event = try #require(events.last) @@ -429,7 +429,7 @@ struct NativeCrashToolCorrectionTests { return try NativeXcodeInstallation(developerDirectory: contents.appending(component: "Developer")) } - private func finishedJob(_ started: [String: JSONValue], correction: NativeCrashToolCorrection, + private func finishedJob(_ started: [String: JSONValue], tools: NativeCrashTools, context: NativeToolContext) async throws -> [String: JSONValue] { guard case .string(let jobID) = started["jobId"] else { throw FixtureError.missingField } let clock = ContinuousClock() @@ -443,7 +443,7 @@ struct NativeCrashToolCorrectionTests { guard clock.now < deadline else { throw FixtureError.jobDidNotFinish } latest = try await execute(.wait, input: .object(["job_id": .string(jobID), "after_revision": .number(.int(revision)), "wait_seconds": .number(.int(5))]), - correction: correction, context: context) + tools: tools, context: context) } } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift index cb59116f..bdeb74dc 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewDiscoveryTests.swift @@ -8,7 +8,7 @@ struct NativePreviewDiscoveryTests { @Test func recognizesRegistryNamesWithMangledWordSubstitutions() { let symbol = "_$s15EmbeddedPreview04$s15a89Preview0024FrameworkViewswift_ynAHffMX12_0_33_11075570A56CB59BAD1AB26CEC639C6ELl0B0fMf_15B12RegistryfMu_VMn" let name = "15EmbeddedPreview04$s15a89Preview0024FrameworkViewswift_ynAHffMX12_0_33_11075570A56CB59BAD1AB26CEC639C6ELl0B0fMf_15B12RegistryfMu_V" - #expect(NativePreviewCorrection.registryNames(in: symbol) == [name]) + #expect(NativePreviewTool.registryNames(in: symbol) == [name]) } @Test func discoversProgramRootsFromCompilerMainSymbols() { @@ -22,8 +22,8 @@ struct NativePreviewDiscoveryTests { "_$s\(widgetRoot)VMn", "_main", ].joined(separator: "\n") - #expect(NativePreviewCorrection.programRootNames(in: symbols) == [appRoot, widgetRoot]) - #expect(NativePreviewCorrection.programRootNames(in: "_$s\(widgetRoot)VMn") == []) + #expect(NativePreviewTool.programRootNames(in: symbols) == [appRoot, widgetRoot]) + #expect(NativePreviewTool.programRootNames(in: "_$s\(widgetRoot)VMn") == []) } @Test func programLibrariesMatchTheBuiltHostImage() async throws { @@ -41,8 +41,8 @@ struct NativePreviewDiscoveryTests { try FileManager.default.copyItem(at: output, to: stagedHost) try FileManager.default.copyItem(at: otherOutput, to: otherLibrary) - #expect(try NativePreviewCorrection.programLibraries(previewLibraries: [otherLibrary, stagedHost], output: output) == [stagedHost]) - #expect(try NativePreviewCorrection.programLibraries(previewLibraries: [otherLibrary], output: output) == []) + #expect(try NativePreviewTool.programLibraries(previewLibraries: [otherLibrary, stagedHost], output: output) == [stagedHost]) + #expect(try NativePreviewTool.programLibraries(previewLibraries: [otherLibrary], output: output) == []) } @Test func includesEmbeddedFrameworkExecutablesAndDebugLibraries() async throws { @@ -74,16 +74,16 @@ struct NativePreviewDiscoveryTests { try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) .write(to: wrongFramework.appendingPathComponent("Info.plist")) - let libraries = try NativePreviewCorrection.registryLibraries(in: app, previewLibraries: [preview]) + let libraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: [preview]) let expected = [preview, rootDylib, executable, frameworkPreview, dylib, nestedDylib, wrongExecutable] .map { $0.resolvingSymlinksInPath().path } #expect(Set(libraries.map(\.path)) == Set(expected)) - let frameworkPaths = try NativePreviewCorrection.libraryPaths(in: app, previewLibraries: [preview], + let frameworkPaths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [preview], registryLibraries: libraries, sourceOutput: sourceOutput) #expect(frameworkPaths == ["FixtureApp.debug.dylib", "Frameworks/FixtureKit.framework/FixtureImplementation"]) - let staticPaths = try NativePreviewCorrection.libraryPaths(in: app, previewLibraries: [preview], + let staticPaths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [preview], registryLibraries: libraries, sourceOutput: app.deletingLastPathComponent().appendingPathComponent("FixturePackage.o")) #expect(staticPaths == ["FixtureApp.debug.dylib"]) } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift index 27506267..a9b9fd81 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewLocationTests.swift @@ -6,12 +6,12 @@ import Testing struct NativePreviewLocationTests { @Test func unicodePrefixUsesMacroByteCoordinates() throws { let source = "import SwiftUI\n/* 🌸 */ #Preview { Text(\"A\") }\n" - #expect(try NativePreviewCorrection.registryColumn(in: source, line: 2, utf16Column: 9) == 12) + #expect(try NativePreviewTool.registryColumn(in: source, line: 2, utf16Column: 9) == 12) } @Test func changedSourceCannotUseStaleCoordinates() { #expect(throws: NativeRuntimeError.self) { - try NativePreviewCorrection.registryColumn(in: "#Preview {}", line: 1, utf16Column: 100) + try NativePreviewTool.registryColumn(in: "#Preview {}", line: 1, utf16Column: 100) } } } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewOptionsTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewOptionsTests.swift index 4e633d53..f6ba4528 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewOptionsTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewOptionsTests.swift @@ -9,7 +9,7 @@ struct NativePreviewOptionsTests { @Test func advertisesFiveMinutePreviewTimeout() throws { let native = #"{"name":"RenderPreview","inputSchema":{"properties":[{"name":"timeout","isRequired":false,"description":"Defaults to 120 seconds.","type":{"integer":{}}}]}}"# let tool = try NativeSchemaConverter.tool(from: Data(native.utf8), workspaceScoped: true) - let corrected = NativePreviewCorrection.describe(tool) + let corrected = NativePreviewTool.describe(tool) let timeout = try nativeTestField(corrected.descriptor, "inputSchema", "properties", "timeout") #expect(try nativeTestField(timeout, "default") == .number(.int(300))) #expect(try nativeTestField(timeout, "description") == .string("The time in seconds to wait for the preview, including building and preparing its render destination. Defaults to 300 seconds.")) @@ -19,7 +19,7 @@ struct NativePreviewOptionsTests { func previewTimeoutDefaultsPreserveExplicitValues(_ timeout: Int?) throws { var arguments: [String: JSONValue] = ["sourceFilePath": .string("ContentView.swift")] if let timeout { arguments["timeout"] = .number(.int(Int64(timeout))) } - let prepared = NativePreviewCorrection.prepareArguments(arguments) + let prepared = NativePreviewTool.prepareArguments(arguments) let input = try JSONSerialization.data(withJSONObject: prepared.mapValues(\.foundationObject)) let decoded = try JSONDecoder().decode(PreviewTimeoutInput.self, from: input) #expect(decoded.timeout == timeout ?? 300) @@ -70,7 +70,7 @@ struct NativePreviewOptionsTests { } @Test func widgetFamilyPresentationAndTimelineUseDirectRenderer() { - let options = NativePreviewCorrection.directOptions(variants: [ + let options = NativePreviewTool.directOptions(variants: [ "Widget Family": "Large", "Presentation": "Placeholder", "Color Scheme": "Dark Appearance", ], controls: ["timelineIndex": Optional(1) as Any, "toggleState": Optional.none as Any]) @@ -82,14 +82,14 @@ struct NativePreviewOptionsTests { } @Test func firstTimelineIndexIsPreserved() { - let options = NativePreviewCorrection.directOptions(variants: [:], + let options = NativePreviewTool.directOptions(variants: [:], controls: ["timelineIndex": Optional(0) as Any]) #expect(options.timelineIndex == 0) #expect(!options.requiresNativePipeline) } @Test func groupItemSelectionUsesDirectRenderer() { - let options = NativePreviewCorrection.directOptions(variants: [:], + let options = NativePreviewTool.directOptions(variants: [:], controls: ["groupItemIndex": Optional(1) as Any, "timelineIndex": Optional.none as Any]) #expect(options.groupItemIndex == 1) #expect(options.timelineIndex == nil) @@ -97,7 +97,7 @@ struct NativePreviewOptionsTests { } @Test func activityControlsPreserveStaleSelectionAndDisabledToggle() { - let options = NativePreviewCorrection.directOptions( + let options = NativePreviewTool.directOptions( variants: ["View Style": "Content (Smart Stack)", "Activity View Context": "Stale", "Color Scheme": "Dark Appearance"], controls: ["timelineIndex": Optional(1) as Any, "toggleState": Optional(false) as Any]) @@ -112,7 +112,7 @@ struct NativePreviewOptionsTests { @Test func advertisesGroupItemObjectsMatchingNativeOutput() throws { let native = #"{"name":"RenderPreview","inputSchema":{"properties":[]},"outputSchema":{"properties":[{"name":"previewSnapshotPath","isRequired":false,"type":{"string":{}}},{"name":"supportedCanvasControlOverrides","isRequired":false,"type":{"object":{"schema":{"properties":[{"name":"groupItems","isRequired":false,"type":{"array":{"itemType":{"integer":{}}}}}]}}}}]}}"# let tool = try NativeSchemaConverter.tool(from: Data(native.utf8), workspaceScoped: true) - let corrected = NativePreviewCorrection.describe(tool) + let corrected = NativePreviewTool.describe(tool) let item = try nativeTestField(corrected.descriptor, "outputSchema", "properties", "supportedCanvasControlOverrides", "properties", "groupItems", "items") #expect(try nativeTestField(item, "type") == .string("object")) #expect(try nativeTestField(item, "properties", "index", "type") == .string("integer")) @@ -121,7 +121,7 @@ struct NativePreviewOptionsTests { } @Test func unknownVariantsReachRendererValidationAndUnknownControlsKeepNativeRendering() { - let options = NativePreviewCorrection.directOptions(variants: [ + let options = NativePreviewTool.directOptions(variants: [ "View Style": "Unknown Style", "Color Scheme": "Unknown Appearance", "Unknown Group": "Unknown Value", "Contrast": "Increased Contrast", ], controls: [:]) @@ -130,12 +130,12 @@ struct NativePreviewOptionsTests { "Color Scheme": "Unknown Appearance", "Unknown Group": "Unknown Value", "Contrast": "Increased Contrast", ]) #expect(!options.requiresNativePipeline) - #expect(NativePreviewCorrection.directOptions(variants: [:], + #expect(NativePreviewTool.directOptions(variants: [:], controls: ["futureControl": Optional(1) as Any]).requiresNativePipeline) } @Test func displayVariantsUseDirectRenderer() { - let options = NativePreviewCorrection.directOptions(variants: [ + let options = NativePreviewTool.directOptions(variants: [ "Color Scheme": "Dark Appearance", "Contrast": "Increased Contrast", "Dynamic Type": "AX 1", "Control Borders": "Shown", "Orientation": "Landscape Left", ], controls: [:]) @@ -143,13 +143,13 @@ struct NativePreviewOptionsTests { } @Test func displayVariantsWithWidgetOptionsUseDirectRenderer() { - #expect(!NativePreviewCorrection.directOptions(variants: [ + #expect(!NativePreviewTool.directOptions(variants: [ "Widget Family": "Medium", "Color Scheme": "Dark Appearance", "Dynamic Type": "AX 1", ], controls: [:]).requiresNativePipeline) } @Test func activityDefaultStylePreservesTimelineAndAppearance() { - let options = NativePreviewCorrection.directOptions(variants: ["Color Scheme": "Dark Appearance"], + let options = NativePreviewTool.directOptions(variants: ["Color Scheme": "Dark Appearance"], controls: ["timelineIndex": Optional(1) as Any]) #expect(options.timelineIndex == 1) #expect(options.displayVariants == ["Color Scheme": "Dark Appearance"]) diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewProcessTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewProcessTests.swift index a8846c90..783b496d 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewProcessTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewProcessTests.swift @@ -80,7 +80,7 @@ struct NativePreviewProcessTests { try await previewBinaryOutput("/usr/bin/xcrun", ["--sdk", "macosx", "clang", "-framework", "Foundation", source.path, "-o", executable.path]) for (locale, greeting) in [("ja_JP", "こんにちは"), ("en_US", "Hello")] { - let output = try await fixture.process.run(executable.path, NativePreviewCorrection.rendererArguments(localization: locale)) + let output = try await fixture.process.run(executable.path, NativePreviewTool.rendererArguments(localization: locale)) #expect(output == "\(greeting)\n\(locale)\n") } } diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewSnapshotTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewSnapshotTests.swift index 7d420583..9ea0ef5a 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewSnapshotTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewSnapshotTests.swift @@ -8,12 +8,12 @@ import Testing struct NativePreviewSnapshotTests { @Test func thumbnailCapsTheLongestSideWithoutUpscaling() throws { let large = try image(width: 2622, height: 1206) - let thumbnail = try #require(NativePreviewCorrection.thumbnail(from: large, maximumDimension: 1500, + let thumbnail = try #require(NativePreviewTool.thumbnail(from: large, maximumDimension: 1500, framebufferMask: nil, rotationDegrees: nil, swapsAxes: false)) #expect(thumbnail.width == 1500) #expect(thumbnail.height == 689) let small = try image(width: 180, height: 90) - let unchanged = try #require(NativePreviewCorrection.thumbnail(from: small, maximumDimension: 1500, + let unchanged = try #require(NativePreviewTool.thumbnail(from: small, maximumDimension: 1500, framebufferMask: nil, rotationDegrees: nil, swapsAxes: false)) #expect(unchanged.width == 180) #expect(unchanged.height == 90) @@ -26,7 +26,7 @@ struct NativePreviewSnapshotTests { return true } let source = try image(width: 80, height: 40) - let images = NativePreviewCorrection.SnapshotImages() + let images = NativePreviewTool.SnapshotImages() func bitmap(_ image: CGImage, degrees: Double) throws -> NSBitmapImageRep { let png = try images.png(from: pngData(image), image: image, framebufferMask: mask, rotationDegrees: degrees, swapsAxes: true, exclusion: nil, exclusionImage: nil) @@ -50,9 +50,9 @@ struct NativePreviewSnapshotTests { context.fill(CGRect(x: 10, y: 70, width: 20, height: 10)) let overlay = try #require(context.makeImage()) let source = try image(width: 80, height: 40) - let left = try #require(NativePreviewCorrection.thumbnail(from: source, maximumDimension: 1500, + let left = try #require(NativePreviewTool.thumbnail(from: source, maximumDimension: 1500, framebufferMask: nil, rotationDegrees: 90, swapsAxes: true, exclusionImage: overlay)) - let right = try #require(NativePreviewCorrection.thumbnail(from: source, maximumDimension: 1500, + let right = try #require(NativePreviewTool.thumbnail(from: source, maximumDimension: 1500, framebufferMask: nil, rotationDegrees: 270, swapsAxes: true, exclusionImage: overlay)) let leftBitmap = NSBitmapImageRep(cgImage: left) let rightBitmap = NSBitmapImageRep(cgImage: right) @@ -65,7 +65,7 @@ struct NativePreviewSnapshotTests { @Test func thinPreviewRetainsADrawableThumbnail() throws { let source = try image(width: 1, height: 6000) - let thumbnail = try #require(NativePreviewCorrection.thumbnail(from: source, maximumDimension: 1500, + let thumbnail = try #require(NativePreviewTool.thumbnail(from: source, maximumDimension: 1500, framebufferMask: nil, rotationDegrees: nil, swapsAxes: false)) #expect(thumbnail.width == 1) #expect(thumbnail.height == 1500) @@ -82,7 +82,7 @@ struct NativePreviewSnapshotTests { try profile.write(to: resources.appendingPathComponent("profile.plist")) let resource = resources.appendingPathComponent("Mask.png") try pngData(image(width: 40, height: 80)).write(to: resource) - let images = NativePreviewCorrection.SnapshotImages() + let images = NativePreviewTool.SnapshotImages() let source = try image(width: 40, height: 80) let sourcePNG = try pngData(source) func thumbnail() throws -> NSBitmapImageRep { @@ -100,7 +100,7 @@ struct NativePreviewSnapshotTests { } @Test func displayExclusionChangesWithItsEncodedPixels() throws { - let images = NativePreviewCorrection.SnapshotImages() + let images = NativePreviewTool.SnapshotImages() let source = try image(width: 20, height: 20) let sourcePNG = try pngData(source) let white = try pngData(image(width: 20, height: 20)) diff --git a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewCorrectionTests.swift b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift similarity index 93% rename from Tests/XcodeMCPNativeRuntimeTests/NativePreviewCorrectionTests.swift rename to Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift index f33ab002..b5e4aef8 100644 --- a/Tests/XcodeMCPNativeRuntimeTests/NativePreviewCorrectionTests.swift +++ b/Tests/XcodeMCPNativeRuntimeTests/NativePreviewToolTests.swift @@ -5,7 +5,7 @@ import XcodeMCPWire @Suite @MainActor -struct NativePreviewCorrectionTests { +struct NativePreviewToolTests { @Test func previewResultMatchesTheAdvertisedOutputContract() { let result: JSONValue = .object([ "previewSnapshotPath": .string("/preview.png"), @@ -16,7 +16,7 @@ struct NativePreviewCorrectionTests { "supportedPreviewVariantOverrides": .object(["Color Scheme": .array([.string("Dark")])]), ]) let current: JSONValue = .object(["properties": .object(["snapshot": .object([:])])]) - #expect(NativePreviewCorrection.formatResult(result, outputSchema: current) == .object([ + #expect(NativePreviewTool.formatResult(result, outputSchema: current) == .object([ "snapshot": .object(["path": .string("/preview.png")]), "displayName": .string("Preview"), "errors": .array([]), "supportedOverrides": .object([ @@ -26,10 +26,10 @@ struct NativePreviewCorrectionTests { "previewVariants": .object(["Color Scheme": .array([.string("Dark")])]), ]), ])) - #expect(NativePreviewCorrection.formatResult(result, outputSchema: .object([ + #expect(NativePreviewTool.formatResult(result, outputSchema: .object([ "properties": .object(["previewSnapshotPath": .object([:])]), ])) == result) - #expect(NativePreviewCorrection.formatResult(result, outputSchema: nil) == result) + #expect(NativePreviewTool.formatResult(result, outputSchema: nil) == result) } @Test func decodedDefaultsAndExplicitValuesDoNotRequireNativeGetters() throws { @@ -39,28 +39,28 @@ struct NativePreviewCorrectionTests { "_previewVariantOverrides": StoredDefault(wrappedValue: ["Orientation": "Landscape"]), "_timeout": StoredDefault(wrappedValue: 123), ] - let index: Int = try NativePreviewCorrection.decodedProperty("previewDefinitionIndexInFile", in: fields) - let variants: [String: String] = try NativePreviewCorrection.decodedProperty("previewVariantOverrides", in: fields) - let timeout: Int = try NativePreviewCorrection.decodedProperty("timeout", in: fields) + let index: Int = try NativePreviewTool.decodedProperty("previewDefinitionIndexInFile", in: fields) + let variants: [String: String] = try NativePreviewTool.decodedProperty("previewVariantOverrides", in: fields) + let timeout: Int = try NativePreviewTool.decodedProperty("timeout", in: fields) #expect(index == 7) #expect(variants == ["Orientation": "Landscape"]) #expect(timeout == 123) let defaults: [String: Any] = ["_index": StoredDefault(wrappedValue: 0), "_variants": StoredDefault(wrappedValue: [String: String]())] - let first: Int = try NativePreviewCorrection.decodedProperty("index", in: defaults) - let empty: [String: String] = try NativePreviewCorrection.decodedProperty("variants", in: defaults) + let first: Int = try NativePreviewTool.decodedProperty("index", in: defaults) + let empty: [String: String] = try NativePreviewTool.decodedProperty("variants", in: defaults) #expect(first == 0) #expect(empty.isEmpty) } @Test func unsupportedDecodedStorageFallsBackInsteadOfGuessingDefaults() throws { #expect(throws: NativeRuntimeError.self) { - let _: Int = try NativePreviewCorrection.decodedProperty("timeout", in: [:]) + let _: Int = try NativePreviewTool.decodedProperty("timeout", in: [:]) } #expect(throws: NativeRuntimeError.self) { - let _: Int = try NativePreviewCorrection.decodedProperty("timeout", in: ["_timeout": "invalid"]) + let _: Int = try NativePreviewTool.decodedProperty("timeout", in: ["_timeout": "invalid"]) } - let plain: Int = try NativePreviewCorrection.decodedProperty("timeout", in: ["timeout": 80]) + let plain: Int = try NativePreviewTool.decodedProperty("timeout", in: ["timeout": 80]) #expect(plain == 80) } @@ -78,7 +78,7 @@ struct NativePreviewCorrectionTests { linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: true, isRunnable: isRunnable) } - let selected = try NativePreviewCorrection.selectTarget(targets, source: source, platform: platform) + let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: platform) #expect(selected.source.moduleName == platform.rawValue) #expect(selected.host.moduleName == platform.rawValue) } @@ -90,7 +90,7 @@ struct NativePreviewCorrectionTests { sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", root.appendingPathComponent("Watch.app/Watch.debug.dylib").path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: true, isRunnable: true) #expect(throws: NativePipelineRequired.self) { - try NativePreviewCorrection.selectTarget([watch], source: source, platform: .iOS) + try NativePreviewTool.selectTarget([watch], source: source, platform: .iOS) } } @@ -111,7 +111,7 @@ struct NativePreviewCorrectionTests { buildableName: "SharedPreview.o", sdkRoot: "iphonesimulator", sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", library.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false)] : []) - let selected = try NativePreviewCorrection.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) #expect(selected.host.moduleName == "RunnableApp") #expect(selected.source.moduleName == (sharedLibrary ? "SharedPreview" : "RunnableApp")) } @@ -134,7 +134,7 @@ struct NativePreviewCorrectionTests { try Data("resource".utf8).write(to: product.appendingPathComponent("Contents/Resources/Marker.txt")) try Data("renderer".utf8).write(to: helper.appendingPathComponent("XcodeMCPPreviewRenderer")) try Data("library".utf8).write(to: helper.appendingPathComponent("Frameworks/libPreview.dylib")) - try NativePreviewCorrection.prepareApp(product: product, helper: helper, app: app, platform: .macOS) + try NativePreviewTool.prepareApp(product: product, helper: helper, app: app, platform: .macOS) let info = try #require(Bundle(url: app)?.infoDictionary) #expect(info["CFBundleIdentifier"] as? String == "dev.lynnswap.MacFixture") #expect(info["NSMainStoryboardFile"] == nil) @@ -148,7 +148,7 @@ struct NativePreviewCorrectionTests { @Test func watchRendererRunsWithoutACompanionApp() { let original: [String: Any] = ["CFBundleIdentifier": "dev.lynnswap.WatchFixture", "WKCompanionAppBundleIdentifier": "dev.lynnswap.Companion", "WKRunsIndependentlyOfCompanionApp": true] - let info = NativePreviewCorrection.rendererInfo(original, platform: .watchOS) + let info = NativePreviewTool.rendererInfo(original, platform: .watchOS) #expect(info["WKApplication"] as? Bool == true) #expect(info["WKWatchOnly"] as? Bool == true) #expect(info["WKCompanionAppBundleIdentifier"] == nil) @@ -167,7 +167,7 @@ struct NativePreviewCorrectionTests { debugDylibEnabled: true, isRunnable: false) } #expect(throws: NativePipelineRequired.self) { - try NativePreviewCorrection.selectTarget(targets, source: source, platform: .iOS) + try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) } } @@ -185,11 +185,11 @@ struct NativePreviewCorrectionTests { linkCommandLine: ["-o", root.appendingPathComponent("FixtureHost.app/FixtureHost.debug.dylib").path, product.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: true)] } - let selected = try NativePreviewCorrection.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) #expect(selected.source.architecture == "arm64") #expect(selected.host.architecture == "arm64") #expect(throws: NativePipelineRequired.self) { - try NativePreviewCorrection.selectTarget(targets.filter { $0.architecture == "x86_64" }, source: source, platform: .iOS) + try NativePreviewTool.selectTarget(targets.filter { $0.architecture == "x86_64" }, source: source, platform: .iOS) } } @@ -216,7 +216,7 @@ struct NativePreviewCorrectionTests { try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: dylib, to: binary) } - let selected = try NativePreviewCorrection.selectTarget(hosts + [feature], source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(hosts + [feature], source: source, platform: .iOS) #expect(selected.host.outputURL == hosts[1].outputURL) #expect(selected.source.outputURL == feature.outputURL) #expect(selected.source.moduleName == feature.moduleName) @@ -245,7 +245,7 @@ struct NativePreviewCorrectionTests { try FileManager.default.createDirectory(at: binary.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: frameworkBinary, to: binary) } - let selected = try NativePreviewCorrection.selectTarget(hosts + [framework], source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(hosts + [framework], source: source, platform: .iOS) #expect(selected.host.outputURL == (embedded ? hosts[1].outputURL : framework.outputURL)) #expect(selected.source.outputURL == framework.outputURL) #expect(selected.source.moduleName == framework.moduleName) @@ -269,7 +269,7 @@ struct NativePreviewCorrectionTests { sdkRoot: "iphonesimulator", sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", archive.path], linkerWorkingDirectory: nil, objectFiles: [object], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false) - let selected = try NativePreviewCorrection.selectTarget(hosts + [package], source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(hosts + [package], source: source, platform: .iOS) #expect(selected.host.outputURL == hosts[1].outputURL) #expect(selected.source.outputURL == package.outputURL) #expect(selected.source.moduleName == package.moduleName) @@ -294,7 +294,7 @@ struct NativePreviewCorrectionTests { sdkRoot: "iphonesimulator", sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", product.path], linkerWorkingDirectory: nil, objectFiles: [root.appendingPathComponent("PackageContent.o")], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false) - let selected = try NativePreviewCorrection.selectTarget(hosts + [package], source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(hosts + [package], source: source, platform: .iOS) #expect(selected.host.outputURL == hosts[1].outputURL) #expect(selected.source.outputURL == package.outputURL) #expect(selected.source.moduleName == package.moduleName) @@ -311,7 +311,7 @@ struct NativePreviewCorrectionTests { try Data("diagnostic".utf8).write(to: log) var stagedApp: URL? do { - let value = try await NativePreviewCorrection.withStagedDirectory(in: root) { directory in + let value = try await NativePreviewTool.withStagedDirectory(in: root) { directory in let app = directory.appendingPathComponent("PreviewAgent.app") stagedApp = app try FileManager.default.createDirectory(at: app, withIntermediateDirectories: false) @@ -354,7 +354,7 @@ struct NativePreviewCorrectionTests { sdkVariant: nil, architecture: "arm64", linkCommandLine: ["-o", platform.executableDirectory(in: app).appendingPathComponent("Host.debug.dylib").path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: true)) } - let selected = try NativePreviewCorrection.selectTarget(targets, source: source, platform: platform) + let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: platform) #expect(selected.source.moduleName == "FixtureKit") #expect(selected.host.moduleName == (embedded ? "Host" : "FixtureKit")) } @@ -372,7 +372,7 @@ struct NativePreviewCorrectionTests { let app = NativePreviewBuild.Target(moduleName: "Host", buildableName: "Host.app", sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: [binary.path, "-o", appImage.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: true) - let selected = try NativePreviewCorrection.selectTarget([framework, app], source: source, platform: .macOS) + let selected = try NativePreviewTool.selectTarget([framework, app], source: source, platform: .macOS) #expect(selected.source.moduleName == "FixtureKit") #expect(selected.host.moduleName == "FixtureKit") } @@ -434,7 +434,7 @@ struct NativePreviewCorrectionTests { sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: archiveCommand, linkerWorkingDirectory: nil, objectFiles: [core, object, previewObject], sourceFiles: [source, coreSource, previewCode], debugDylibEnabled: false, isRunnable: false, compileCommandLine: compileCommand) - let standalone = try NativePreviewCorrection.selectTarget([target], source: source, platform: .macOS) + let standalone = try NativePreviewTool.selectTarget([target], source: source, platform: .macOS) #expect(standalone.host.moduleName == "FixtureKit") let appURL = root.appendingPathComponent("Host.app") let appImage = appURL.appendingPathComponent("Contents/MacOS/Host.debug.dylib") @@ -505,13 +505,13 @@ struct NativePreviewCorrectionTests { try await previewBinaryOutput("/usr/bin/codesign", ["--force", "--sign", "-", appImage.path]) let appSymbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", appImage.path]) #expect(appSymbols.contains("_static_preview_value") == forceLoad) - #expect(!NativePreviewCorrection.registryNames(in: appSymbols).isEmpty == forceLoad) + #expect(!NativePreviewTool.registryNames(in: appSymbols).isEmpty == forceLoad) let protectedFiles = [binary, support, appImage, fileList, dependencyInfo, mergedArchive] let originals = try protectedFiles.map { try Data(contentsOf: $0) } let app = NativePreviewBuild.Target(moduleName: "Host", buildableName: "Host.app", sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: appCommand, linkerWorkingDirectory: root.path, objectFiles: [appObject, packageObject], sourceFiles: [], debugDylibEnabled: true, isRunnable: true) - let hosted = try NativePreviewCorrection.selectTarget([target, app], source: source, platform: .macOS) + let hosted = try NativePreviewTool.selectTarget([target, app], source: source, platform: .macOS) #expect(hosted.host.moduleName == "Host") #expect(hosted.source.moduleName == "FixtureKit") let helper = root.appendingPathComponent("Helper") @@ -555,19 +555,19 @@ struct NativePreviewCorrectionTests { environment: ["DYLD_LIBRARY_PATH": support.deletingLastPathComponent().path]) #expect(baseline == "dev.lynnswap.StaticHost\nhost resource\n\(appURL.resolvingSymlinksInPath().path)\n") let staged = root.appendingPathComponent("Preview.app") - let products = try NativePreviewCorrection.prepareApp(product: appURL, helper: helper, app: staged, platform: .macOS, + let products = try NativePreviewTool.prepareApp(product: appURL, helper: helper, app: staged, platform: .macOS, staticProduct: true) - let linked = try await NativePreviewCorrection.linkStaticProduct(hosted.source, host: hosted.host, in: staged, products: products, platform: .macOS, process: process) - let dependencies = try NativePreviewCorrection.frameworkDependencies(for: [hosted.source], targets: [target, app], + let linked = try await NativePreviewTool.linkStaticProduct(hosted.source, host: hosted.host, in: staged, products: products, platform: .macOS, process: process) + let dependencies = try NativePreviewTool.frameworkDependencies(for: [hosted.source], targets: [target, app], platform: .macOS, in: products, linkedImages: [try #require(hosted.source.outputURL).resolvingSymlinksInPath(): linked]) - try NativePreviewCorrection.copyFrameworkDependencies(dependencies, into: products) - try await NativePreviewCorrection.relocateFrameworkDependencies(dependencies, in: products, process: process) - let libraries = try NativePreviewCorrection.registryLibraries(in: staged, previewLibraries: [linked.url]) - let paths = try NativePreviewCorrection.libraryPaths(in: staged, previewLibraries: [linked.url], registryLibraries: libraries, + try NativePreviewTool.copyFrameworkDependencies(dependencies, into: products) + try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: products, process: process) + let libraries = try NativePreviewTool.registryLibraries(in: staged, previewLibraries: [linked.url]) + let paths = try NativePreviewTool.libraryPaths(in: staged, previewLibraries: [linked.url], registryLibraries: libraries, sourceOutput: linked.url) #expect(paths == ["Contents/Frameworks/XcodeMCPPreviewSource.dylib"]) let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", linked.url.path]) - #expect(!NativePreviewCorrection.registryNames(in: symbols).isEmpty) + #expect(!NativePreviewTool.registryNames(in: symbols).isEmpty) _ = try await process.run("/usr/bin/codesign", ["--force", "--sign", "-", staged.path]) _ = try await process.run("/usr/bin/codesign", ["--verify", "--strict", "--deep", staged.path]) let executable = staged.appendingPathComponent("Contents/MacOS/XcodeMCPPreviewRenderer") @@ -719,13 +719,13 @@ struct NativePreviewCorrectionTests { } let originalSymbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", image.path]) #expect(!originalSymbols.contains("_static_preview_value")) - #expect(NativePreviewCorrection.registryNames(in: originalSymbols).isEmpty) + #expect(NativePreviewTool.registryNames(in: originalSymbols).isEmpty) let baseline = try await process.run(executable.path, []) let files = try #require(FileManager.default.enumerator(at: parent, includingPropertiesForKeys: [.isRegularFileKey])) let protectedFiles = try files.compactMap { $0 as? URL }.filter { try $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true } + [archive, dependency, leaf] let originalBytes = try protectedFiles.map { try Data(contentsOf: $0) } - let staged = try await NativePreviewCorrection.prepareNativeExtension(source: sourceTarget, host: host, containingApp: parent, + let staged = try await NativePreviewTool.prepareNativeExtension(source: sourceTarget, host: host, containingApp: parent, in: root.appendingPathComponent("NativePreview"), targets: [sourceTarget, host], platform: .macOS, process: process) let stagedProduct = staged.appendingPathComponent("Contents/PlugIns/Widget.appex") let stagedImage = stagedProduct.appendingPathComponent("Contents/MacOS/Widget.debug.dylib") @@ -758,7 +758,7 @@ struct NativePreviewCorrectionTests { } let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", stagedImage.path]) #expect(symbols.contains("_static_preview_value")) - #expect(!NativePreviewCorrection.registryNames(in: symbols).isEmpty) + #expect(!NativePreviewTool.registryNames(in: symbols).isEmpty) #expect(try NativePreviewBinary.dynamicLibrary(at: stagedImage)?.identifier == "@rpath/Widget.debug.dylib") #expect(try NativePreviewBinary.matches(executable, stagedProduct.appendingPathComponent("Contents/MacOS/Widget"))) for bundle in [stagedProduct, staged] { @@ -905,11 +905,11 @@ struct NativePreviewCorrectionTests { let app = root.appendingPathComponent("Staged/Preview.app") let agent = try previewAgent(in: root, helper: helper) try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: false) - let products = try NativePreviewCorrection.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS, + let products = try NativePreviewTool.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS, staticProduct: true) let developer = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]).trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developer)), artifacts: root) - let linked = try await NativePreviewCorrection.linkStaticProduct(target, in: app, products: products, platform: .macOS, process: process) + let linked = try await NativePreviewTool.linkStaticProduct(target, in: app, products: products, platform: .macOS, process: process) let image = linked.url let runtime = try await previewBinaryOutput("/usr/bin/xcrun", ["--sdk", "macosx", "clang", "-print-file-name=libclang_rt.asan_osx_dynamic.dylib"]).trimmingCharacters(in: .whitespacesAndNewlines) @@ -917,18 +917,18 @@ struct NativePreviewCorrectionTests { "ASAN_OPTIONS": "color=never:external_symbolizer_path='':abort_on_error=1", "DYLD_INSERT_LIBRARIES": runtime, ] - let dependencies = try NativePreviewCorrection.frameworkDependencies(for: [target], targets: [target], platform: .macOS, + let dependencies = try NativePreviewTool.frameworkDependencies(for: [target], targets: [target], platform: .macOS, in: products, linkedImages: [try #require(target.outputURL).resolvingSymlinksInPath(): linked], environment: nativeEnvironment) - try NativePreviewCorrection.copyFrameworkDependencies(dependencies, into: products) - let libraries = try NativePreviewCorrection.registryLibraries(in: app, previewLibraries: [image], products: products) - let paths = try NativePreviewCorrection.libraryPaths(in: app, previewLibraries: [image], registryLibraries: libraries, + try NativePreviewTool.copyFrameworkDependencies(dependencies, into: products) + let libraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: [image], products: products) + let paths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [image], registryLibraries: libraries, sourceOutput: image, products: products) #expect(paths == ["../Products/" + products.lastPathComponent + "/XcodeMCPPreviewSource.dylib"]) - #expect(try NativePreviewCorrection.programLibraries(previewLibraries: libraries, output: image) == [image.resolvingSymlinksInPath()]) + #expect(try NativePreviewTool.programLibraries(previewLibraries: libraries, output: image) == [image.resolvingSymlinksInPath()]) let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-j", image.path]).split(whereSeparator: \.isNewline) #expect(symbols.contains("_static_preview_value")) #expect(symbols.contains("_main")) - try await NativePreviewCorrection.relocateFrameworkDependencies(dependencies, in: products, process: process) + try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: products, process: process) let stagedExecutable = NativePreviewPlatform.macOS.executableDirectory(in: app).appendingPathComponent(executable.lastPathComponent) let helperIdentifier = try #require(Bundle(url: agent)?.bundleIdentifier) let text = try await process.run(stagedExecutable.path, [app.appendingPathComponent(paths[0]).path], environment: nativeEnvironment) @@ -961,7 +961,7 @@ struct NativePreviewCorrectionTests { try FileManager.default.copyItem(at: app, to: installedApp) try FileManager.default.copyItem(at: products.deletingLastPathComponent(), to: installedApp.deletingLastPathComponent().appendingPathComponent("Products")) - try NativePreviewCorrection.removeStagedApp(app) + try NativePreviewTool.removeStagedApp(app) let installedExecutable = NativePreviewPlatform.macOS.executableDirectory(in: installedApp).appendingPathComponent(executable.lastPathComponent) let installedText = try await process.run(installedExecutable.path, [installedApp.appendingPathComponent(paths[0]).path], environment: nativeEnvironment) @@ -976,7 +976,7 @@ struct NativePreviewCorrectionTests { let rebuiltFramework = root.appendingPathComponent("OtherDestination/FixtureKit.framework") try FileManager.default.createDirectory(at: rebuiltFramework.deletingLastPathComponent(), withIntermediateDirectories: false) try FileManager.default.copyItem(at: framework, to: rebuiltFramework) - let refreshedProducts = try NativePreviewCorrection.prepareApp(product: agent, sourceProduct: rebuiltFramework, helper: helper, app: app, platform: .macOS, + let refreshedProducts = try NativePreviewTool.prepareApp(product: agent, sourceProduct: rebuiltFramework, helper: helper, app: app, platform: .macOS, staticProduct: true) #expect(!FileManager.default.fileExists(atPath: image.path)) #expect(try Data(contentsOf: refreshedProducts.appendingPathComponent("FixtureKit.framework/FixtureKit")) == original) @@ -1048,7 +1048,7 @@ struct NativePreviewCorrectionTests { let host = NativePreviewBuild.Target(moduleName: "Host", buildableName: "Host.app", sdkRoot: "macosx", sdkVariant: nil, architecture: "arm64", linkCommandLine: command, linkerWorkingDirectory: root.path, objectFiles: [sourceObject], sourceFiles: [], debugDylibEnabled: true, isRunnable: true) - let selection = try NativePreviewCorrection.selectTarget([dependency, host], source: dependencyObject.appendingPathExtension("c"), platform: .macOS) + let selection = try NativePreviewTool.selectTarget([dependency, host], source: dependencyObject.appendingPathExtension("c"), platform: .macOS) #expect(selection.source.outputURL == dependencyOutput) #expect(selection.host.outputURL == hostOutput) selectedSource = selection.source @@ -1057,7 +1057,7 @@ struct NativePreviewCorrectionTests { selectedSource = source selectedHost = nil } - let image = try await NativePreviewCorrection.linkStaticProduct(selectedSource, host: selectedHost, + let image = try await NativePreviewTool.linkStaticProduct(selectedSource, host: selectedHost, in: root.appendingPathComponent("Staged/Preview.app"), products: products, platform: .macOS, process: process) let symbols = try await previewBinaryOutput("/usr/bin/xcrun", ["nm", "-jU", image.url.path]).split(whereSeparator: \.isNewline) @@ -1175,7 +1175,7 @@ struct NativePreviewCorrectionTests { } roots[0].containsPreviewSource = true let source = root.appendingPathComponent("Source.swift") - let selection = try NativePreviewCorrection.selectTarget(targets, source: source, platform: .macOS) + let selection = try NativePreviewTool.selectTarget(targets, source: source, platform: .macOS) #expect(selection.source.outputURL == selection.host.outputURL) let originalFiles = try targets.map { try #require($0.outputURL) } + (frameworkSupport ? [privateSupport] : []) let original = try originalFiles.map { try Data(contentsOf: $0) } @@ -1221,17 +1221,17 @@ struct NativePreviewCorrectionTests { let agent = try previewAgent(in: root, helper: helper) let app = root.appendingPathComponent("Staged").appendingPathComponent(agent.lastPathComponent) try FileManager.default.createDirectory(at: app.deletingLastPathComponent(), withIntermediateDirectories: false) - let products = try NativePreviewCorrection.prepareApp(product: agent, sourceProduct: selection.source.outputURL, + let products = try NativePreviewTool.prepareApp(product: agent, sourceProduct: selection.source.outputURL, helper: helper, app: app, platform: .macOS, staticProduct: true, resourceURLs: selection.source.resourceURLs) let developer = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]).trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developer)), artifacts: root) - let images = try await NativePreviewCorrection.linkStaticProducts(for: roots, in: app, products: products, + let images = try await NativePreviewTool.linkStaticProducts(for: roots, in: app, products: products, platform: .macOS, process: process) - let dependencies = try NativePreviewCorrection.frameworkDependencies(for: roots, targets: targets, platform: .macOS, + let dependencies = try NativePreviewTool.frameworkDependencies(for: roots, targets: targets, platform: .macOS, in: products, agentApp: app, linkedImages: images) - try NativePreviewCorrection.copyFrameworkDependencies(dependencies, into: products) + try NativePreviewTool.copyFrameworkDependencies(dependencies, into: products) let libraries = dependencies.rootLibraries.map { products.appendingPathComponent($0) } - try await NativePreviewCorrection.relocateFrameworkDependencies(dependencies, in: products, process: process) + try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: products, process: process) try await previewBinaryOutput("/usr/bin/codesign", ["--force", "--sign", "-", app.path]) try await previewBinaryOutput("/usr/bin/codesign", ["--verify", "--deep", "--strict", app.path]) let executable = NativePreviewPlatform.macOS.executableDirectory(in: app).appendingPathComponent("XcodeMCPPreviewRenderer") @@ -1319,7 +1319,7 @@ struct NativePreviewCorrectionTests { try FileManager.default.copyItem(at: framework, to: products.appendingPathComponent(framework.lastPathComponent)) let developer = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]).trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developer)), artifacts: root) - let image = try await NativePreviewCorrection.linkStaticProduct(target, in: root.appendingPathComponent("Staged/Preview.app"), + let image = try await NativePreviewTool.linkStaticProduct(target, in: root.appendingPathComponent("Staged/Preview.app"), products: products, platform: platform, process: process).url let linked = try #require(try NativePreviewBinary.dynamicLibrary(at: image)) #expect(linked.dependencies.contains { $0.contains("/iOSSupport/") && $0.contains("/SwiftUI.framework/") }) @@ -1359,7 +1359,7 @@ struct NativePreviewCorrectionTests { try Data("renderer".utf8).write(to: helper.appendingPathComponent("XcodeMCPPreviewRenderer")) let agent = try previewAgent(in: root, helper: helper, platform: platform) - try NativePreviewCorrection.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: platform) + try NativePreviewTool.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: platform) let staged = platform.frameworksDirectory(in: app).appendingPathComponent("FixtureKit.framework") let bundle = try #require(Bundle(url: staged)) @@ -1370,10 +1370,10 @@ struct NativePreviewCorrectionTests { let expectedFamilies: [Int]? = platform == .iOS ? [1, 2] : nil #expect(Bundle(url: app)?.infoDictionary?["UIDeviceFamily"] as? [Int] == expectedFamilies) #expect(Bundle(url: app)?.url(forResource: "Marker", withExtension: "txt") == nil) - #expect(try NativePreviewCorrection.appName(product: framework, containingApp: nil, localization: "ja-JP") == "Framework JA") + #expect(try NativePreviewTool.appName(product: framework, containingApp: nil, localization: "ja-JP") == "Framework JA") #expect(try Data(contentsOf: platform.executableDirectory(in: app).appendingPathComponent("XcodeMCPPreviewRenderer")) == Data("renderer".utf8)) - let libraries = try NativePreviewCorrection.registryLibraries(in: app, previewLibraries: []) - let paths = try NativePreviewCorrection.libraryPaths(in: app, previewLibraries: [], registryLibraries: libraries, sourceOutput: binary) + let libraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: []) + let paths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [], registryLibraries: libraries, sourceOutput: binary) #expect(paths == [String(staged.appendingPathComponent(relativeBinary).path.dropFirst(app.path.count + 1))]) #expect(try String(contentsOf: resources.appendingPathComponent("Marker.txt"), encoding: .utf8) == "framework resource") } @@ -1466,7 +1466,7 @@ struct NativePreviewCorrectionTests { if kind == .absoluteBuilt { targets.append(target(library)) } let helper = root.appendingPathComponent("Helper") let app = root.appendingPathComponent("Preview.app") - let dependencies = try NativePreviewCorrection.frameworkDependencies(for: [sourceTarget], targets: targets, platform: .macOS, + let dependencies = try NativePreviewTool.frameworkDependencies(for: [sourceTarget], targets: targets, platform: .macOS, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), sourceProduct: source.deletingLastPathComponent()) try FileManager.default.createDirectory(at: helper.appendingPathComponent("Frameworks"), withIntermediateDirectories: true) let loaderSource = root.appendingPathComponent("Loader.c") @@ -1478,26 +1478,26 @@ struct NativePreviewCorrectionTests { try await previewBinaryOutput(helper.appendingPathComponent("XcodeMCPPreviewRenderer").path, [source.path]) } let agent = try previewAgent(in: root, helper: helper) - try NativePreviewCorrection.prepareApp(product: agent, sourceProduct: source.deletingLastPathComponent(), helper: helper, app: app, + try NativePreviewTool.prepareApp(product: agent, sourceProduct: source.deletingLastPathComponent(), helper: helper, app: app, platform: .macOS) - try NativePreviewCorrection.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) + try NativePreviewTool.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) let developerDirectory = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]) .trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developerDirectory)), artifacts: root) let frameworks = app.appendingPathComponent("Contents/Frameworks") - let stagedLibraries = try NativePreviewCorrection.registryLibraries(in: app, previewLibraries: []) + let stagedLibraries = try NativePreviewTool.registryLibraries(in: app, previewLibraries: []) for binary in originalBinaries { #expect(try stagedLibraries.contains { try NativePreviewBinary.matches(binary, $0) }) } #expect(try !stagedLibraries.contains { try NativePreviewBinary.matches(unrelated, $0) }) - let paths = try NativePreviewCorrection.libraryPaths(in: app, previewLibraries: [], + let paths = try NativePreviewTool.libraryPaths(in: app, previewLibraries: [], registryLibraries: stagedLibraries, sourceOutput: source) #expect(paths == ["Contents/Frameworks/Feature.framework/Feature"]) let dependencyPath = try #require(dependencies.products[dependencyAlias.deletingLastPathComponent().resolvingSymlinksInPath()]) let stagedDependency = try #require(Bundle(url: frameworks.appendingPathComponent(dependencyPath))) let stagedMarker = try #require(stagedDependency.url(forResource: "Marker", withExtension: "txt")) #expect(try String(contentsOf: stagedMarker, encoding: .utf8) == "dependency resource") - try await NativePreviewCorrection.relocateFrameworkDependencies(dependencies, + try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), process: process) try await previewBinaryOutput(app.appendingPathComponent("Contents/MacOS/XcodeMCPPreviewRenderer").path, [frameworks.appendingPathComponent("Feature.framework/Feature").path]) @@ -1530,7 +1530,7 @@ struct NativePreviewCorrectionTests { linkerWorkingDirectory: root.path, objectFiles: [], sourceFiles: [], debugDylibEnabled: false, isRunnable: false) let helper = root.appendingPathComponent("Helper") let app = root.appendingPathComponent("Preview.app") - let dependencies = try NativePreviewCorrection.frameworkDependencies(for: [target], targets: [target], platform: .macOS, + let dependencies = try NativePreviewTool.frameworkDependencies(for: [target], targets: [target], platform: .macOS, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), sourceProduct: framework) try FileManager.default.createDirectory(at: helper.appendingPathComponent("Frameworks"), withIntermediateDirectories: true) let loaderSource = root.appendingPathComponent("Loader.c") @@ -1543,13 +1543,13 @@ struct NativePreviewCorrectionTests { try await previewBinaryOutput(helper.appendingPathComponent("XcodeMCPPreviewRenderer").path, [source.path]) let agent = try previewAgent(in: root, helper: helper) - try NativePreviewCorrection.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS) - try NativePreviewCorrection.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) + try NativePreviewTool.prepareApp(product: agent, sourceProduct: framework, helper: helper, app: app, platform: .macOS) + try NativePreviewTool.copyFrameworkDependencies(dependencies, into: NativePreviewPlatform.macOS.frameworksDirectory(in: app)) let developerDirectory = try await previewBinaryOutput("/usr/bin/xcode-select", ["-p"]) .trimmingCharacters(in: .whitespacesAndNewlines) let process = NativePreviewProcess(installation: try NativeXcodeInstallation(developerDirectory: URL(filePath: developerDirectory)), artifacts: root) - try await NativePreviewCorrection.relocateFrameworkDependencies(dependencies, + try await NativePreviewTool.relocateFrameworkDependencies(dependencies, in: NativePreviewPlatform.macOS.frameworksDirectory(in: app), process: process) try await previewBinaryOutput(app.appendingPathComponent("Contents/MacOS/XcodeMCPPreviewRenderer").path, @@ -1577,7 +1577,7 @@ struct NativePreviewCorrectionTests { linkCommandLine: ["-o", library.path], linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: false, isRunnable: false)] : []) - let selected = try NativePreviewCorrection.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) #expect(selected.host.outputURL == target.outputURL) #expect(selected.source.moduleName == (linkedLibrary ? "ExtensionPreview" : "Extension")) } @@ -1592,7 +1592,7 @@ struct NativePreviewCorrectionTests { linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [source], debugDylibEnabled: true, isRunnable: product == "Host.app") } - let selected = try NativePreviewCorrection.selectTarget(targets, source: source, platform: .iOS) + let selected = try NativePreviewTool.selectTarget(targets, source: source, platform: .iOS) #expect(selected.host.outputURL == targets[1].outputURL) #expect(selected.source.outputURL == targets[1].outputURL) } @@ -1617,9 +1617,9 @@ struct NativePreviewCorrectionTests { linkerWorkingDirectory: nil, objectFiles: [], sourceFiles: [], debugDylibEnabled: true, isRunnable: name != "Unselected") } - #expect(try NativePreviewCorrection.containingApp(for: output, targets: hosts)?.path + #expect(try NativePreviewTool.containingApp(for: output, targets: hosts)?.path == root.appendingPathComponent("Matching.app").path) - #expect(try NativePreviewCorrection.containingApp(for: output, targets: [hosts[0]]) == nil) + #expect(try NativePreviewTool.containingApp(for: output, targets: [hosts[0]]) == nil) } @Test(arguments: [false, true]) @@ -1649,7 +1649,7 @@ struct NativePreviewCorrectionTests { try originalInfo.write(to: product.appendingPathComponent("Info.plist")) let clientIdentifier = nativeClient ? "dev.lynnswap.PreviewClient" : nil - try NativePreviewCorrection.prepareApp(product: product, helper: helper, app: app, containingApp: containing, + try NativePreviewTool.prepareApp(product: product, helper: helper, app: app, containingApp: containing, clientIdentifier: clientIdentifier) #expect(try Data(contentsOf: app.appendingPathComponent("Assets.car")) == resource) @@ -1690,7 +1690,7 @@ struct NativePreviewCorrectionTests { .write(to: localization.appendingPathComponent("InfoPlist.strings")) } - let name = try NativePreviewCorrection.appName(product: product, containingApp: hasContainingApp ? parent : nil, + let name = try NativePreviewTool.appName(product: product, containingApp: hasContainingApp ? parent : nil, localization: "ja-JP") #expect(name == (hasContainingApp ? "Parent JA" : "Extension JA")) } @@ -1718,7 +1718,7 @@ struct NativePreviewCorrectionTests { try PropertyListSerialization.data(fromPropertyList: info, format: .binary, options: 0) .write(to: product.appendingPathComponent("Info.plist")) - try NativePreviewCorrection.prepareApp(product: product, helper: helper, app: app) + try NativePreviewTool.prepareApp(product: product, helper: helper, app: app) #expect(try Data(contentsOf: app.appendingPathComponent("XcodeMCPPreviewRenderer")) == rendererExecutable) #expect(try Data(contentsOf: app.appendingPathComponent("Frameworks/libPreviewRuntime.dylib")) == rendererFramework) @@ -1753,7 +1753,7 @@ struct NativePreviewCorrectionTests { "UIAppFonts": ["FixtureFont.otf"], "FixtureCustom": ["environment": "staging"], ] - let output = NativePreviewCorrection.rendererInfo(input) + let output = NativePreviewTool.rendererInfo(input) #expect(output["CFBundleExecutable"] as? String == "XcodeMCPPreviewRenderer") #expect(output["CFBundlePackageType"] as? String == "APPL") @@ -1780,7 +1780,7 @@ struct NativePreviewCorrectionTests { @Test func timeoutPreservesCleanupFailure() async { let identifier = UUID().uuidString do { - try await NativePreviewCorrection.withTimeout(seconds: 0) { + try await NativePreviewTool.withTimeout(seconds: 0) { do { try await Task.sleep(for: .seconds(60)) } catch is CancellationError { @@ -1802,10 +1802,10 @@ struct NativePreviewCorrectionTests { try FileManager.default.createDirectory(at: app.appendingPathComponent("Contents/Frameworks/IDEFoundation.framework"), withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: root) } - let correction = NativePreviewCorrection(installation: try NativeXcodeInstallation(developerDirectory: app)) + let tool = NativePreviewTool(installation: try NativeXcodeInstallation(developerDirectory: app)) let input = try JSONEncoder().encode(PreviewInput(temporaryArtifactsPath: root.path, sourceFilePath: "ContentView.swift")) let nativeEvent = Data(#"{"type":"completed","data":{"native":true}}"#.utf8) - let stream = try await correction.execute(inputType: PreviewInput.self, input: input, artifactsRoot: root) { + let stream = try await tool.execute(inputType: PreviewInput.self, input: input, artifactsRoot: root) { AsyncStream { continuation in continuation.yield(nativeEvent) continuation.finish()