Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Keep Guest System's restart note until the guest restarts

Jacky6e0488ceb9b5
diff --git a/VPhoneLaunchpad/Tests/TemplatesTests.swift b/VPhoneLaunchpad/Tests/TemplatesTests.swift
index 2580271b..4fab1a06 100644
--- a/VPhoneLaunchpad/Tests/TemplatesTests.swift
+++ b/VPhoneLaunchpad/Tests/TemplatesTests.swift
@@ -8,6 +8,7 @@ struct TemplatesTests {
commandArguments()
patchOverrides()
creationPlan()
+ guestRestart()
try templateList()
try templateFind()
notices()
@@ -230,6 +231,49 @@ struct TemplatesTests {
typealias Step = VPhoneLaunchpadCreationStep
+ // MARK: - Guest restart
+
+ static func guestRestart() {
+ let processes: [String: Any] = ["processes": [
+ ["pid": 412, "name": "launchd_sim", "start_time": 1_791_500_000.5],
+ ["pid": 1, "name": "launchd", "start_time": 1_791_453_600.25],
+ ]]
+ let boot = VPhoneLaunchpadPendingRestart.boot(fromProcesses: processes)
+ precondition(boot == 1_791_453_600.25, "launchd's start time: \(String(describing: boot))")
+ precondition(VPhoneLaunchpadPendingRestart.boot(fromProcesses: ["processes": []]) == nil, "No launchd")
+
+ // Switching to None: the apply says a restart is needed, the profile
+ // read afterwards does not.
+ let applyNone: [String: Any] = ["enabled": Array(repeating: "label", count: 141), "failed": [], "reboot_required": true]
+ let profile = VPhoneLaunchpadServiceProfile(["profile": "none", "supported": true, "running": [], "reboot_required": false])
+ precondition(!profile.rebootRequired && profile.profile == "none" && profile.groups.isEmpty, "The profile forgets")
+ guard let pending = VPhoneLaunchpadPendingRestart.afterApply(applyNone, pending: nil, boot: boot) else {
+ preconditionFailure("The apply's answer is kept")
+ }
+ precondition(pending.boot == boot, "Made in this boot")
+ precondition(!pending.hasRestarted(currentBoot: boot), "Same boot: still pending")
+ precondition(!pending.hasRestarted(currentBoot: boot.map { $0 + 0.4 }), "Rounding is not a boot")
+ precondition(!pending.hasRestarted(currentBoot: nil), "A guest that does not answer has not restarted")
+ precondition(pending.hasRestarted(currentBoot: 1_791_457_200), "A later boot")
+
+ // A second change keeps the first one's boot; one needing no restart clears it.
+ let older = VPhoneLaunchpadPendingRestart(boot: 10)
+ precondition(VPhoneLaunchpadPendingRestart.afterApply(["reboot_required": true], pending: older, boot: 20) == older,
+ "The earliest boot counts")
+ precondition(VPhoneLaunchpadPendingRestart.afterApply(["reboot_required": false], pending: older, boot: 20) == nil,
+ "Nothing to restart for")
+ precondition(VPhoneLaunchpadPendingRestart.afterApply([:], pending: nil, boot: 20) == nil, "An older guest says nothing")
+ precondition(!VPhoneLaunchpadPendingRestart(boot: nil).hasRestarted(currentBoot: 20), "Unknown boot: wait for a stop")
+
+ let trimmed = VPhoneLaunchpadServiceProfile([
+ "profile": "trimmed", "supported": true, "running": ["a", "b"], "reboot_required": true,
+ "record": ["groups": ["base", "accounts"], "allow": ["com.apple.x"]],
+ ])
+ precondition(trimmed.rebootRequired && trimmed.running == 2 && trimmed.groups == ["base", "accounts"] && trimmed.allow == ["com.apple.x"],
+ "Trimmed profile")
+ print("Guest restart tests passed")
+ }
+
// MARK: - JSON
/// `vm template list --json` as 2.9.0 prints it: pretty, keys sorted,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
index 9b977694..e8a8850e 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift
@@ -167,6 +167,10 @@
await panel(model, .templates, "14-templates", suffix)
guestSystemRunning = true
await sheet(.guestSystem(path("research-01")), "15-guest-system", suffix)
+ // Switched to None: the guest no longer reports a restart.
+ guestSystemRestartPending = true
+ await sheet(.guestSystem(path("research-01")), "15b-guest-system-restart-pending", suffix)
+ guestSystemRestartPending = false
guestSystemRunning = false
await sheet(.guestSystem(labMachine), "15a-guest-system-stopped", suffix)
model.machines.applyPreviewNotice()
@@ -524,9 +528,16 @@
/// Whether the Guest System sheet sees its machine running.
static var guestSystemRunning = false
- /// Stands in for `services.profile`.
+ /// Whether a profile change waits for the guest to restart.
+ static var guestSystemRestartPending = false
+
+ /// Stands in for `services.profile`. After a switch to None the
+ /// guest keeps no record, so it reports no restart either.
static var serviceProfile: [String: Any] {
- [
+ if guestSystemRestartPending {
+ return ["profile": "none", "supported": true, "running": [], "reboot_required": false]
+ }
+ return [
"profile": "trimmed", "supported": true, "running": [], "reboot_required": false,
"record": ["groups": ["base", "app_store", "signin_followup"], "allow": []],
]
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
index 8be81500..fabb6970 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings
@@ -3061,6 +3061,40 @@
}
}
},
+ "The guest has restarted." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The guest has restarted."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゲストを再起動しました。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "게스트가 재시동되었습니다."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Máy khách đã khởi động lại."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "客户机已重启。"
+ }
+ }
+ }
+ },
"TV" : {
"localizations" : {
"en" : {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift
index 63e5eb06..3da4a8f9 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadGuestSystemView.swift
@@ -2,29 +2,6 @@ import SwiftUI
// MARK: - State read from the guest
-/// `services.profile`, as much of it as the sheet shows.
-nonisolated struct VPhoneLaunchpadServiceProfile: Equatable, Sendable {
- var profile: String
- var supported: Bool
- /// The groups and allowed labels the guest's record holds, passed back
- /// when the profile is applied again so `--accounts-off` stays.
- var groups: [String]
- var allow: [String]
- /// Labels the profile turned off that still run until the guest restarts.
- var running: Int
- var rebootRequired: Bool
-
- init(_ result: [String: Any]) {
- profile = result["profile"] as? String ?? "none"
- supported = result["supported"] as? Bool ?? false
- let record = result["record"] as? [String: Any]
- groups = record?["groups"] as? [String] ?? []
- allow = record?["allow"] as? [String] ?? []
- running = (result["running"] as? [Any])?.count ?? 0
- rebootRequired = result["reboot_required"] as? Bool ?? false
- }
-}
-
/// One backup `apps.removed_system` lists.
nonisolated struct VPhoneLaunchpadRemovedApp: Identifiable, Hashable, Sendable {
let id: String
@@ -56,6 +33,11 @@ struct VPhoneLaunchpadGuestSystemView: View {
@Environment(VPhoneLaunchpadModel.self) private var model
@Environment(\.dismiss) private var dismiss
@State private var profile: VPhoneLaunchpadServiceProfile?
+ /// A change the guest takes on only when it restarts, kept by the library
+ /// until it has (`VPhoneLaunchpadPendingRestart`).
+ @State private var restartPending = false
+ /// Waits for the guest to come back after Restart Guest.
+ @State private var restartTask: Task<Void, Never>?
@State private var chosenProfile = "trimmed"
@State private var removedApps: [VPhoneLaunchpadRemovedApp]?
@State private var selectedApps: Set<String> = []
@@ -114,6 +96,7 @@ struct VPhoneLaunchpadGuestSystemView: View {
await load()
}
}
+ .onDisappear { restartTask?.cancel() }
.errorAlert($error)
}
@@ -128,15 +111,17 @@ struct VPhoneLaunchpadGuestSystemView: View {
Text("None").tag("none")
}
HStack {
- if profile.rebootRequired {
+ if needsRestart {
Label("Restart required", systemImage: "arrow.clockwise")
.foregroundStyle(.orange)
.font(.callout)
}
Spacer()
- if profile.rebootRequired {
- Button("Restart Guest") { Task { await restartGuest() } }
- .disabled(isWorking)
+ if needsRestart {
+ Button("Restart Guest") {
+ restartTask = Task { await restartGuest() }
+ }
+ .disabled(isWorking)
}
Button("Apply") { Task { await applyProfile() } }
.disabled(isWorking || chosenProfile == profile.profile || (!profile.supported && chosenProfile == "trimmed"))
@@ -160,6 +145,12 @@ struct VPhoneLaunchpadGuestSystemView: View {
}
}
+ /// The guest's own word, or a change Launchpad applied that the guest
+ /// no longer reports: switching to None clears its record.
+ private var needsRestart: Bool {
+ profile?.rebootRequired == true || restartPending
+ }
+
// MARK: - Apps
@ViewBuilder
@@ -218,6 +209,8 @@ struct VPhoneLaunchpadGuestSystemView: View {
if VPhoneLaunchpadPreview.isActive {
profile = VPhoneLaunchpadServiceProfile(VPhoneLaunchpadPreview.serviceProfile)
chosenProfile = profile?.profile ?? "trimmed"
+ restartPending = VPhoneLaunchpadPreview.guestSystemRestartPending
+ profileNote = restartPending ? String(localized: "\(0) turned off, \(141) turned back on.") : nil
removedApps = VPhoneLaunchpadRemovedApp.list(VPhoneLaunchpadPreview.removedSystemApps)
selectedApps = ["com.apple.news"]
return
@@ -228,6 +221,7 @@ struct VPhoneLaunchpadGuestSystemView: View {
let state = try await VPhoneLaunchpadServiceProfile(library.guestCall(machine, "services.profile"))
profile = state
chosenProfile = state.profile
+ restartPending = await library.isGuestRestartPending(machine)
removedApps = try await VPhoneLaunchpadRemovedApp.list(library.guestCall(machine, "apps.removed_system"))
selectedApps.formIntersection(Set(removedApps?.map(\.id) ?? []))
} catch {
@@ -246,8 +240,12 @@ struct VPhoneLaunchpadGuestSystemView: View {
params["groups"] = profile.groups
params["allow"] = profile.allow
}
+ // The boot the change is made in, to tell when the guest has restarted.
+ let boot = await library.guestBoot(machine)
do {
let result = try await library.guestCall(machine, "services.profile.apply", params)
+ library.recordServiceProfileApply(machine, result: result, boot: boot)
+ restartPending = library.pendingGuestRestarts[machine] != nil
let disabled = (result["disabled"] as? [Any])?.count ?? 0
let enabled = (result["enabled"] as? [Any])?.count ?? 0
let failed = (result["failed"] as? [Any])?.count ?? 0
@@ -262,14 +260,30 @@ struct VPhoneLaunchpadGuestSystemView: View {
}
}
+ /// Restarts the guest, then waits up to three minutes for it to answer
+ /// from a new boot and reads its state again.
private func restartGuest() async {
isWorking = true
defer { isWorking = false }
+ let waiting = await VPhoneLaunchpadPendingRestart(boot: library.guestBoot(machine))
do {
_ = try await library.guestCall(machine, "system.reboot", ["force": true], timeout: 30)
profileNote = String(localized: "The guest is restarting.")
} catch {
self.error = VPhoneLaunchpadError(String(localized: "Unable to Restart the Guest"), detail: VPhoneLaunchpadError.message(for: error))
+ return
+ }
+ for _ in 0 ..< 60 {
+ try? await Task.sleep(for: .seconds(3))
+ guard !Task.isCancelled, isRunning else {
+ return
+ }
+ if await waiting.hasRestarted(currentBoot: library.guestBoot(machine)) {
+ profileNote = String(localized: "The guest has restarted.")
+ library.forgetPendingRestart(machine)
+ await load()
+ return
+ }
}
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
index 6304698e..2cf708eb 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift
@@ -222,6 +222,8 @@ final class VPhoneLaunchpadMachineLibrary {
}
let paths = machines.map(\.path)
externallyRunning = await Task.detached { Self.machinesHoldingDisks(paths) }.value
+ // A stopped machine's guest boots afresh when it starts again.
+ pendingGuestRestarts = pendingGuestRestarts.filter { state(of: $0.key) != .stopped }
await loadBindings(paths)
refreshDiskUsage()
}
@@ -901,6 +903,44 @@ final class VPhoneLaunchpadMachineLibrary {
return (reply as? [String: Any])?["result"] as? [String: Any] ?? [:]
}
+ // MARK: - Guest restarts
+
+ /// Service profile changes waiting for their guest to restart, by
+ /// machine. Kept for this Launchpad session, so the Guest System sheet
+ /// shows them when it opens again.
+ private(set) var pendingGuestRestarts: [Path: VPhoneLaunchpadPendingRestart] = [:]
+
+ /// The guest's current boot, launchd's start time; nil when the guest
+ /// does not answer.
+ func guestBoot(_ machine: Path) async -> Double? {
+ guard let result = try? await guestCall(machine, "processes.list", ["filter": "launchd"], timeout: 20) else {
+ return nil
+ }
+ return VPhoneLaunchpadPendingRestart.boot(fromProcesses: result)
+ }
+
+ /// Keeps what `services.profile.apply` left waiting for a restart.
+ func recordServiceProfileApply(_ machine: Path, result: [String: Any], boot: Double?) {
+ pendingGuestRestarts[machine] = VPhoneLaunchpadPendingRestart.afterApply(result, pending: pendingGuestRestarts[machine], boot: boot)
+ }
+
+ /// Whether a change still waits for the guest to restart. Forgets it once
+ /// the guest answers from a later boot.
+ func isGuestRestartPending(_ machine: Path) async -> Bool {
+ guard let pending = pendingGuestRestarts[machine] else {
+ return false
+ }
+ if await pending.hasRestarted(currentBoot: guestBoot(machine)) {
+ pendingGuestRestarts[machine] = nil
+ return false
+ }
+ return true
+ }
+
+ func forgetPendingRestart(_ machine: Path) {
+ pendingGuestRestarts[machine] = nil
+ }
+
// MARK: - Export
/// An export queued or under way. `fraction` is nil until the command
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
index 964a6962..6dab3877 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadTemplates.swift
@@ -496,3 +496,67 @@ nonisolated struct VPhoneLaunchpadTemplateNotice: Identifiable, Hashable, Sendab
return nil
}
}
+
+// MARK: - Guest System
+
+/// `services.profile`, as much of it as the Guest System sheet shows.
+nonisolated struct VPhoneLaunchpadServiceProfile: Equatable, Sendable {
+ var profile: String
+ var supported: Bool
+ /// The groups and allowed labels the guest's record holds, passed back
+ /// when the profile is applied again so `--accounts-off` stays.
+ var groups: [String]
+ var allow: [String]
+ /// Labels the profile turned off that still run until the guest restarts.
+ var running: Int
+ var rebootRequired: Bool
+
+ init(_ result: [String: Any]) {
+ profile = result["profile"] as? String ?? "none"
+ supported = result["supported"] as? Bool ?? false
+ let record = result["record"] as? [String: Any]
+ groups = record?["groups"] as? [String] ?? []
+ allow = record?["allow"] as? [String] ?? []
+ running = (result["running"] as? [Any])?.count ?? 0
+ rebootRequired = result["reboot_required"] as? Bool ?? false
+ }
+}
+
+/// A service profile change waiting for its guest to restart.
+///
+/// `services.profile` cannot say this for every change: switching to None
+/// clears the guest's record, and with it the labels `reboot_required` is
+/// counted from, while the services it turned back on start only with the
+/// next boot. So the apply's own answer is kept until the guest has booted
+/// again, which shows as a new start time of launchd (pid 1).
+nonisolated struct VPhoneLaunchpadPendingRestart: Hashable, Sendable {
+ /// When launchd started in the boot the change was made in; nil when the
+ /// guest did not say. Without it, only the machine stopping clears this.
+ let boot: Double?
+
+ /// The guest's boot from `processes.list`: launchd's start time.
+ static func boot(fromProcesses result: [String: Any]) -> Double? {
+ let rows = result["processes"] as? [[String: Any]] ?? []
+ return rows.first { $0["pid"] as? Int == 1 }?["start_time"] as? Double
+ }
+
+ /// What is pending after `services.profile.apply` answered `result`. A
+ /// change still waiting keeps the boot it was made in; an apply that
+ /// needs no restart, such as one undoing a change that never ran, leaves
+ /// nothing pending.
+ static func afterApply(_ result: [String: Any], pending: Self?, boot: Double?) -> Self? {
+ guard result["reboot_required"] as? Bool == true else {
+ return nil
+ }
+ return pending ?? Self(boot: boot)
+ }
+
+ /// Whether the guest has booted since the change: both boots known, and
+ /// a second or more apart.
+ func hasRestarted(currentBoot: Double?) -> Bool {
+ guard let boot, let currentBoot else {
+ return false
+ }
+ return abs(currentBoot - boot) >= 1
+ }
+}