Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

vphone-launchpad: maintenance progress, helper authorization, 2.12.1

Jackyeea4b1b33897
diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfig
index 1add1472..b7fe12b7 100644
--- a/VPhoneLaunchpad/Configuration/Version.xcconfig
+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig
@@ -1,4 +1,4 @@
MARKETING_VERSION = 2.12.0
// Bump whenever the helper changes. The app blesses the helper again when the
// installed helper's version or bytes differ from the copy it embeds.
-CURRENT_PROJECT_VERSION = 20
+CURRENT_PROJECT_VERSION = 21
diff --git a/VPhoneLaunchpad/Tests/MaintenanceProgressTests.sh b/VPhoneLaunchpad/Tests/MaintenanceProgressTests.sh
new file mode 100755
index 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.swift
new file mode 100644
index 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/Machines/VPhoneLaunchpadMaintenanceProgress.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMaintenanceProgress.swift
new file mode 100644
index 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.swift
new file mode 100644
index 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)
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swift
index 55a0a345..1d1678d2 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swift
@@ -19,7 +19,8 @@ enum VPhoneLaunchpadHelperAuthorization {
"class": "user",
"group": "admin",
"authenticate-user": true,
- "timeout": 300,
+ // Omit timeout to reuse the credential for the login session,
+ // unless it is explicitly destroyed. Zero would require reauthentication.
"shared": false,
"version": 1,
"comment": comment,
@@ -47,7 +48,7 @@ enum VPhoneLaunchpadHelperAuthorization {
}
/// True when the stored rule still asks for an administrator with no
- /// shared credential.
+ /// shared credential and retains the login-session lifetime.
private static func ruleIsIntact() -> Bool {
var stored: CFDictionary?
guard AuthorizationRightGet(right, &stored) == errAuthorizationSuccess,
@@ -57,7 +58,8 @@ enum VPhoneLaunchpadHelperAuthorization {
&& rule["group"] as? String == "admin"
&& rule["authenticate-user"] as? Bool != false
&& rule["shared"] as? Bool == false
- && (rule["timeout"] as? Int).map { $0 <= 300 } == true
+ // authd normalizes an omitted timeout to INT_MAX on readback.
+ && (rule["timeout"] == nil || (rule["timeout"] as? Int) == Int(Int32.max))
&& rule["rule"] == nil
&& rule["allow-root"] as? Bool != true
}