Skip to content

A native macOS app for managing virtual iPhones - browse, create, and boot iOS research VMs from a single window.

Swift

core: Implement VPhoneWSCore library and tests

zqxwce1368b53f611c
diff --git a/Sources/VPhoneWSCore/CLI/VPhoneCLIClient+Manage.swift b/Sources/VPhoneWSCore/CLI/VPhoneCLIClient+Manage.swift
new file mode 100644
index 0000000..ab3cafc
--- /dev/null
+++ b/Sources/VPhoneWSCore/CLI/VPhoneCLIClient+Manage.swift
@@ -0,0 +1,23 @@
+import Foundation
+
+extension VPhoneCLIClient {
+ public func setConfig(name: String, cpu: Int?, memoryMB: Int?, network: String?) async throws {
+ var argv = ["vm", "config", name]
+ if let cpu { argv += ["--cpu", String(cpu)] }
+ if let memoryMB { argv += ["--memory", String(memoryMB)] }
+ if let network { argv += ["--network", network] }
+ _ = try await runText(argv)
+ }
+
+ public func clone(name: String, to newName: String) async throws {
+ _ = try await runText(["vm", "clone", name, newName])
+ }
+
+ public func rename(name: String, to newName: String) async throws {
+ _ = try await runText(["vm", "rename", name, newName])
+ }
+
+ public func delete(name: String) async throws {
+ _ = try await runText(["vm", "delete", name, "--force"])
+ }
+}
diff --git a/Sources/VPhoneWSCore/CLI/VPhoneCLIClient.swift b/Sources/VPhoneWSCore/CLI/VPhoneCLIClient.swift
new file mode 100644
index 0000000..d76d041
--- /dev/null
+++ b/Sources/VPhoneWSCore/CLI/VPhoneCLIClient.swift
@@ -0,0 +1,89 @@
+import Foundation
+
+public enum VPhoneCLIError: Error, Equatable {
+ case nonZeroExit(code: Int32, stderr: String)
+ /// vphone-cli was terminated by a signal before it could run — almost always
+ /// AMFI's SIGKILL because the amfidont allowlist daemon isn't active.
+ case killedOnLaunch(signal: Int32)
+ case decodeFailed(String)
+
+ /// Plain-English, actionable text for surfacing in the UI.
+ public var userMessage: String {
+ switch self {
+ case .killedOnLaunch(let signal):
+ if signal == SIGKILL {
+ return "vphone-cli was killed on launch (SIGKILL). The AMFI allowlist daemon "
+ + "(amfidont) isn't running — vphone-cli is a signed binary that AMFI blocks "
+ + "without it. Start it with `vphone-amfidont`, then reload."
+ }
+ return "vphone-cli was killed on launch by signal \(signal)."
+ case .nonZeroExit(let code, let stderr):
+ let trimmed = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty
+ ? "vphone-cli exited with code \(code)."
+ : "vphone-cli failed (exit \(code)): \(trimmed)"
+ case .decodeFailed(let detail):
+ return "Couldn't read vphone-cli output: \(detail)"
+ }
+ }
+}
+
+public struct VPhoneCLIClient: Sendable {
+ let executable: URL
+ let libraryRoot: String?
+ let runner: CLIRunner
+
+ public init(executable: URL, libraryRoot: String?, runner: CLIRunner) {
+ self.executable = executable
+ self.libraryRoot = libraryRoot
+ self.runner = runner
+ }
+
+ public func listVMs() async throws -> [VMReport] {
+ let data = try await runJSON(["vm", "list", "--json"])
+ return try decode([VMReport].self, from: data)
+ }
+
+ public func info(name: String) async throws -> VMReport {
+ let data = try await runJSON(["vm", "info", name, "--json"])
+ return try decode(VMReport.self, from: data)
+ }
+
+ public func stop(name: String) async throws {
+ _ = try await runText(["vm", "stop", name])
+ }
+
+ /// `fw catalog` takes no --library-root, so run it directly (not via runText).
+ public func fetchCatalog() async throws -> FirmwareCatalog {
+ let result = try await runner.run(
+ executable: executable, arguments: ["fw", "catalog", "--json"], environment: nil)
+ guard result.succeeded else { throw Self.failure(result) }
+ return try decode(FirmwareCatalog.self, from: Data(result.stdout.utf8))
+ }
+
+ private func runJSON(_ base: [String]) async throws -> Data {
+ let stdout = try await runText(base)
+ return Data(stdout.utf8)
+ }
+
+ @discardableResult
+ func runText(_ base: [String]) async throws -> String {
+ var argv = base
+ if let libraryRoot { argv += ["--library-root", libraryRoot] }
+ let result = try await runner.run(executable: executable, arguments: argv, environment: nil)
+ guard result.succeeded else { throw Self.failure(result) }
+ return result.stdout
+ }
+
+ /// A signal-terminated child means the binary never ran (AMFI); anything else is a real exit code.
+ static func failure(_ result: CLIResult) -> VPhoneCLIError {
+ result.terminatedBySignal
+ ? .killedOnLaunch(signal: result.exitCode)
+ : .nonZeroExit(code: result.exitCode, stderr: result.stderr)
+ }
+
+ private func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
+ do { return try JSONDecoder().decode(type, from: data) }
+ catch { throw VPhoneCLIError.decodeFailed(String(describing: error)) }
+ }
+}
diff --git a/Sources/VPhoneWSCore/CLI/VPhoneCLILocator.swift b/Sources/VPhoneWSCore/CLI/VPhoneCLILocator.swift
new file mode 100644
index 0000000..753635d
--- /dev/null
+++ b/Sources/VPhoneWSCore/CLI/VPhoneCLILocator.swift
@@ -0,0 +1,47 @@
+import Foundation
+
+public enum VPhoneCLILocation: Equatable, Sendable {
+ case found(URL)
+ case notFound
+}
+
+public struct VPhoneCLILocator: Sendable {
+ /// Bundled `.app` launches inherit launchd's minimal `PATH`, which omits Homebrew's install dirs.
+ public static let wellKnownPaths = ["/opt/homebrew/bin/vphone-cli", "/usr/local/bin/vphone-cli"]
+
+ public init() {}
+
+ public func locate(
+ explicit: String?,
+ envPath: String?,
+ pathLookup: (String) -> URL?,
+ fileExists: (String) -> Bool
+ ) -> VPhoneCLILocation {
+ if let explicit, !explicit.isEmpty {
+ return .found(URL(fileURLWithPath: explicit))
+ }
+ if let envPath, !envPath.isEmpty, fileExists(envPath) {
+ return .found(URL(fileURLWithPath: envPath))
+ }
+ if let onPath = pathLookup("vphone-cli") {
+ return .found(onPath)
+ }
+ if let wellKnown = Self.wellKnownPaths.first(where: fileExists) {
+ return .found(URL(fileURLWithPath: wellKnown))
+ }
+ return .notFound
+ }
+
+ public static func whichLookup(_ name: String) -> URL? {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/which")
+ process.arguments = [name]
+ let pipe = Pipe(); process.standardOutput = pipe
+ guard (try? process.run()) != nil else { return nil }
+ process.waitUntilExit()
+ guard process.terminationStatus == 0 else { return nil }
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
+ let path = String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ return path.isEmpty ? nil : URL(fileURLWithPath: path)
+ }
+}
diff --git a/Sources/VPhoneWSCore/Host/HostCheck.swift b/Sources/VPhoneWSCore/Host/HostCheck.swift
new file mode 100644
index 0000000..cc70569
--- /dev/null
+++ b/Sources/VPhoneWSCore/Host/HostCheck.swift
@@ -0,0 +1,20 @@
+public enum CheckStatus: Equatable, Sendable {
+ case ok
+ case attention
+}
+
+public struct HostCheck: Identifiable, Equatable, Sendable {
+ public let id: String
+ public let title: String
+ public let status: CheckStatus
+ public let detail: String
+ public let fixCommand: String?
+
+ public init(id: String, title: String, status: CheckStatus, detail: String, fixCommand: String? = nil) {
+ self.id = id
+ self.title = title
+ self.status = status
+ self.detail = detail
+ self.fixCommand = fixCommand
+ }
+}
diff --git a/Sources/VPhoneWSCore/Host/HostReadiness.swift b/Sources/VPhoneWSCore/Host/HostReadiness.swift
new file mode 100644
index 0000000..d0feebe
--- /dev/null
+++ b/Sources/VPhoneWSCore/Host/HostReadiness.swift
@@ -0,0 +1,145 @@
+import Foundation
+
+public struct HostReadiness: Sendable {
+ let runner: CLIRunner
+
+ public init(runner: CLIRunner) {
+ self.runner = runner
+ }
+
+ public static func evalNestedVM(hvVmmPresent stdout: String) -> HostCheck {
+ let nested = stdout.trimmingCharacters(in: .whitespacesAndNewlines) != "0"
+ return HostCheck(
+ id: "nested",
+ title: nested ? "Running inside a VM" : "Not running inside a VM",
+ status: nested ? .attention : .ok,
+ detail: nested ? "kern.hv_vmm_present = 1 — nested PV=3 guests can't boot." : "kern.hv_vmm_present = 0 — good."
+ )
+ }
+
+ public static func evalMacOS(version: OperatingSystemVersion) -> HostCheck {
+ let ok = version.majorVersion >= 15
+ return HostCheck(
+ id: "macos",
+ title: "macOS 15 or newer",
+ status: ok ? .ok : .attention,
+ detail: "macOS \(version.majorVersion).\(version.minorVersion)"
+ )
+ }
+
+ /// AMFI must be bypassed for the signed vphone-cli binary to launch. Two documented
+ /// routes satisfy this: the `amfi_get_out_of_my_way=1` boot-arg (kernel-wide) or the
+ /// `amfidont` daemon (per-app userspace allow). Either one passes the check.
+ public static func evalAMFI(psOutput: String, bootArgs: String) -> HostCheck {
+ let amfidontRunning = psOutput.split(separator: "\n").contains { line in
+ line.contains("amfidont") && !line.contains("vphone-amfidont")
+ }
+ let bootArgSet = bootArgIsSet(bootArgs, "amfi_get_out_of_my_way")
+ let ok = amfidontRunning || bootArgSet
+
+ let title: String, detail: String
+ if bootArgSet {
+ title = "AMFI disabled via boot-arg"
+ detail = "amfi_get_out_of_my_way=1 in boot-args — AMFI is out of the way; amfidont not needed."
+ } else if amfidontRunning {
+ title = "AMFI allowlist (amfidont) is running"
+ detail = "amfidont is active."
+ } else {
+ title = "AMFI will block vphone-cli"
+ detail = "Neither amfi_get_out_of_my_way=1 (boot-args) nor amfidont is active — the signed "
+ + "VM binary is killed on launch. Run amfidont, or set the boot-arg and reboot."
+ }
+ return HostCheck(id: "amfi", title: title, status: ok ? .ok : .attention,
+ detail: detail, fixCommand: ok ? nil : "vphone-amfidont")
+ }
+
+ /// True when boot-args carries `key=<v>` with a nonzero value (1, 0x1, …).
+ static func bootArgIsSet(_ bootArgs: String, _ key: String) -> Bool {
+ for token in bootArgs.split(whereSeparator: { " \t\n".contains($0) }) {
+ guard token.hasPrefix("\(key)=") else { continue }
+ let value = token.dropFirst(key.count + 1)
+ return !value.isEmpty && value != "0" && value != "0x0"
+ }
+ return false
+ }
+
+ /// PCC research VMs only boot when research guests are allowed (SIP subfeature).
+ public static func evalResearchGuests(csrutilOutput: String) -> HostCheck {
+ // `csrutil allow-research-guests status` → "Allow Research Guests status: enabled|disabled".
+ let enabled = csrutilOutput.lowercased().contains("enabled")
+ return HostCheck(
+ id: "research-guests",
+ title: enabled ? "Research guests allowed" : "Research guests not allowed",
+ status: enabled ? .ok : .attention,
+ detail: enabled
+ ? "csrutil allow-research-guests: enabled."
+ : "csrutil allow-research-guests is disabled — PCC research VMs won't boot. Enable it from Recovery.",
+ fixCommand: enabled ? nil : "csrutil allow-research-guests enable"
+ )
+ }
+
+ public static func evalCLI(_ location: VPhoneCLILocation) -> HostCheck {
+ if case .found(let url) = location {
+ return HostCheck(id: "cli", title: "vphone-cli found", status: .ok, detail: url.path)
+ }
+ return HostCheck(
+ id: "cli",
+ title: "vphone-cli not found",
+ status: .attention,
+ detail: "Not on PATH.",
+ fixCommand: "brew install zqxwce/tap/vphone-cli"
+ )
+ }
+
+ public func runAll() async -> [HostCheck] {
+ async let hv = sysctl("kern.hv_vmm_present")
+ async let ps = psCommands()
+ async let bargs = bootArgs()
+ async let rguests = researchGuests()
+ let cliLoc = VPhoneCLILocator().locate(
+ explicit: nil,
+ envPath: nil,
+ pathLookup: VPhoneCLILocator.whichLookup,
+ fileExists: FileManager.default.fileExists(atPath:)
+ )
+ return [
+ Self.evalCLI(cliLoc),
+ Self.evalMacOS(version: ProcessInfo.processInfo.operatingSystemVersion),
+ Self.evalNestedVM(hvVmmPresent: await hv),
+ Self.evalResearchGuests(csrutilOutput: await rguests),
+ Self.evalAMFI(psOutput: await ps, bootArgs: await bargs),
+ ]
+ }
+
+ private func sysctl(_ key: String) async -> String {
+ (try? await runner.run(
+ executable: URL(fileURLWithPath: "/usr/sbin/sysctl"),
+ arguments: ["-n", key],
+ environment: nil
+ ))?.stdout ?? ""
+ }
+
+ private func psCommands() async -> String {
+ (try? await runner.run(
+ executable: URL(fileURLWithPath: "/bin/ps"),
+ arguments: ["-ax", "-o", "command="],
+ environment: nil
+ ))?.stdout ?? ""
+ }
+
+ private func bootArgs() async -> String {
+ (try? await runner.run(
+ executable: URL(fileURLWithPath: "/usr/sbin/nvram"),
+ arguments: ["boot-args"],
+ environment: nil
+ ))?.stdout ?? ""
+ }
+
+ private func researchGuests() async -> String {
+ (try? await runner.run(
+ executable: URL(fileURLWithPath: "/usr/bin/csrutil"),
+ arguments: ["allow-research-guests", "status"],
+ environment: nil
+ ))?.stdout ?? ""
+ }
+}
diff --git a/Sources/VPhoneWSCore/Lifecycle/LaunchCoordinator.swift b/Sources/VPhoneWSCore/Lifecycle/LaunchCoordinator.swift
new file mode 100644
index 0000000..83eb0ad
--- /dev/null
+++ b/Sources/VPhoneWSCore/Lifecycle/LaunchCoordinator.swift
@@ -0,0 +1,47 @@
+import Foundation
+import AppKit
+
+@MainActor
+public final class LaunchCoordinator {
+ private let executable: URL
+ private let libraryRoot: String?
+ private let launcher: ProcessLauncher
+ private let client: VPhoneCLIClient
+ private let probe: RunningStateProbe
+
+ public init(
+ executable: URL, libraryRoot: String?, launcher: ProcessLauncher,
+ client: VPhoneCLIClient, probe: RunningStateProbe
+ ) {
+ self.executable = executable
+ self.libraryRoot = libraryRoot
+ self.launcher = launcher
+ self.client = client
+ self.probe = probe
+ }
+
+ public func launch(name: String) throws {
+ var argv = ["vm", "launch", name]
+ if let libraryRoot { argv += ["--library-root", libraryRoot] }
+ _ = try launcher.launch(executable: executable, arguments: argv, environment: nil)
+ }
+
+ public func stop(name: String) async throws {
+ try await client.stop(name: name)
+ }
+
+ /// Bring the VM's GUI window forward. The window belongs to the
+ /// `vphone-cli --config …/config.plist` process — NOT the Virtualization XPC
+ /// helper that holds Disk.img — so match on the config path, not lsof.
+ public func showScreen(name: String) async {
+ let root = libraryRoot ?? AppEnvironment.defaultLibraryRoot()
+ let configPath = "\(root)/\(name)/config.plist"
+ guard let pid = await probe.firstPID(commandContaining: configPath),
+ let app = NSRunningApplication(processIdentifier: pid) else { return }
+ app.unhide()
+ // macOS 14+ activation is cooperative: the active app (us) must yield to
+ // the target, otherwise its own activate() is ignored.
+ NSApp.yieldActivation(to: app)
+ app.activate()
+ }
+}
diff --git a/Sources/VPhoneWSCore/Models/FirmwareCatalog.swift b/Sources/VPhoneWSCore/Models/FirmwareCatalog.swift
new file mode 100644
index 0000000..3782917
--- /dev/null
+++ b/Sources/VPhoneWSCore/Models/FirmwareCatalog.swift
@@ -0,0 +1,29 @@
+public struct FirmwareImage: Codable, Equatable, Sendable, Hashable {
+ public let name: String
+ public let url: String
+
+ public init(name: String, url: String) {
+ self.name = name; self.url = url
+ }
+}
+
+public struct FirmwarePairing: Codable, Equatable, Sendable {
+ public let ios: FirmwareImage
+ public let recommendedCloudOS: FirmwareImage
+}
+
+public struct FirmwareCatalog: Codable, Equatable, Sendable {
+ public let pairings: [FirmwarePairing]
+
+ public init(pairings: [FirmwarePairing]) { self.pairings = pairings }
+
+ public var iosImages: [FirmwareImage] { pairings.map(\.ios) }
+
+ /// Distinct cloudOS images (dedup by url), first-seen order — the manual-mode menu.
+ public var cloudOSImages: [FirmwareImage] {
+ var seen = Set<String>()
+ return pairings.compactMap {
+ seen.insert($0.recommendedCloudOS.url).inserted ? $0.recommendedCloudOS : nil
+ }
+ }
+}
diff --git a/Sources/VPhoneWSCore/Models/VMReport.swift b/Sources/VPhoneWSCore/Models/VMReport.swift
new file mode 100644
index 0000000..2fd48e0
--- /dev/null
+++ b/Sources/VPhoneWSCore/Models/VMReport.swift
@@ -0,0 +1,44 @@
+public struct OSVersion: Codable, Equatable, Sendable {
+ public let version: String
+ public let build: String
+}
+
+public struct RestoreInfo: Codable, Equatable, Sendable {
+ public let ios: OSVersion
+ public let cloudOS: OSVersion
+ public let device: String?
+ public let variant: String?
+
+ public init(ios: OSVersion, cloudOS: OSVersion, device: String? = nil, variant: String? = nil) {
+ self.ios = ios; self.cloudOS = cloudOS; self.device = device; self.variant = variant
+ }
+}
+
+public struct NetworkInfo: Codable, Equatable, Sendable {
+ public let mode: String
+ public let macAddress: String?
+ public let bridgeInterface: String?
+}
+
+public struct VMReport: Codable, Equatable, Sendable {
+ public let name: String
+ public let cpuCount: Int
+ public let memoryMB: Int
+ public let diskSizeBytes: Int64
+ public let network: NetworkInfo?
+ public let udid: String?
+ public let restoreInfo: RestoreInfo?
+
+ public init(
+ name: String, cpuCount: Int, memoryMB: Int, diskSizeBytes: Int64,
+ network: NetworkInfo? = nil, udid: String? = nil, restoreInfo: RestoreInfo? = nil
+ ) {
+ self.name = name
+ self.cpuCount = cpuCount
+ self.memoryMB = memoryMB
+ self.diskSizeBytes = diskSizeBytes
+ self.network = network
+ self.udid = udid
+ self.restoreInfo = restoreInfo
+ }
+}
diff --git a/Sources/VPhoneWSCore/Process/CLIRunner.swift b/Sources/VPhoneWSCore/Process/CLIRunner.swift
new file mode 100644
index 0000000..68265e1
--- /dev/null
+++ b/Sources/VPhoneWSCore/Process/CLIRunner.swift
@@ -0,0 +1,19 @@
+import Foundation
+
+public struct CLIResult: Sendable {
+ public let stdout: String
+ public let stderr: String
+ public let exitCode: Int32
+ /// True when the child was terminated by a signal (e.g. SIGKILL from AMFI)
+ /// rather than exiting on its own. `exitCode` then holds the signal number.
+ public let terminatedBySignal: Bool
+ public var succeeded: Bool { exitCode == 0 }
+ public init(stdout: String, stderr: String, exitCode: Int32, terminatedBySignal: Bool = false) {
+ self.stdout = stdout; self.stderr = stderr; self.exitCode = exitCode
+ self.terminatedBySignal = terminatedBySignal
+ }
+}
+
+public protocol CLIRunner: Sendable {
+ func run(executable: URL, arguments: [String], environment: [String: String]?) async throws -> CLIResult
+}
diff --git a/Sources/VPhoneWSCore/Process/ProcessLauncher.swift b/Sources/VPhoneWSCore/Process/ProcessLauncher.swift
new file mode 100644
index 0000000..c10a3ae
--- /dev/null
+++ b/Sources/VPhoneWSCore/Process/ProcessLauncher.swift
@@ -0,0 +1,19 @@
+import Foundation
+
+public struct LaunchedProcess: Sendable { public let pid: Int32 }
+
+public protocol ProcessLauncher: Sendable {
+ func launch(executable: URL, arguments: [String], environment: [String: String]?) throws -> LaunchedProcess
+}
+
+public struct SystemProcessLauncher: ProcessLauncher {
+ public init() {}
+ public func launch(executable: URL, arguments: [String], environment: [String: String]?) throws -> LaunchedProcess {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ if let environment { process.environment = environment }
+ try process.run()
+ return LaunchedProcess(pid: process.processIdentifier)
+ }
+}
diff --git a/Sources/VPhoneWSCore/Process/StreamingRunner.swift b/Sources/VPhoneWSCore/Process/StreamingRunner.swift
new file mode 100644
index 0000000..6ded235
--- /dev/null
+++ b/Sources/VPhoneWSCore/Process/StreamingRunner.swift
@@ -0,0 +1,224 @@
+import Foundation
+#if canImport(Darwin)
+import Darwin
+#endif
+
+/// A committed line (terminated by `\n`) or a live overwrite of the current
+/// line (terminated by `\r`, as terminal progress bars do).
+public enum StreamEvent: Sendable, Equatable {
+ case line(String)
+ case update(String)
+}
+
+public protocol StreamingRunner: Sendable {
+ func run(executable: URL, arguments: [String], environment: [String: String]?,
+ onStart: @escaping @Sendable (Int32) -> Void,
+ onEvent: @escaping @Sendable (StreamEvent) -> Void) async throws -> Int32
+}
+
+/// Splits a raw byte stream applying minimal terminal semantics: `\n` commits a
+/// line, a lone `\r` emits the current text as a live overwrite (progress bars),
+/// and `\r\n` is a single commit. State survives chunk boundaries.
+private final class TerminalSplitter: @unchecked Sendable {
+ private let lock = NSLock()
+ private var partial = Data()
+ private var pendingCR = false
+ private let onEvent: @Sendable (StreamEvent) -> Void
+
+ init(onEvent: @escaping @Sendable (StreamEvent) -> Void) {
+ self.onEvent = onEvent
+ }
+
+ func append(_ chunk: Data) {
+ lock.lock()
+ var events: [StreamEvent] = []
+ for byte in chunk {
+ if pendingCR {
+ pendingCR = false
+ if byte == 0x0A {
+ events.append(.line(Self.decode(partial)))
+ partial.removeAll(keepingCapacity: true)
+ continue
+ }
+ events.append(.update(Self.decode(partial)))
+ partial.removeAll(keepingCapacity: true)
+ }
+ switch byte {
+ case 0x0D: pendingCR = true
+ case 0x0A:
+ events.append(.line(Self.decode(partial)))
+ partial.removeAll(keepingCapacity: true)
+ default: partial.append(byte)
+ }
+ }
+ lock.unlock()
+ for e in events { onEvent(e) }
+ }
+
+ func flush() {
+ lock.lock()
+ pendingCR = false
+ let remainder = partial
+ partial.removeAll()
+ lock.unlock()
+ if !remainder.isEmpty { onEvent(.line(Self.decode(remainder))) }
+ }
+
+ private static func decode(_ d: Data) -> String {
+ stripANSI(String(decoding: d, as: UTF8.self))
+ }
+
+ /// The log is a plain text view, not a terminal — drop ANSI escape sequences
+ /// (color, erase-line, cursor moves) that progress bars emit, keeping the
+ /// visible text and bar glyphs. Escape sequences never contain \r/\n, so a
+ /// full sequence is always contained in one emitted line/update.
+ static func stripANSI(_ s: String) -> String {
+ guard s.contains("\u{1B}") else { return s }
+ var out = String()
+ out.reserveCapacity(s.count)
+ let chars = Array(s)
+ var i = 0
+ while i < chars.count {
+ guard chars[i] == "\u{1B}" else { out.append(chars[i]); i += 1; continue }
+ i += 1
+ guard i < chars.count else { break }
+ if chars[i] == "[" { // CSI: ESC [ … final byte @-~
+ i += 1
+ while i < chars.count {
+ let a = chars[i].asciiValue
+ i += 1
+ if let a, a >= 0x40, a <= 0x7E { break }
+ }
+ } else if chars[i] == "]" { // OSC: ESC ] … BEL or ST (ESC \)
+ i += 1
+ while i < chars.count {
+ if chars[i] == "\u{07}" { i += 1; break }
+ if chars[i] == "\u{1B}", i + 1 < chars.count, chars[i + 1] == "\\" { i += 2; break }
+ i += 1
+ }
+ } else { // other 2-char escape
+ i += 1
+ }
+ }
+ return out
+ }
+}
+
+private final class ExitCodeBox: @unchecked Sendable {
+ private let lock = NSLock()
+ private var value: Int32 = 0
+ func set(_ code: Int32) { lock.lock(); value = code; lock.unlock() }
+ func get() -> Int32 { lock.lock(); defer { lock.unlock() }; return value }
+}
+
+private final class ResumeGuard: @unchecked Sendable {
+ private let lock = NSLock()
+ private var didResume = false
+
+ func resumeOnce(_ body: () -> Void) {
+ lock.lock()
+ defer { lock.unlock() }
+ guard !didResume else { return }
+ didResume = true
+ body()
+ }
+}
+
+public struct SystemStreamingRunner: StreamingRunner {
+ public init() {}
+
+ public func run(executable: URL, arguments: [String], environment: [String: String]?,
+ onStart: @escaping @Sendable (Int32) -> Void,
+ onEvent: @escaping @Sendable (StreamEvent) -> Void) async throws -> Int32 {
+ try await withCheckedThrowingContinuation { continuation in
+ // Run the child under a pseudo-terminal, not a pipe: programs
+ // line-buffer stdout to a TTY but BLOCK-buffer it to a pipe, so a
+ // pipe only surfaces output at ~8KB boundaries / on exit. A PTY
+ // makes isatty(stdout) true → output flushes live.
+ var master: Int32 = 0
+ var slave: Int32 = 0
+ var win = winsize(ws_row: 60, ws_col: 220, ws_xpixel: 0, ws_ypixel: 0)
+ // Raw mode: keep isatty() true but make the PTY a transparent byte
+ // conduit — no CR translation, echo, or line editing.
+ var term = termios()
+ cfmakeraw(&term)
+ guard openpty(&master, &slave, nil, &term, &win) == 0 else {
+ continuation.resume(throwing: POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO))
+ return
+ }
+ let slaveHandle = FileHandle(fileDescriptor: slave, closeOnDealloc: false)
+
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ var env = environment ?? ProcessInfo.processInfo.environment
+ if env["TERM"] == nil { env["TERM"] = "xterm-256color" }
+ // Python (pmd3 restore bridge) block-buffers stdout even on a TTY;
+ // force it unbuffered so its lines stream live like everything else.
+ env["PYTHONUNBUFFERED"] = "1"
+ process.environment = env
+ process.standardOutput = slaveHandle
+ process.standardError = slaveHandle
+ process.standardInput = FileHandle.nullDevice
+
+ let splitter = TerminalSplitter(onEvent: onEvent)
+ let exitCodeBox = ExitCodeBox()
+ let resumeGuard = ResumeGuard()
+
+ let group = DispatchGroup()
+ group.enter() // read thread
+ group.enter() // process termination
+
+ // A GCD readability source over a PTY master fd coalesces and only
+ // fires at EOF; a dedicated blocking read loop returns promptly on
+ // each write (raw mode → no line-discipline hold), so output is live.
+ let readThread = Thread {
+ let size = 65_536
+ let buf = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 1)
+ defer { buf.deallocate() }
+ while true {
+ let n = read(master, buf, size)
+ if n > 0 {
+ splitter.append(Data(bytes: buf, count: n))
+ } else {
+ break // 0 = EOF, -1 = error (EIO once the slave closes)
+ }
+ }
+ group.leave()
+ }
+ readThread.stackSize = 1 << 20
+
+ process.terminationHandler = { proc in
+ exitCodeBox.set(proc.terminationStatus)
+ group.leave()
+ }
+
+ group.notify(queue: .global()) {
+ splitter.flush()
+ close(master)
+ resumeGuard.resumeOnce {
+ continuation.resume(returning: exitCodeBox.get())
+ }
+ }
+
+ do {
+ try process.run()
+ onStart(process.processIdentifier)
+ readThread.start()
+ // Parent drops its slave copy so the master read hits EOF when
+ // the child (last slave holder) exits.
+ try? slaveHandle.close()
+ } catch {
+ // Don't close master here — the two leaves below fire `notify`,
+ // which owns the master close. Closing it twice can clobber an
+ // fd another (parallel) run just reused.
+ try? slaveHandle.close()
+ resumeGuard.resumeOnce {
+ continuation.resume(throwing: error)
+ }
+ group.leave() // read thread never started
+ group.leave() // termination never fires
+ }
+ }
+ }
+}
diff --git a/Sources/VPhoneWSCore/Process/SystemCLIRunner.swift b/Sources/VPhoneWSCore/Process/SystemCLIRunner.swift
new file mode 100644
index 0000000..1180c8e
--- /dev/null
+++ b/Sources/VPhoneWSCore/Process/SystemCLIRunner.swift
@@ -0,0 +1,123 @@
+import Foundation
+
+private final class ProcessOutputAccumulator: @unchecked Sendable {
+ private let lock = NSLock()
+ private var stdout = Data()
+ private var stderr = Data()
+ private var exitCode: Int32 = 0
+ private var bySignal = false
+
+ func appendStdout(_ chunk: Data) {
+ lock.lock(); stdout.append(chunk); lock.unlock()
+ }
+
+ func appendStderr(_ chunk: Data) {
+ lock.lock(); stderr.append(chunk); lock.unlock()
+ }
+
+ func setTermination(code: Int32, bySignal: Bool) {
+ lock.lock(); exitCode = code; self.bySignal = bySignal; lock.unlock()
+ }
+
+ func makeResult() -> CLIResult {
+ lock.lock()
+ defer { lock.unlock() }
+ return CLIResult(
+ stdout: String(decoding: stdout, as: UTF8.self),
+ stderr: String(decoding: stderr, as: UTF8.self),
+ exitCode: exitCode,
+ terminatedBySignal: bySignal)
+ }
+}
+
+private final class ResumeGuard: @unchecked Sendable {
+ private let lock = NSLock()
+ private var didResume = false
+
+ func resumeOnce(_ body: () -> Void) {
+ lock.lock()
+ defer { lock.unlock() }
+ guard !didResume else { return }
+ didResume = true
+ body()
+ }
+}
+
+public struct SystemCLIRunner: CLIRunner {
+ public init() {}
+
+ public func run(executable: URL, arguments: [String], environment: [String: String]?) async throws -> CLIResult {
+ try await withCheckedThrowingContinuation { continuation in
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ if let environment { process.environment = environment }
+ let outPipe = Pipe(); let errPipe = Pipe()
+ process.standardOutput = outPipe
+ process.standardError = errPipe
+
+ let accumulator = ProcessOutputAccumulator()
+ let resumeGuard = ResumeGuard()
+
+ let group = DispatchGroup()
+ group.enter()
+ group.enter()
+ group.enter()
+
+ // `availableData` RAISES an ObjC exception on a read error (e.g. the fd
+ // erroring when the child dies abnormally) — uncatchable in Swift, so it
+ // aborts. `read(upToCount:)` THROWS instead; try? turns EOF/error into a
+ // clean "done" without crashing.
+ outPipe.fileHandleForReading.readabilityHandler = { handle in
+ guard let chunk = (try? handle.read(upToCount: 65_536)) ?? nil, !chunk.isEmpty else {
+ handle.readabilityHandler = nil
+ group.leave()
+ return
+ }
+ accumulator.appendStdout(chunk)
+ }
+ errPipe.fileHandleForReading.readabilityHandler = { handle in
+ guard let chunk = (try? handle.read(upToCount: 65_536)) ?? nil, !chunk.isEmpty else {
+ handle.readabilityHandler = nil
+ group.leave()
+ return
+ }
+ accumulator.appendStderr(chunk)
+ }
+ process.terminationHandler = { proc in
+ accumulator.setTermination(
+ code: proc.terminationStatus,
+ bySignal: proc.terminationReason == .uncaughtSignal)
+ group.leave()
+ }
+
+ group.notify(queue: .global()) {
+ let result = accumulator.makeResult()
+ outPipe.fileHandleForReading.closeFile()
+ errPipe.fileHandleForReading.closeFile()
+ resumeGuard.resumeOnce {
+ continuation.resume(returning: result)
+ }
+ }
+
+ do {
+ try process.run()
+ } catch {
+ outPipe.fileHandleForReading.readabilityHandler = nil
+ errPipe.fileHandleForReading.readabilityHandler = nil
+ // `Process` never closed anything here since the child never launched.
+ outPipe.fileHandleForReading.closeFile()
+ errPipe.fileHandleForReading.closeFile()
+ outPipe.fileHandleForWriting.closeFile()
+ errPipe.fileHandleForWriting.closeFile()
+ resumeGuard.resumeOnce {
+ continuation.resume(throwing: error)
+ }
+ // Balance the three enters above so `notify` still fires.
+ group.leave()
+ group.leave()
+ group.leave()
+ }
+ }
+ }
+}
diff --git a/Sources/VPhoneWSCore/State/RunningStateProbe.swift b/Sources/VPhoneWSCore/State/RunningStateProbe.swift
new file mode 100644
index 0000000..d96f05f
--- /dev/null
+++ b/Sources/VPhoneWSCore/State/RunningStateProbe.swift
@@ -0,0 +1,41 @@
+import Foundation
+
+public struct RunningStateProbe: Sendable {
+ static let lsof = URL(fileURLWithPath: "/usr/sbin/lsof")
+ let runner: CLIRunner
+
+ public init(runner: CLIRunner) { self.runner = runner }
+
+ public static func parsePIDs(_ stdout: String) -> [Int32] {
+ stdout.split(whereSeparator: \.isNewline)
+ .compactMap { Int32($0.trimmingCharacters(in: .whitespaces)) }
+ }
+
+ /// `lsof -t` exits non-zero when nothing matches — that means "not running", not an error.
+ public func pids(diskImagePath: String) async throws -> [Int32] {
+ let result = try await runner.run(
+ executable: Self.lsof, arguments: ["-t", "--", diskImagePath], environment: nil)
+ return Self.parsePIDs(result.stdout)
+ }
+
+ public func isRunning(diskImagePath: String) async throws -> Bool {
+ try await !pids(diskImagePath: diskImagePath).isEmpty
+ }
+
+ /// First running process whose full command line contains `needle`. Used to
+ /// find the GUI VM process (`vphone-cli --config …/config.plist`), which is
+ /// distinct from the Virtualization XPC helper that actually holds Disk.img.
+ public func firstPID(commandContaining needle: String) async -> Int32? {
+ let out = (try? await runner.run(
+ executable: URL(fileURLWithPath: "/bin/ps"),
+ arguments: ["-Ao", "pid=,command="], environment: nil))?.stdout ?? ""
+ for line in out.split(whereSeparator: \.isNewline) {
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ guard trimmed.contains(needle),
+ let space = trimmed.firstIndex(of: " "),
+ let pid = Int32(trimmed[trimmed.startIndex..<space]) else { continue }
+ return pid
+ }
+ return nil
+ }
+}
diff --git a/Sources/VPhoneWSCore/Store/AppEnvironment.swift b/Sources/VPhoneWSCore/Store/AppEnvironment.swift
new file mode 100644
index 0000000..ec80803
--- /dev/null
+++ b/Sources/VPhoneWSCore/Store/AppEnvironment.swift
@@ -0,0 +1,46 @@
+import Foundation
+
+public enum AppEnvironment {
+ public static func defaultLibraryRoot() -> String {
+ if let override = ProcessInfo.processInfo.environment["VPHONE_LIBRARY_ROOT"], !override.isEmpty {
+ return override
+ }
+ return NSHomeDirectory() + "/.vphone/VMs"
+ }
+
+ public struct Services {
+ public let store: VMStore
+ public let coordinator: LaunchCoordinator
+ public let client: VPhoneCLIClient
+ public let readiness: HostReadiness
+ public let taskCenter: TaskCenter
+ public let executable: URL
+ public let commandBuilder: VPhoneCommandBuilder
+ public let variants: VariantStore
+ }
+
+ @MainActor
+ public static func makeServices(explicitCLIPath: String? = nil) -> Services? {
+ let location = VPhoneCLILocator().locate(
+ explicit: explicitCLIPath,
+ envPath: ProcessInfo.processInfo.environment["VPHONE_CLI_PATH"],
+ pathLookup: VPhoneCLILocator.whichLookup,
+ fileExists: FileManager.default.fileExists(atPath:))
+ guard case .found(let exe) = location else { return nil }
+ let runner = SystemCLIRunner()
+ let root = defaultLibraryRoot()
+ let probe = RunningStateProbe(runner: runner)
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: root, runner: runner)
+ return Services(
+ store: VMStore(client: client, probe: probe, libraryRoot: root),
+ coordinator: LaunchCoordinator(
+ executable: exe, libraryRoot: root, launcher: SystemProcessLauncher(),
+ client: client, probe: probe),
+ client: client,
+ readiness: HostReadiness(runner: runner),
+ taskCenter: TaskCenter(runner: SystemStreamingRunner()),
+ executable: exe,
+ commandBuilder: VPhoneCommandBuilder(libraryRoot: root),
+ variants: VariantStore(libraryRoot: root))
+ }
+}
diff --git a/Sources/VPhoneWSCore/Store/VMRow.swift b/Sources/VPhoneWSCore/Store/VMRow.swift
new file mode 100644
index 0000000..94118aa
--- /dev/null
+++ b/Sources/VPhoneWSCore/Store/VMRow.swift
@@ -0,0 +1,14 @@
+public struct VMRow: Identifiable, Equatable, Sendable {
+ public let report: VMReport
+ public var isRunning: Bool
+ public var id: String { report.name }
+
+ public init(report: VMReport, isRunning: Bool) {
+ self.report = report; self.isRunning = isRunning
+ }
+
+ public var displayVersions: String {
+ guard let ri = report.restoreInfo else { return "—" }
+ return "iOS \(ri.ios.version) · cloudOS \(ri.cloudOS.version)"
+ }
+}
diff --git a/Sources/VPhoneWSCore/Store/VMStore.swift b/Sources/VPhoneWSCore/Store/VMStore.swift
new file mode 100644
index 0000000..a9f7101
--- /dev/null
+++ b/Sources/VPhoneWSCore/Store/VMStore.swift
@@ -0,0 +1,35 @@
+import Foundation
+import Observation
+
+@MainActor
+@Observable
+public final class VMStore {
+ public private(set) var rows: [VMRow] = []
+ public private(set) var loadError: String?
+
+ private let client: VPhoneCLIClient
+ private let probe: RunningStateProbe
+ private let libraryRoot: String
+
+ public init(client: VPhoneCLIClient, probe: RunningStateProbe, libraryRoot: String) {
+ self.client = client; self.probe = probe; self.libraryRoot = libraryRoot
+ }
+
+ public func refresh() async {
+ do {
+ let reports = try await client.listVMs()
+ var next: [VMRow] = []
+ for report in reports {
+ let disk = "\(libraryRoot)/\(report.name)/Disk.img"
+ let running = (try? await probe.isRunning(diskImagePath: disk)) ?? false
+ next.append(VMRow(report: report, isRunning: running))
+ }
+ rows = next
+ loadError = nil
+ } catch let error as VPhoneCLIError {
+ loadError = error.userMessage
+ } catch {
+ loadError = String(describing: error)
+ }
+ }
+}
diff --git a/Sources/VPhoneWSCore/Tasks/StageParser.swift b/Sources/VPhoneWSCore/Tasks/StageParser.swift
new file mode 100644
index 0000000..77647f6
--- /dev/null
+++ b/Sources/VPhoneWSCore/Tasks/StageParser.swift
@@ -0,0 +1,21 @@
+import Foundation
+
+public enum LogEvent: Equatable, Sendable {
+ case stage(String)
+ case marker(String)
+ case plain(String)
+}
+
+public enum StageParser {
+ public static func classify(_ line: String) -> LogEvent {
+ let t = line.trimmingCharacters(in: .whitespaces)
+ if t.hasPrefix("===") && t.hasSuffix("===") && t.count > 6 {
+ let inner = t.dropFirst(3).dropLast(3).trimmingCharacters(in: .whitespaces)
+ return .stage(String(inner))
+ }
+ for m in ["[*]", "[+]", "[-]", "[!]"] where t.hasPrefix(m) {
+ return .marker(line)
+ }
+ return .plain(line)
+ }
+}
diff --git a/Sources/VPhoneWSCore/Tasks/TaskCenter.swift b/Sources/VPhoneWSCore/Tasks/TaskCenter.swift
new file mode 100644
index 0000000..b63bd6e
--- /dev/null
+++ b/Sources/VPhoneWSCore/Tasks/TaskCenter.swift
@@ -0,0 +1,24 @@
+import Foundation
+import Observation
+
+@MainActor
+@Observable
+public final class TaskCenter {
+ public private(set) var tasks: [TaskModel] = []
+ private let runner: StreamingRunner
+
+ public init(runner: StreamingRunner) {
+ self.runner = runner
+ }
+
+ @discardableResult
+ public func start(
+ title: String, plannedStages: [String], stageMap: [String: String] = [:],
+ executable: URL, arguments: [String]
+ ) -> TaskModel {
+ let model = TaskModel(title: title, plannedStages: plannedStages, stageMap: stageMap)
+ tasks.insert(model, at: 0)
+ Task { await model.run(executable: executable, arguments: arguments, runner: runner) }
+ return model
+ }
+}
diff --git a/Sources/VPhoneWSCore/Tasks/TaskModel.swift b/Sources/VPhoneWSCore/Tasks/TaskModel.swift
new file mode 100644
index 0000000..ade0b29
--- /dev/null
+++ b/Sources/VPhoneWSCore/Tasks/TaskModel.swift
@@ -0,0 +1,138 @@
+import Foundation
+import Observation
+
+public enum TaskStatus: Equatable, Sendable {
+ case running
+ case succeeded
+ case cancelled
+ case failed(Int32)
+}
+
+/// One stage's worth of output, grouped under its `=== banner ===`. `liveLine`
+/// is the in-progress line being overwritten by a progress bar's `\r` updates;
+/// it commits into `lines` when a newline arrives or the stage ends.
+public struct LogSegment: Identifiable, Equatable, Sendable {
+ public let id: Int
+ public let title: String
+ public var lines: [String]
+ public var liveLine: String?
+ public var isDone: Bool
+}
+
+@MainActor
+@Observable
+public final class TaskModel: Identifiable {
+ public let id = UUID()
+ public let title: String
+ public let plannedStages: [String]
+ public private(set) var currentStage: String?
+ public private(set) var completedStages: [String] = []
+ public private(set) var segments: [LogSegment] = []
+ public private(set) var status: TaskStatus = .running
+
+ public var logLines: [String] { segments.flatMap(\.lines) }
+
+ /// Full log as shareable text, grouped under each stage banner.
+ public var exportText: String {
+ var out = "\(title)\n\n"
+ for seg in segments {
+ out += "=== \(seg.title) ===\n"
+ for line in seg.lines { out += line + "\n" }
+ if let live = seg.liveLine { out += live + "\n" }
+ out += "\n"
+ }
+ return out
+ }
+
+ private let stageMap: [String: String]
+ private var pid: Int32?
+
+ public init(title: String, plannedStages: [String], stageMap: [String: String] = [:]) {
+ self.title = title
+ self.plannedStages = plannedStages
+ self.stageMap = stageMap
+ }
+
+ public func run(executable: URL, arguments: [String], runner: StreamingRunner) async {
+ let (stream, continuation) = AsyncStream<StreamEvent>.makeStream(of: StreamEvent.self)
+ let runTask = Task {
+ let code = (try? await runner.run(
+ executable: executable,
+ arguments: arguments,
+ environment: nil,
+ onStart: { [weak self] pid in
+ Task { @MainActor in self?.pid = pid }
+ },
+ onEvent: { event in continuation.yield(event) }
+ )) ?? -1
+ continuation.finish()
+ return code
+ }
+
+ for await event in stream {
+ handle(event)
+ }
+
+ let code = await runTask.value
+ if status != .cancelled {
+ if code == 0 {
+ if let current = currentStage {
+ completedStages.append(current)
+ currentStage = nil
+ }
+ finishLastSegment()
+ status = .succeeded
+ } else {
+ status = .failed(code)
+ }
+ }
+ }
+
+ public func cancel() {
+ if let pid {
+ kill(pid, SIGINT)
+ }
+ status = .cancelled
+ }
+
+ private func handle(_ event: StreamEvent) {
+ switch event {
+ case .line(let raw):
+ switch StageParser.classify(raw) {
+ case .stage(let banner):
+ let display = stageMap[banner] ?? banner
+ // Chips track only the planned stages; setup/teardown banners
+ // (vm new, Done, …) still open their own log segment.
+ if plannedStages.isEmpty || plannedStages.contains(display) {
+ if let current = currentStage { completedStages.append(current) }
+ currentStage = display
+ }
+ finishLastSegment()
+ segments.append(LogSegment(id: segments.count, title: display, lines: [], liveLine: nil, isDone: false))
+ case .marker, .plain:
+ ensureSegment()
+ segments[segments.count - 1].lines.append(raw)
+ segments[segments.count - 1].liveLine = nil
+ }
+ case .update(let text):
+ ensureSegment()
+ segments[segments.count - 1].liveLine = text
+ }
+ }
+
+ private func ensureSegment() {
+ if segments.isEmpty {
+ segments.append(LogSegment(id: 0, title: "Starting up", lines: [], liveLine: nil, isDone: false))
+ }
+ }
+
+ private func finishLastSegment() {
+ guard !segments.isEmpty else { return }
+ let i = segments.count - 1
+ if let live = segments[i].liveLine {
+ segments[i].lines.append(live)
+ segments[i].liveLine = nil
+ }
+ segments[i].isDone = true
+ }
+}
diff --git a/Sources/VPhoneWSCore/Tasks/VPhoneCommandBuilder.swift b/Sources/VPhoneWSCore/Tasks/VPhoneCommandBuilder.swift
new file mode 100644
index 0000000..ffca9ab
--- /dev/null
+++ b/Sources/VPhoneWSCore/Tasks/VPhoneCommandBuilder.swift
@@ -0,0 +1,38 @@
+public struct VPhoneCommandBuilder: Sendable {
+ public let libraryRoot: String?
+ public init(libraryRoot: String?) { self.libraryRoot = libraryRoot }
+
+ // Display chips (mockup task console). The CLI's `=== … ===` banners map to these.
+ public static let createStages = ["Prepare", "Patch", "Restore", "Install CFW", "First boot"]
+
+ // CLI banner (inner text of `=== … ===`) → display chip. Banners absent here
+ // ("vm new", "JB Finalize", "Done", "Boot analysis") don't drive a chip.
+ public static let createStageMap: [String: String] = [
+ "fw prepare": "Prepare",
+ "fw patch": "Patch",
+ "Restore phase": "Restore",
+ "CFW install (host-mount)": "Install CFW",
+ "First boot": "First boot",
+ ]
+
+ public func createArgs(
+ name: String, variant: String, iphoneSource: String, cloudosSource: String, diskSizeGB: Int
+ ) -> [String] {
+ withLibraryRoot(["vm", "create", name, "-V", variant,
+ "--iphone-source", iphoneSource, "--cloudos-source", cloudosSource,
+ "--disk-size", String(diskSizeGB), "--root-popup", "-v"])
+ }
+
+ public func exportArgs(name: String, out: String) -> [String] {
+ withLibraryRoot(["vm", "export", name, "-o", out])
+ }
+
+ public func importArgs(archive: String, name: String) -> [String] {
+ withLibraryRoot(["vm", "import", "-i", archive, "-n", name])
+ }
+
+ private func withLibraryRoot(_ argv: [String]) -> [String] {
+ guard let libraryRoot else { return argv }
+ return argv + ["--library-root", libraryRoot]
+ }
+}
diff --git a/Sources/VPhoneWSCore/VPhoneWSCore.swift b/Sources/VPhoneWSCore/VPhoneWSCore.swift
new file mode 100644
index 0000000..62c5e21
--- /dev/null
+++ b/Sources/VPhoneWSCore/VPhoneWSCore.swift
@@ -0,0 +1,3 @@
+public enum VPhoneWSCore {
+ public static let version = "0.1.0"
+}
diff --git a/Sources/VPhoneWSCore/Variant/VariantStore.swift b/Sources/VPhoneWSCore/Variant/VariantStore.swift
new file mode 100644
index 0000000..a1f2301
--- /dev/null
+++ b/Sources/VPhoneWSCore/Variant/VariantStore.swift
@@ -0,0 +1,22 @@
+import Foundation
+
+public struct VariantStore: Sendable {
+ private struct Sidecar: Codable { let variant: String }
+ private let libraryRoot: String
+ public init(libraryRoot: String) { self.libraryRoot = libraryRoot }
+
+ private func url(_ name: String) -> URL {
+ URL(fileURLWithPath: "\(libraryRoot)/\(name)/.vphone-ws.json")
+ }
+
+ public func setVariant(_ variant: String, forVM name: String) throws {
+ let data = try JSONEncoder().encode(Sidecar(variant: variant))
+ try data.write(to: url(name))
+ }
+
+ public func variant(forVM name: String) -> String? {
+ guard let data = try? Data(contentsOf: url(name)),
+ let side = try? JSONDecoder().decode(Sidecar.self, from: data) else { return nil }
+ return side.variant
+ }
+}
diff --git a/tests/VPhoneWSCoreTests/CLIRunnerTests.swift b/tests/VPhoneWSCoreTests/CLIRunnerTests.swift
new file mode 100644
index 0000000..494daf6
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/CLIRunnerTests.swift
@@ -0,0 +1,109 @@
+import Foundation
+import Testing
+@testable import VPhoneWSCore
+
+@Test func fakeRunnerReturnsStubbedResultAndRecordsCall() async throws {
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["vm", "list", "--json"],
+ result: CLIResult(stdout: "[]", stderr: "", exitCode: 0))
+
+ let out = try await fake.run(
+ executable: URL(fileURLWithPath: "/usr/bin/vphone-cli"),
+ arguments: ["vm", "list", "--json"], environment: nil)
+
+ #expect(out.stdout == "[]")
+ #expect(out.exitCode == 0)
+ #expect(fake.calls.count == 1)
+ #expect(fake.calls[0].arguments == ["vm", "list", "--json"])
+}
+
+@Test func systemRunnerCapturesStdoutAndExitCode() async throws {
+ let runner = SystemCLIRunner()
+ let out = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/echo"),
+ arguments: ["hello"], environment: nil)
+ #expect(out.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == "hello")
+ #expect(out.exitCode == 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemRunnerDoesNotDeadlockOnLargeStdout() async throws {
+ let runner = SystemCLIRunner()
+ let out = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "yes X | head -c 200000"], environment: nil)
+ #expect(out.stdout.utf8.count == 200_000)
+ #expect(out.exitCode == 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemRunnerDoesNotDeadlockOnLargeStderr() async throws {
+ let runner = SystemCLIRunner()
+ let out = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "yes X | head -c 200000 1>&2"], environment: nil)
+ #expect(out.stderr.utf8.count == 200_000)
+ #expect(out.exitCode == 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemRunnerThrowsPromptlyForInvalidExecutable() async throws {
+ let runner = SystemCLIRunner()
+ await #expect(throws: (any Error).self) {
+ _ = try await runner.run(
+ executable: URL(fileURLWithPath: "/nonexistent/definitely-not-a-binary"),
+ arguments: [], environment: nil)
+ }
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemRunnerSurvivesHighConcurrencyChurn() async throws {
+ let runner = SystemCLIRunner()
+ try await withThrowingTaskGroup(of: Int32.self) { group in
+ for i in 0..<120 {
+ group.addTask {
+ try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "echo out-\(i); echo err-\(i) 1>&2"], environment: nil
+ ).exitCode
+ }
+ }
+ var count = 0
+ for try await code in group {
+ #expect(code == 0)
+ count += 1
+ }
+ #expect(count == 120)
+ }
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemRunnerHandlesAbnormalTermination() async throws {
+ let runner = SystemCLIRunner()
+ let out = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "echo partial; kill -9 $$"], environment: nil)
+ #expect(out.stdout.contains("partial"))
+ #expect(out.exitCode == 9)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemRunnerDoesNotLeakFileDescriptorsOnSuccess() async throws {
+ let runner = SystemCLIRunner()
+ let echo = URL(fileURLWithPath: "/bin/echo")
+
+ func openFDCount() -> Int {
+ (try? FileManager.default.contentsOfDirectory(atPath: "/dev/fd").count) ?? 0
+ }
+
+ _ = try await runner.run(executable: echo, arguments: ["warmup"], environment: nil)
+
+ let before = openFDCount()
+ for _ in 0..<200 {
+ let out = try await runner.run(executable: echo, arguments: ["hi"], environment: nil)
+ #expect(out.exitCode == 0)
+ }
+ let after = openFDCount()
+
+ #expect(after - before < 20)
+}
diff --git a/tests/VPhoneWSCoreTests/FirmwareCatalogTests.swift b/tests/VPhoneWSCoreTests/FirmwareCatalogTests.swift
new file mode 100644
index 0000000..2a02de4
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/FirmwareCatalogTests.swift
@@ -0,0 +1,33 @@
+import Foundation
+import Testing
+@testable import VPhoneWSCore
+
+@Test func decodesCatalogAndDerivesOptions() throws {
+ let json = """
+ {"pairings":[
+ {"ios":{"name":"iOS 26.3","url":"u-ios-263"},"recommendedCloudOS":{"name":"cloudOS 26.3","url":"u-cos-263"}},
+ {"ios":{"name":"iOS 26.3.1","url":"u-ios-2631"},"recommendedCloudOS":{"name":"cloudOS 26.3","url":"u-cos-263"}},
+ {"ios":{"name":"iOS 26.4","url":"u-ios-264"},"recommendedCloudOS":{"name":"cloudOS 26.4","url":"u-cos-264"}}
+ ]}
+ """
+ let cat = try JSONDecoder().decode(FirmwareCatalog.self, from: Data(json.utf8))
+ #expect(cat.pairings.count == 3)
+ #expect(cat.pairings[0].recommendedCloudOS.url == "u-cos-263")
+ #expect(cat.iosImages.map(\.name) == ["iOS 26.3", "iOS 26.3.1", "iOS 26.4"])
+ // cloudOS deduped by url, first-seen order (263 appears twice → once).
+ #expect(cat.cloudOSImages.map(\.name) == ["cloudOS 26.3", "cloudOS 26.4"])
+}
+
+@Test func fetchCatalogRunsWithoutLibraryRoot() async throws {
+ let fake = FakeCLIRunner()
+ let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+ fake.stub(arguments: ["fw", "catalog", "--json"],
+ result: CLIResult(stdout: #"{"pairings":[]}"#, stderr: "", exitCode: 0))
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: "/lib", runner: fake)
+
+ let cat = try await client.fetchCatalog()
+
+ #expect(cat.pairings.isEmpty)
+ // `fw catalog` rejects --library-root; the call must not append it.
+ #expect(fake.calls.last?.arguments == ["fw", "catalog", "--json"])
+}
diff --git a/tests/VPhoneWSCoreTests/HostReadinessTests.swift b/tests/VPhoneWSCoreTests/HostReadinessTests.swift
new file mode 100644
index 0000000..69dfd17
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/HostReadinessTests.swift
@@ -0,0 +1,47 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+@Test func nestedVMEvaluator() {
+ #expect(HostReadiness.evalNestedVM(hvVmmPresent: "0\n").status == .ok)
+ #expect(HostReadiness.evalNestedVM(hvVmmPresent: "1\n").status == .attention)
+}
+
+@Test func macOSEvaluator() {
+ #expect(HostReadiness.evalMacOS(version: .init(majorVersion: 15, minorVersion: 2, patchVersion: 0)).status == .ok)
+ #expect(HostReadiness.evalMacOS(version: .init(majorVersion: 14, minorVersion: 6, patchVersion: 0)).status == .attention)
+}
+
+@Test func amfiEvaluator() {
+ let running = "/usr/sbin/cfprefsd\nPython -m amfidont --spoof-apple --path /Applications/vphone-cli.app\nloginwindow\n"
+ #expect(HostReadiness.evalAMFI(psOutput: running, bootArgs: "").status == .ok)
+
+ // The `vphone-amfidont` wrapper process is not the daemon itself.
+ let wrapperOnly = "/bin/zsh /opt/homebrew/bin/vphone-amfidont\nloginwindow\n"
+ #expect(HostReadiness.evalAMFI(psOutput: wrapperOnly, bootArgs: "").status == .attention)
+
+ // The boot-arg alone satisfies the check even with no amfidont running.
+ let viaBootArg = HostReadiness.evalAMFI(
+ psOutput: "loginwindow\n", bootArgs: "boot-args\tamfi_get_out_of_my_way=1 -v\n")
+ #expect(viaBootArg.status == .ok)
+ #expect(viaBootArg.fixCommand == nil)
+
+ // A zeroed boot-arg does not count.
+ #expect(HostReadiness.evalAMFI(psOutput: "loginwindow\n", bootArgs: "amfi_get_out_of_my_way=0").status == .attention)
+
+ let miss = HostReadiness.evalAMFI(psOutput: "loginwindow\nWindowServer\n", bootArgs: "")
+ #expect(miss.status == .attention)
+ #expect(miss.fixCommand != nil)
+}
+
+@Test func researchGuestsEvaluator() {
+ #expect(HostReadiness.evalResearchGuests(csrutilOutput: "Allow Research Guests status: enabled\n").status == .ok)
+ let off = HostReadiness.evalResearchGuests(csrutilOutput: "Allow Research Guests status: disabled\n")
+ #expect(off.status == .attention)
+ #expect(off.fixCommand == "csrutil allow-research-guests enable")
+}
+
+@Test func cliEvaluator() {
+ #expect(HostReadiness.evalCLI(.found(URL(fileURLWithPath: "/opt/homebrew/bin/vphone-cli"))).status == .ok)
+ #expect(HostReadiness.evalCLI(.notFound).status == .attention)
+}
diff --git a/tests/VPhoneWSCoreTests/LaunchCoordinatorTests.swift b/tests/VPhoneWSCoreTests/LaunchCoordinatorTests.swift
new file mode 100644
index 0000000..2f828c1
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/LaunchCoordinatorTests.swift
@@ -0,0 +1,30 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+private let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+
+@MainActor
+@Test func launchSpawnsWithExplicitNameAndLibraryRoot() throws {
+ let launcher = FakeProcessLauncher(stubPID: 77)
+ let runner = FakeCLIRunner()
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: "/lib", runner: runner)
+ let coord = LaunchCoordinator(
+ executable: exe, libraryRoot: "/lib", launcher: launcher, client: client,
+ probe: RunningStateProbe(runner: runner))
+ try coord.launch(name: "a")
+ #expect(launcher.calls[0].arguments == ["vm", "launch", "a", "--library-root", "/lib"])
+}
+
+@MainActor
+@Test func stopRunsVmStop() async throws {
+ let runner = FakeCLIRunner()
+ runner.stub(arguments: ["vm", "stop", "a", "--library-root", "/lib"],
+ result: CLIResult(stdout: "a: stopped", stderr: "", exitCode: 0))
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: "/lib", runner: runner)
+ let coord = LaunchCoordinator(
+ executable: exe, libraryRoot: "/lib", launcher: FakeProcessLauncher(stubPID: 5),
+ client: client, probe: RunningStateProbe(runner: runner))
+ try await coord.stop(name: "a")
+ #expect(runner.calls.contains { $0.arguments == ["vm", "stop", "a", "--library-root", "/lib"] })
+}
diff --git a/tests/VPhoneWSCoreTests/ProcessLauncherTests.swift b/tests/VPhoneWSCoreTests/ProcessLauncherTests.swift
new file mode 100644
index 0000000..2d55b0e
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/ProcessLauncherTests.swift
@@ -0,0 +1,18 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+@Test func fakeLauncherRecordsAndReturnsPID() throws {
+ let fake = FakeProcessLauncher(stubPID: 4242)
+ let p = try fake.launch(executable: URL(fileURLWithPath: "/x"), arguments: ["vm", "launch", "a"], environment: nil)
+ #expect(p.pid == 4242)
+ #expect(fake.calls.count == 1)
+ #expect(fake.calls[0].arguments == ["vm", "launch", "a"])
+}
+
+@Test func systemLauncherStartsProcessWithoutWaiting() throws {
+ let launcher = SystemProcessLauncher()
+ let p = try launcher.launch(executable: URL(fileURLWithPath: "/bin/sleep"), arguments: ["5"], environment: nil)
+ #expect(p.pid > 0)
+ kill(p.pid, SIGTERM)
+}
diff --git a/tests/VPhoneWSCoreTests/RunningStateProbeTests.swift b/tests/VPhoneWSCoreTests/RunningStateProbeTests.swift
new file mode 100644
index 0000000..4a9bf46
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/RunningStateProbeTests.swift
@@ -0,0 +1,25 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+@Test func parsePIDsIgnoresBlankLines() {
+ #expect(RunningStateProbe.parsePIDs("123\n456\n") == [123, 456])
+ #expect(RunningStateProbe.parsePIDs("") == [])
+ #expect(RunningStateProbe.parsePIDs("\n \n789\n") == [789])
+}
+
+@Test func isRunningReflectsPIDPresence() async throws {
+ let disk = "/Users/me/.vphone/VMs/a/Disk.img"
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["-t", "--", disk], result: CLIResult(stdout: "4242\n", stderr: "", exitCode: 0))
+ let probe = RunningStateProbe(runner: fake)
+ #expect(try await probe.isRunning(diskImagePath: disk) == true)
+}
+
+@Test func isRunningFalseWhenLsofNonZeroWithNoHolders() async throws {
+ let disk = "/Users/me/.vphone/VMs/b/Disk.img"
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["-t", "--", disk], result: CLIResult(stdout: "", stderr: "", exitCode: 1))
+ let probe = RunningStateProbe(runner: fake)
+ #expect(try await probe.isRunning(diskImagePath: disk) == false)
+}
diff --git a/tests/VPhoneWSCoreTests/SmokeTests.swift b/tests/VPhoneWSCoreTests/SmokeTests.swift
new file mode 100644
index 0000000..c0bf890
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/SmokeTests.swift
@@ -0,0 +1,6 @@
+import Testing
+@testable import VPhoneWSCore
+
+@Test func coreExposesVersion() {
+ #expect(VPhoneWSCore.version == "0.1.0")
+}
diff --git a/tests/VPhoneWSCoreTests/StageParserTests.swift b/tests/VPhoneWSCoreTests/StageParserTests.swift
new file mode 100644
index 0000000..21d39e5
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/StageParserTests.swift
@@ -0,0 +1,10 @@
+import Testing
+@testable import VPhoneWSCore
+
+@Test func classifiesBannersMarkersAndPlain() {
+ #expect(StageParser.classify("=== Restore phase ===") == .stage("Restore phase"))
+ #expect(StageParser.classify("=== CFW install ===") == .stage("CFW install"))
+ #expect(StageParser.classify("[+] SHSH fetched") == .marker("[+] SHSH fetched"))
+ #expect(StageParser.classify("[-] panic") == .marker("[-] panic"))
+ #expect(StageParser.classify("uploading ramdisk") == .plain("uploading ramdisk"))
+}
diff --git a/tests/VPhoneWSCoreTests/StreamingRunnerTests.swift b/tests/VPhoneWSCoreTests/StreamingRunnerTests.swift
new file mode 100644
index 0000000..1af5df3
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/StreamingRunnerTests.swift
@@ -0,0 +1,175 @@
+import Foundation
+import Testing
+@testable import VPhoneWSCore
+
+private final class StreamCollector: @unchecked Sendable {
+ private let lock = NSLock()
+ private var pid: Int32 = 0
+ private var lines: [String] = []
+
+ func recordStart(_ pid: Int32) { lock.lock(); self.pid = pid; lock.unlock() }
+ func recordLine(_ line: String) { lock.lock(); lines.append(line); lock.unlock() }
+
+ var startedPID: Int32 { lock.lock(); defer { lock.unlock() }; return pid }
+ var seenLines: [String] { lock.lock(); defer { lock.unlock() }; return lines }
+}
+
+@Test func fakeStreamerEmitsLinesThenExit() async throws {
+ let fake = FakeStreamingRunner(lines: ["=== Prepare ===", "[+] done"], exitCode: 0, stubPID: 9)
+ let collector = StreamCollector()
+ let code = try await fake.run(executable: URL(fileURLWithPath: "/x"), arguments: [], environment: nil,
+ onStart: { collector.recordStart($0) }, onEvent: { if case .line(let s) = $0 { collector.recordLine(s) } })
+ #expect(collector.startedPID == 9)
+ #expect(collector.seenLines == ["=== Prepare ===", "[+] done"])
+ #expect(code == 0)
+}
+
+@Test func systemStreamerEchoesLines() async throws {
+ let runner = SystemStreamingRunner()
+ let collector = StreamCollector()
+ let code = try await runner.run(executable: URL(fileURLWithPath: "/bin/echo"), arguments: ["one\ntwo"],
+ environment: nil, onStart: { collector.recordStart($0) }, onEvent: { if case .line(let s) = $0 { collector.recordLine(s) } })
+ #expect(code == 0)
+ #expect(collector.seenLines.contains("one"))
+ #expect(collector.seenLines.contains("two"))
+ #expect(collector.startedPID > 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerHandlesLargeOutputWithoutDeadlockOrTruncation() async throws {
+ let runner = SystemStreamingRunner()
+ let collector = StreamCollector()
+ let code = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "yes X | head -c 200000"],
+ environment: nil,
+ onStart: { collector.recordStart($0) },
+ onEvent: { if case .line(let s) = $0 { collector.recordLine(s) } })
+
+ let lines = collector.seenLines
+ let totalBytes = lines.reduce(0) { $0 + $1.utf8.count + 1 }
+ #expect(lines.count == 100_000)
+ #expect(lines.allSatisfy { $0 == "X" })
+ #expect(totalBytes == 200_000)
+ #expect(code == 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerThrowsPromptlyForInvalidExecutable() async throws {
+ let runner = SystemStreamingRunner()
+ await #expect(throws: (any Error).self) {
+ _ = try await runner.run(
+ executable: URL(fileURLWithPath: "/nonexistent/definitely-not-a-binary"),
+ arguments: [], environment: nil, onStart: { _ in }, onEvent: { _ in })
+ }
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerFlushesTrailingLineWithoutNewline() async throws {
+ let runner = SystemStreamingRunner()
+ let collector = StreamCollector()
+ let code = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "printf 'line-one\\nno-newline-tail'"],
+ environment: nil,
+ onStart: { collector.recordStart($0) },
+ onEvent: { if case .line(let s) = $0 { collector.recordLine(s) } })
+
+ #expect(collector.seenLines == ["line-one", "no-newline-tail"])
+ #expect(code == 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerCapturesStderrThroughMergedPipe() async throws {
+ let runner = SystemStreamingRunner()
+ let collector = StreamCollector()
+ let code = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "echo out; echo err 1>&2"],
+ environment: nil,
+ onStart: { collector.recordStart($0) },
+ onEvent: { if case .line(let s) = $0 { collector.recordLine(s) } })
+
+ #expect(collector.seenLines.contains("out"))
+ #expect(collector.seenLines.contains("err"))
+ #expect(code == 0)
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerStripsAnsiEscapes() async throws {
+ // Progress bars emit color / erase-line escapes; the log is plain text, so
+ // they must be stripped, leaving the visible characters.
+ let runner = SystemStreamingRunner()
+ let collector = StreamCollector()
+ let code = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "printf 'a\\033[31mRED\\033[0m\\033[Kb\\n'"],
+ environment: nil,
+ onStart: { _ in },
+ onEvent: { if case .line(let s) = $0 { collector.recordLine(s) } })
+
+ #expect(code == 0)
+ #expect(collector.seenLines == ["aREDb"])
+}
+
+private final class TimedRecorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var _lines: [String] = []
+ private var _times: [TimeInterval] = []
+ private let start = Date()
+ func recordLine(_ s: String) {
+ lock.lock(); defer { lock.unlock() }
+ _lines.append(s); _times.append(Date().timeIntervalSince(start))
+ }
+ var lines: [String] { lock.lock(); defer { lock.unlock() }; return _lines }
+ // Wall-clock between the first and last line — factors out process start-up.
+ var spread: TimeInterval {
+ lock.lock(); defer { lock.unlock() }
+ guard let f = _times.first, let l = _times.last else { return 0 }
+ return l - f
+ }
+}
+
+private final class EventRecorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var _events: [StreamEvent] = []
+ func record(_ e: StreamEvent) { lock.lock(); _events.append(e); lock.unlock() }
+ var events: [StreamEvent] { lock.lock(); defer { lock.unlock() }; return _events }
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerDeliversLinesLiveNotAtExit() async throws {
+ // Python line-buffers stdout to a TTY (our PTY) but block-buffers to a pipe.
+ // On a pipe all three lines would arrive together at exit (spread ~0); over
+ // the PTY they must arrive ~0.3s apart as they're printed.
+ let runner = SystemStreamingRunner()
+ let rec = TimedRecorder()
+ let code = try await runner.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "printf 'a\\n'; sleep 0.3; printf 'b\\n'; sleep 0.3; printf 'c\\n'"],
+ environment: nil,
+ onStart: { _ in },
+ onEvent: { if case .line(let s) = $0 { rec.recordLine(s) } })
+ #expect(code == 0)
+ #expect(rec.lines == ["a", "b", "c"])
+ #expect(rec.spread > 0.4) // arrived spread out (live), not batched at exit
+}
+
+@Test(.timeLimit(.minutes(1)))
+func systemStreamerTreatsCarriageReturnAsLiveOverwrite() async throws {
+ // A progress bar overwrites one line via \r. Those must be live `.update`s,
+ // not committed `.line`s — otherwise the log shows duplicate progress lines.
+ let runner = SystemStreamingRunner()
+ let rec = EventRecorder()
+ let code = try await runner.run(
+ executable: URL(fileURLWithPath: "/usr/bin/python3"),
+ arguments: ["-c", "import sys\nfor p in ['10%','20%','30%']:\n sys.stdout.write(p+'\\r'); sys.stdout.flush()\nsys.stdout.write('done\\n')"],
+ environment: nil,
+ onStart: { _ in },
+ onEvent: { rec.record($0) })
+ let committed = rec.events.compactMap { if case .line(let s) = $0 { return s } else { return nil } }
+ let updates = rec.events.compactMap { if case .update(let s) = $0 { return s } else { return nil } }
+ #expect(code == 0)
+ #expect(committed == ["done"]) // only the real newline commits
+ #expect(updates.contains("10%") && updates.contains("20%")) // progress = live overwrites
+}
diff --git a/tests/VPhoneWSCoreTests/Support/FakeCLIRunner.swift b/tests/VPhoneWSCoreTests/Support/FakeCLIRunner.swift
new file mode 100644
index 0000000..1903e27
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/Support/FakeCLIRunner.swift
@@ -0,0 +1,18 @@
+import Foundation
+@testable import VPhoneWSCore
+
+final class FakeCLIRunner: CLIRunner, @unchecked Sendable {
+ struct Call { let executable: URL; let arguments: [String]; let environment: [String: String]? }
+ private(set) var calls: [Call] = []
+ private var stubs: [[String]: CLIResult] = [:]
+
+ func stub(arguments: [String], result: CLIResult) { stubs[arguments] = result }
+
+ func run(executable: URL, arguments: [String], environment: [String: String]?) async throws -> CLIResult {
+ calls.append(Call(executable: executable, arguments: arguments, environment: environment))
+ guard let result = stubs[arguments] else {
+ return CLIResult(stdout: "", stderr: "no stub for \(arguments)", exitCode: 127)
+ }
+ return result
+ }
+}
diff --git a/tests/VPhoneWSCoreTests/Support/FakeProcessLauncher.swift b/tests/VPhoneWSCoreTests/Support/FakeProcessLauncher.swift
new file mode 100644
index 0000000..8de457d
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/Support/FakeProcessLauncher.swift
@@ -0,0 +1,14 @@
+import Foundation
+@testable import VPhoneWSCore
+
+final class FakeProcessLauncher: ProcessLauncher, @unchecked Sendable {
+ struct Call { let executable: URL; let arguments: [String]; let environment: [String: String]? }
+ private(set) var calls: [Call] = []
+ let stubPID: Int32
+ init(stubPID: Int32 = 1) { self.stubPID = stubPID }
+
+ func launch(executable: URL, arguments: [String], environment: [String: String]?) throws -> LaunchedProcess {
+ calls.append(Call(executable: executable, arguments: arguments, environment: environment))
+ return LaunchedProcess(pid: stubPID)
+ }
+}
diff --git a/tests/VPhoneWSCoreTests/Support/FakeStreamingRunner.swift b/tests/VPhoneWSCoreTests/Support/FakeStreamingRunner.swift
new file mode 100644
index 0000000..febe083
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/Support/FakeStreamingRunner.swift
@@ -0,0 +1,22 @@
+import Foundation
+@testable import VPhoneWSCore
+
+final class FakeStreamingRunner: StreamingRunner, @unchecked Sendable {
+ let lines: [String]
+ let exitCode: Int32
+ let stubPID: Int32
+
+ init(lines: [String], exitCode: Int32, stubPID: Int32 = 1) {
+ self.lines = lines
+ self.exitCode = exitCode
+ self.stubPID = stubPID
+ }
+
+ func run(executable: URL, arguments: [String], environment: [String: String]?,
+ onStart: @escaping @Sendable (Int32) -> Void,
+ onEvent: @escaping @Sendable (StreamEvent) -> Void) async throws -> Int32 {
+ onStart(stubPID)
+ for line in lines { onEvent(.line(line)) }
+ return exitCode
+ }
+}
diff --git a/tests/VPhoneWSCoreTests/TaskCenterTests.swift b/tests/VPhoneWSCoreTests/TaskCenterTests.swift
new file mode 100644
index 0000000..6e1c139
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/TaskCenterTests.swift
@@ -0,0 +1,23 @@
+import Foundation
+import Testing
+@testable import VPhoneWSCore
+
+private let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+
+@MainActor
+@Test func startInsertsAtFrontAndRuns() async {
+ let runner = FakeStreamingRunner(lines: ["=== Export ===", "[+] done"], exitCode: 0)
+ let center = TaskCenter(runner: runner)
+
+ let first = center.start(title: "Export a", plannedStages: ["Export"], executable: exe, arguments: ["vm", "export", "a"])
+ #expect(center.tasks.map(\.id) == [first.id])
+
+ let second = center.start(title: "Export b", plannedStages: [], executable: exe, arguments: ["vm", "export", "b"])
+ #expect(center.tasks.map(\.id) == [second.id, first.id])
+
+ while first.status == .running || second.status == .running {
+ await Task.yield()
+ }
+ #expect(first.status == .succeeded)
+ #expect(second.status == .succeeded)
+}
diff --git a/tests/VPhoneWSCoreTests/TaskModelTests.swift b/tests/VPhoneWSCoreTests/TaskModelTests.swift
new file mode 100644
index 0000000..5bc466a
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/TaskModelTests.swift
@@ -0,0 +1,66 @@
+import Foundation
+import Testing
+@testable import VPhoneWSCore
+
+private let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+
+@MainActor
+@Test func runAdvancesStagesAndSucceeds() async {
+ let runner = FakeStreamingRunner(
+ lines: ["=== Prepare ===", "[*] downloading", "=== Restore phase ===", "[+] ok"],
+ exitCode: 0)
+ let task = TaskModel(title: "Create a", plannedStages: ["Prepare", "Restore phase"])
+ await task.run(executable: exe, arguments: ["vm", "create", "a"], runner: runner)
+ // Every planned stage reads done once the task succeeds — nothing left "current".
+ #expect(task.completedStages == ["Prepare", "Restore phase"])
+ #expect(task.currentStage == nil)
+ #expect(task.logLines.contains("[*] downloading"))
+ #expect(task.status == .succeeded)
+}
+
+@MainActor
+@Test func mapsCreateBannersToMockupChips() async {
+ let runner = FakeStreamingRunner(
+ lines: ["=== vm new ===", "=== fw prepare ===", "=== fw patch ===",
+ "=== Restore phase ===", "=== CFW install (host-mount) ===",
+ "=== First boot ===", "=== Done ==="],
+ exitCode: 0)
+ let task = TaskModel(
+ title: "Create a",
+ plannedStages: VPhoneCommandBuilder.createStages,
+ stageMap: VPhoneCommandBuilder.createStageMap)
+ await task.run(executable: exe, arguments: [], runner: runner)
+ // "vm new" / "Done" are unmapped → no chip; mapped banners drive the chips in order.
+ #expect(task.completedStages == ["Prepare", "Patch", "Restore", "Install CFW", "First boot"])
+ #expect(task.currentStage == nil)
+ #expect(task.status == .succeeded)
+}
+
+@MainActor
+@Test func groupsOutputIntoPerStageSegments() async {
+ let runner = FakeStreamingRunner(
+ lines: ["preflight ok", "=== fw prepare ===", "[*] downloading", "[+] merged",
+ "=== fw patch ===", "[+] applied 52"],
+ exitCode: 0)
+ let task = TaskModel(
+ title: "Create a",
+ plannedStages: VPhoneCommandBuilder.createStages,
+ stageMap: VPhoneCommandBuilder.createStageMap)
+ await task.run(executable: exe, arguments: [], runner: runner)
+ // Leading output → "Starting up"; each banner opens its own grouped segment.
+ let titles = task.segments.map(\.title)
+ let allDone = task.segments.allSatisfy { $0.isDone }
+ #expect(titles == ["Starting up", "Prepare", "Patch"])
+ #expect(task.segments[0].lines == ["preflight ok"])
+ #expect(task.segments[1].lines == ["[*] downloading", "[+] merged"])
+ #expect(task.segments[2].lines == ["[+] applied 52"])
+ #expect(allDone)
+}
+
+@MainActor
+@Test func nonZeroExitMarksFailed() async {
+ let runner = FakeStreamingRunner(lines: ["[-] boom"], exitCode: 3)
+ let task = TaskModel(title: "Create a", plannedStages: [])
+ await task.run(executable: exe, arguments: [], runner: runner)
+ #expect(task.status == .failed(3))
+}
diff --git a/tests/VPhoneWSCoreTests/VMReportTests.swift b/tests/VPhoneWSCoreTests/VMReportTests.swift
new file mode 100644
index 0000000..db542d1
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VMReportTests.swift
@@ -0,0 +1,20 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+@Test func decodesListWithAndWithoutRestoreInfo() throws {
+ let json = """
+ [
+ {"name":"research-jb","cpuCount":8,"memoryMB":8192,"diskSizeBytes":68719476736,
+ "restoreInfo":{"ios":{"version":"27.0","build":"24A5380h"},
+ "cloudOS":{"version":"26.4","build":"23E5207q"}}},
+ {"name":"blank","cpuCount":8,"memoryMB":8192,"diskSizeBytes":68719476736}
+ ]
+ """
+ let reports = try JSONDecoder().decode([VMReport].self, from: Data(json.utf8))
+ #expect(reports.count == 2)
+ #expect(reports[0].name == "research-jb")
+ #expect(reports[0].restoreInfo?.ios.version == "27.0")
+ #expect(reports[0].restoreInfo?.cloudOS.build == "23E5207q")
+ #expect(reports[1].restoreInfo == nil)
+}
diff --git a/tests/VPhoneWSCoreTests/VMStoreTests.swift b/tests/VPhoneWSCoreTests/VMStoreTests.swift
new file mode 100644
index 0000000..dac9ff0
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VMStoreTests.swift
@@ -0,0 +1,35 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+private func report(_ name: String, restore: RestoreInfo? = nil) -> VMReport {
+ VMReport(name: name, cpuCount: 8, memoryMB: 8192, diskSizeBytes: 1, restoreInfo: restore)
+}
+
+@Test func rowDisplaysVersionsOrDash() {
+ let ri = RestoreInfo(ios: .init(version: "27.0", build: "24A5380h"),
+ cloudOS: .init(version: "26.4", build: "23E5207q"))
+ #expect(VMRow(report: report("a", restore: ri), isRunning: true).displayVersions == "iOS 27.0 · cloudOS 26.4")
+ #expect(VMRow(report: report("b"), isRunning: false).displayVersions == "—")
+}
+
+@MainActor
+@Test func refreshPopulatesRowsWithRunningState() async throws {
+ let listJSON = "[{\"name\":\"a\",\"cpuCount\":8,\"memoryMB\":8192,\"diskSizeBytes\":1}," +
+ "{\"name\":\"b\",\"cpuCount\":8,\"memoryMB\":8192,\"diskSizeBytes\":1}]"
+ let fake = FakeCLIRunner()
+ let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+ fake.stub(arguments: ["vm", "list", "--json", "--library-root", "/lib"],
+ result: CLIResult(stdout: listJSON, stderr: "", exitCode: 0))
+ fake.stub(arguments: ["-t", "--", "/lib/a/Disk.img"], result: CLIResult(stdout: "999\n", stderr: "", exitCode: 0))
+ fake.stub(arguments: ["-t", "--", "/lib/b/Disk.img"], result: CLIResult(stdout: "", stderr: "", exitCode: 1))
+
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: "/lib", runner: fake)
+ let store = VMStore(client: client, probe: RunningStateProbe(runner: fake), libraryRoot: "/lib")
+ await store.refresh()
+
+ #expect(store.rows.map(\.report.name) == ["a", "b"])
+ #expect(store.rows.first(where: { $0.report.name == "a" })?.isRunning == true)
+ #expect(store.rows.first(where: { $0.report.name == "b" })?.isRunning == false)
+ #expect(store.loadError == nil)
+}
diff --git a/tests/VPhoneWSCoreTests/VPhoneCLIClientManageTests.swift b/tests/VPhoneWSCoreTests/VPhoneCLIClientManageTests.swift
new file mode 100644
index 0000000..58d99da
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VPhoneCLIClientManageTests.swift
@@ -0,0 +1,33 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+private let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+
+private func client(_ runner: FakeCLIRunner) -> VPhoneCLIClient {
+ VPhoneCLIClient(executable: exe, libraryRoot: nil, runner: runner)
+}
+
+@Test func setConfigOnlyIncludesGivenFields() async throws {
+ let r = FakeCLIRunner()
+ r.stub(arguments: ["vm", "config", "a", "--cpu", "6", "--network", "bridged"],
+ result: CLIResult(stdout: "updated", stderr: "", exitCode: 0))
+ try await client(r).setConfig(name: "a", cpu: 6, memoryMB: nil, network: "bridged")
+ #expect(r.calls[0].arguments == ["vm", "config", "a", "--cpu", "6", "--network", "bridged"])
+}
+
+@Test func deletePassesForce() async throws {
+ let r = FakeCLIRunner()
+ r.stub(arguments: ["vm", "delete", "a", "--force"], result: CLIResult(stdout: "deleted a", stderr: "", exitCode: 0))
+ try await client(r).delete(name: "a")
+ #expect(r.calls[0].arguments == ["vm", "delete", "a", "--force"])
+}
+
+@Test func cloneAndRenamePassBothNames() async throws {
+ let r = FakeCLIRunner()
+ r.stub(arguments: ["vm", "clone", "a", "b"], result: CLIResult(stdout: "cloned", stderr: "", exitCode: 0))
+ r.stub(arguments: ["vm", "rename", "b", "c"], result: CLIResult(stdout: "renamed", stderr: "", exitCode: 0))
+ try await client(r).clone(name: "a", to: "b")
+ try await client(r).rename(name: "b", to: "c")
+ #expect(r.calls.map(\.arguments) == [["vm","clone","a","b"], ["vm","rename","b","c"]])
+}
diff --git a/tests/VPhoneWSCoreTests/VPhoneCLIClientTests.swift b/tests/VPhoneWSCoreTests/VPhoneCLIClientTests.swift
new file mode 100644
index 0000000..b6f8060
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VPhoneCLIClientTests.swift
@@ -0,0 +1,52 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+private let exe = URL(fileURLWithPath: "/usr/bin/vphone-cli")
+
+@Test func listAssemblesArgvAndDecodes() async throws {
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["vm", "list", "--json", "--library-root", "/lib"],
+ result: CLIResult(stdout: "[{\"name\":\"a\",\"cpuCount\":8,\"memoryMB\":8192,\"diskSizeBytes\":1}]",
+ stderr: "", exitCode: 0))
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: "/lib", runner: fake)
+ let vms = try await client.listVMs()
+ #expect(vms.map(\.name) == ["a"])
+ #expect(fake.calls[0].arguments == ["vm", "list", "--json", "--library-root", "/lib"])
+}
+
+@Test func infoAssemblesArgvWithExplicitName() async throws {
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["vm", "info", "a", "--json"],
+ result: CLIResult(stdout: "{\"name\":\"a\",\"cpuCount\":8,\"memoryMB\":8192,\"diskSizeBytes\":1}",
+ stderr: "", exitCode: 0))
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: nil, runner: fake)
+ let vm = try await client.info(name: "a")
+ #expect(vm.name == "a")
+}
+
+@Test func nonZeroExitThrows() async throws {
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["vm", "list", "--json"],
+ result: CLIResult(stdout: "", stderr: "boom", exitCode: 1))
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: nil, runner: fake)
+ await #expect(throws: VPhoneCLIError.nonZeroExit(code: 1, stderr: "boom")) {
+ _ = try await client.listVMs()
+ }
+}
+
+@Test func signalTerminationThrowsKilledOnLaunch() async throws {
+ let fake = FakeCLIRunner()
+ fake.stub(arguments: ["vm", "list", "--json"],
+ result: CLIResult(stdout: "", stderr: "", exitCode: 9, terminatedBySignal: true))
+ let client = VPhoneCLIClient(executable: exe, libraryRoot: nil, runner: fake)
+ await #expect(throws: VPhoneCLIError.killedOnLaunch(signal: 9)) {
+ _ = try await client.listVMs()
+ }
+}
+
+@Test func killedOnLaunchMessageNamesAmfidont() {
+ let msg = VPhoneCLIError.killedOnLaunch(signal: SIGKILL).userMessage
+ #expect(msg.contains("amfidont"))
+ #expect(msg.contains("vphone-amfidont"))
+}
diff --git a/tests/VPhoneWSCoreTests/VPhoneCLILocatorTests.swift b/tests/VPhoneWSCoreTests/VPhoneCLILocatorTests.swift
new file mode 100644
index 0000000..af873d6
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VPhoneCLILocatorTests.swift
@@ -0,0 +1,71 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+@Test func prefersExplicitThenPathThenNotFound() {
+ let loc = VPhoneCLILocator()
+ let explicit = URL(fileURLWithPath: "/opt/custom/vphone-cli")
+
+ #expect(loc.locate(explicit: explicit.path, envPath: nil, pathLookup: { _ in nil }, fileExists: { _ in false }) == .found(explicit))
+ let onPath = URL(fileURLWithPath: "/opt/homebrew/bin/vphone-cli")
+ #expect(loc.locate(explicit: nil, envPath: nil, pathLookup: { $0 == "vphone-cli" ? onPath : nil }, fileExists: { _ in false }) == .found(onPath))
+ #expect(loc.locate(explicit: nil, envPath: nil, pathLookup: { _ in nil }, fileExists: { _ in false }) == .notFound)
+}
+
+@Test func envOverrideWinsOverPathLookup() {
+ let loc = VPhoneCLILocator()
+ let envPath = "/custom/env/vphone-cli"
+ let onPath = URL(fileURLWithPath: "/opt/homebrew/bin/vphone-cli")
+
+ #expect(loc.locate(
+ explicit: nil,
+ envPath: envPath,
+ pathLookup: { $0 == "vphone-cli" ? onPath : nil },
+ fileExists: { $0 == envPath }
+ ) == .found(URL(fileURLWithPath: envPath)))
+}
+
+@Test func envOverrideIgnoredWhenFileMissing() {
+ let loc = VPhoneCLILocator()
+ let onPath = URL(fileURLWithPath: "/opt/homebrew/bin/vphone-cli")
+
+ #expect(loc.locate(
+ explicit: nil,
+ envPath: "/custom/env/vphone-cli",
+ pathLookup: { $0 == "vphone-cli" ? onPath : nil },
+ fileExists: { _ in false }
+ ) == .found(onPath))
+}
+
+@Test func wellKnownFallbackUsedWhenExplicitEnvAndPathLookupAllMiss() {
+ let loc = VPhoneCLILocator()
+
+ #expect(loc.locate(
+ explicit: nil,
+ envPath: nil,
+ pathLookup: { _ in nil },
+ fileExists: { $0 == "/usr/local/bin/vphone-cli" }
+ ) == .found(URL(fileURLWithPath: "/usr/local/bin/vphone-cli")))
+}
+
+@Test func wellKnownFallbackPrefersHomebrewAppleSiliconFirst() {
+ let loc = VPhoneCLILocator()
+
+ #expect(loc.locate(
+ explicit: nil,
+ envPath: nil,
+ pathLookup: { _ in nil },
+ fileExists: { _ in true }
+ ) == .found(URL(fileURLWithPath: "/opt/homebrew/bin/vphone-cli")))
+}
+
+@Test func notFoundOnlyWhenEverythingMisses() {
+ let loc = VPhoneCLILocator()
+
+ #expect(loc.locate(
+ explicit: nil,
+ envPath: nil,
+ pathLookup: { _ in nil },
+ fileExists: { _ in false }
+ ) == .notFound)
+}
diff --git a/tests/VPhoneWSCoreTests/VPhoneCommandBuilderTests.swift b/tests/VPhoneWSCoreTests/VPhoneCommandBuilderTests.swift
new file mode 100644
index 0000000..bfa18ee
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VPhoneCommandBuilderTests.swift
@@ -0,0 +1,14 @@
+import Testing
+@testable import VPhoneWSCore
+
+@Test func createIncludesRootPopupVerboseSourcesDiskAndLibraryRoot() {
+ let b = VPhoneCommandBuilder(libraryRoot: "/lib")
+ #expect(b.createArgs(name: "a", variant: "jb", iphoneSource: "26.3", cloudosSource: "26.4", diskSizeGB: 128) ==
+ ["vm","create","a","-V","jb","--iphone-source","26.3","--cloudos-source","26.4","--disk-size","128","--root-popup","-v","--library-root","/lib"])
+}
+
+@Test func exportAndImportArgs() {
+ let b = VPhoneCommandBuilder(libraryRoot: nil)
+ #expect(b.exportArgs(name: "a", out: "/tmp/a.tar.xz") == ["vm","export","a","-o","/tmp/a.tar.xz"])
+ #expect(b.importArgs(archive: "/tmp/a.tar.xz", name: "restored") == ["vm","import","-i","/tmp/a.tar.xz","-n","restored"])
+}
diff --git a/tests/VPhoneWSCoreTests/VariantStoreTests.swift b/tests/VPhoneWSCoreTests/VariantStoreTests.swift
new file mode 100644
index 0000000..4e2f006
--- /dev/null
+++ b/tests/VPhoneWSCoreTests/VariantStoreTests.swift
@@ -0,0 +1,14 @@
+import Testing
+import Foundation
+@testable import VPhoneWSCore
+
+@Test func writesAndReadsVariant() throws {
+ let root = NSTemporaryDirectory() + "vws-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(atPath: root + "/myvm", withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(atPath: root) }
+
+ let store = VariantStore(libraryRoot: root)
+ #expect(store.variant(forVM: "myvm") == nil)
+ try store.setVariant("jb", forVM: "myvm")
+ #expect(store.variant(forVM: "myvm") == "jb")
+}