Run a virtual iPhone on an Apple Silicon Mac.
Swift
Show Irisin bootstrap progress in Guest menu
Lakrbd0720ab606c
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex ce23bd28..db01e00e 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -48,6 +48,13 @@ script runs and the dpkg database is not changed. The reply includes the tag,bootstrap path, registration record, and launchd status. A successful bootstrapwrites `.vphoned-boostrap-completed` beside the running vphoned binary; laterrequests refuse to bootstrap again when that marker exists.+The VM window exposes the same operation at Guest > Install Bootstrap…;+choose Rootless or RootHide in the confirmation sheet. The item is enabled+when vphoned advertises `bootstrap_install`. Its sheet polls+`GET /v1/bootstrap/status` (RPC `bootstrap.status`) while installation runs.+The status reports `phase` and, during download, `downloaded_bytes` and+`total_bytes` when the server provides a length. The sheet shows the download+progress, then the installation result without closing.## HTTP and WebSocket contractdiff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 6d52621f..98f900df 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -203,6 +203,8 @@ enum GuestAPI {jailbreak: jailbreakInfo(),layout: layout,)+ case "bootstrap.status":+ return GuestIrisinInstaller.status()case "input.touch":guard let phase = (params["phase"] as? String).flatMap(TouchPhase.init(rawValue:)) else {throw GuestAPIError.invalidRequest("phase must be down, move or up")diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 8f69faaf..aedcd8bf 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -175,6 +175,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlecase (.POST, "/v1/apps/open-url"): "apps.open_url"case (.POST, "/v1/apps/install"): "apps.install"case (.POST, "/v1/bootstrap/install"): "bootstrap.install"+ case (.GET, "/v1/bootstrap/status"): "bootstrap.status"case (.POST, "/v1/input/touch"): "input.touch"case (.POST, "/v1/input/hid"): "input.hid"case (.GET, "/v1/location"): "location.current"diff --git a/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift b/VPhoneDaemon/Daemon/GuestIrisinInstaller.swiftindex 3083802f..d16c652e 100644--- a/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift+++ b/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift@@ -9,6 +9,8 @@ enum GuestIrisinInstaller {private static let releaseURL = URL(string: "https://api.github.com/repos/Lakr233/Irisin/releases/latest")!private static let serviceLabel = "wiki.qaq.irisind"private static let installLock = NSLock()+ private static let progressLock = NSLock()+ nonisolated(unsafe) private static var progress: [String: Any] = ["phase": "idle"]private static let completionMarker = Bundle.main.executableURL!.deletingLastPathComponent().appendingPathComponent(".vphoned-boostrap-completed")@@ -19,7 +21,38 @@ enum GuestIrisinInstaller {guard !itemExists(completionMarker) else {throw GuestAPIError.operationFailed("Irisin bootstrap already completed: \(completionMarker.path)")}+ setProgress(["phase": "preparing", "layout": layout])+ do {+ let result = try performInstall(jailbreak: jailbreak, layout: layout)+ setProgress(["phase": "completed", "layout": layout,+ "version": result["version"] ?? "", "jbroot": result["jbroot"] ?? ""])+ return result+ } catch {+ setProgress(["phase": "failed", "layout": layout, "error": String(describing: error)])+ throw error+ }+ }++ static func status() -> [String: Any] {+ progressLock.lock()+ defer { progressLock.unlock() }+ return progress+ }+ private static func setProgress(_ value: [String: Any]) {+ progressLock.lock()+ progress = value+ progressLock.unlock()+ }++ private static func downloadProgress(received: Int64, total: Int64) {+ progressLock.lock()+ progress["downloaded_bytes"] = received+ if total > 0 { progress["total_bytes"] = total }+ progressLock.unlock()+ }++ private static func performInstall(jailbreak: [String: Any], layout: String) throws -> [String: Any] {let detectedLayout = jailbreak["layout"] as? Stringguard layout == "rootless" || layout == "roothide" else {throw GuestAPIError.invalidRequest("layout must be rootless or roothide")@@ -38,18 +71,21 @@ enum GuestIrisinInstaller {let architecture = layout == "roothide" ? "iphoneos-arm64e" : "iphoneos-arm64"let release = try releaseAsset(architecture: architecture)+ setProgress(["phase": "downloading", "layout": layout, "tag": release.tag,+ "downloaded_bytes": 0])let work = FileManager.default.temporaryDirectory.appendingPathComponent("vphoned-irisin-\(UUID().uuidString)", isDirectory: true)try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: work) }let package = work.appendingPathComponent(release.name)- let packageData = try fetch(release.url)+ let packageData = try fetch(release.url, reportDownload: true)let digest = SHA256.hash(data: packageData).map { String(format: "%02x", $0) }.joined()guard digest == release.digest else {throw GuestAPIError.operationFailed("Irisin release asset SHA-256 mismatch")}try packageData.write(to: package, options: .atomic)+ setProgress(["phase": "extracting", "layout": layout, "tag": release.tag])let metadata = try readDeb(package.path)let control = metadata["control"] as? [String: String] ?? [:]@@ -87,6 +123,7 @@ enum GuestIrisinInstaller {var replaced: [(target: URL, backup: URL?)] = []do {+ setProgress(["phase": "installing", "layout": layout, "tag": release.tag])for (source, target) in components {replaced.append(try replace(source, at: target))}@@ -335,7 +372,7 @@ enum GuestIrisinInstaller {}}- private static func fetch(_ url: URL) throws -> Data {+ private static func fetch(_ url: URL, reportDownload: Bool = false) throws -> Data {let configuration = URLSessionConfiguration.ephemeralconfiguration.timeoutIntervalForRequest = 30configuration.timeoutIntervalForResource = 180@@ -349,9 +386,20 @@ enum GuestIrisinInstaller {result.finish(data: data, response: response, error: error)}task.resume()- guard result.semaphore.wait(timeout: .now() + 190) == .success else {- task.cancel()- throw GuestAPIError.operationFailed("Irisin download timed out")+ let deadline = Date().addingTimeInterval(190)+ while result.semaphore.wait(timeout: .now() + 0.2) != .success {+ if reportDownload {+ downloadProgress(received: task.countOfBytesReceived,+ total: task.countOfBytesExpectedToReceive)+ }+ if Date() >= deadline {+ task.cancel()+ throw GuestAPIError.operationFailed("Irisin download timed out")+ }+ }+ if reportDownload {+ downloadProgress(received: task.countOfBytesReceived,+ total: task.countOfBytesExpectedToReceive)}let (data, response) = try result.value!.get()guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstringsindex ecf446e1..5c7e44a1 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings@@ -1,6 +1,66 @@{"sourceLanguage": "en","strings": {+ "Install Bootstrap…": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Install Bootstrap…" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "安装引导环境…" } }+ } },+ "Install Bootstrap": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Install Bootstrap" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "安装引导环境" } }+ } },+ "Choose the bootstrap layout. This installs the latest Irisin release once in the guest.": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Choose the bootstrap layout. This installs the latest Irisin release once in the guest." } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "选择引导环境布局。将在客体中安装一次最新版 Irisin。" } }+ } },+ "Rootless": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Rootless" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "Rootless" } }+ } },+ "RootHide": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "RootHide" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "RootHide" } }+ } },+ "Installing the latest Irisin release in the guest.": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Installing the latest Irisin release in the guest." } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "正在客体中安装最新版 Irisin。" } }+ } },+ "Preparing bootstrap…": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Preparing bootstrap…" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "正在准备引导环境…" } }+ } },+ "Downloading Irisin…": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Downloading Irisin…" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "正在下载 Irisin…" } }+ } },+ "Downloading Irisin: %@ of %@": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Downloading Irisin: %@ of %@" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "正在下载 Irisin:%@ / %@" } }+ } },+ "Extracting Irisin…": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Extracting Irisin…" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "正在解压 Irisin…" } }+ } },+ "Registering Irisin…": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Registering Irisin…" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "正在注册 Irisin…" } }+ } },+ "Bootstrap installed": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Bootstrap installed" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "引导环境已安装" } }+ } },+ "Bootstrap installation failed": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Bootstrap installation failed" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "引导环境安装失败" } }+ } },+ "Installed Irisin %@ in %@.": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Installed Irisin %@ in %@." } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "已安装 Irisin %@,位置:%@。" } }+ } },+ "Daemon start: %@": { "localizations": {+ "en": { "stringUnit": { "state": "translated", "value": "Daemon start: %@" } },+ "zh-Hans": { "stringUnit": { "state": "translated", "value": "守护进程启动:%@" } }+ } },", low power": {"localizations": {"en": {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 5786dbe8..52594781 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -296,6 +296,17 @@ final class VPhoneGuestControl {return result["msg"] as? String ?? "Installed \(localURL.lastPathComponent)."}+ func installBootstrap(layout: String) async throws -> [String: Any] {+ guard guestCapabilities.contains("bootstrap_install") else {+ throw ControlError.unsupportedCapability("bootstrap_install")+ }+ return try await call("bootstrap.install", params: ["layout": layout])+ }++ func bootstrapStatus() async throws -> [String: Any] {+ return try await call("bootstrap.status")+ }+func clipboardGet() async throws -> ClipboardContent {let (info, image) = try await sendRequest(["t": "clipboard_get"])return ClipboardContent(diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swiftindex b69c24db..4c9b1a48 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuConnect.swift@@ -25,6 +25,13 @@ extension VPhoneMenuController {menu.addItem(NSMenuItem.separator())+ let installBootstrap = makeItem("Install Bootstrap…", action: #selector(installBootstrap))+ installBootstrap.isEnabled = false+ installBootstrapItem = installBootstrap+ menu.addItem(installBootstrap)++ menu.addItem(NSMenuItem.separator())+let clipboardMenu = NSMenu(title: "Clipboard")clipboardMenu.autoenablesItems = falselet clipGet = makeItem(@@ -101,6 +108,113 @@ extension VPhoneMenuController {settingsSetItem?.isEnabled = available}+ func updateBootstrapAvailability(available: Bool) {+ installBootstrapItem?.isEnabled = available && !isInstallingBootstrap+ }++ @objc func installBootstrap() {+ VPhoneAlert.present(+ title: "Install Bootstrap",+ message: "Choose the bootstrap layout. This installs the latest Irisin release once in the guest.",+ style: .informational,+ buttons: ["Rootless", "RootHide", "Cancel"],+ ) { [weak self] response in+ let layout: String+ switch response {+ case .alertFirstButtonReturn: layout = "rootless"+ case .alertSecondButtonReturn: layout = "roothide"+ default: return+ }+ self?.performBootstrapInstallation(layout: layout)+ }+ }++ private func performBootstrapInstallation(layout: String) {+ isInstallingBootstrap = true+ installBootstrapItem?.isEnabled = false+ let alert = NSAlert()+ alert.messageText = VPhoneLocalization.text("Install Bootstrap")+ alert.informativeText = VPhoneLocalization.text("Installing the latest Irisin release in the guest.")+ let close = alert.addButton(withTitle: VPhoneLocalization.text("Close"))+ close.isEnabled = false+ let accessory = NSView(frame: NSRect(x: 0, y: 0, width: 360, height: 52))+ let statusLabel = NSTextField(labelWithString: VPhoneLocalization.text("Preparing bootstrap…"))+ statusLabel.frame = NSRect(x: 0, y: 26, width: 360, height: 22)+ statusLabel.lineBreakMode = .byTruncatingMiddle+ accessory.addSubview(statusLabel)+ let indicator = NSProgressIndicator(frame: NSRect(x: 0, y: 4, width: 360, height: 16))+ indicator.style = .bar+ indicator.isIndeterminate = true+ indicator.startAnimation(nil)+ accessory.addSubview(indicator)+ alert.accessoryView = accessory+ VPhoneAlert.present(alert)++ Task {+ defer {+ isInstallingBootstrap = false+ updateBootstrapAvailability(+ available: control.isConnected && control.guestCapabilities.contains("bootstrap_install"),+ )+ indicator.stopAnimation(nil)+ close.isEnabled = true+ }+ let poller = Task {+ while !Task.isCancelled {+ if let status = try? await control.bootstrapStatus() {+ updateBootstrapProgress(status, label: statusLabel, indicator: indicator)+ }+ try? await Task.sleep(for: .milliseconds(250))+ }+ }+ do {+ let result = try await control.installBootstrap(layout: layout)+ poller.cancel()+ let version = result["version"] as? String ?? ""+ let root = result["jbroot"] as? String ?? ""+ indicator.isIndeterminate = false+ indicator.doubleValue = 100+ statusLabel.stringValue = VPhoneLocalization.text("Bootstrap installed")+ var message = VPhoneLocalization.format("Installed Irisin %@ in %@.", version, root)+ if let warning = result["service_start_warning"] as? String {+ message += "\n\n" + VPhoneLocalization.format("Daemon start: %@", warning)+ }+ alert.informativeText = message+ } catch {+ poller.cancel()+ statusLabel.stringValue = VPhoneLocalization.text("Bootstrap installation failed")+ alert.alertStyle = .warning+ alert.informativeText = String(describing: error)+ }+ }+ }++ private func updateBootstrapProgress(+ _ status: [String: Any], label: NSTextField, indicator: NSProgressIndicator+ ) {+ switch status["phase"] as? String {+ case "downloading":+ let received = status["downloaded_bytes"] as? Int64 ?? 0+ let total = status["total_bytes"] as? Int64 ?? 0+ if total > 0 {+ indicator.isIndeterminate = false+ indicator.minValue = 0+ indicator.maxValue = Double(total)+ indicator.doubleValue = Double(received)+ let current = ByteCountFormatter.string(fromByteCount: received, countStyle: .file)+ let expected = ByteCountFormatter.string(fromByteCount: total, countStyle: .file)+ label.stringValue = VPhoneLocalization.format("Downloading Irisin: %@ of %@", current, expected)+ } else {+ label.stringValue = VPhoneLocalization.text("Downloading Irisin…")+ }+ case "extracting":+ label.stringValue = VPhoneLocalization.text("Extracting Irisin…")+ case "installing":+ label.stringValue = VPhoneLocalization.text("Registering Irisin…")+ default: break+ }+ }+func updateConnectAvailability(available: Bool) {connectFileBrowserItem?.isEnabled = availableconnectKeychainBrowserItem?.isEnabled = availablediff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swiftindex 03be0c7c..a3b9d6e6 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift@@ -19,6 +19,8 @@ class VPhoneMenuController {var connectDevModeStatusItem: NSMenuItem?var connectPingItem: NSMenuItem?var connectGuestHashItem: NSMenuItem?+ var installBootstrapItem: NSMenuItem?+ var isInstallingBootstrap = falsevar installPackageItem: NSMenuItem?var clipboardGetItem: NSMenuItem?var clipboardSetItem: NSMenuItem?diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 16f82bbc..be561734 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -194,6 +194,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {control.onConnect = { [weak self, weak mc, weak provider = locationProvider] caps inmc?.updateConnectAvailability(available: true)mc?.updateInstallAvailability(available: caps.contains("ipa_install"))+ mc?.updateBootstrapAvailability(available: caps.contains("bootstrap_install"))mc?.updateAppsAvailability(available: caps.contains("apps"))mc?.updateURLAvailability(available: caps.contains("url"))mc?.updateClipboardAvailability(available: caps.contains("clipboard"))@@ -216,6 +217,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {control.onDisconnect = { [weak mc, weak provider = locationProvider] inmc?.updateConnectAvailability(available: false)mc?.updateInstallAvailability(available: false)+ mc?.updateBootstrapAvailability(available: false)mc?.updateAppsAvailability(available: false)mc?.updateURLAvailability(available: false)mc?.updateClipboardAvailability(available: false)