Run a virtual iPhone on an Apple Silicon Mac.
Swift
Show the progress and output of guest environment updates
Jacky2430924e6088
diff --git a/VPhoneLaunchpad/Tests/MaintenanceProgressTests.sh b/VPhoneLaunchpad/Tests/MaintenanceProgressTests.shnew file mode 100755index 00000000..c2795c26--- /dev/null+++ b/VPhoneLaunchpad/Tests/MaintenanceProgressTests.sh@@ -0,0 +1,13 @@+#!/bin/zsh+set -euo pipefail++launchpad="${0:a:h:h}"+temporary="$(/usr/bin/mktemp -d)"+trap '/bin/rm -rf "$temporary"' EXIT++/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \+ -parse-as-library \+ "$launchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceProgress.swift" \+ "$launchpad/Tests/MaintenanceProgressTests.swift" \+ -o "$temporary/maintenance-progress-tests"+"$temporary/maintenance-progress-tests" "$@"diff --git a/VPhoneLaunchpad/Tests/MaintenanceProgressTests.swift b/VPhoneLaunchpad/Tests/MaintenanceProgressTests.swiftnew file mode 100644index 00000000..ab1e1edb--- /dev/null+++ b/VPhoneLaunchpad/Tests/MaintenanceProgressTests.swift@@ -0,0 +1,81 @@+import Foundation++/// How the maintenance sheet reads `cfw update-environment` output: the step+/// under way from unindented markers, and every warning at any depth, over+/// the lines a real run prints.+@main+struct MaintenanceProgressTests {+ static func expect(_ condition: Bool, _ message: @autoclosure () -> String, line: Int = #line) {+ precondition(condition, "line \(line): \(message())")+ }++ static func main() {+ stages()+ warnings()+ notable()+ print("Maintenance progress tests passed: stages, warnings, notable lines")+ }++ /// Lines as an environment update prints them, in order.+ static let sample = [+ "$ vphone-cli cfw update-environment fz-b",+ "[*] Patch preset: standard (126 patches on)",+ "/dev/disk8 \tGUID_partition_scheme",+ "[*] Guest Environment Update: fz-b",+ " [·] usr/lib/libmisfix.plist: already present, left as it is",+ " [+] 0x1BDD2: 2573 -> 4141 (\"%s/%s.gl\" -> \"%s/AA.gl\")",+ " [+] seputil gigalocker name pinned to \"AA.gl\"",+ " [!] system-launchd-cfw-jetsam: patch step failed, left in its prior state: not found",+ "warning: could not mark the install as in progress: EPERM",+ " Before: pacibsp; stp x22, x21, [sp, #-0x30]!",+ "[*] Board device tree: FirmwareOriginals/iPhone17,3/DeviceTree.d47ap.im4p",+ " [+] product/product-name: 'syscfg/prde' -> 'iPhone 16'",+ "[!] 1 guest patch(es) failed and were left in their prior state: system-launchd-cfw-jetsam",+ "[+] Guest environment updated; start the VM to pick it up",+ ]++ static func read(_ lines: [String]) -> VPhoneLaunchpadMaintenanceProgress {+ var progress = VPhoneLaunchpadMaintenanceProgress()+ for line in lines {+ progress.read(line)+ }+ return progress+ }++ static func stages() {+ expect(read([]).stage == nil, "no output has no stage")+ expect(read(Array(sample.prefix(3))).stage == "Patch preset: standard (126 patches on)", "the first step")+ // Indented markers are detail within a step, not a step.+ expect(read(Array(sample.prefix(8))).stage == "Guest Environment Update: fz-b", "indented lines leave the step")+ expect(read(Array(sample.prefix(12))).stage?.hasPrefix("Board device tree:") == true, "a later step replaces it")+ expect(read(sample).stage == "Guest environment updated; start the VM to pick it up", "the closing line")+ expect(read(["[*] Step", "[*] "]).stage == "Step", "an empty marker keeps the step")+ }++ static func warnings() {+ let progress = read(sample)+ expect(progress.warningCount == 3, "three warnings, got \(progress.warningCount)")+ expect(progress.warnings == [+ "system-launchd-cfw-jetsam: patch step failed, left in its prior state: not found",+ "warning: could not mark the install as in progress: EPERM",+ "1 guest patch(es) failed and were left in their prior state: system-launchd-cfw-jetsam",+ ], "warnings in order, markers removed: \(progress.warnings)")+ expect(read(["Error: Unknown option '--work-parent'"]).warningCount == 1, "an argument error warns")+ expect(read(["[!]", " [!] "]).warningCount == 0, "a bare marker does not warn")+ expect(read(["the warning: is not at the start"]).warningCount == 0, "only a leading warning: counts")++ let many = read((0 ..< 80).map { "[!] step \($0)" })+ expect(many.warningCount == 80, "every warning is counted")+ expect(many.warnings.count == VPhoneLaunchpadMaintenanceProgress.maximumWarnings, "only the first are kept")+ expect(many.warnings.first == "step 0", "the first is kept first")+ }++ /// Only lines that change the progress cross to the main actor; reading+ /// just those must give what reading every line gives.+ static func notable() {+ let notable = sample.filter(VPhoneLaunchpadMaintenanceProgress.isNotable)+ expect(read(notable) == read(sample), "the notable lines carry the whole progress")+ expect(notable.count == 7, "seven notable lines, got \(notable.count)")+ expect(!VPhoneLaunchpadMaintenanceProgress.isNotable(" [+] seputil gigalocker name pinned"), "detail is not notable")+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swiftindex 2889bcf2..2028e7d4 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift@@ -886,6 +886,23 @@ struct VPhoneLaunchpadControlCommands {}}+ /// A maintenance command for a client: it shows in the app as a run of+ /// Launchpad's own would, without opening its sheet, and its output+ /// streams to the client too.+ private func maintenance(+ _ kind: VPhoneLaunchpadMaintenanceRun.Kind,+ on machine: VPhoneLaunchpadMachinePath,+ emit: @escaping Emit,+ _ command: (@escaping @Sendable (String) -> Void) async throws -> Int32,+ ) async throws -> Int32 {+ try await library.runMaintenance(+ VPhoneLaunchpadMaintenanceRun(kind: kind, machine: machine),+ presents: false,+ forward: emit,+ command,+ )+ }+private func installCustomFirmware(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {let machine = try await machine(request)let version = try bundleVersion(of: machine)@@ -893,13 +910,16 @@ struct VPhoneLaunchpadControlCommands {throw VPhoneLaunchpadError("Stop \(machine.name) before installing CFW.")}try await requireDiskUnheld(machine)- let status = try await model.helper.installCustomFirmware(- bundleVersion: version,- machineName: machine.name,- libraryRoot: machine.libraryRoot,- keepArtifacts: request.flag("keep-artifacts"),- onLine: emit,- )+ let keepArtifacts = request.flag("keep-artifacts")+ let status = try await maintenance(.installCustomFirmware, on: machine, emit: emit) { [helper = model.helper] onLine in+ try await helper.installCustomFirmware(+ bundleVersion: version,+ machineName: machine.name,+ libraryRoot: machine.libraryRoot,+ keepArtifacts: keepArtifacts,+ onLine: onLine,+ )+ }guard status == 0 else {throw VPhoneLaunchpadError("Unable to install custom firmware. Check the log for details.")}@@ -914,12 +934,14 @@ struct VPhoneLaunchpadControlCommands {throw VPhoneLaunchpadError("Stop \(machine.name) before updating its guest environment.")}try await requireDiskUnheld(machine)- let status = try await model.helper.updateGuestEnvironment(- bundleVersion: version,- machineName: machine.name,- libraryRoot: machine.libraryRoot,- onLine: emit,- )+ let status = try await maintenance(.updateGuestEnvironment, on: machine, emit: emit) { [helper = model.helper] onLine in+ try await helper.updateGuestEnvironment(+ bundleVersion: version,+ machineName: machine.name,+ libraryRoot: machine.libraryRoot,+ onLine: onLine,+ )+ }guard status == 0 else {throw VPhoneLaunchpadError("Unable to update the guest environment. Check the log for details.")}@@ -934,12 +956,14 @@ struct VPhoneLaunchpadControlCommands {throw VPhoneLaunchpadError("Stop \(machine.name) before updating its kernel.")}try await requireDiskUnheld(machine)- let status = try await model.helper.updateKernel(- bundleVersion: version,- machineName: machine.name,- libraryRoot: machine.libraryRoot,- onLine: emit,- )+ let status = try await maintenance(.updateKernel, on: machine, emit: emit) { [helper = model.helper] onLine in+ try await helper.updateKernel(+ bundleVersion: version,+ machineName: machine.name,+ libraryRoot: machine.libraryRoot,+ onLine: onLine,+ )+ }guard status == 0 else {throw VPhoneLaunchpadError("Unable to update the kernel. Check the log for details.")}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex d2fd0542..0c655637 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -6337,40 +6337,6 @@}}},- "Choose Show Console Log for the full output." : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Choose Show Console Log for the full output."- }- },- "ja" : {- "stringUnit" : {- "state" : "translated",- "value" : "完全な出力は「コンソールログを表示」で確認できます。"- }- },- "ko" : {- "stringUnit" : {- "state" : "translated",- "value" : "전체 출력은 '콘솔 로그 보기'에서 확인하십시오."- }- },- "vi" : {- "stringUnit" : {- "state" : "translated",- "value" : "Chọn Hiển thị nhật ký bảng điều khiển để xem toàn bộ đầu ra."- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "选择“显示控制台日志”查看完整输出。"- }- }- }- },"Choose…" : {"localizations" : {"en" : {@@ -9124,6 +9090,96 @@"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法更新 %@ 的客户机环境" } }}},+ "Update Guest Environment of %@" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Update Guest Environment of %@" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ のゲスト環境を更新" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@의 게스트 환경 업데이트" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cập nhật môi trường máy khách của %@" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "更新 %@ 的客户机环境" } }+ }+ },+ "Install Custom Firmware on %@" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Install Custom Firmware on %@" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ にカスタムファームウェアをインストール" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@에 커스텀 펌웨어 설치" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cài firmware tùy chỉnh cho %@" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "为 %@ 安装自定义固件" } }+ }+ },+ "Update Kernel of %@" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Update Kernel of %@" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@ のカーネルを更新" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@의 커널 업데이트" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cập nhật kernel của %@" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "更新 %@ 的内核" } }+ }+ },+ "Guest environment updated." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Guest environment updated." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ゲスト環境を更新しました。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "게스트 환경을 업데이트했습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã cập nhật môi trường máy khách." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "客户机环境已更新。" } }+ }+ },+ "Custom firmware installed." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Custom firmware installed." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カスタムファームウェアをインストールしました。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커스텀 펌웨어를 설치했습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã cài firmware tùy chỉnh." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "自定义固件已安装。" } }+ }+ },+ "Kernel updated." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Kernel updated." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "カーネルを更新しました。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "커널을 업데이트했습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đã cập nhật kernel." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "内核已更新。" } }+ }+ },+ "It continues if you close this window." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "It continues if you close this window." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "このウインドウを閉じても処理は続行されます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 윈도우를 닫아도 작업은 계속됩니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tác vụ vẫn tiếp tục nếu bạn đóng cửa sổ này." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "关闭此窗口后,操作仍会继续。" } }+ }+ },+ "Open Log File" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Open Log File" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ログファイルを開く" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "로그 파일 열기" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Mở tệp nhật ký" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "打开日志文件" } }+ }+ },+ "^[%lld warning](inflect: true)" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "^[%lld warning](inflect: true)" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%lld 件の警告" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "경고 %lld개" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%lld cảnh báo" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%lld 个警告" } }+ }+ },+ "Show…" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Show…" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "表示…" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "보기…" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Hiển thị…" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "显示…" } }+ }+ },"Install Custom Firmware" : {"localizations" : {"en" : {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swiftindex bbdeb152..52019dd4 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift@@ -126,6 +126,9 @@ struct VPhoneLaunchpadMachineInspector: View {)}}+ if let run = library.maintenance[machine.path] {+ maintenanceRow(run)+ }if let started = library.startedAt[machine.path] {LabeledContent("Started", value: started.formatted(date: .omitted, time: .shortened))}@@ -279,6 +282,41 @@ struct VPhoneLaunchpadMachineInspector: View {}}+ // MARK: - Maintenance++ /// The machine's latest CFW install or update this session: the step it+ /// is on, or how it ended, and a way back to its progress and output.+ private func maintenanceRow(_ run: VPhoneLaunchpadMaintenanceRun) -> some View {+ LabeledContent {+ HStack(spacing: 6) {+ VPhoneLaunchpadMaintenanceElapsed(run: run)+ Button("Show…") { model.machineSheetRequest = .maintenance(machine.path) }+ .controlSize(.small)+ }+ } label: {+ Label {+ VStack(alignment: .leading, spacing: 2) {+ Text(verbatim: run.kind.title)+ .lineLimit(1)+ if let line = run.isRunning ? run.progress.stage : run.failure?.message {+ Text(verbatim: line)+ .font(.caption)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .truncationMode(.middle)+ .help(line)+ } else if run.progress.warningCount > 0 {+ Text("^[\(run.progress.warningCount) warning](inflect: true)")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ } icon: {+ VPhoneLaunchpadStatusIcon(status: run.status)+ }+ }+ }+// MARK: - Patches/// What a patch read depends on: the machine, the bundle that reads it,diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swiftindex b237c3c9..65ac49a9 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift@@ -46,6 +46,15 @@ final class VPhoneLaunchpadMachineLibrary {/// machine's disk image, the machine's own VM included.private var diskHolders: [Path: [VPhoneLaunchpadDiskHolder]] = [:]private var activities: [Path: String] = [:]+ /// The last `cfw install` or update run on each machine this session,+ /// kept once it ends so its sheet and the inspector can say how it went.+ private(set) var maintenance: [Path: VPhoneLaunchpadMaintenanceRun] = [:]+ /// Machines whose maintenance sheet is open: their failures show there,+ /// not as an alert.+ var showsMaintenance: Set<Path> = []+ /// A run that has just started from Launchpad itself, for the machines+ /// view to open its sheet. It clears this once it has.+ var maintenanceSheetRequest: Path?private var isRefreshing = falseprivate var timer: Timer?@@ -551,7 +560,7 @@ final class VPhoneLaunchpadMachineLibrary {}/// Runs `cfw install` again through the helper, for a machine whose last- /// install did not finish. Output goes to the machine's console log.+ /// install did not finish.func installCustomFirmware(_ machine: Path) async {guard let version = bundleVersion(for: machine) else {actionError = VPhoneLaunchpadError(String(localized: "No Core Bundle version is installed. Install one in Core Bundle."))@@ -560,31 +569,17 @@ final class VPhoneLaunchpadMachineLibrary {guard await requireDiskUnheld(machine) else {return}- activities[machine] = String(localized: "Installing custom firmware…")- defer { activities[machine] = nil }- appendConsoleLog(machine, "$ vphone-cli cfw install \(machine.name)")- let log = Self.consoleLog(machine)- do {- let status = try await helper.installCustomFirmware(+ let installed = await performMaintenance(.installCustomFirmware, on: machine) { onLine in+ try await helper.installCustomFirmware(bundleVersion: version,machineName: machine.name,libraryRoot: machine.libraryRoot,keepArtifacts: true,- onLine: { line in Self.append(line, to: log) },+ onLine: onLine,)- if status != 0 {- actionError = VPhoneLaunchpadError(- String(localized: "Unable to install custom firmware. Check the log for details."),- detail: String(localized: "Choose Show Console Log for the full output."),- )- } else {- recordGuestEnvironment(machine, version)- }- } catch {- if !(error is CancellationError) {- actionError = error as? VPhoneLaunchpadError- ?? VPhoneLaunchpadError(String(localized: "Unable to install custom firmware. Check the log for details."), detail: error.localizedDescription)- }+ }+ if installed {+ recordGuestEnvironment(machine, version)}await refresh()}@@ -607,32 +602,16 @@ final class VPhoneLaunchpadMachineLibrary {guard await requireDiskUnheld(machine, explain: explain) else {return false}- var updated = false- activities[machine] = String(localized: "Updating guest environment…")- defer { activities[machine] = nil }- appendConsoleLog(machine, "$ vphone-cli cfw update-environment \(machine.name)")- let log = Self.consoleLog(machine)- do {- let status = try await helper.updateGuestEnvironment(+ let updated = await performMaintenance(.updateGuestEnvironment, on: machine, explain: explain) { onLine in+ try await helper.updateGuestEnvironment(bundleVersion: version,machineName: machine.name,libraryRoot: machine.libraryRoot,- onLine: { line in Self.append(line, to: log) },+ onLine: onLine,)- if status != 0 {- actionError = explain(VPhoneLaunchpadError(- String(localized: "Unable to update the guest environment."),- detail: String(localized: "Choose Show Console Log for the full output."),- ))- } else {- recordGuestEnvironment(machine, version)- updated = true- }- } catch {- if !(error is CancellationError) {- actionError = explain(error as? VPhoneLaunchpadError- ?? VPhoneLaunchpadError(String(localized: "Unable to update the guest environment."), detail: error.localizedDescription))- }+ }+ if updated {+ recordGuestEnvironment(machine, version)}await refresh()return updated@@ -649,30 +628,90 @@ final class VPhoneLaunchpadMachineLibrary {guard await requireDiskUnheld(machine) else {return}- activities[machine] = String(localized: "Updating kernel…")- defer { activities[machine] = nil }- appendConsoleLog(machine, "$ vphone-cli cfw update-kernel \(machine.name)")- let log = Self.consoleLog(machine)- do {- let status = try await helper.updateKernel(+ await performMaintenance(.updateKernel, on: machine) { onLine in+ try await helper.updateKernel(bundleVersion: version,machineName: machine.name,libraryRoot: machine.libraryRoot,- onLine: { line in Self.append(line, to: log) },+ onLine: onLine,)+ }+ await refresh()+ }++ // MARK: - Maintenance runs++ /// Runs one of the helper's maintenance commands with the machine shown+ /// busy. Each line goes to the machine's console log, as it always has,+ /// to the run's own log, which its sheet follows, and to `forward`; the+ /// few that mark a step or a warning reach the run itself. `presents`+ /// asks the machines view to open the sheet. A failure is recorded on the+ /// run in the words its sheet and an alert use; what the helper throws is+ /// thrown on.+ func runMaintenance(+ _ run: VPhoneLaunchpadMaintenanceRun,+ presents: Bool,+ forward: (@Sendable (String) -> Void)? = nil,+ _ command: (@escaping @Sendable (String) -> Void) async throws -> Int32,+ ) async throws -> Int32 {+ let machine = run.machine+ maintenance[machine] = run+ activities[machine] = run.kind.activity+ defer { activities[machine] = nil }+ if presents {+ maintenanceSheetRequest = machine+ }+ let banner = "$ vphone-cli \(run.kind.command) \(machine.name)"+ appendConsoleLog(machine, banner)+ run.log.write(banner)+ let console = Self.consoleLog(machine)+ let log = run.log+ let output: @Sendable (String) -> Void = { [weak run] line in+ Self.append(line, to: console)+ log.write(line)+ forward?(line)+ if VPhoneLaunchpadMaintenanceProgress.isNotable(line) {+ Task { @MainActor in run?.read(line) }+ }+ }+ do {+ let status = try await command(output)if status != 0 {- actionError = VPhoneLaunchpadError(- String(localized: "Unable to update the kernel."),- detail: String(localized: "Choose Show Console Log for the full output."),- )+ run.failure = VPhoneLaunchpadError(run.kind.failure, detail: log.tail)}+ run.finish(succeeded: status == 0)+ return status} catch {if !(error is CancellationError) {- actionError = error as? VPhoneLaunchpadError- ?? VPhoneLaunchpadError(String(localized: "Unable to update the kernel."), detail: error.localizedDescription)+ run.failure = error as? VPhoneLaunchpadError+ ?? VPhoneLaunchpadError(run.kind.failure, detail: error.localizedDescription)}+ run.finish(succeeded: false)+ throw error}- await refresh()+ }++ /// `runMaintenance` for a button or a menu item: its sheet opens, and a+ /// failure, reworded by `explain`, becomes `actionError` unless that+ /// sheet is open to show it. True once the command has succeeded.+ @discardableResult+ private func performMaintenance(+ _ kind: VPhoneLaunchpadMaintenanceRun.Kind,+ on machine: Path,+ explain: (VPhoneLaunchpadError) -> VPhoneLaunchpadError = { $0 },+ _ command: (@escaping @Sendable (String) -> Void) async throws -> Int32,+ ) async -> Bool {+ let run = VPhoneLaunchpadMaintenanceRun(kind: kind, machine: machine)+ if (try? await runMaintenance(run, presents: true, command)) == 0 {+ return true+ }+ if let failure = run.failure {+ run.failure = explain(failure)+ if !showsMaintenance.contains(machine) {+ actionError = run.failure+ }+ }+ return false}/// Stops a machine. The guest is asked to shut down first, so it quits itsdiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swiftindex fabf97a1..ce64527a 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift@@ -13,6 +13,7 @@ struct VPhoneLaunchpadMachinesView: View {case clone(MachinePath)case snapshots(MachinePath)case console(MachinePath)+ case maintenance(MachinePath)case guestSystem(MachinePath)case commands@@ -26,6 +27,7 @@ struct VPhoneLaunchpadMachinesView: View {case let .clone(machine): "clone-\(machine.url.path)"case let .snapshots(machine): "snapshots-\(machine.url.path)"case let .console(machine): "console-\(machine.url.path)"+ case let .maintenance(machine): "maintenance-\(machine.url.path)"case let .guestSystem(machine): "guest-system-\(machine.url.path)"case .commands: "commands"}@@ -121,6 +123,19 @@ struct VPhoneLaunchpadMachinesView: View {}// So New Machine opens on the catalog rather than loading it..task(id: model.bundles.defaultVersion) { await VPhoneLaunchpadNewMachineView.prefetchCatalog(model) }+ // A CFW install or update started here shows its progress at once.+ // Another sheet open keeps its place; the inspector offers the+ // progress then. A run already over by the time the list is back+ // on screen does not open.+ .onChange(of: library.maintenanceSheetRequest, initial: true) {+ guard let machine = library.maintenanceSheetRequest else {+ return+ }+ library.maintenanceSheetRequest = nil+ if sheet == nil, library.maintenance[machine]?.isRunning == true {+ sheet = .maintenance(machine)+ }+ }.onChange(of: model.deletionRequest, initial: true) {if !model.deletionRequest.isEmpty {deletion = model.deletionRequest@@ -440,6 +455,8 @@ struct VPhoneLaunchpadMachinesView: View {VPhoneLaunchpadSnapshotsView(machine: path)case let .console(path):VPhoneLaunchpadConsoleView(title: "\(path.name) Console", url: VPhoneLaunchpadMachineLibrary.consoleLog(path))+ case let .maintenance(path):+ VPhoneLaunchpadMaintenanceView(machine: path)case let .guestSystem(path):VPhoneLaunchpadGuestSystemView(machine: path)case .commands:diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceProgress.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceProgress.swiftnew file mode 100644index 00000000..bf07b87e--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceProgress.swift@@ -0,0 +1,58 @@+import Foundation++// MARK: - Maintenance progress++/// What the output of `cfw install`, `cfw update-environment` or+/// `cfw update-kernel` says about how far it has come. The CLI reports no+/// fraction, but it starts each step with an unindented `[*]` line and marks+/// a step that failed with `[!]`, which a run of several hundred lines of+/// patch detail otherwise buries.+nonisolated struct VPhoneLaunchpadMaintenanceProgress: Equatable, Sendable {+ /// The step under way: the last unindented `[*]`, `[+]` or `[!]` line,+ /// without its marker.+ private(set) var stage: String?+ /// Lines that say something went wrong, at any depth: `[!]` steps left+ /// in their prior state, `warning:` and `error:` lines. The first+ /// `maximumWarnings` are kept.+ private(set) var warnings: [String] = []+ /// Every such line, kept or not.+ private(set) var warningCount = 0++ static let maximumWarnings = 50++ private static let stageMarkers = ["[*] ", "[+] ", "[!] "]+ private static let warningPrefixes = ["warning:", "error:"]++ /// Cheap enough to ask of every line on the helper's queue, so only the+ /// few lines that change the progress cross to the main actor.+ static func isNotable(_ line: String) -> Bool {+ stageMarkers.contains(where: line.hasPrefix) || warning(in: line) != nil+ }++ mutating func read(_ line: String) {+ if let marker = Self.stageMarkers.first(where: line.hasPrefix) {+ let text = line.dropFirst(marker.count).trimmingCharacters(in: .whitespaces)+ if !text.isEmpty {+ stage = text+ }+ }+ if let warning = Self.warning(in: line) {+ warningCount += 1+ if warnings.count < Self.maximumWarnings {+ warnings.append(warning)+ }+ }+ }++ /// The line, trimmed and without a `[!]` marker, when it reports a+ /// failure or a warning.+ private static func warning(in line: String) -> String? {+ let trimmed = line.trimmingCharacters(in: .whitespaces)+ if trimmed.hasPrefix("[!]") {+ let text = trimmed.dropFirst(3).trimmingCharacters(in: .whitespaces)+ return text.isEmpty ? nil : text+ }+ let lowered = trimmed.lowercased()+ return warningPrefixes.contains(where: lowered.hasPrefix) ? trimmed : nil+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceView.swiftnew file mode 100644index 00000000..a8412da9--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceView.swift@@ -0,0 +1,232 @@+import AppKit+import Observation+import SwiftUI++// MARK: - Run++/// One `cfw install`, `cfw update-environment` or `cfw update-kernel` the+/// helper runs on a stopped machine. Its output goes to a log of its own,+/// which the progress sheet follows, as well as to the machine's console+/// log; the model keeps only the step under way and the lines that warn.+@MainActor+@Observable+final class VPhoneLaunchpadMaintenanceRun {+ enum Kind: Sendable {+ case installCustomFirmware+ case updateGuestEnvironment+ case updateKernel++ var title: String {+ switch self {+ case .installCustomFirmware: String(localized: "Install Custom Firmware")+ case .updateGuestEnvironment: String(localized: "Update Guest Environment")+ case .updateKernel: String(localized: "Update Kernel")+ }+ }++ /// The machine's state while it runs.+ var activity: String {+ switch self {+ case .installCustomFirmware: String(localized: "Installing custom firmware…")+ case .updateGuestEnvironment: String(localized: "Updating guest environment…")+ case .updateKernel: String(localized: "Updating kernel…")+ }+ }++ var finished: String {+ switch self {+ case .installCustomFirmware: String(localized: "Custom firmware installed.")+ case .updateGuestEnvironment: String(localized: "Guest environment updated.")+ case .updateKernel: String(localized: "Kernel updated.")+ }+ }++ var failure: String {+ switch self {+ case .installCustomFirmware: String(localized: "Unable to install custom firmware. Check the log for details.")+ case .updateGuestEnvironment: String(localized: "Unable to update the guest environment.")+ case .updateKernel: String(localized: "Unable to update the kernel.")+ }+ }++ func sheetTitle(_ machine: String) -> String {+ switch self {+ case .installCustomFirmware: String(localized: "Install Custom Firmware on \(machine)")+ case .updateGuestEnvironment: String(localized: "Update Guest Environment of \(machine)")+ case .updateKernel: String(localized: "Update Kernel of \(machine)")+ }+ }++ var command: String {+ switch self {+ case .installCustomFirmware: "cfw install"+ case .updateGuestEnvironment: "cfw update-environment"+ case .updateKernel: "cfw update-kernel"+ }+ }+ }++ let kind: Kind+ let machine: VPhoneLaunchpadMachinePath+ let startedAt = Date()+ private(set) var finishedAt: Date?+ private(set) var succeeded = false+ private(set) var progress = VPhoneLaunchpadMaintenanceProgress()+ /// Set by the caller once the run has failed, in the words the alert+ /// would use.+ var failure: VPhoneLaunchpadError?+ let log: VPhoneLaunchpadLogWriter++ init(kind: Kind, machine: VPhoneLaunchpadMachinePath) {+ self.kind = kind+ self.machine = machine+ log = VPhoneLaunchpadLogWriter(url: VPhoneLaunchpadMachineLibrary.consoleLog(machine, suffix: "-maintenance"))+ }++ var isRunning: Bool {+ finishedAt == nil+ }++ var status: VPhoneLaunchpadStatus {+ if isRunning {+ return .running+ }+ if !succeeded {+ return .failed+ }+ return progress.warningCount > 0 ? .warning : .passed+ }++ func read(_ line: String) {+ progress.read(line)+ }++ func finish(succeeded: Bool) {+ self.succeeded = succeeded+ finishedAt = Date()+ }+}++// MARK: - Sheet++/// A maintenance run's progress: the step under way, how long it has taken,+/// the steps that warned, and its output as it arrives. It follows the+/// machine's latest run, so it stays useful when another one starts.+struct VPhoneLaunchpadMaintenanceView: View {+ let machine: VPhoneLaunchpadMachinePath+ @Environment(VPhoneLaunchpadModel.self) private var model+ @Environment(\.dismiss) private var dismiss++ private var library: VPhoneLaunchpadMachineLibrary {+ model.machines+ }++ var body: some View {+ let run = library.maintenance[machine]+ VPhoneLaunchpadSheet(+ Text(verbatim: run?.kind.sheetTitle(machine.name) ?? machine.name),+ width: VPhoneLaunchpadSheetSize.wide,+ ) {+ VStack(alignment: .leading, spacing: 12) {+ if let run {+ summary(run)+ if !run.progress.warnings.isEmpty {+ warnings(run.progress)+ }+ }+ VPhoneLaunchpadLogTerminal(url: VPhoneLaunchpadMachineLibrary.consoleLog(machine, suffix: "-maintenance"))+ .frame(maxWidth: .infinity, minHeight: 420, maxHeight: .infinity)+ }+ .padding(.horizontal, 16)+ .padding(.vertical, 12)+ } accessory: {+ Button("Open Log File") {+ NSWorkspace.shared.open(VPhoneLaunchpadMachineLibrary.consoleLog(machine, suffix: "-maintenance"))+ }+ if run?.isRunning == true {+ Text("It continues if you close this window.")+ .foregroundStyle(.secondary)+ }+ } actions: {+ Button("Close") { dismiss() }+ .keyboardShortcut(.cancelAction)+ }+ // A failure shown here is not raised as an alert as well.+ .onAppear { library.showsMaintenance.insert(machine) }+ .onDisappear { library.showsMaintenance.remove(machine) }+ }++ private func summary(_ run: VPhoneLaunchpadMaintenanceRun) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: 8) {+ VPhoneLaunchpadStatusIcon(status: run.status)+ VStack(alignment: .leading, spacing: 2) {+ Text(verbatim: headline(run))+ if let stage = run.progress.stage, run.isRunning || !run.succeeded {+ Text(verbatim: stage)+ .font(.caption.monospaced())+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .truncationMode(.middle)+ .help(stage)+ }+ if let detail = run.failure?.detail {+ Text(verbatim: detail)+ .font(.caption)+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ .lineLimit(6)+ }+ }+ Spacer(minLength: 16)+ VPhoneLaunchpadMaintenanceElapsed(run: run)+ }+ }++ private func headline(_ run: VPhoneLaunchpadMaintenanceRun) -> String {+ if run.isRunning {+ return run.kind.activity+ }+ if run.succeeded {+ return run.kind.finished+ }+ return run.failure?.message ?? String(localized: "Unable to Complete Action")+ }++ private func warnings(_ progress: VPhoneLaunchpadMaintenanceProgress) -> some View {+ DisclosureGroup {+ ScrollView {+ Text(verbatim: progress.warnings.joined(separator: "\n"))+ .font(.caption.monospaced())+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .frame(maxHeight: 120)+ } label: {+ Label {+ Text("^[\(progress.warningCount) warning](inflect: true)")+ } icon: {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.yellow)+ }+ }+ }+}++// MARK: - Elapsed++/// How long a run has taken: counting while it runs, fixed once it ends.+struct VPhoneLaunchpadMaintenanceElapsed: View {+ let run: VPhoneLaunchpadMaintenanceRun++ var body: some View {+ Group {+ if let finishedAt = run.finishedAt {+ Text(verbatim: VPhoneLaunchpadCreationView.duration(finishedAt.timeIntervalSince(run.startedAt)))+ } else {+ Text(run.startedAt, style: .timer)+ }+ }+ .monospacedDigit()+ .foregroundStyle(.secondary)+ }+}