Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Implement UI for editing SoundBoard's debugging user defaults

Guilherme Rambob45d6b328b19
diff --git a/Research/Firmware/homepod_soundboard_controls.md b/Research/Firmware/homepod_soundboard_controls.md
index fb36d5bf..62d10fe7 100644
--- a/Research/Firmware/homepod_soundboard_controls.md
+++ b/Research/Firmware/homepod_soundboard_controls.md
@@ -138,6 +138,39 @@ These host stubs verify marshaling; they do not establish SoundBoard XPC effects
Detailed REA records, method encodings, enum tables and annotated cache
disassembly are retained under `.build/homepod-ui-research/`.
+## User defaults browser (2026-10-23)
+
+Device Controls → HomePod → User Defaults opens a sheet populated by the
+guest's `getUserDefaults:` reply. The `info.decoded` SBSDefaultInfo metadata
+defines each row's name, description, Boolean/integer/floating-point/string
+editor, factory value, bounds and reinitialization hint. The native `mod`
+field identifies stored overrides, including overrides equal to the factory
+value. No host list of preference names is used; unknown types remain visible
+and read-only. Search matches names and descriptions, and Overrides Only
+filters on the native override state.
+
+Edits remain drafts until Save. Numeric input is finite, checked against the
+declared range, and integers preserve 64-bit precision. Set sends the native
+string argument through `setUserDefaults:withValue:`; Reset removes a single
+override through `resetUserDefault:`. Both setters report submission, so the
+model rereads the defaults for up to six attempts before confirming success.
+Unconfirmed writes retain their drafts and report the failed readback.
+Refreshing preserves other drafts; closing with edits asks before discarding.
+The HomePod section also offers Restart SoundBoard, using the existing
+`services.kickstart` operation for `com.apple.SoundBoard` with kill and force.
+No new guest operation or firmware patch is required.
+
+Validation used the owner's Copy Reply export (150 defaults) and an isolated
+simulated SoundBoard store. Tests cover all exported current values, string
+Booleans, bounds, large integers, unsupported metadata, duplicate rejection,
+search, draft retention, asynchronous save/reset, unconfirmed writes and
+readback errors. A captured guest connection checks restart's service label,
+kill/force arguments, disconnect guard and failure state. The actual SwiftUI
+sheet was reviewed with all 150 exported rows: search, Boolean save/reset,
+numeric range feedback, disabled invalid saves and discard confirmation.
+These UI checks used the simulated store and did not modify guest defaults.
+The full VPhone bundle build passed.
+
## Setup completion and inverse
`system-homepod-exp-setup_bypass` is a declared optional patch, gated to HomePod
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index 255248c9..60582a84 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -1,6 +1,43 @@
{
"sourceLanguage" : "en",
"strings" : {
+ "%lld of %lld defaults · %lld unsaved changes" : {
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "new",
+ "value": "%1$lld of %2$lld defaults · %3$lld unsaved changes"
+ }
+ }
+ }
+ },
+ "Change the search or filter to browse other defaults." : {},
+ "Default Value" : {},
+ "Discard Changes" : {},
+ "Discard Edit" : {},
+ "Discard unsaved changes?" : {},
+ "Done" : {},
+ "Edited" : {},
+ "Enabled" : {},
+ "HomePod User Defaults" : {},
+ "HomePod user defaults" : {},
+ "Maximum" : {},
+ "Metadata" : {},
+ "Minimum" : {},
+ "No Matching Defaults" : {},
+ "Override" : {},
+ "Overrides Only" : {},
+ "Read current values and metadata. Unsaved edits are preserved." : {},
+ "Reading defaults from SoundBoard…" : {},
+ "Remove this setting's override in SoundBoard." : {},
+ "Requires reinitialization; restart SoundBoard after applying this change." : {},
+ "Reset to Default" : {},
+ "Restart SoundBoard" : {},
+ "Search names and descriptions" : {},
+ "Stored Override" : {},
+ "This value type is available for browsing only." : {},
+ "User Defaults" : {},
+ "User Defaults…" : {},
"Animation": {
},
"Commands without a reply report submission. SoundBoard applies them asynchronously.": {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/HomePodDefaultsTests.swift b/VPhoneExecutable/VPhoneVirtualization/Tests/HomePodDefaultsTests.swift
new file mode 100644
index 00000000..3dccd35a
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/HomePodDefaultsTests.swift
@@ -0,0 +1,203 @@
+import AppKit
+import SwiftUI
+
+@main
+struct HomePodDefaultsTests {
+ @MainActor static func main() async throws {
+ let preview = Bundle.main.bundleURL.pathExtension == "app"
+ if preview {
+ _ = NSApplication.shared
+ NSApp.setActivationPolicy(.regular)
+ let url = Bundle.main.resourceURL!.appendingPathComponent("defaults.json")
+ let reply = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any]
+ let store = DefaultsStore(reply: reply)
+ let window = NSWindow(contentRect: NSRect(x: 200, y: 200, width: 960, height: 680),
+ styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
+ window.title = "HomePod Defaults Preview"
+ window.isReleasedWhenClosed = false
+ window.contentView = NSHostingView(rootView: DefaultsPreview(store: store))
+ window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ NSApp.run()
+ return
+ }
+
+ if CommandLine.arguments.count > 1 {
+ let data = try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1]))
+ let reply = try JSONSerialization.jsonObject(with: data) as! [String: Any]
+ let entries = try VPhoneHomePodUserDefault.parse(reply)
+ precondition(entries.count == 150 && Set(entries.map(\.id)).count == 150)
+ for entry in entries { _ = try entry.validated(entry.currentValue) }
+ print("All 150 exported defaults decoded and their current typed values validated")
+ }
+
+ let store = DefaultsStore(reply: fixture())
+ let model = VPhoneHomePodDefaultsModel(call: store.call)
+ await model.load()
+ precondition(model.error == nil && model.entries.count == 6)
+ let boolean = model.entries.first { $0.id == "Boolean" }!
+ let integer = model.entries.first { $0.id == "Integer" }!
+ let real = model.entries.first { $0.id == "Float" }!
+ let string = model.entries.first { $0.id == "String" }!
+ let wide = model.entries.first { $0.id == "Wide" }!
+ let unsupported = model.entries.first { $0.id == "Future" }!
+ precondition(boolean.kind == .bool && boolean.currentValue == "1" && boolean.requiresReinit)
+ precondition((try? boolean.validated("false")) == "0")
+ precondition((try? wide.validated(wide.currentValue)) == "18446744073709551615")
+ precondition((try? string.validated(" spaced text ")) == " spaced text ")
+ precondition(unsupported.kind == .unsupported && unsupported.currentValue == "{\"a\":1}")
+ for value in ["1.5", "101", "-1", "18446744073709551616"] { rejects { try integer.validated(value) } }
+ for value in ["nan", "inf", "-inf", "2.1", "text"] { rejects { try real.validated(value) } }
+ precondition((try? real.validated("1e0")) == "1.0")
+ rejects { try unsupported.validated("1") }
+ model.searchText = "adjustable number"
+ precondition(model.visibleEntries.map(\.id) == ["Integer"])
+ model.searchText = ""
+ model.overridesOnly = true
+ precondition(model.visibleEntries.map(\.id) == ["Boolean"])
+ model.overridesOnly = false
+
+ model.edit(string, text: "draft")
+ model.edit(integer, text: "20")
+ await model.load()
+ precondition(model.text(for: string) == "draft" && model.pendingCount == 2)
+ store.delayedReads = 1
+ await model.save(integer)
+ precondition(model.error == nil && model.status == "Saved Integer.")
+ precondition(model.pendingCount == 1 && model.text(for: string) == "draft")
+ precondition(store.writes.last?.0 == "setUserDefaults:withValue:" && store.writes.last?.1 == ["name": "Integer", "value": "20"])
+ precondition(model.entries.first { $0.id == "Integer" }!.isModified)
+
+ let currentInteger = model.entries.first { $0.id == "Integer" }!
+ model.edit(currentInteger, text: "101")
+ let count = store.writes.count
+ await model.save(currentInteger)
+ precondition(model.error != nil && store.writes.count == count && model.drafts[integer.id] == "101")
+ model.discard(currentInteger)
+
+ // Reset removes an override even when its value equals the factory value.
+ await model.reset(boolean)
+ precondition(model.error == nil && model.status == "Reset Boolean.")
+ precondition(store.writes.last?.0 == "resetUserDefault:" && store.writes.last?.1 == ["name": "Boolean"])
+ precondition(!model.entries.first { $0.id == "Boolean" }!.isModified)
+ precondition(model.text(for: string) == "draft")
+
+ store.ignoresWrites = true
+ model.edit(real, text: "1.5")
+ await model.save(real)
+ precondition(model.status == nil && model.error?.contains("has not reported") == true)
+ precondition(model.drafts[real.id] == "1.5")
+ store.ignoresWrites = false
+ store.failsReadback = true
+ await model.save(real)
+ precondition(model.status == nil && model.error?.contains("Change submitted") == true)
+ precondition(model.drafts[real.id] == "1.5")
+
+ var duplicate = fixture()
+ var value = duplicate["value"] as! [String: Any]
+ var rows = value["array"] as! [[String: Any]]
+ rows.append(rows[0])
+ value["array"] = rows
+ duplicate["value"] = value
+ rejects { try VPhoneHomePodUserDefault.parse(duplicate) }
+ rejects { try VPhoneHomePodUserDefault.parse(["value": [:]]) }
+ let control = VPhoneGuestControl()
+ let debug = VPhoneHomePodDebugModel(control: control)
+ await debug.restartSoundBoard()
+ precondition(debug.error == nil && !debug.isBusy && control.requests.count == 1)
+ precondition(control.requests[0].0 == "services.kickstart")
+ precondition(control.requests[0].1["label"] as? String == "com.apple.SoundBoard")
+ precondition(control.requests[0].1["kill"] as? Bool == true && control.requests[0].1["force"] as? Bool == true)
+ control.isConnected = false
+ await debug.restartSoundBoard()
+ precondition(control.requests.count == 1)
+ control.isConnected = true
+ control.fails = true
+ await debug.restartSoundBoard()
+ precondition(debug.error != nil && !debug.isBusy)
+ print("Typed editors, bounds, 64-bit precision, search, overrides, draft preservation, save/reset readback and failure handling passed")
+ print("SoundBoard restart targets only its launchd service; disconnected and failed requests are handled")
+ }
+
+ static func rejects<T>(_ operation: () throws -> T) {
+ do { _ = try operation(); preconditionFailure("Expected invalid input to be rejected") }
+ catch {}
+ }
+
+ static func fixture() -> [String: Any] {
+ func row(_ name: String, _ type: String, _ value: Any, _ factory: Any,
+ modified: Bool = false, min: Int? = nil, max: Int? = nil) -> [String: Any] {
+ ["info": ["decoded": ["stringForUserDefault": name,
+ "userDescription": name == "Integer" ? "An adjustable number" : name,
+ "valueType": type, "defaultValue": factory,
+ "isBool": type == "bool", "isDouble": type == "float",
+ "rangeMin": min.map { $0 as Any } ?? NSNull(),
+ "rangeMax": max.map { $0 as Any } ?? NSNull(),
+ "requiresReinit": type == "bool"]], "value": value, "mod": modified]
+ }
+ return ["operation": "getUserDefaults:", "value": ["array": [
+ row("Boolean", "bool", "1", 1, modified: true),
+ row("Integer", "int", 10, 10, min: 0, max: 100),
+ row("Float", "float", 1.9, 1.9, min: 0, max: 2),
+ row("String", "string", "", ""),
+ row("Wide", "int", NSNumber(value: UInt64.max), 0),
+ row("Future", "dictionary", ["a": 1], ["a": 1]),
+ ]]]
+ }
+}
+
+/// Only this harness links the debug model to a captured guest connection.
+@MainActor
+final class VPhoneGuestControl {
+ var isConnected = true
+ var guestCapabilities = ["homepod_debug", "service_kickstart"]
+ var requests: [(String, [String: Any])] = []
+ var fails = false
+
+ func call(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {
+ requests.append((method, params))
+ if fails { throw VPhoneHomePodDefaultsError("Restart refused") }
+ return ["label": "com.apple.SoundBoard", "pid": 123]
+ }
+}
+
+@MainActor
+private final class DefaultsStore {
+ var rows: [[String: Any]]
+ var writes: [(String, [String: String])] = []
+ var delayedReads = 0
+ var ignoresWrites = false
+ var failsReadback = false
+ private var pending: (String, [String: String])?
+
+ init(reply: [String: Any]) { rows = (reply["value"] as! [String: Any])["array"] as! [[String: Any]] }
+
+ func call(_ operation: String, arguments: [String: String]) async throws -> [String: Any] {
+ if operation == "getUserDefaults:" {
+ if !writes.isEmpty && failsReadback { throw VPhoneHomePodDefaultsError("Disconnected") }
+ if delayedReads > 0 { delayedReads -= 1 }
+ else if let (operation, arguments) = pending {
+ let index = rows.firstIndex { (($0["info"] as? [String: Any])?["decoded"] as? [String: Any])?["stringForUserDefault"] as? String == arguments["name"] }!
+ let metadata = (rows[index]["info"] as! [String: Any])["decoded"] as! [String: Any]
+ rows[index]["value"] = operation == "resetUserDefault:" ? metadata["defaultValue"] : arguments["value"]
+ rows[index]["mod"] = operation != "resetUserDefault:"
+ self.pending = nil
+ }
+ return ["operation": operation, "value": ["array": rows]]
+ }
+ precondition(operation == "setUserDefaults:withValue:" || operation == "resetUserDefault:")
+ writes.append((operation, arguments))
+ if !ignoresWrites { pending = (operation, arguments) }
+ return ["operation": operation, "submitted": true]
+ }
+}
+
+private struct DefaultsPreview: View {
+ let store: DefaultsStore
+ @State private var isPresented = true
+ var body: some View {
+ Button("Browse HomePod User Defaults") { isPresented = true }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .sheet(isPresented: $isPresented) { VPhoneHomePodDefaultsView(call: store.call) }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-defaults-tests.sh b/VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-defaults-tests.sh
new file mode 100755
index 00000000..5f598505
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-defaults-tests.sh
@@ -0,0 +1,14 @@
+#!/bin/zsh
+set -euo pipefail
+
+tests="${0:a:h}"
+repo="${tests:h:h:h}"
+out="$repo/.build/homepod-defaults-tests"
+mkdir -p "$out"
+xcrun --sdk macosx swiftc -swift-version 6 -strict-concurrency=complete -parse-as-library \
+ -module-cache-path "$out/module-cache" \
+ "$tests:h/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsModel.swift" \
+ "$tests:h/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsView.swift" \
+ "$tests:h/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift" \
+ "$tests/HomePodDefaultsTests.swift" -o "$out/HomePodDefaultsTests"
+"$out/HomePodDefaultsTests" "$@"
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift
index 50dbaa55..2442adf2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift
@@ -71,6 +71,20 @@ final class VPhoneHomePodDebugModel {
values = Dictionary(uniqueKeysWithValues: (selected?.arguments ?? []).map { ($0.name, $0.initial.editorText) })
}
+ func restartSoundBoard() async {
+ guard !isBusy, control.isConnected else { return }
+ isBusy = true
+ error = nil
+ defer { isBusy = false }
+ do {
+ let response = try await control.call("services.kickstart", params: [
+ "label": "com.apple.SoundBoard", "kill": true, "force": true,
+ ])
+ let data = try JSONSerialization.data(withJSONObject: response, options: [.prettyPrinted, .sortedKeys])
+ result = String(decoding: data, as: UTF8.self)
+ } catch { self.error = String(describing: error) }
+ }
+
func execute() async {
guard !isBusy, control.isConnected, let operation = selected, operation.available else { return }
isBusy = true
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift
index 8bda0f59..0a48ea3f 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift
@@ -2,6 +2,7 @@ import SwiftUI
struct VPhoneHomePodDebugSection: View {
@State private var model: VPhoneHomePodDebugModel
+ @State private var showsUserDefaults = false
init(control: VPhoneGuestControl) {
_model = State(initialValue: VPhoneHomePodDebugModel(control: control))
@@ -9,6 +10,18 @@ struct VPhoneHomePodDebugSection: View {
var body: some View {
Section("HomePod") {
+ HStack {
+ Button("User Defaults…") { showsUserDefaults = true }
+ Spacer()
+ Button("Restart SoundBoard") { Task { await model.restartSoundBoard() } }
+ .disabled(!model.control.guestCapabilities.contains("service_kickstart"))
+ }
+ .disabled(model.isBusy || !model.control.isConnected || !model.control.guestCapabilities.contains("homepod_debug"))
+ .sheet(isPresented: $showsUserDefaults) {
+ VPhoneHomePodDefaultsView { operation, arguments in
+ try await model.control.call("homepod.debug.call", params: ["operation": operation, "arguments": arguments])
+ }
+ }
Picker("SoundBoard Debug Control", selection: $model.selectedID) {
ForEach(model.groups) { group in
Section(group.id) {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsModel.swift
new file mode 100644
index 00000000..8edbf463
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsModel.swift
@@ -0,0 +1,218 @@
+import Foundation
+import Observation
+
+/// A default's identity, editor and constraints come from SBSDefaultInfo, not
+/// a host-maintained list of SoundBoard flags. Archived bytes are not needed.
+struct VPhoneHomePodUserDefault: Identifiable, Equatable {
+ enum Kind: String, CaseIterable { case bool, int, float, string, unsupported }
+
+ let id: String
+ let description: String
+ let kind: Kind
+ let nativeType: String
+ let currentValue: String
+ let defaultValue: String
+ let rangeMin: Decimal?
+ let rangeMax: Decimal?
+ let isModified: Bool
+ let requiresReinit: Bool
+
+ func validated(_ input: String) throws -> String {
+ let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
+ let value: String
+ switch kind {
+ case .bool:
+ switch trimmed.lowercased() {
+ case "1", "true", "yes": value = "1"
+ case "0", "false", "no": value = "0"
+ default: throw VPhoneHomePodDefaultsError("Enter a Boolean value.")
+ }
+ case .int:
+ if let number = Int64(trimmed) { value = String(number) }
+ else if let number = UInt64(trimmed) { value = String(number) }
+ else { throw VPhoneHomePodDefaultsError("Enter a whole number within the 64-bit range.") }
+ case .float:
+ guard let number = Double(trimmed), number.isFinite else {
+ throw VPhoneHomePodDefaultsError("Enter a finite number using a period as the decimal separator.")
+ }
+ value = String(number)
+ case .string: return input
+ case .unsupported: throw VPhoneHomePodDefaultsError("This firmware's value type is not supported by the editor.")
+ }
+ if kind == .int || kind == .float {
+ guard let number = Decimal(string: value, locale: Locale(identifier: "en_US_POSIX")) else {
+ throw VPhoneHomePodDefaultsError("The number is outside the supported range.")
+ }
+ if let rangeMin, number < rangeMin { throw VPhoneHomePodDefaultsError("The value is below the minimum of \(rangeMin).") }
+ if let rangeMax, number > rangeMax { throw VPhoneHomePodDefaultsError("The value is above the maximum of \(rangeMax).") }
+ }
+ return value
+ }
+
+ static func parse(_ response: [String: Any]) throws -> [Self] {
+ guard let value = response["value"] as? [String: Any], let array = value["array"] as? [[String: Any]] else {
+ throw VPhoneHomePodDefaultsError("SoundBoard did not return a user defaults list.")
+ }
+ var seen: Set<String> = []
+ return try array.map { row in
+ guard let info = row["info"] as? [String: Any], let metadata = info["decoded"] as? [String: Any],
+ let name = metadata["stringForUserDefault"] as? String, !name.isEmpty,
+ seen.insert(name).inserted else {
+ throw VPhoneHomePodDefaultsError("SoundBoard returned missing or duplicate default metadata.")
+ }
+ let type = metadata["valueType"] as? String ?? "unknown"
+ let kind: Kind = (metadata["isBool"] as? Bool) == true ? .bool
+ : (metadata["isDouble"] as? Bool) == true ? .float : Kind(rawValue: type) ?? .unsupported
+ return Self(id: name, description: metadata["userDescription"] as? String ?? name,
+ kind: kind, nativeType: type,
+ currentValue: text(row["value"], kind: kind),
+ defaultValue: text(metadata["defaultValue"], kind: kind),
+ rangeMin: decimal(metadata["rangeMin"]), rangeMax: decimal(metadata["rangeMax"]),
+ isModified: (row["mod"] as? Bool) == true,
+ requiresReinit: (metadata["requiresReinit"] as? Bool) == true)
+ }.sorted { $0.id.localizedStandardCompare($1.id) == .orderedAscending }
+ }
+
+ private static func text(_ value: Any?, kind: Kind) -> String {
+ let text: String
+ if let string = value as? String { text = string }
+ else if let number = value as? NSNumber { text = number.stringValue }
+ else if let value, !(value is NSNull), JSONSerialization.isValidJSONObject(value),
+ let data = try? JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) {
+ text = String(decoding: data, as: UTF8.self)
+ } else { return "" }
+ if kind == .bool {
+ switch text.lowercased() {
+ case "true", "yes", "1": return "1"
+ case "false", "no", "0": return "0"
+ default: break
+ }
+ }
+ return text
+ }
+
+ private static func decimal(_ value: Any?) -> Decimal? {
+ guard let number = value as? NSNumber else { return nil }
+ return Decimal(string: number.stringValue, locale: Locale(identifier: "en_US_POSIX"))
+ }
+}
+
+struct VPhoneHomePodDefaultsError: Error, CustomStringConvertible {
+ let description: String
+ init(_ description: String) { self.description = description }
+}
+
+@MainActor
+@Observable
+final class VPhoneHomePodDefaultsModel {
+ typealias Call = @MainActor (String, [String: String]) async throws -> [String: Any]
+ @ObservationIgnored private let call: Call
+
+ private(set) var entries: [VPhoneHomePodUserDefault] = []
+ private(set) var visibleEntries: [VPhoneHomePodUserDefault] = []
+ private(set) var drafts: [String: String] = [:]
+ var selectedID: String?
+ var searchText = "" { didSet { updateVisibleEntries() } }
+ var overridesOnly = false { didSet { updateVisibleEntries() } }
+ private(set) var isBusy = false
+ private(set) var hasLoaded = false
+ private(set) var error: String?
+ private(set) var status: String?
+
+ var selected: VPhoneHomePodUserDefault? { entries.first { $0.id == selectedID } }
+ var pendingCount: Int { drafts.count }
+
+ init(call: @escaping Call) { self.call = call }
+
+ func text(for entry: VPhoneHomePodUserDefault) -> String { drafts[entry.id] ?? entry.currentValue }
+
+ func edit(_ entry: VPhoneHomePodUserDefault, text: String) {
+ guard !isBusy else { return }
+ let validated = try? entry.validated(text)
+ if text == entry.currentValue || (validated != nil && validated == (try? entry.validated(entry.currentValue))) {
+ drafts.removeValue(forKey: entry.id)
+ } else { drafts[entry.id] = text }
+ status = nil
+ }
+
+ func discard(_ entry: VPhoneHomePodUserDefault) { drafts.removeValue(forKey: entry.id) }
+
+ func validationError(for entry: VPhoneHomePodUserDefault) -> String? {
+ do { _ = try entry.validated(text(for: entry)); return nil }
+ catch { return String(describing: error) }
+ }
+
+ func load() async {
+ guard !isBusy else { return }
+ isBusy = true
+ error = nil
+ defer { isBusy = false }
+ do { apply(try await read()) }
+ catch { self.error = String(describing: error) }
+ }
+
+ func save(_ entry: VPhoneHomePodUserDefault) async {
+ guard !isBusy, drafts[entry.id] != nil else { return }
+ await change(entry, reset: false)
+ }
+
+ func reset(_ entry: VPhoneHomePodUserDefault) async {
+ guard !isBusy, entry.isModified else { return }
+ await change(entry, reset: true)
+ }
+
+ private func change(_ entry: VPhoneHomePodUserDefault, reset: Bool) async {
+ isBusy = true
+ error = nil
+ status = nil
+ defer { isBusy = false }
+ var submitted = false
+ do {
+ let requested = reset ? nil : try entry.validated(text(for: entry))
+ var arguments = ["name": entry.id]
+ if let requested { arguments["value"] = requested }
+ _ = try await call(reset ? "resetUserDefault:" : "setUserDefaults:withValue:", arguments)
+ submitted = true
+ // These setters return submission, not completion. Read back the
+ // guest value before clearing a draft or claiming that it saved.
+ for attempt in 0..<6 {
+ if attempt > 0 { try await Task.sleep(for: .milliseconds(200)) }
+ let refreshed = try await read()
+ apply(refreshed)
+ guard let current = refreshed.first(where: { $0.id == entry.id }) else { break }
+ let matches = reset ? !current.isModified
+ : current.isModified && (try? current.validated(current.currentValue)) == requested
+ if matches {
+ drafts.removeValue(forKey: entry.id)
+ status = reset ? "Reset \(entry.id)." : "Saved \(entry.id)."
+ return
+ }
+ }
+ throw VPhoneHomePodDefaultsError("SoundBoard has not reported the requested change. Refresh to check its current value.")
+ } catch {
+ self.error = submitted ? "Change submitted, but could not confirm it: \(error)" : String(describing: error)
+ }
+ }
+
+ private func read() async throws -> [VPhoneHomePodUserDefault] {
+ try VPhoneHomePodUserDefault.parse(await call("getUserDefaults:", [:]))
+ }
+
+ private func apply(_ entries: [VPhoneHomePodUserDefault]) {
+ self.entries = entries
+ // Refresh preserves edits, including edits to other selected defaults.
+ let names = Set(entries.map(\.id))
+ drafts = drafts.filter { names.contains($0.key) }
+ hasLoaded = true
+ updateVisibleEntries()
+ }
+
+ private func updateVisibleEntries() {
+ visibleEntries = entries.filter {
+ (!overridesOnly || $0.isModified) && (searchText.isEmpty
+ || $0.id.localizedCaseInsensitiveContains(searchText)
+ || $0.description.localizedCaseInsensitiveContains(searchText))
+ }
+ if !visibleEntries.contains(where: { $0.id == selectedID }) { selectedID = visibleEntries.first?.id }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsView.swift
new file mode 100644
index 00000000..c0e76b79
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDefaultsView.swift
@@ -0,0 +1,220 @@
+import SwiftUI
+
+struct VPhoneHomePodDefaultsView: View {
+ @Environment(\.dismiss) private var dismiss
+ @State private var model: VPhoneHomePodDefaultsModel
+ @State private var confirmsDiscard = false
+
+ init(call: @escaping VPhoneHomePodDefaultsModel.Call) {
+ _model = State(initialValue: VPhoneHomePodDefaultsModel(call: call))
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ VPhoneHomePodDefaultsToolbar(model: model)
+ Divider()
+ HSplitView {
+ VPhoneHomePodDefaultsList(model: model)
+ .frame(minWidth: 240, idealWidth: 300, maxWidth: 400)
+ if let entry = model.selected {
+ VPhoneHomePodDefaultEditor(model: model, entry: entry)
+ .id(entry.id)
+ .frame(minWidth: 380, maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ ContentUnavailableView(model.hasLoaded ? "No Matching Defaults" : "User Defaults",
+ systemImage: "slider.horizontal.3",
+ description: Text(model.hasLoaded ? "Change the search or filter to browse other defaults." : "Reading defaults from SoundBoard…"))
+ .frame(minWidth: 380, maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+ Divider()
+ VPhoneHomePodDefaultsFooter(model: model) {
+ if model.pendingCount > 0 { confirmsDiscard = true }
+ else { dismiss() }
+ }
+ }
+ .frame(minWidth: 760, idealWidth: 900, minHeight: 500, idealHeight: 600)
+ .interactiveDismissDisabled(model.isBusy || model.pendingCount > 0)
+ .confirmationDialog("Discard unsaved changes?", isPresented: $confirmsDiscard, titleVisibility: .visible) {
+ Button("Discard Changes", role: .destructive) { dismiss() }
+ Button("Cancel", role: .cancel) {}
+ }
+ .task { await model.load() }
+ }
+}
+
+private struct VPhoneHomePodDefaultsToolbar: View {
+ @Bindable var model: VPhoneHomePodDefaultsModel
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack {
+ Text("HomePod User Defaults").font(.headline)
+ Spacer()
+ if model.isBusy { ProgressView().controlSize(.small) }
+ Button("Refresh", systemImage: "arrow.clockwise") { Task { await model.load() } }
+ .disabled(model.isBusy)
+ .help("Read current values and metadata. Unsaved edits are preserved.")
+ }
+ HStack(spacing: 16) {
+ TextField("Search names and descriptions", text: $model.searchText)
+ .textFieldStyle(.roundedBorder)
+ Toggle("Overrides Only", isOn: $model.overridesOnly)
+ .toggleStyle(.checkbox)
+ }
+ }
+ .padding(16)
+ }
+}
+
+private struct VPhoneHomePodDefaultsList: View {
+ @Bindable var model: VPhoneHomePodDefaultsModel
+
+ var body: some View {
+ List(selection: $model.selectedID) {
+ ForEach(model.visibleEntries) { entry in
+ VPhoneHomePodDefaultRow(name: entry.id, value: entry.currentValue,
+ isModified: entry.isModified, hasDraft: model.drafts[entry.id] != nil)
+ .tag(entry.id)
+ }
+ }
+ .overlay {
+ if !model.hasLoaded && model.isBusy { ProgressView() }
+ }
+ .accessibilityLabel("HomePod user defaults")
+ }
+}
+
+private struct VPhoneHomePodDefaultRow: View {
+ let name: String
+ let value: String
+ let isModified: Bool
+ let hasDraft: Bool
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(verbatim: name)
+ .font(.system(.body, design: .monospaced))
+ .lineLimit(2)
+ HStack(spacing: 8) {
+ Text(value.isEmpty ? "\"\"" : value)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ Spacer(minLength: 0)
+ if hasDraft { Text("Edited") }
+ else if isModified { Text("Override") }
+ }
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ .padding(.vertical, 3)
+ }
+}
+
+private struct VPhoneHomePodDefaultEditor: View {
+ @Bindable var model: VPhoneHomePodDefaultsModel
+ let entry: VPhoneHomePodUserDefault
+
+ var body: some View {
+ Form {
+ Section {
+ Text(verbatim: entry.id)
+ .font(.system(.headline, design: .monospaced))
+ .textSelection(.enabled)
+ Text(verbatim: entry.description)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ if entry.requiresReinit {
+ Label("Requires reinitialization; restart SoundBoard after applying this change.", systemImage: "arrow.clockwise")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+ }
+ Section("Value") {
+ VPhoneHomePodDefaultValueEditor(entry: entry, value: Binding {
+ model.text(for: entry)
+ } set: { model.edit(entry, text: $0) })
+ if let error = model.validationError(for: entry) {
+ Text(verbatim: error).font(.callout).foregroundStyle(.red)
+ }
+ HStack {
+ Button("Save") { Task { await model.save(entry) } }
+ .disabled(model.drafts[entry.id] == nil || model.validationError(for: entry) != nil)
+ Button("Discard Edit") { model.discard(entry) }
+ .disabled(model.drafts[entry.id] == nil)
+ Spacer()
+ Button("Reset to Default") { Task { await model.reset(entry) } }
+ .disabled(!entry.isModified)
+ .help("Remove this setting's override in SoundBoard.")
+ }
+ }
+ Section("Metadata") {
+ LabeledContent("Type") { Text(verbatim: entry.nativeType) }
+ LabeledContent("Current Value") { Text(verbatim: display(entry.currentValue)) }
+ LabeledContent("Default Value") { Text(verbatim: display(entry.defaultValue)) }
+ if let minimum = entry.rangeMin {
+ LabeledContent("Minimum") { Text(verbatim: String(describing: minimum)) }
+ }
+ if let maximum = entry.rangeMax {
+ LabeledContent("Maximum") { Text(verbatim: String(describing: maximum)) }
+ }
+ LabeledContent("Stored Override") {
+ if entry.isModified { Text("Yes") } else { Text("No") }
+ }
+ }
+ .textSelection(.enabled)
+ }
+ .formStyle(.grouped)
+ .disabled(model.isBusy)
+ }
+
+ private func display(_ value: String) -> String { value.isEmpty ? "\"\"" : value }
+}
+
+private struct VPhoneHomePodDefaultValueEditor: View {
+ let entry: VPhoneHomePodUserDefault
+ @Binding var value: String
+
+ var body: some View {
+ VStack(alignment: .leading) {
+ switch entry.kind {
+ case .bool:
+ Toggle("Enabled", isOn: Binding { value == "1" } set: { value = $0 ? "1" : "0" })
+ case .int, .float:
+ TextField("Value", text: $value)
+ .font(.system(.body, design: .monospaced))
+ case .string:
+ TextField("Value", text: $value, axis: .vertical)
+ .lineLimit(1...6)
+ .font(.system(.body, design: .monospaced))
+ case .unsupported:
+ Text(verbatim: value).textSelection(.enabled)
+ Text("This value type is available for browsing only.").foregroundStyle(.secondary)
+ }
+ }
+ }
+}
+
+private struct VPhoneHomePodDefaultsFooter: View {
+ let model: VPhoneHomePodDefaultsModel
+ let done: () -> Void
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 16) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("\(model.visibleEntries.count) of \(model.entries.count) defaults · \(model.pendingCount) unsaved changes")
+ .font(.caption).foregroundStyle(.secondary)
+ if let error = model.error {
+ Text(verbatim: error).foregroundStyle(.red).textSelection(.enabled)
+ } else if let status = model.status {
+ Text(verbatim: status).foregroundStyle(.secondary).textSelection(.enabled)
+ }
+ }
+ Spacer()
+ Button("Done", action: done)
+ .keyboardShortcut(.cancelAction)
+ .disabled(model.isBusy)
+ }
+ .padding(16)
+ }
+}