Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Better HomePod display, bypass setup, debug controls

Guilherme Rambo3a05611390c7
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 8ddc5701..085740ea 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1,5 +1,36 @@
# Patch Comparison: Regular / Development / Jailbreak / Experimental
+> **HomePod setup completion and controls (2026-10-22, live validation).**
+> New `system-homepod-exp-setup_bypass` is HomePod-only, restricted to 27.x,
+> and selected only by `homepod-mini`. It installs the System marker
+> `/usr/share/vphone/HomePodSetup.plist`. A short-lived mobile helper journals
+> `SetupDone` and `SetupFinishedAllSteps` in `com.apple.purplebuddy`, synchronizes
+> them, and calls the donor's `BYSetupAssistantPrepareLaunchSentinel` before
+> checking the native needs-setup and initial-run APIs. The sentinel is a
+> per-user POSIX semaphore, not a filesystem flag. Removing the marker restores
+> exactly the original two keys, including absent values; the inverse survives
+> until native restoration succeeds. The helper remains installed for rollback
+> even if vphoned is deselected. This completes local setup state; it does not
+> provision an Apple Account or HomeKit home. **Live late-start correction:**
+> an already-running HPSetup retains assistant/voice-trigger assertions even
+> after SoundBoard receives completion and runs post-setup initialization.
+> Native preparation publishes fresh completion; after verification, the helper
+> replays the donor's exported notification only for an existing sentinel and
+> gracefully stops only mobile's exact
+> `/Applications/HPSetup.app/HPSetup`, rechecking identity immediately before
+> SIGTERM. It observes disappearance before reporting success; failures retain
+> the inverse for retry. No SIGKILL, arbitrary process verb or new entitlement.
+> Opt-out does not terminate processes. No new instruction patch.
+> vphoned also exposes all 29 `SBSDebugInterface` methods through a fixed,
+> ABI-checked catalog using `com.apple.debuginfo.soundboard`; the HomePod-only
+> Controls section includes native animation/phase choices and typed button and
+> LED replay adapters. The host top cap now uses runtime-compiled Metal 4 optics
+> with a macOS 15 Metal compatibility path. GPU tests and 35 Xcode catalog and
+> selection tests pass. Final bundle `2.11.0-local.26745ac8` passed live late
+> completion (one native init), fresh/repeated boot, and native Metal display
+> presentation/reconnection. Opt-out restored absent keys and setup behavior.
+> See [implementation, live evidence, and service boundaries](Firmware/homepod_soundboard_controls.md).
+
> **HomePod top cap (2026-10-22).** `system-homepod-exp-top_cap` installs
> `/usr/share/vphone/HomePodDisplay.plist`, extracted from the selected board's
> `/arm-io/dockchannel-rtp/rtp-transport/display` node. It preserves the donor's
diff --git a/Research/Firmware/homepod_mini_support.md b/Research/Firmware/homepod_mini_support.md
index 50780e6a..047d9575 100644
--- a/Research/Firmware/homepod_mini_support.md
+++ b/Research/Firmware/homepod_mini_support.md
@@ -179,10 +179,14 @@ Frame generation and native report submission remain Apple's. The adapter uses
a signed load command in SoundBoard and
preserves its original entitlements.
-The Mac window displays a circular diffuser, adding both guest light layers and
-clamping emitted intensity. Its diffuser, color response and layer composition
-are visual approximations; the exact optical/hardware composition is not
-established by the inspected userspace code. Delivery keeps one snapshot request
+The Mac window displays a circular diffuser using runtime-compiled Metal 4
+shaders (with the same shader on the macOS 15 Metal compatibility path). It adds
+both guest light layers, blends neighboring emitters through a normalized
+two-scale point-spread function, attenuates the opaque edge, and draws the
+independent +/- channels as etched markings. Its diffuser, color response and
+layer composition are visual approximations; the exact optical/hardware
+composition is not established by the inspected userspace code. No optional
+Xcode Metal compiler download is needed to build the application. Delivery keeps one snapshot request
in flight at up to 60 Hz, drops intermediate frames, blanks on connection loss,
and pauses requests while minimized. No host animation substitutes for output.
The accessible +/- controls send consumer volume HID down/up (0xE9/0xEA),
@@ -225,3 +229,9 @@ input mapping yet and is excluded from accessibility/tab navigation.
Runtime artifacts for these checks are under `.build/homepod-ui-research/`.
Siri activation and its multicolor animations remain unvalidated; report and
renderer tests exercise RGB channels without claiming those services work.
+
+The subsequent Metal rendering, complete SoundBoard debug controls, and optional
+setup-completion helper are documented in
+[HomePod SoundBoard controls and setup](homepod_soundboard_controls.md). These
+changes have offline validation; the live results above apply to the preceding
+HID/display implementation, not to the new helper or debug effects.
diff --git a/Research/Firmware/homepod_soundboard_controls.md b/Research/Firmware/homepod_soundboard_controls.md
new file mode 100644
index 00000000..c2b8f715
--- /dev/null
+++ b/Research/Firmware/homepod_soundboard_controls.md
@@ -0,0 +1,357 @@
+# HomePod SoundBoard controls and setup
+
+## Scope and validation boundary
+
+This extends the HomePod mini support for AudioAccessory5,1, HomePod Software
+27.0 (24J361). The implementation adds a Metal top-cap renderer, the complete
+SoundBoardServices debug interface, and optional local setup completion. Initial
+validation was offline; on 2026-10-22 the owner authorized bundle installation
+and live tests on the existing `homepod-mini` VM. The live results and remaining
+service boundaries are recorded below.
+
+## Runtime Metal renderer
+
+`VPhoneHomePodMetalView` replaces AppKit gradient/LED drawing while native
+buttons retain accessibility, focus and the existing consumer HID input path.
+The source string in `VPhoneHomePodShader.swift` is compiled at runtime using
+`MTL4Compiler` and `MTL4LibraryDescriptor`, then an `MTL4RenderPipelineDescriptor`.
+Submission uses an actual `MTL4CommandQueue`, command allocator, command buffer,
+argument table and explicit residency set. Each of three slots owns its input
+buffers and command memory until GPU feedback. Snapshots arriving while all
+slots are busy collapse to the newest pending frame. The UI does not wait for
+GPU completion. Drawable acquisition/presentation uses the Metal 4 drawable
+wait/signal protocol.
+
+Metal 4 is used on a supporting GPU on macOS 26 or later. The macOS 15 minimum
+is retained with runtime MSL 3.1 compilation and the older command queue API;
+both paths use the same optical shader. There are no `.metal` build inputs,
+`metal`/`metallib` invocations or optional Xcode Metal toolchain dependencies.
+Apple's [Metal 4 compilation API](https://developer.apple.com/documentation/metal/using-the-metal-4-compilation-api)
+and [core API documentation](https://developer.apple.com/documentation/metal/understanding-the-metal-4-core-api),
+checked against the selected SDK headers, describe these separate APIs.
+
+The shader uses the donor device-tree coordinates without stretching the
+unpopulated rim. A normalized Gaussian mixture (weights 0.86/0.14, sigma
+0.155/0.29 in cap coordinates) spreads the guest's two summed light banks.
+Normalization includes unlit emitters so sparse patterns remain visible. A
+smooth radial mask suppresses light near the opaque rim. Exposure and a soft
+shoulder preserve colored highlights; an sRGB render target performs one final
+transfer. Static glass/rim shading and analytic +/- masks supply the surface.
+Only guest brightness controls illumination. There is no time input, host Siri
+animation or interpolated invented frame.
+
+The optical parameters are an approximation informed by the original mini's
+[Apple launch photography](https://www.apple.com/newsroom/2020/10/apple-introduces-homepod-mini-a-powerful-smart-speaker-with-amazing-sound/)
+and [Apple's status-light examples](https://support.apple.com/en-us/101607).
+They reproduce broad mixed light and a dark edge; they are not measurements of
+the diffuser, spectral response or exact layer composition. The current product
+page describes a newer mini and was not treated as B520 hardware evidence.
+
+`VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-metal-tests.sh` compiles
+the actual shader/backend with Swift and runs without a VM. On macOS 27.0.1,
+Apple M2 Max, the real Metal 4 compiler/queue passed off/white/RGB isolation,
+edge attenuation, independent icon lighting, diffuser blending, identical-frame
+determinism and eight rounds of three concurrent frames. The MSL 3.1 path
+matched Metal 4 output within two byte levels. Synthetic image fixtures are in
+`.build/homepod-metal-tests/`; multicolor fixtures are not evidence of Siri
+working in a guest. The GPU probe needs GPU access outside the process sandbox.
+A separate scratch app compiled the actual `VPhoneHomePodDisplayView`, renderer
+and shader. Its 640-point Retina window displayed the synthetic multicolor
+frame through a real CAMetalDrawable, retained accessible volume buttons, and
+redrew correctly when zoomed to a wide desktop window and restored. This needed
+no VM or installed bundle. The initial scratch-app minimize test hit a UI automation limitation; its two
+owned test processes were terminated. The later live VM window was successfully
+minimized and restored, with continued native frames, as recorded below.
+
+## Complete SoundBoard debug interface
+
+The donor SoundBoardServices cache image was extracted with repaired Objective-C
+metadata and stubs; SHA-256
+`5e5d68df84c8c3a54669a1618ea1cb8f3d12996b4ffe5d9be3828b62917cf41a`.
+REA inventory `ev_9490010b3a7f2ac743b300cfd85baa88060529dde104530675217ac23d7be5e2`
+contains 29 debug methods plus lifecycle methods. Exact argument encodings and
+reply block types were recovered from the original cache's optimized relative
+method lists and `SBSDebugInfoImplementer` protocol, rather than inferred from
+decompiler casts. Original-cache disassembly of `SBSServer` demonstrates the
+`com.apple.debuginfo.soundboard` entitlement gate; vphoned carries that grant.
+SoundBoard's executable is not changed for this interface.
+
+| Group | Exposed selectors |
+| --- | --- |
+| Diagnostics | `getAllDebugInfo:`, `getSelectDebugInfo:reply:` |
+| Display | `getLEDInfo:`, `sendLEDCommand:`, `render:`, `setLEDContents:`, `setBootSpinner:` |
+| Audio | `getVolume:`, `setVolume:`, `playTone:`, `stopTone:`, `siriSay:` |
+| Input | `sendButtonCommand:` |
+| Tuning | `getTuningInfo:`, `setTuningInfoOnBox:at:withValue:` |
+| Preferences | `getUserDefaults:`, `setUserDefaults:withValue:`, `resetUserDefault:`, `resetAllUserDefaults`, `getFeatureFlags:`, `setFeatureFlags:` |
+| Network | `triggerWiFiCoreCapture:`, `setWifiEnabled:`, `disassociateCurrentNetwork`, `disassociateNetworkWithName:` |
+| Software Update | `injectSWUpdateToHome:`, `setHomeUpdateState:`, `clearHomeSWUpdate`, `suScanForSoftwareUpdate` |
+
+`homepod.debug.catalog` advertises the fixed operations and per-method ABI
+availability. `homepod.debug.call` accepts an operation from that catalog and a
+typed arguments object. There is no arbitrary selector invocation. Availability
+requires SoundBoard.app and a loadable `SBSDebugInterface`; `homepod_debug` is
+independent of top-cap patch selection. Host visibility comes from the VM's
+HomePod identity, so this section does not appear for Apple TV or iPhone guests.
+It remains visible but disabled while disconnected and explains unavailable
+guest support.
+
+Seven operations return asynchronous replies (five dictionaries, a feature-flag
+array and Float volume). Reads have a three-second deadline; late replies are
+ignored, and a timed-out XPC client is reopened for a later call. The remaining
+22 native methods have no acknowledgement; the UI reports submission, without
+claiming that SoundBoard applied the command. JSON replies preserve Foundation
+collections and data, and decode native feature flags/default metadata where
+available while retaining archived bytes.
+
+The native wire adapters follow the donor implementations:
+
+- `render:` uses animation and phase strings. All 25 feature names and 20 phase
+ values recovered from the native enum tables appear in pickers. SoundBoard
+ converts space-separated animation words to its feature spelling.
+- `sendButtonCommand:` requires secure archived `HPButtonEvent` data. Typed
+ fields produce the native archive; existing archives can be sent as base64.
+ Buttons are Minus, Plus, Center and Cover (1–4). Actions are TouchMightHaveBegun,
+ TapRegistered, HoldBegan, HoldEnded and TouchCancelled (1–5). Integer widths,
+ tap counts, mach times and Boolean fields are checked before construction.
+- `setLEDContents:` requires a nonempty replay array, not HID report bytes.
+ Each frame contains `LedValuesTimestamp` (ascending UInt64) and
+ `LedValuesData` (native NSData). B520's replay buffer contains 40 Float RGB
+ triples, 480 bytes, including icon channels; it differs from the 245-byte
+ packed MiniDisplay output report. The editor accepts exact base64, RGB triples
+ or an RGB fill and converts to native data with geometry/length validation.
+- Feature-flag dictionaries use `domain`, `feature`, `value`. User-default
+ replies include secure `SBSDefaultInfo` archives, retained as base64 and
+ additionally decoded for readable metadata. Software-update injection retains
+ the native dictionary interface and documented keys in the editor.
+
+`VPhoneDaemon/Tests/run-homepod-debug-tests.sh` exercises all 29 unique catalog
+IDs against a frozen, independently recovered 24J361 method-encoding fixture,
+object/Float replies, typed multi-argument invocation, strict Boolean versus
+numeric types, native button archives (including UInt64.max mach time), replay
+encoding/base64, missing ABI/unknown operation rejection and timeout behavior.
+It also delivers a reply after the timeout and confirms the next request does
+not inherit that stale result. The setup-journal harness explicitly rejects both
+duplicate absent keys and keys appearing in both original and absent sets,
+without writing preferences.
+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/`.
+
+## Setup completion and inverse
+
+`system-homepod-exp-setup_bypass` is a declared optional patch, gated to HomePod
+27.x and enabled only in the `homepod-mini` preset. Other presets explicitly
+disable it, and explicit selection for another family is rejected. Its System
+marker is `/usr/share/vphone/HomePodSetup.plist`, with `Enabled=true`.
+
+The reveal procedure uses the donor's own setup flow:
+
+1. Extract SoundBoardFramework and SetupAssistant from the 24J361 cache with
+ Objective-C/stub repair. Their SHA-256 values are respectively
+ `a352a2ba4025e714ca8b7208490991d821f63387aeb5268c7937974029246749` and
+ `b214983fb007e97304bdb18299a9d71f4828f0563844d3c4134a92f82cb598d9`.
+2. Follow `SBSetupController.deviceNeedsSetup` into
+ `BYSetupAssistantNeedsToRun`. The internal function has an explicit
+ AudioAccessory branch returning the inverse of `SetupDone`; this is not an
+ assumption borrowed from iPhone setup.
+3. Follow `SBSetupController._setBuddyComplete`: it writes `SetupDone` in
+ `com.apple.purplebuddy`, current user/any host, synchronizes, and calls
+ `BYSetupAssistantPrepareLaunchSentinel`. Independently follow
+ `BYSetupAssistantHasCompletedInitialRun` to `SetupFinishedAllSteps`.
+4. Trace stock sentinel preparation/clearing: it uses
+ `sem_open`/`sem_unlink("purplebuddy.sentinel")`, a per-user semaphore, and
+ publishes the native finished notification. SoundBoard's setup check either
+ calls `runSetupGatedInitialization` immediately or waits for that notification.
+ This supports either process launch ordering without invoking SoundBoard's
+ private initialization manually.
+
+Relevant REA records include
+`ev_d061572b15543450b80e40a49a80a4a9fa7a2fb5ea9f98ca432783fc8675f0ba`
+(AudioAccessory gate),
+`ev_ee864420a79b7fcd589e2a5e715f737d1504258744899d0604f78f84875dc202`
+(native completion), and
+`ev_974490d0674d54c2e49d69fb08ea8dab75d760c323cb8d5574fd6b9037858fce`
+(sentinel preparation). Unresolved decompiler stubs were correlated with original
+cache disassembly. These are reconstructed control-flow observations, not source.
+
+Data is encrypted during host installation. The installer instead stages
+`vphone-homepod-setup` and a launchd job running as mobile (501). Before its
+first write the helper saves exactly the original two preference values,
+including which keys were absent, in
+`/var/mobile/Library/Application Support/vphone/HomePodSetupOriginal.plist`
+(0600 inside a 0700 directory). Repeated boots preserve the first inverse and
+leave unrelated preferences alone. After synchronization it calls stock
+sentinel preparation and requires `NeedsToRun=false` and
+`HasCompletedInitialRun=true`. Native preparation publishes completion when
+creating the sentinel. If the native gate was already complete immediately
+before preparation, the helper replays the donor's exported
+`BYSetupAssistantFinishedDarwinNotification` instead, avoiding duplicate
+post-setup initialization for a newly created sentinel. It gracefully ends any remaining
+mobile HPSetup session. Process enumeration is restricted to effective UID 501;
+the full `/Applications/HPSetup.app/HPSetup` executable path is checked again
+immediately before SIGTERM. A bounded disappearance/quiet check handles an app
+launch already in flight. There is no escalation to SIGKILL. Missing process
+APIs, unreadable owned-process identity, signal errors or a lingering setup
+process make the helper fail and retry, retaining its original-key journal.
+Status/error/date are written to
+`HomePodSetupStatus.plist` in the same directory.
+
+On deselection the marker is removed, and the helper restores just those two
+keys, prepares the stock sentinel and verifies the restored native state before
+deleting the journal. A failed synchronization or native verification keeps the
+journal for retry. The runtime is installed for every HomePod environment update
+even if vphoned and the bypass are deselected, so opt-out retains a rollback
+path. With neither marker nor journal the helper exits without loading the
+framework or modifying preferences. launchd retries unsuccessful runs with a
+15-second throttle; successful runs exit.
+
+This supplies local setup completion only. It does not create activation
+tickets, Apple Account credentials, a HomeKit home, network pairing or identity.
+`make -C VPhoneGuestComponents test-homepod-setup` passed journal creation,
+idempotence, absent/existing-key restoration, unrelated edits, synchronization
+failure retention, invalid/duplicate journal rejection and file-mode checks.
+Native transition tests additionally model the donor's creation-only event and
+verify one fresh-completion event, one existing-sentinel recovery event, no
+opt-out publication, and no publication after failed verification. This
+conditional relies on the analyzed retail HomePod path (`ForceNoBuddy=false`);
+internal NonUI/unsupported overrides and concurrent external sentinel mutation
+are outside that evidence. The tvOS arm64e helper builds and signs with system
+SDK/framework dependencies.
+All 35 owning Xcode catalog/selection tests passed, including preset roundtrips,
+version/family gates and exclusion of Apple TV payloads.
+The process harness additionally covers both launch orderings, an in-flight
+launch, exact executable matching, identity changes before signaling, denied
+identity lookup, enumeration failure, timeout without stronger signals and
+refusal to operate as another user.
+
+Xcode MCP builds of `vphone-vm` and the iOS-device `vphoned` target passed.
+The aggregate `VPhone` scheme is absent from MCP's scheme list, so the finished
+bundle was built with the documented `xcodebuild` fallback and passed both bundle
+admission and `codesign --verify --deep --strict`. The initial offline build log is
+`.build/homepod-ui-research/metal-debug-setup-bundle-build.log`; subsequent live
+iteration logs are in `.build/homepod-ui-research/live-metal-debug-setup/`.
+
+## Live validation scope
+
+The completed tests cover signed bundle installation, real Metal drawable
+presentation and window lifecycle, native XPC queries and representative
+reversible writes, setup completion from an unconfigured baseline, late
+HPSetup teardown, repeat boot and opt-out restoration. All 29 operations are
+exposed and runtime ABI-available; all seven query operations return native
+replies. The remaining write methods are submission-only native APIs. Their
+physical Wi-Fi, tuning, update/HomeKit and Apple-service effects depend on guest
+hardware and real provisioning; interface availability is not proof of those
+effects. Audible tone/speech output and cloud Siri requests were not established.
+TestLEDDraw's internal-content gate is documented rather than bypassed.
+
+## Live investigation (2026-10-22)
+
+The owner authorized bundle updates. Launchpad installed
+`2.11.0-local.352ddbd3` with `--keep-default`, rebound only `homepod-mini`, and
+updated its guest environment through the normal helper. An APFS clone of the
+stopped VM disk and its original patch selection were saved under
+`.build/homepod-ui-research/live-metal-debug-setup/` before mutation.
+
+- The guest booted in five seconds. All 29 runtime method signatures are
+ available. All seven reads returned native replies, including 150 default
+ records and 2,917 feature flags. Volume changed from 0.53 to 0.58 and read
+ back within Float precision, then was restored. A debug default changed and
+ reset with readback. Tone 0 was submitted and stopped; audible output has not
+ yet been established.
+- The real HomePod Controls window shows the complete grouped operation menu,
+ argument editors and animation/phase choices. Native volume input produced
+ the white HUD through the Metal renderer. A native replay with 40 red RGB
+ triples produced nineteen red HID pixels and lit icon channels; the real cap
+ rendered red. Evidence includes `native-volume-metal.png` and
+ `native-replay-red-metal.png` in that directory.
+- Further native tracing establishes prerequisites that are now described in
+ the catalog help: `render:` needs `HomePodBuddyConnection=1` and SoundBoard
+ restart to create its debug Buddy controller. `sendLEDCommand:` requires the
+ TestLEDDraw activity, created only on internal-content builds. Retail firmware
+ may accept and ignore it; this is distinct from shader or wire-format failure.
+ The native all-color grammar is `all 255 0 0` (channels divided by 256), and an
+ empty command clears TestLEDDraw. Replay works independently of those gates.
+ Its exact order is nineteen Siri RGB triples, two icon RGB triples, then
+ nineteen AOD RGB triples. Times are deltas from the first timestamp; a single
+ black frame replaces replay and ends it safely. Empty arrays are rejected
+ because the native implementation indexes the first element unconditionally.
+- `SoundBoardFinishedSetup=false` does not contradict configured startup. It
+ is a legacy persisted diagnostic record, while functional activity/application
+ gates use `SBSetupController.deviceNeedsSetup` → native SetupAssistant state.
+ Already-completed startup intentionally skips the legacy controller and goes
+ directly to post-setup initialization. The bounded source analysis and REA
+ IDs are in `soundboard-finished-setup-findings.md` under the evidence directory's
+ parent. Real HomeKit provisioning remains separate.
+- Initial opt-out restored the two original values and removed the journal.
+ A temporary mobile fixture then removed exactly the two completion keys and
+ called stock sentinel preparation: native NeedsSetup became true and initial
+ run completion false. Restarting SoundBoard brought HPSetup to the foreground
+ and disabled Siri, establishing a real unconfigured baseline.
+- **Late-start defect reproduced and corrected:** with that unconfigured baseline, the shipped helper was
+ deliberately disabled at boot and then started after HPSetup was active.
+ It reported success and changed the native predicates, but HPSetup remained
+ foreground and Siri remained disabled. The flags alone do not prove successful
+ late completion. Captured native logs show `setupdone` received,
+ `_setupFinished` and `Doing post setup init`; that path alone does not dismiss
+ HPSetup. A graceful termination of only the verified HPSetup process immediately
+ removed the foreground activity and enabled Siri/Hey Siri. The helper now
+ performs that exact teardown after verified completion and reports success
+ only after disappearance. Bundle `2.11.0-local.a2a1cf33` passed the controlled
+ late-start test: native needs-setup was false, initial-run completion true,
+ HPSetup process count zero, and Siri/Hey Siri enabled. Its bundled and running
+ helper hashes matched. Logs showed graceful HPSetup exit and released
+ assertions. This first correction also exposed duplicate completion
+ notifications; the conditional publication described above addresses that.
+- Opt-out on the corrected helper restored both originally absent completion
+ keys, removed the inverse journal and returned native NeedsSetup=true /
+ CompletedInitialRun=false. A new boot ran HPSetup in the foreground with Siri
+ disabled, confirming restoration rather than just marker removal.
+
+The final bundle is `2.11.0-local.26745ac8`, installed through Launchpad and
+bound only to `homepod-mini`; the library default and other VMs are unchanged.
+The final helper SHA-256 is
+`1e7ec8eb39b18055ab0e11d4aa2b719f964b86397d06cd59583baef48f103f8e`, verified
+against bytes read back from the running guest. Final results:
+
+- With HPSetup deliberately running before the helper, captured SoundBoard logs
+ contain exactly one `setupdone`, one `_setupFinished`, and one `Doing post
+ setup init`. HPSetup exited by SIGTERM, its assertions were invalidated, and
+ native Siri/Hey Siri became enabled. The helper reported success only after
+ the process disappeared.
+- A fresh normal boot from native NeedsSetup=true / CompletedInitialRun=false
+ completed successfully without HPSetup remaining. A second normal boot
+ reported fresh success, preserved the original absent-key journal, and kept
+ Siri/Hey Siri enabled with no foreground setup activity. These cover normal
+ concurrent startup and deliberately late helper startup; only the latter
+ has a controlled, observed process ordering.
+- Native Siri `On` then `Thinking` produced changing multicolor inner-bank
+ frames through SoundBoard → virtual MiniDisplay HID → guest WebSocket → the
+ actual Metal cap. The live window redrew when zoomed and restored. It also
+ redrew after minimize/restore; restoring required the owner because the UI
+ automation tool could not reactivate a minimized `.bundle` through Launch
+ Services. Native volume HUD and replay-color presentation were tested above.
+- Restarting SoundBoard recovered debug replies. Restarting vphoned interrupted
+ the request as expected, then display reports and queries resumed; the new
+ display generation had zero rejected reports. The short disconnect's blank
+ frame was not separately captured.
+- The actual Controls menu lists all 29 operations. Its live volume reply and
+ final Center/TapRegistered `coalesced:true` editor were inspected. Other
+ hardware/service-dependent effects remain within the boundary above.
+- Cleanup reset `HomePodBuddyConnection` to its stock false value, restarted
+ SoundBoard, restored the original volume 0.53, and removed the temporary
+ fixture job/output. Boot had removed the fixture binary/plist from `/var/tmp`.
+ The final selection is the `homepod-mini` preset with empty override lists,
+ setup helper enabled, native setup complete, and the final GUI VM running.
+- No SoundBoard, vphoned or setup-helper crash report was present. Existing
+ guest `ProxiedCrashCopier`, locationd and other service reports remain; the
+ result is not a claim that all donor daemons run without faults.
+
+Evidence is in `.build/homepod-ui-research/live-metal-debug-setup/`: final
+bundle build log; `final-late-*`, `final-normal-*`, `final-repeat-*` and
+`corrected-optout-*` native records; `final-native-siri-metal*.png`,
+`final-native-metal-restored.png`, and Controls screenshots. The APFS disk clone
+and original patch selection are retained there for local recovery. No
+activation ticket, Apple Account or HomeKit identity was fabricated. The
+fixture is not shipped in the bundle.
+
diff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
index 50a3bd3f..031cbfa9 100644
--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
@@ -53,6 +53,8 @@
<true/>
<key>com.apple.backboardd.launchapplications</key>
<true/>
+ <key>com.apple.debuginfo.soundboard</key>
+ <true/>
<key>com.apple.developer.hid.virtual.device</key>
<true/>
<key>com.apple.developer.networking.HotspotHelper</key>
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
index a3a18e25..71252ff8 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -25,6 +25,7 @@ extension GuestAPI {
executeGyroscope,
executeAttitude,
executeHomePodDisplay,
+ executeHomePodDebug,
]
for area in areas {
if let result = try area(method, params) {
diff --git a/VPhoneDaemon/Daemon/GuestAPI+HomePodDebug.swift b/VPhoneDaemon/Daemon/GuestAPI+HomePodDebug.swift
new file mode 100644
index 00000000..b1c38890
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+HomePodDebug.swift
@@ -0,0 +1,45 @@
+import Foundation
+import VphonedNative
+
+/// SoundBoard's complete SBSDebugInterface, restricted to its fixed operation
+/// catalog. The native bridge checks each method's ABI before invoking it.
+enum GuestHomePodDebug {
+ static var capabilities: [String] {
+ vp_homepod_debug_available() ? ["homepod_debug"] : []
+ }
+
+ static func call(_ operation: String, arguments: [String: Any] = [:]) throws -> [String: Any] {
+ let encoded = try JSONSerialization.data(withJSONObject: arguments, options: [.sortedKeys])
+ guard let text = String(data: encoded, encoding: .utf8),
+ let json = operation.withCString({ operation in
+ text.withCString { vp_homepod_debug_copy_json(operation, $0) }
+ })
+ else { throw GuestAPIError.operationFailed("Could not call SoundBoard debug interface") }
+ defer { free(json) }
+ let data = Data(bytes: json, count: strlen(json))
+ guard let envelope = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ throw GuestAPIError.operationFailed("Invalid SoundBoard debug reply")
+ }
+ guard envelope["ok"] as? Bool == true else {
+ throw GuestAPIError.operationFailed(envelope["error"] as? String ?? "SoundBoard debug operation failed")
+ }
+ return envelope["result"] as? [String: Any] ?? [:]
+ }
+}
+
+extension GuestAPI {
+ static func executeHomePodDebug(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "homepod.debug.catalog":
+ return try GuestHomePodDebug.call("catalog")
+ case "homepod.debug.call":
+ let operation = try string(params, "operation")
+ guard let arguments = params["arguments"] as? [String: Any] else {
+ throw GuestAPIError.invalidRequest("arguments must be an object")
+ }
+ return try GuestHomePodDebug.call(operation, arguments: arguments)
+ default:
+ return nil
+ }
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 67d2681e..16dd8c69 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -150,7 +150,7 @@ enum GuestAPI {
"motion_gyroscope",
"motion_gyroscope_toggle",
"motion_attitude",
- ] + pointerCapabilities() + GuestHomePodDisplay.capabilities,
+ ] + pointerCapabilities() + GuestHomePodDisplay.capabilities + GuestHomePodDebug.capabilities,
]
}
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index c041c418..d0c3c920 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -21,6 +21,10 @@ void vp_homepod_display_start(void);
bool vp_homepod_display_is_configured(void);
/// Latest guest-written MiniDisplay frame and geometry, malloc-owned JSON.
char *vp_homepod_display_copy_json(void);
+/// SoundBoardServices debug controls, available only on HomePod firmware.
+bool vp_homepod_debug_available(void);
+/// Validated operation result or error, returned as malloc-owned JSON.
+char *vp_homepod_debug_copy_json(const char *operation, const char *arguments_json);
/// Load the IOKit digitizer symbols used for multi-finger injection. Idempotent,
/// safe to call more than once; returns false (injection then stays a no-op)
diff --git a/VPhoneDaemon/Native/vphoned_homepod_debug.m b/VPhoneDaemon/Native/vphoned_homepod_debug.m
new file mode 100644
index 00000000..2dac6082
--- /dev/null
+++ b/VPhoneDaemon/Native/vphoned_homepod_debug.m
@@ -0,0 +1,396 @@
+/* SoundBoardServices 27.0 SBSDebugInterface. The selector/argument inventory is
+ * the complete SBSDebugInfoImplementer protocol in AudioAccessory5,1 24J361.
+ * This bridge calls the framework's own XPC client; it does not inject code into
+ * SoundBoard. See Research/Firmware/homepod_mini_support.md. */
+#import <Foundation/Foundation.h>
+#import <objc/message.h>
+#import <objc/runtime.h>
+#include <dlfcn.h>
+#include <math.h>
+#include <unistd.h>
+
+static NSDictionary *argument(NSString *name, NSString *type, id initial, NSString *help) {
+ return @{ @"name": name, @"type": type, @"initial": initial, @"help": help };
+}
+
+static NSDictionary *operation(NSString *selector, NSString *title, NSString *group,
+ NSArray *arguments, NSString *reply, NSString *help) {
+ return @{ @"id": selector, @"title": title, @"group": group,
+ @"arguments": arguments, @"reply": reply, @"help": help };
+}
+
+static NSArray<NSDictionary *> *operations(void) {
+ static NSArray *catalog;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ NSDictionary *(^text)(NSString *, NSString *) = ^(NSString *name, NSString *help) {
+ return argument(name, @"string", @"", help);
+ };
+ NSDictionary *(^array)(NSString *, NSString *) = ^(NSString *name, NSString *help) {
+ return argument(name, @"array", @[], help);
+ };
+ catalog = @[
+ operation(@"getAllDebugInfo:", @"Read All Debug Info", @"Diagnostics", @[], @"object", @"Read SoundBoard's complete diagnostic dictionary."),
+ operation(@"getSelectDebugInfo:reply:", @"Read Selected Debug Info", @"Diagnostics", @[array(@"keys", @"Diagnostic key names from Read All Debug Info.")], @"object", @"Read a subset of SoundBoard diagnostics."),
+ operation(@"getLEDInfo:", @"Read LED Info", @"Display", @[], @"object", @"Read SoundBoard's display, media and power state."),
+ operation(@"sendLEDCommand:", @"Send LED Command", @"Display", @[text(@"command", @"VisualSource command, for example all 255 0 0. Separate commands with newlines; an empty string clears TestLEDDraw.")], @"none", @"TestLEDDraw requires an internal-content build. Retail guests may accept this command without drawing; use Set LED Contents for native frame replay."),
+ operation(@"render:", @"Render Animation", @"Display", @[argument(@"options", @"dictionary", @{@"animation": @"setup", @"phase": @"On"}, @"Animation name and phase; both keys are required.")], @"none", @"Enable HomePodBuddyConnection with Set User Default (value 1), then restart SoundBoard before rendering animations."),
+ operation(@"setLEDContents:", @"Set LED Contents", @"Display", @[argument(@"contents", @"replay", @[@{@"LedValuesTimestamp": @0, @"LedValuesData": @{@"fill": @[@0, @0, @0]}}], @"Nonempty frame array. Each frame has a UInt64 LedValuesTimestamp (mach ticks relative to the first frame) and LedValuesData: {\"base64\":\"…\"}, {\"fill\":[r,g,b]}, or {\"rgb\":[[r,g,b],…]}. HomePod mini uses 19 Siri, 2 icon, then 19 AOD Float RGB triples (480 bytes). A single black frame replaces and ends replay.")], @"none", @"Replay native display frames through SoundBoard's display service."),
+ operation(@"setBootSpinner:", @"Set Boot Spinner", @"Display", @[argument(@"enabled", @"bool", @NO, @"Show or hide the boot spinner.")], @"none", @"Control SoundBoard's boot spinner."),
+ operation(@"getVolume:", @"Read SoundBoard Volume", @"Audio", @[], @"float", @"Read SoundBoard's Audio/Video volume."),
+ operation(@"setVolume:", @"Set SoundBoard Volume", @"Audio", @[argument(@"value", @"float", @0.5, @"Audio/Video volume, 0 to 1.")], @"none", @"Set volume through SoundBoard's volume manager."),
+ operation(@"playTone:", @"Play Tone", @"Audio", @[argument(@"tone", @"uint32", @0, @"Native UInt32 tone identifier.")], @"none", @"Play a native SoundBoard UI tone."),
+ operation(@"stopTone:", @"Stop Tone", @"Audio", @[argument(@"tone", @"uint32", @0, @"The tone identifier used by Play Tone.")], @"none", @"Stop a native SoundBoard UI tone."),
+ operation(@"siriSay:", @"Speak with Siri", @"Audio", @[text(@"text", @"Text passed to SoundBoard's Siri manager.")], @"none", @"Ask SoundBoard's Siri manager to speak text."),
+ operation(@"sendButtonCommand:", @"Send Button Event", @"Input", @[argument(@"event", @"button", @{@"button": @3, @"action": @2, @"numberOfTaps": @1, @"startMachTime": @0, @"deviceSideways": @NO, @"coalesced": @YES}, @"Buttons: 1 Minus, 2 Plus, 3 Center, 4 Cover. Actions: 1 TouchMightHaveBegun, 2 TapRegistered, 3 HoldBegan, 4 HoldEnded, 5 TouchCancelled. For TapRegistered, coalesced:true sends the final tap gesture; use false for raw, uncoalesced events. Use HPButtonEvent fields, or {\"base64\":\"…\"} for an existing secure archive.")], @"none", @"Create and securely archive an HPButtonEvent for SoundBoard."),
+ operation(@"getTuningInfo:", @"Read Tuning Info", @"Tuning", @[], @"object", @"Read SoundBoard's exposed tuning boxes and parameters."),
+ operation(@"setTuningInfoOnBox:at:withValue:", @"Set Tuning Value", @"Tuning", @[text(@"box", @"Box name from Read Tuning Info."), text(@"parameter", @"Parameter name from Read Tuning Info."), argument(@"value", @"float", @0, @"Native Float tuning value.")], @"none", @"Change an exposed tuning parameter."),
+ operation(@"getUserDefaults:", @"Read User Defaults", @"Preferences", @[], @"object", @"Read SoundBoard's debug defaults and their metadata."),
+ operation(@"setUserDefaults:withValue:", @"Set User Default", @"Preferences", @[text(@"name", @"Default name from Read User Defaults."), text(@"value", @"String parsed by SoundBoard according to the default's native type.")], @"none", @"Set one SoundBoard debug default."),
+ operation(@"resetUserDefault:", @"Reset User Default", @"Preferences", @[text(@"name", @"Default name from Read User Defaults.")], @"none", @"Restore one SoundBoard debug default."),
+ operation(@"resetAllUserDefaults", @"Reset All User Defaults", @"Preferences", @[], @"none", @"Restore every SoundBoard debug default."),
+ operation(@"getFeatureFlags:", @"Read Feature Flags", @"Preferences", @[], @"object", @"Read SoundBoard's exposed feature flags."),
+ operation(@"setFeatureFlags:", @"Set Feature Flags", @"Preferences", @[array(@"flags", @"Feature flag dictionary representations returned by Read Feature Flags.")], @"none", @"Submit feature flag dictionary representations."),
+ operation(@"triggerWiFiCoreCapture:", @"Capture Wi-Fi Diagnostics", @"Network", @[text(@"reason", @"Reason included in the Wi-Fi CoreCapture request.")], @"none", @"Trigger SoundBoard's Wi-Fi CoreCapture facility."),
+ operation(@"setWifiEnabled:", @"Set Wi-Fi Enabled", @"Network", @[argument(@"enabled", @"bool", @YES, @"Turn Wi-Fi on or off.")], @"none", @"Change SoundBoard's Wi-Fi state."),
+ operation(@"disassociateCurrentNetwork", @"Disassociate Current Network", @"Network", @[], @"none", @"Disconnect SoundBoard from its current Wi-Fi network."),
+ operation(@"disassociateNetworkWithName:", @"Disassociate Named Network", @"Network", @[text(@"name", @"Wi-Fi network name.")], @"none", @"Disassociate a Wi-Fi network by name."),
+ operation(@"injectSWUpdateToHome:", @"Inject Home Software Update", @"Software Update", @[argument(@"options", @"dictionary", @{}, @"Native keys: serverAssetAlgorithm, serverAssetMeasurement, serverAssetURL, majorVer, minorVer, state, updateVer, productBuildVersion, downloadSize.")], @"none", @"Inject a software update description into the Home."),
+ operation(@"setHomeUpdateState:", @"Set Home Update State", @"Software Update", @[argument(@"state", @"int64", @0, @"Native signed 64-bit Home update state.")], @"none", @"Change the Home's software update state."),
+ operation(@"clearHomeSWUpdate", @"Clear Home Software Update", @"Software Update", @[], @"none", @"Clear the injected Home software update."),
+ operation(@"suScanForSoftwareUpdate", @"Scan for Software Update", @"Software Update", @[], @"none", @"Ask SoundBoard to scan for a software update."),
+ ];
+ });
+ return catalog;
+}
+
+static Class debugClass(void) {
+#ifndef VP_HOMEPOD_DEBUG_TESTING
+ if (access("/System/Library/CoreServices/SoundBoard.app/SoundBoard", F_OK) != 0) return Nil;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ dlopen("/System/Library/PrivateFrameworks/SoundBoardServices.framework/SoundBoardServices", RTLD_NOW);
+ });
+#endif
+ return NSClassFromString(@"SBSDebugInterface");
+}
+
+bool vp_homepod_debug_available(void) { return debugClass() != Nil; }
+
+static const char *argumentEncoding(NSString *type) {
+ if ([type isEqual:@"bool"]) return @encode(BOOL);
+ if ([type isEqual:@"float"]) return @encode(float);
+ if ([type isEqual:@"uint32"]) return @encode(uint32_t);
+ if ([type isEqual:@"int64"]) return @encode(int64_t);
+ return @encode(id);
+}
+
+static BOOL matchesSignature(NSMethodSignature *signature, NSDictionary *spec) {
+ NSArray *arguments = spec[@"arguments"];
+ BOOL hasReply = ![spec[@"reply"] isEqual:@"none"];
+ if (!signature || strcmp(signature.methodReturnType, @encode(void)) != 0 ||
+ signature.numberOfArguments != 2 + arguments.count + (hasReply ? 1 : 0)) return NO;
+ for (NSUInteger i = 0; i < arguments.count; i++) {
+ if (strcmp([signature getArgumentTypeAtIndex:i + 2], argumentEncoding(arguments[i][@"type"])) != 0) return NO;
+ }
+ return !hasReply || strcmp([signature getArgumentTypeAtIndex:arguments.count + 2], @encode(void (^)(id))) == 0;
+}
+
+static id JSONValue(id value, NSUInteger depth) {
+ if (!value || value == NSNull.null) return NSNull.null;
+ if (depth > 24) return @{@"error": @"Reply exceeded nesting limit"};
+ if ([value isKindOfClass:NSString.class] || [value isKindOfClass:NSNumber.class]) return value;
+ if ([value isKindOfClass:NSDictionary.class]) {
+ NSMutableDictionary *out = NSMutableDictionary.dictionary;
+ for (id key in value) out[[key description]] = JSONValue(value[key], depth + 1);
+ return out;
+ }
+ if ([value isKindOfClass:NSArray.class] || [value isKindOfClass:NSSet.class]) {
+ NSMutableArray *out = NSMutableArray.array;
+ for (id item in value) [out addObject:JSONValue(item, depth + 1)];
+ return out;
+ }
+ if ([value isKindOfClass:NSData.class]) {
+ NSMutableDictionary *out = [@{@"base64": [value base64EncodedStringWithOptions:0], @"length": @([value length])} mutableCopy];
+ Class infoClass = NSClassFromString(@"SBSDefaultInfo");
+ if (infoClass) {
+ NSSet *classes = [NSSet setWithObjects:infoClass, NSDictionary.class, NSArray.class, NSString.class, NSNumber.class, NSData.class, NSNull.class, nil];
+ id decoded = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:value error:NULL];
+ if (decoded) out[@"decoded"] = JSONValue(decoded, depth + 1);
+ }
+ return out;
+ }
+ if ([value isKindOfClass:NSURL.class]) return [value absoluteString];
+ if ([value isKindOfClass:NSDate.class]) return @([value timeIntervalSince1970]);
+ NSString *name = NSStringFromClass([value class]);
+ if ([name isEqual:@"SBSFeatureFlag"]) return JSONValue([value valueForKey:@"dictionaryRepresentation"], depth + 1);
+ if ([name isEqual:@"SBSDefaultInfo"]) {
+ NSMutableDictionary *out = NSMutableDictionary.dictionary;
+ for (NSString *key in @[@"stringForUserDefault", @"userDescription", @"defaultValue", @"isBool", @"isDouble", @"rangeMin", @"rangeMax", @"requiresReinit", @"defaultType", @"valueType"]) {
+ out[key] = JSONValue([value valueForKey:key], depth + 1);
+ }
+ return out;
+ }
+ return @{@"class": name, @"description": [value description]};
+}
+
+static BOOL nativeNumber(id value) {
+ return [value isKindOfClass:NSNumber.class] && CFGetTypeID((__bridge CFTypeRef)value) != CFBooleanGetTypeID();
+}
+static BOOL nativeUnsigned(id value, uint64_t maximum) {
+ if (!nativeNumber(value)) return NO;
+ const char *type = [value objCType];
+ if (strcmp(type, @encode(float)) == 0 || strcmp(type, @encode(double)) == 0) return NO;
+ return [value compare:@0] != NSOrderedAscending && [value compare:@(maximum)] != NSOrderedDescending;
+}
+static BOOL nativeSigned(id value) {
+ if (!nativeNumber(value)) return NO;
+ const char *type = [value objCType];
+ return strcmp(type, @encode(double)) != 0 && strcmp(type, @encode(float)) != 0 &&
+ [value compare:@(INT64_MIN)] != NSOrderedAscending && [value compare:@(INT64_MAX)] != NSOrderedDescending;
+}
+static BOOL nativeBoolean(id value) {
+ return [value isKindOfClass:NSNumber.class] && CFGetTypeID((__bridge CFTypeRef)value) == CFBooleanGetTypeID();
+}
+
+static NSUInteger replayColorCount(void) {
+#ifdef VP_HOMEPOD_DEBUG_TESTING
+ return 40;
+#else
+ NSDictionary *configuration = [NSDictionary dictionaryWithContentsOfFile:@"/usr/share/vphone/HomePodDisplay.plist"];
+ NSData *coordinates = configuration[@"MDXCoords"], *hardware = configuration[@"MDHWVersion"];
+ if (![coordinates isKindOfClass:NSData.class] || !coordinates.length || coordinates.length % 4 ||
+ ![hardware isKindOfClass:NSData.class] || hardware.length != 4) return 0;
+ uint32_t version;
+ memcpy(&version, hardware.bytes, sizeof(version));
+ NSUInteger leds = coordinates.length / 4;
+ if (leds > 4096) return 0;
+ // Peppy animation buffers have one RGB triple per LED in each bank plus
+ // the two volume icons. The replay buffer uses Float channels, unlike HID.
+ return leds * (version > 2 ? 2 : 1) + 2;
+#endif
+}
+
+static id replayContents(id value, NSString **error) {
+ if (![value isKindOfClass:NSArray.class] || [value count] == 0) {
+ *error = @"contents must be a nonempty array of replay frame dictionaries"; return nil;
+ }
+ NSUInteger count = replayColorCount();
+ if (!count) { *error = @"Display geometry is unavailable; enable the HomePod top-cap patch before replaying frames"; return nil; }
+ NSMutableArray *result = NSMutableArray.array;
+ uint64_t previous = 0;
+ for (id frame in value) {
+ if (![frame isKindOfClass:NSDictionary.class] || !nativeUnsigned(frame[@"LedValuesTimestamp"], UINT64_MAX)) {
+ *error = @"Every replay frame needs a UInt64 LedValuesTimestamp"; return nil;
+ }
+ uint64_t timestamp = [frame[@"LedValuesTimestamp"] unsignedLongLongValue];
+ if (result.count && timestamp < previous) { *error = @"Replay timestamps must be in ascending order"; return nil; }
+ previous = timestamp;
+ id input = frame[@"LedValuesData"];
+ if (![input isKindOfClass:NSDictionary.class]) { *error = @"LedValuesData must be a base64, fill, or rgb object"; return nil; }
+ NSData *data;
+ if ([input[@"base64"] isKindOfClass:NSString.class]) {
+ data = [[NSData alloc] initWithBase64EncodedString:input[@"base64"] options:0];
+ } else {
+ NSArray *colors = input[@"rgb"];
+ if (input[@"fill"]) {
+ NSMutableArray *fill = NSMutableArray.array;
+ for (NSUInteger i = 0; i < count; i++) [fill addObject:input[@"fill"]];
+ colors = fill;
+ }
+ if (![colors isKindOfClass:NSArray.class] || colors.count != count) {
+ *error = [NSString stringWithFormat:@"Replay rgb needs %lu RGB triples", (unsigned long)count]; return nil;
+ }
+ NSMutableData *encoded = [NSMutableData dataWithCapacity:count * 3 * sizeof(float)];
+ for (id color in colors) {
+ if (![color isKindOfClass:NSArray.class] || [color count] != 3) { *error = @"Replay RGB values must be three-element arrays"; return nil; }
+ for (id channel in color) {
+ if (!nativeNumber(channel) || !isfinite([channel doubleValue]) || fabs([channel doubleValue]) > FLT_MAX) {
+ *error = @"Replay RGB channels must be finite Float numbers"; return nil;
+ }
+ float scalar = [channel floatValue];
+ [encoded appendBytes:&scalar length:sizeof(scalar)];
+ }
+ }
+ data = encoded;
+ }
+ if (!data || data.length != count * 3 * sizeof(float)) {
+ *error = [NSString stringWithFormat:@"Replay LedValuesData needs exactly %lu bytes", (unsigned long)(count * 3 * sizeof(float))]; return nil;
+ }
+ NSMutableDictionary *converted = [frame mutableCopy];
+ converted[@"LedValuesData"] = data;
+ [result addObject:converted];
+ }
+ return result;
+}
+
+static id buttonData(id value, NSString **error) {
+ if (![value isKindOfClass:NSDictionary.class]) { *error = @"event must be an HPButtonEvent object or a base64 archive object"; return nil; }
+ if (value[@"base64"]) {
+ if (![value[@"base64"] isKindOfClass:NSString.class]) { *error = @"base64 must be a string"; return nil; }
+ NSData *data = [[NSData alloc] initWithBase64EncodedString:value[@"base64"] options:0];
+ if (!data) *error = @"event base64 is invalid";
+ return data;
+ }
+#ifndef VP_HOMEPOD_DEBUG_TESTING
+ dlopen("/System/Library/PrivateFrameworks/SoundBoardFramework.framework/SoundBoardFramework", RTLD_NOW);
+#endif
+ Class cls = NSClassFromString(@"HPButtonEvent");
+ if (!cls) { *error = @"HPButtonEvent is unavailable"; return nil; }
+ id event = [cls new];
+ for (NSString *key in @[@"button", @"action", @"numberOfTaps", @"startMachTime", @"deviceSideways", @"coalesced"]) {
+ id field = value[key];
+ BOOL valid;
+ if ([key isEqual:@"deviceSideways"] || [key isEqual:@"coalesced"]) valid = nativeBoolean(field);
+ else if ([key isEqual:@"numberOfTaps"]) valid = nativeSigned(field) && [field longLongValue] >= 0;
+ else valid = nativeUnsigned(field, UINT64_MAX);
+ if (!valid) { *error = [NSString stringWithFormat:@"event.%@ has an invalid type or is outside its native integer range", key]; return nil; }
+ [event setValue:field forKey:key];
+ }
+ id data = [event valueForKey:@"data"];
+ if (![data isKindOfClass:NSData.class]) { *error = @"HPButtonEvent could not be securely archived"; return nil; }
+ return data;
+}
+
+static id validatedArgument(id value, NSDictionary *spec, NSString **error) {
+ NSString *type = spec[@"type"], *name = spec[@"name"];
+ if ([type isEqual:@"button"]) return buttonData(value, error);
+ if ([type isEqual:@"replay"]) return replayContents(value, error);
+ Class cls = Nil;
+ if ([type isEqual:@"string"]) cls = NSString.class;
+ if ([type isEqual:@"array"]) cls = NSArray.class;
+ if ([type isEqual:@"dictionary"]) cls = NSDictionary.class;
+ if (cls) {
+ if ([value isKindOfClass:cls]) return value;
+ } else if ([value isKindOfClass:NSNumber.class]) {
+ double number = [value doubleValue];
+ if ([type isEqual:@"bool"] && nativeBoolean(value)) return value;
+ if ([type isEqual:@"float"] && nativeNumber(value) && isfinite(number) && fabs(number) <= FLT_MAX) return value;
+ if ([type isEqual:@"uint32"] && nativeUnsigned(value, UINT32_MAX)) return value;
+ if ([type isEqual:@"int64"] && nativeSigned(value)) return value;
+ }
+ *error = [NSString stringWithFormat:@"%@ must be %@", name, type];
+ return nil;
+}
+
+@interface VPHomePodDebugReply : NSObject
+@property(nonatomic) id value;
+@property(nonatomic) NSString *error;
+@property(nonatomic) BOOL closed;
+@end
+@implementation VPHomePodDebugReply
+@end
+
+static NSDictionary *executeOperation(NSDictionary *spec, NSDictionary *arguments, id client, NSString **error) {
+ SEL selector = NSSelectorFromString(spec[@"id"]);
+ NSMethodSignature *signature = [client methodSignatureForSelector:selector];
+ if (!matchesSignature(signature, spec)) { *error = @"SoundBoardServices method signature differs from the supported HomePod firmware"; return nil; }
+ NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
+ invocation.selector = selector;
+ invocation.target = client;
+ // Transformed NSData arguments must stay alive until retainArguments takes
+ // ownership, even when ARC shortens local lifetimes in an optimized build.
+ __attribute__((objc_precise_lifetime)) NSMutableArray *objects = NSMutableArray.array;
+ NSArray *parameters = spec[@"arguments"];
+ for (NSUInteger i = 0; i < parameters.count; i++) {
+ NSDictionary *parameter = parameters[i];
+ id value = validatedArgument(arguments[parameter[@"name"]], parameter, error);
+ if (!value) return nil;
+ [objects addObject:value];
+ NSString *type = parameter[@"type"];
+ if ([type isEqual:@"float"]) { float scalar = [value floatValue]; [invocation setArgument:&scalar atIndex:i + 2]; }
+ else if ([type isEqual:@"bool"]) { BOOL scalar = [value boolValue]; [invocation setArgument:&scalar atIndex:i + 2]; }
+ else if ([type isEqual:@"uint32"]) { uint32_t scalar = [value unsignedIntValue]; [invocation setArgument:&scalar atIndex:i + 2]; }
+ else if ([type isEqual:@"int64"]) { int64_t scalar = [value longLongValue]; [invocation setArgument:&scalar atIndex:i + 2]; }
+ else { [invocation setArgument:&value atIndex:i + 2]; }
+ }
+ if ([spec[@"id"] isEqual:@"setVolume:"] && ([arguments[@"value"] doubleValue] < 0 || [arguments[@"value"] doubleValue] > 1)) {
+ *error = @"Volume must be between 0 and 1"; return nil;
+ }
+ if ([spec[@"id"] isEqual:@"render:"]) {
+ NSDictionary *options = arguments[@"options"];
+ if (![options[@"animation"] isKindOfClass:NSString.class] || ![options[@"phase"] isKindOfClass:NSString.class]) {
+ *error = @"Render options require animation and phase strings"; return nil;
+ }
+ }
+ NSString *replyKind = spec[@"reply"];
+ if ([replyKind isEqual:@"none"]) {
+ [invocation retainArguments];
+ [invocation invoke];
+ // SBSDebugInterface has no completion for writes. Do not claim applied.
+ return @{@"operation": spec[@"id"], @"submitted": @YES};
+ }
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
+ VPHomePodDebugReply *reply = [VPHomePodDebugReply new];
+ void (^complete)(id) = ^(id value) {
+ @synchronized (reply) {
+ if (reply.closed) return;
+ @try { reply.value = JSONValue(value, 0); }
+ @catch (NSException *exception) { reply.error = exception.reason ?: exception.name; }
+ reply.closed = YES;
+ }
+ dispatch_semaphore_signal(done);
+ };
+ id completion;
+ if ([replyKind isEqual:@"float"]) completion = [^(float value) { complete(@(value)); } copy];
+ else completion = [^(id value) { complete(value); } copy];
+ [invocation setArgument:&completion atIndex:parameters.count + 2];
+ [invocation retainArguments];
+ [invocation invoke];
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC)) != 0) {
+ @synchronized (reply) { reply.closed = YES; }
+ *error = @"SoundBoard did not reply within 3 seconds. Check that it is running and vphoned has com.apple.debuginfo.soundboard.";
+ return nil;
+ }
+ if (reply.error) { *error = reply.error; return nil; }
+ return @{@"operation": spec[@"id"], @"value": reply.value ?: NSNull.null};
+}
+
+char *vp_homepod_debug_copy_json(const char *operationName, const char *argumentsJSON) {
+ @autoreleasepool {
+ NSDictionary *result = nil;
+ NSString *error = nil;
+ @try {
+ Class cls = debugClass();
+ if (!cls) error = @"SoundBoard debugging is available only on a HomePod guest";
+ else if (!operationName || strcmp(operationName, "catalog") == 0) {
+ NSMutableArray *catalog = NSMutableArray.array;
+ for (NSDictionary *spec in operations()) {
+ NSMutableDictionary *entry = [spec mutableCopy];
+ entry[@"available"] = @(matchesSignature([cls instanceMethodSignatureForSelector:NSSelectorFromString(spec[@"id"])], spec));
+ [catalog addObject:entry];
+ }
+ // HomePodBuddyTypes.Feature / FeaturePhase raw-value switch
+ // tables from SoundBoardFramework 24J361. The framework accepts
+ // animation names as spaced words, then forms lowerCamelCase.
+ result = @{@"available": @YES, @"interface": @"SBSDebugInterface", @"operations": catalog,
+ @"animations": @[@"none", @"lux thresholds", @"true tone", @"alarms", @"apple care", @"dropin", @"doorbell", @"factory reset", @"identify", @"intercom", @"now playing", @"proximity handoff", @"setup", @"siri", @"sae", @"siri sparkle", @"telephony", @"thermal overload", @"timers", @"bad boot args", @"crash blip", @"home kit sync", @"boot up", @"factory reset f w", @"low power"],
+ @"phases": @[@"On", @"Off", @"AirDrop", @"Sysdiagnose", @"Reset Tone", @"Plus Tap", @"Minus Tap", @"Center Tap", @"Approach", @"Cancel", @"Complete", @"Audio Passcode", @"Manual Passcode", @"Post Passcode", @"Timed Out", @"Listening", @"Thinking", @"Presenting", @"Mute", @"Unmute"]};
+ } else {
+ NSString *name = @(operationName);
+ NSDictionary *spec = nil;
+ for (NSDictionary *candidate in operations()) if ([candidate[@"id"] isEqual:name]) { spec = candidate; break; }
+ if (!spec) error = @"Unknown SoundBoard debug operation";
+ else {
+ NSData *data = [@(argumentsJSON ?: "{}") dataUsingEncoding:NSUTF8StringEncoding];
+ id arguments = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
+ if (![arguments isKindOfClass:NSDictionary.class]) error = @"arguments must be a JSON object";
+ else {
+ // Keep the framework's XPC client alive after asynchronous writes.
+ static id client;
+ @synchronized (cls) {
+ if (!client) client = [cls new];
+ result = executeOperation(spec, arguments, client, &error);
+ if (error) client = nil; // Reopen after a dead SoundBoard connection.
+ }
+ }
+ }
+ }
+ } @catch (NSException *exception) {
+ error = [NSString stringWithFormat:@"SoundBoard debug operation failed: %@", exception.reason ?: exception.name];
+ }
+ NSDictionary *envelope = error ? @{@"ok": @NO, @"error": error} : @{@"ok": @YES, @"result": result ?: @{}};
+ NSData *data = [NSJSONSerialization dataWithJSONObject:envelope options:NSJSONWritingSortedKeys error:NULL];
+ return data ? strndup(data.bytes, data.length) : strdup("{\"ok\":false,\"error\":\"Could not encode SoundBoard reply\"}");
+ }
+}
diff --git a/VPhoneDaemon/Tests/HomePodDebugTests.m b/VPhoneDaemon/Tests/HomePodDebugTests.m
new file mode 100644
index 00000000..0b97f468
--- /dev/null
+++ b/VPhoneDaemon/Tests/HomePodDebugTests.m
@@ -0,0 +1,181 @@
+#import <Foundation/Foundation.h>
+#define VP_HOMEPOD_DEBUG_TESTING 1
+#import "../Native/vphoned_homepod_debug.m"
+
+static id received;
+static BOOL neverReply;
+static void (^lateReply)(NSDictionary *);
+
+// Independently recovered method encodings from SoundBoardServices in
+// AudioAccessory5,1 27.0 (24J361), SHA-256
+// 5e5d68df84c8c3a54669a1618ea1cb8f3d12996b4ffe5d9be3828b62917cf41a.
+// Preserve this donor fixture separately from the bridge's argument catalog:
+// matching representative stub methods alone cannot establish full coverage.
+static NSDictionary<NSString *, NSString *> *donorMethodEncodings(void) {
+ return @{
+ @"getAllDebugInfo:": @"v24@0:8@?16",
+ @"getSelectDebugInfo:reply:": @"v32@0:8@16@?24",
+ @"getLEDInfo:": @"v24@0:8@?16",
+ @"sendLEDCommand:": @"v24@0:8@16",
+ @"render:": @"v24@0:8@16",
+ @"setLEDContents:": @"v24@0:8@16",
+ @"setBootSpinner:": @"v20@0:8B16",
+ @"getVolume:": @"v24@0:8@?16",
+ @"setVolume:": @"v20@0:8f16",
+ @"playTone:": @"v20@0:8I16",
+ @"stopTone:": @"v20@0:8I16",
+ @"siriSay:": @"v24@0:8@16",
+ @"sendButtonCommand:": @"v24@0:8@16",
+ @"getTuningInfo:": @"v24@0:8@?16",
+ @"setTuningInfoOnBox:at:withValue:": @"v36@0:8@16@24f32",
+ @"getUserDefaults:": @"v24@0:8@?16",
+ @"setUserDefaults:withValue:": @"v32@0:8@16@24",
+ @"resetUserDefault:": @"v24@0:8@16",
+ @"resetAllUserDefaults": @"v16@0:8",
+ @"getFeatureFlags:": @"v24@0:8@?16",
+ @"setFeatureFlags:": @"v24@0:8@16",
+ @"triggerWiFiCoreCapture:": @"v24@0:8@16",
+ @"setWifiEnabled:": @"v20@0:8B16",
+ @"disassociateCurrentNetwork": @"v16@0:8",
+ @"disassociateNetworkWithName:": @"v24@0:8@16",
+ @"injectSWUpdateToHome:": @"v24@0:8@16",
+ @"setHomeUpdateState:": @"v24@0:8q16",
+ @"clearHomeSWUpdate": @"v16@0:8",
+ @"suScanForSoftwareUpdate": @"v16@0:8",
+ };
+}
+@interface HPButtonEvent : NSObject
+@property(nonatomic) uint64_t button;
+@property(nonatomic) uint64_t action;
+@property(nonatomic) int64_t numberOfTaps;
+@property(nonatomic) uint64_t startMachTime;
+@property(nonatomic) BOOL deviceSideways;
+@property(nonatomic) BOOL coalesced;
+@property(nonatomic, readonly) NSData *data;
+@end
+@implementation HPButtonEvent
+- (NSData *)data {
+ return [NSJSONSerialization dataWithJSONObject:@{@"button": @(self.button), @"action": @(self.action), @"numberOfTaps": @(self.numberOfTaps), @"startMachTime": @(self.startMachTime), @"deviceSideways": @(self.deviceSideways), @"coalesced": @(self.coalesced)} options:0 error:NULL];
+}
+@end
+@interface SBSDebugInterface : NSObject
+@end
+@implementation SBSDebugInterface
+- (void)getAllDebugInfo:(void (^)(NSDictionary *))reply {
+ if (neverReply) lateReply = [reply copy];
+ else reply(@{@"nested": @[@1, @YES], @"data": [@"test" dataUsingEncoding:NSUTF8StringEncoding]});
+}
+- (void)getSelectDebugInfo:(NSArray *)keys reply:(void (^)(NSDictionary *))reply { received = keys; reply(@{@"selected": keys}); }
+- (void)getVolume:(void (^)(float))reply { reply(0.375f); }
+- (void)setVolume:(float)value { received = @(value); }
+- (void)setBootSpinner:(BOOL)value { received = @(value); }
+- (void)playTone:(uint32_t)value { received = @(value); }
+- (void)setHomeUpdateState:(int64_t)value { received = @(value); }
+- (void)setTuningInfoOnBox:(NSString *)box at:(NSString *)name withValue:(float)value { received = @[box, name, @(value)]; }
+- (void)setUserDefaults:(NSString *)name withValue:(NSString *)value { received = @[name, value]; }
+- (void)sendButtonCommand:(NSData *)data { received = data; }
+- (void)setLEDContents:(NSArray *)contents { received = contents; }
+- (void)resetAllUserDefaults { received = @"reset"; }
+@end
+
+static NSDictionary *call(NSString *name, NSDictionary *arguments) {
+ NSData *data = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:NULL];
+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+ char *json = vp_homepod_debug_copy_json(name.UTF8String, text.UTF8String);
+ assert(json);
+ NSDictionary *value = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:json length:strlen(json)] options:0 error:NULL];
+ free(json);
+ assert(value);
+ return value;
+}
+int main(void) {
+ @autoreleasepool {
+ NSDictionary *catalog = call(@"catalog", @{});
+ assert([catalog[@"ok"] boolValue]);
+ NSArray *entries = catalog[@"result"][@"operations"];
+ assert(entries.count == 29);
+ assert([catalog[@"result"][@"animations"] count] == 25);
+ assert([catalog[@"result"][@"phases"] count] == 20);
+ NSMutableSet *selectors = NSMutableSet.set;
+ NSDictionary *donor = donorMethodEncodings();
+ for (NSDictionary *entry in entries) {
+ assert(![selectors containsObject:entry[@"id"]]); [selectors addObject:entry[@"id"]];
+ assert(entry[@"title"] && entry[@"group"] && entry[@"arguments"] && entry[@"reply"]);
+ NSString *encoding = donor[entry[@"id"]];
+ assert(encoding);
+ assert(matchesSignature([NSMethodSignature signatureWithObjCTypes:encoding.UTF8String], entry));
+ }
+ assert([selectors isEqualToSet:[NSSet setWithArray:donor.allKeys]]);
+ NSDictionary *reply = call(@"getAllDebugInfo:", @{});
+ assert([reply[@"ok"] boolValue]);
+ assert([reply[@"result"][@"value"][@"data"][@"base64"] isEqual:@"dGVzdA=="]);
+ reply = call(@"getVolume:", @{});
+ assert([reply[@"result"][@"value"] doubleValue] == 0.375);
+ assert([call(@"getSelectDebugInfo:reply:", @{@"keys": @[@"a", @"b"]})[@"ok"] boolValue]);
+ assert([received isEqual:(@[@"a", @"b"])]);
+ assert([call(@"setVolume:", @{@"value": @0.625})[@"result"][@"submitted"] boolValue]);
+ assert([received doubleValue] == 0.625);
+ assert(![call(@"setVolume:", @{@"value": @2})[@"ok"] boolValue]);
+ assert(![call(@"setVolume:", @{@"value": @YES})[@"ok"] boolValue]);
+ assert([call(@"setBootSpinner:", @{@"enabled": @YES})[@"ok"] boolValue]);
+ assert([received boolValue]);
+ assert(![call(@"setBootSpinner:", @{@"enabled": @1})[@"ok"] boolValue]);
+ assert([call(@"playTone:", @{@"tone": @(UINT32_MAX)})[@"ok"] boolValue]);
+ assert([received unsignedIntValue] == UINT32_MAX);
+ assert(![call(@"playTone:", @{@"tone": @-1})[@"ok"] boolValue]);
+ assert(![call(@"playTone:", @{@"tone": @1.5})[@"ok"] boolValue]);
+ assert(![call(@"playTone:", @{@"tone": @YES})[@"ok"] boolValue]);
+ assert([call(@"setHomeUpdateState:", @{@"state": @(INT64_MIN)})[@"ok"] boolValue]);
+ assert([received longLongValue] == INT64_MIN);
+ assert(![call(@"setHomeUpdateState:", @{@"state": @YES})[@"ok"] boolValue]);
+ assert([call(@"setTuningInfoOnBox:at:withValue:", @{@"box": @"box", @"parameter": @"parameter", @"value": @0.25})[@"ok"] boolValue]);
+ assert([received isEqual:(@[@"box", @"parameter", @0.25])]);
+ assert([call(@"setUserDefaults:withValue:", @{@"name": @"key", @"value": @"1"})[@"ok"] boolValue]);
+ assert([received isEqual:(@[@"key", @"1"])]);
+ assert([call(@"sendButtonCommand:", @{@"event": @{@"base64": @"dGVzdA=="}})[@"ok"] boolValue]);
+ assert([received isEqual:[@"test" dataUsingEncoding:NSUTF8StringEncoding]]);
+ assert(![call(@"sendButtonCommand:", @{@"event": @{@"base64": @"***"}})[@"ok"] boolValue]);
+ NSMutableDictionary *event = [@{@"button": @3, @"action": @2, @"numberOfTaps": @1, @"startMachTime": @(UINT64_MAX), @"deviceSideways": @NO, @"coalesced": @YES} mutableCopy];
+ assert([call(@"sendButtonCommand:", @{@"event": event})[@"ok"] boolValue]);
+ NSDictionary *decoded = [NSJSONSerialization JSONObjectWithData:received options:0 error:NULL];
+ assert([decoded isEqual:event]);
+ event[@"button"] = @-1;
+ assert(![call(@"sendButtonCommand:", @{@"event": event})[@"ok"] boolValue]);
+ event[@"button"] = @1.5;
+ assert(![call(@"sendButtonCommand:", @{@"event": event})[@"ok"] boolValue]);
+ event[@"button"] = @3;
+ event[@"deviceSideways"] = @1;
+ assert(![call(@"sendButtonCommand:", @{@"event": event})[@"ok"] boolValue]);
+ NSArray *frames = @[@{@"LedValuesTimestamp": @0, @"LedValuesData": @{@"fill": @[@0.25, @0.5, @1]}}];
+ assert([call(@"setLEDContents:", @{@"contents": frames})[@"ok"] boolValue]);
+ NSData *pixels = received[0][@"LedValuesData"];
+ assert(pixels.length == 40 * 3 * sizeof(float));
+ const float *channels = pixels.bytes;
+ assert(channels[0] == 0.25 && channels[1] == 0.5 && channels[2] == 1);
+ frames = @[@{@"LedValuesTimestamp": @0, @"LedValuesData": @{@"base64": [pixels base64EncodedStringWithOptions:0]}}];
+ assert([call(@"setLEDContents:", @{@"contents": frames})[@"ok"] boolValue]);
+ assert([received[0][@"LedValuesData"] isEqual:pixels]);
+ assert(![call(@"setLEDContents:", @{@"contents": @[]})[@"ok"] boolValue]);
+ assert(![call(@"setLEDContents:", @{@"contents": @[@{@"LedValuesTimestamp": @0, @"LedValuesData": @{@"base64": @""}}]})[@"ok"] boolValue]);
+ assert(![call(@"setLEDContents:", @{@"contents": @[@{@"LedValuesTimestamp": @YES, @"LedValuesData": @{@"fill": @[@0, @0, @0]}}]})[@"ok"] boolValue]);
+ assert([call(@"resetAllUserDefaults", @{})[@"ok"] boolValue]);
+ assert([received isEqual:@"reset"]);
+ assert(![call(@"performSelector:", @{})[@"ok"] boolValue]);
+ assert(![call(@"getLEDInfo:", @{})[@"ok"] boolValue]); // Missing native ABI is refused.
+ neverReply = YES;
+ NSDate *start = NSDate.date;
+ assert(![call(@"getAllDebugInfo:", @{})[@"ok"] boolValue]);
+ assert(-start.timeIntervalSinceNow >= 2.9 && -start.timeIntervalSinceNow < 4.0);
+ // An old XPC connection may deliver its reply after the deadline. It
+ // must neither affect the next request nor signal a reused semaphore.
+ assert(lateReply);
+ lateReply(@{@"stale": @YES});
+ lateReply = nil;
+ neverReply = NO;
+ reply = call(@"getAllDebugInfo:", @{});
+ assert([reply[@"ok"] boolValue]);
+ assert(reply[@"result"][@"value"][@"stale"] == nil);
+ assert([reply[@"result"][@"value"][@"data"][@"base64"] isEqual:@"dGVzdA=="]);
+ puts("HomePod debug bridge tests passed (all 29 donor ABIs, argument forwarding, replies, rejection, timeout and late reply). ");
+ }
+}
diff --git a/VPhoneDaemon/Tests/run-homepod-debug-tests.sh b/VPhoneDaemon/Tests/run-homepod-debug-tests.sh
new file mode 100755
index 00000000..6aa4221e
--- /dev/null
+++ b/VPhoneDaemon/Tests/run-homepod-debug-tests.sh
@@ -0,0 +1,9 @@
+#!/bin/zsh
+set -euo pipefail
+SCRIPT_DIR="${0:a:h}"
+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/vphone-homepod-debug-tests.XXXXXX")"
+trap 'rm -rf "$TEST_DIR"' EXIT
+xcrun --sdk macosx clang -fobjc-arc -fmodules -Wall -Wextra -Werror \
+ -fmodules-cache-path="$TEST_DIR/modules" -framework Foundation \
+ "$SCRIPT_DIR/HomePodDebugTests.m" -o "$TEST_DIR/homepod-debug-tests"
+"$TEST_DIR/homepod-debug-tests"
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
index d7b0beb3..f59d56f2 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift
@@ -51,7 +51,7 @@ public enum FirmwareGuestPatchResolution {
/// Apple TV OTA swap, GPU injection, or plain-arm64 dyld workarounds.
public static let homePodSupportedGuestPatches = tvSupportedGuestPatches
.subtracting([FirmwareGuestSystemPatchSet.tvTPRO])
- .union([FirmwareGuestSystemPatchSet.homePodTopCap])
+ .union([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])
.union(FirmwarePatchSetCatalog.tvOS27UserlandPatches)
public static func unvalidatedHomePodGuestPatches(enabled: Set<String>) -> [String] {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 890a2b5f..34db9401 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -324,6 +324,13 @@ public enum FirmwareGuestSystemPatchSet {
summary: "Stages the donor MiniDisplay geometry for vphoned's virtual HomePod LED display and volume buttons, with a SoundBoard-only shim for its reserved HID class identity.",
target: .guestFile(path: homePodDisplayPath),
),
+ VPhonePatchDeclaration(
+ identifier: homePodSetupBypass,
+ title: "HomePod setup completion",
+ summary: "Completes the donor's local AudioAccessory setup state as mobile, prepares SetupAssistant's native launch sentinel and lets SoundBoard initialize its post-setup services. Turning it off restores the prior completion flags at the next boot. Does not provision accounts, activation or a HomeKit home.",
+ target: .guestFile(path: homePodSetupPath),
+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),
+ ),
VPhonePatchDeclaration(
identifier: "system-launchdaemons-boot-environment",
title: "Guest environment",
@@ -579,6 +586,8 @@ public enum FirmwareGuestSystemPatchSet {
/// iPad VM patched before `fw patch` copied the board's node.
public static let homePodTopCap = "system-homepod-exp-top_cap"
public static let homePodDisplayPath = "/usr/share/vphone/HomePodDisplay.plist"
+ public static let homePodSetupBypass = "system-homepod-exp-setup_bypass"
+ public static let homePodSetupPath = "/usr/share/vphone/HomePodSetup.plist"
public static let prebootBoardAudio = "preboot-cfw-devicetree_board_audio"
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index f6ec8d15..0e5da88d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -61,7 +61,7 @@ public enum FirmwarePatchSetCatalog {
Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier))
.union(hypervisorConcealmentPatches)
.union(experimentalIdentityPatches)
- .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap])
+ .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])
.union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland])
/// ProMotion: the 120 Hz timing for the paravirtual display.
@@ -219,7 +219,7 @@ public enum FirmwarePatchSetCatalog {
freshly restored 26.4 guest does not survive. The HomePod-only top cap is off.
""",
patchSets: bundledReferences,
- selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap]),
+ selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass]),
)
/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no
@@ -321,10 +321,10 @@ public enum FirmwarePatchSetCatalog {
public static let homePodMiniPreset = VPhonePatchPreset(
identifier: VPhonePatchPreset.homePodMiniIdentifier,
title: "HomePod mini",
- summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned and its donor-driven top cap, without Apple TV OTA replacement or iPhone display, camera and audio hooks.",
+ summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap and local setup completion, without Apple TV OTA replacement or iPhone display, camera and audio hooks.",
patchSets: bundledReferences,
selection: .block(
- manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap])
+ manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])
.union(tvOSBlockedPatches.subtracting(tvOS27UserlandPatches)),
),
)
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index 5e2c5b17..8729bc44 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -26,6 +26,24 @@ struct FirmwareGuestPatchResolutionTests {
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true) == [identifier])
}
+ @Test func `HomePod setup bypass is version gated and never selected for other devices`() throws {
+ let identifier = FirmwareGuestSystemPatchSet.homePodSetupBypass
+ for base in ["26.4", "27.0", "27.1"] {
+ for preset in FirmwarePatchSetCatalog.builtInPresets {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(plan.isEnabled(identifier) == (base.hasPrefix("27.")
+ && preset.identifier == VPhonePatchPreset.homePodMiniIdentifier))
+ }
+ }
+ #expect(FirmwareGuestPatchResolution.unvalidatedHomePodGuestPatches(enabled: [identifier]).isEmpty)
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier]) == [identifier])
+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true) == [identifier])
+ #expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: []).contains(identifier))
+ }
+
@Test
func `TV selection keeps vphoned and excludes iOS payloads and cache patches`() throws {
let standard = try VPhonePatchPlan.resolve(
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index 1da8406b..edf99e3a 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -197,6 +197,7 @@ struct FirmwarePatchSetCatalogTests {
let applicableManual = Set(FirmwarePatchSetCatalog.allDeclarations.filter {
FirmwarePatchSetCatalog.manualOnlyPatches.contains($0.identifier)
&& $0.identifier != FirmwareGuestSystemPatchSet.homePodTopCap
+ && $0.identifier != FirmwareGuestSystemPatchSet.homePodSetupBypass
&& $0.applicability.matches(iOSBase: version, cloudOS: cloud)
}.map(\.identifier))
#expect(experimental.enabled.subtracting(standard.enabled) == applicableManual)
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 7f57e861..e68c2d4e 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -203,6 +203,9 @@ struct VPhoneCustomFirmwareInstaller {
if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodTopCap), device.family != .homePod {
throw ValidationError("The HomePod top-cap patch is supported only for a HomePod guest.")
}
+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodSetupBypass), device.family != .homePod {
+ throw ValidationError("The HomePod setup-completion patch is supported only for a HomePod guest.")
+ }
// Research: an Apple TV 4K userland staged from its OTA, which
// `system-tv-exp-ota_userland` puts in place of the restored one.
let hasOTAUserland = (try? bundleDirectory.isDirectory(VPhoneOTAArchive.userlandDirectoryName)) == true
@@ -1343,6 +1346,26 @@ struct VPhoneCustomFirmwareInstaller {
}
try system.removeItem(topCapPath)
}
+ // Data is encrypted on the host. The mobile boot helper applies this
+ // marker through the donor's preferences/sentinel APIs, or restores its
+ // key-level journal when the marker is absent. Its runtime is staged
+ // with vphoned even when off, so deselection has a path back on boot.
+ let setup = FirmwareGuestSystemPatchSet.homePodSetupBypass
+ let setupPath = String(FirmwareGuestSystemPatchSet.homePodSetupPath.dropFirst())
+ if guestDevice.family == .homePod {
+ try installHomePodSetupRuntime(system: system, work: work)
+ }
+ if plan?.isEnabled(setup) == true {
+ guard guestDevice.family == .homePod else {
+ throw ValidationError("HomePod setup completion requires a HomePod guest.")
+ }
+ _ = try system.directory("usr/share/vphone", create: true, mode: 0o755)
+ let policy = try PropertyListSerialization.data(fromPropertyList: ["Enabled": true], format: .binary, options: 0)
+ try system.writeFile(setupPath, contents: policy, mode: 0o644, owner: Self.guestOwner)
+ live.insert(setup)
+ } else {
+ try system.removeItem(setupPath)
+ }
for (identifier, library) in [
(FirmwareGuestSystemPatchSet.gyroscope, "libvphonegyro.dylib"),
(FirmwareGuestSystemPatchSet.accelerometer, "libvphoneaccelerometer.dylib"),
@@ -2424,6 +2447,23 @@ struct VPhoneCustomFirmwareInstaller {
try system.replaceFile(launchd, fromFileAt: temp, mode: 0o644, owner: Self.guestOwner)
}
+ /// Keep rollback available even when the owner also deselects vphoned.
+ /// This helper is inert when no setup marker or original-key journal exists.
+ private func installHomePodSetupRuntime(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {
+ let helper = try VPhoneGuestBinaries.resolve("vphone-homepod-setup")
+ _ = try system.directory("usr/local/libexec", create: true, mode: 0o755)
+ try system.replaceFile("usr/local/libexec/vphone-homepod-setup", fromFileAt: helper,
+ mode: 0o755, owner: Self.guestOwner)
+ let daemon = resources.guestResources.appendingPathComponent("com.vphone.homepod-setup.plist")
+ try system.replaceFile("System/Library/LaunchDaemons/com.vphone.homepod-setup.plist", fromFileAt: daemon,
+ mode: 0o644, owner: Self.guestOwner)
+ let cache = "System/Library/xpc/launchd.plist"
+ let staged = "homepod-setup-launchd.plist"
+ try system.copyFile(from: cache, to: staged, in: work.directory)
+ try CustomFirmwareDaemons.injectDaemon(into: work.file(staged), name: "com.vphone.homepod-setup", from: daemon)
+ try system.replaceFile(cache, fromFileAt: work.file(staged), mode: 0o644, owner: Self.guestOwner)
+ }
+
/// The host copy of the installed vphoned, for launch-time auto-update.
/// Besides Disk.img, it is the one file root writes into the caller's
/// folder: created beside the old one through the pinned descriptor,
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 6f17f665..e83c8c9b 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -90,6 +90,8 @@ daemon_sdk="$(/usr/bin/otool -l "$guest/vphoned" | /usr/bin/awk '/LC_BUILD_VERSI
/bin/cp "$guest_products/accelerometer/libvphoneaccelerometer.dylib" "$guest/libvphoneaccelerometer.dylib"
/bin/cp "$guest_products/attitude/libvphoneattitude.dylib" "$guest/libvphoneattitude.dylib"
/bin/cp "$guest_products/homepoddisplay/libvphonehomepoddisplay.dylib" "$guest/libvphonehomepoddisplay.dylib"
+/bin/cp "$guest_products/homepodsetup/vphone-homepod-setup" "$guest/vphone-homepod-setup"
+/bin/cp "$guest_products/homepodsetup/com.vphone.homepod-setup.plist" "$guest/com.vphone.homepod-setup.plist"
/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \
"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
# The HAL plugin is a bundle, signed whole by the Makefile; copied as a tree so
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index 75734d26..071ead01 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -122,10 +122,10 @@ fi
for name in vphoned vphoned-tvos launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \
- libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneaccelerometer.dylib libvphoneattitude.dylib libvphonehomepoddisplay.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
+ libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneaccelerometer.dylib libvphoneattitude.dylib libvphonehomepoddisplay.dylib vphone-homepod-setup libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
done
-for name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist; do
+for name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist com.vphone.homepod-setup.plist; do
[[ -f "$guest/$name" ]] || { print -u2 "Missing guest configuration: $name"; exit 1; }
done
# The virtio sound HAL plugin is a whole bundle: audiomxd finds its factory
@@ -176,7 +176,7 @@ while IFS= read -r file; do
"$frameworks/"*)
[[ "$platform" != IOS ]] || { print -u2 "iOS binary in Contents/Frameworks: ${file#$bundle/}"; exit 1; }
;;
- "$guest/vphoned-tvos"|"$guest/libvphonehomepoddisplay.dylib")
+ "$guest/vphoned-tvos"|"$guest/libvphonehomepoddisplay.dylib"|"$guest/vphone-homepod-setup")
# tvOS dyld refuses an iOS-platform daemon on an Apple TV guest.
[[ "$platform" == TVOS ]] || { print -u2 "Non-tvOS binary: ${file#$bundle/}"; exit 1; }
;;
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index d8fcdb49..812fccdf 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -1,6 +1,26 @@
{
"sourceLanguage" : "en",
"strings" : {
+ "Animation": {
+ },
+ "Commands without a reply report submission. SoundBoard applies them asynchronously.": {
+ },
+ "Copy Reply": {
+ },
+ "HomePod": {
+ },
+ "Phase": {
+ },
+ "Reload Controls": {
+ },
+ "Send Command": {
+ },
+ "SoundBoard Debug Control": {
+ },
+ "SoundBoard Reply": {
+ },
+ "This operation's native signature is unavailable on the guest firmware.": {
+ },
"Control Center" : {
"localizations" : {
"en" : { "stringUnit" : { "state" : "translated", "value" : "Control Center" } },
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
index 85f2493c..26d26fe2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist
@@ -88,6 +88,7 @@
<key>Patches</key>
<array>
<string>system-homepod-exp-top_cap</string>
+ <string>system-homepod-exp-setup_bypass</string>
</array>
</dict>
</dict>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index 8993ab8b..40da7039 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -129,7 +129,7 @@
</array>
</dict>
<key>Summary</key>
- <string>Research: HomePod mini's own arm64e TVOS IPSW with vphoned and its donor-driven top cap, without Apple TV OTA replacement or iPhone display, camera and audio hooks.</string>
+ <string>Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap and local setup completion, without Apple TV OTA replacement or iPhone display, camera and audio hooks.</string>
<key>Title</key>
<string>HomePod mini</string>
</dict>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
index c7251306..5d13d5f6 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
@@ -68,6 +68,7 @@
<key>Patches</key>
<array>
<string>system-homepod-exp-top_cap</string>
+ <string>system-homepod-exp-setup_bypass</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-hv_vmm</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index c7e75d40..78bc9351 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -68,6 +68,7 @@
<key>Patches</key>
<array>
<string>system-homepod-exp-top_cap</string>
+ <string>system-homepod-exp-setup_bypass</string>
<string>system-exp-ota_userland</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 7ef97b3d..090833df 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -68,6 +68,7 @@
<key>Patches</key>
<array>
<string>system-homepod-exp-top_cap</string>
+ <string>system-homepod-exp-setup_bypass</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/HomePodMetalProbe.swift b/VPhoneExecutable/VPhoneVirtualization/Tests/HomePodMetalProbe.swift
new file mode 100644
index 00000000..dd3e2ec6
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/HomePodMetalProbe.swift
@@ -0,0 +1,120 @@
+import Foundation
+import MetalKit
+import ImageIO
+import VPhoneCoreKit
+
+/// Executes the real Metal 4 compiler/queue offscreen. This needs no VM, bundle
+/// installation or administrator authorization. Output PNGs support optical QA.
+@main
+struct HomePodMetalProbe {
+ @MainActor
+ static func main() async throws {
+ guard #available(macOS 26.0, *), let device = MTLCreateSystemDefaultDevice(), device.supportsFamily(.metal4) else {
+ throw VPhoneHomePodMetalError.unavailable("This probe requires a Metal 4 GPU and macOS 26 or later.")
+ }
+ let output = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
+ var backend: any VPhoneHomePodMetalBackend = try VPhoneHomePodMetal4Backend(device: device, format: .bgra8Unorm_srgb)
+ print("Runtime compiler and command queue: \(backend.name), \(device.name)")
+ let x: [Float] = [19752, 32768, 45783, 55312, 58799, 55312, 45784, 32768, 19753, 10224, 6737, 10224, 23240, 36256, 45784, 42296, 29280, 19752, 32768].map { $0 / 65536 }
+ let y: [Float] = [55312, 58799, 55312, 45784, 32768, 19753, 10224, 6737, 10224, 19752, 32768, 45783, 42296, 45784, 36256, 23240, 19752, 29280, 32768].map { $0 / 65536 }
+ let size = 640
+
+ func render(_ name: String, colors: [SIMD3<Float>], plus: Float = 0, minus: Float = 0) async throws -> [UInt8] {
+ let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm_srgb, width: size, height: size, mipmapped: false)
+ descriptor.storageMode = .shared
+ descriptor.usage = .renderTarget
+ guard let texture = device.makeTexture(descriptor: descriptor) else { throw VPhoneHomePodMetalError.unavailable("No offscreen target.") }
+ let leds = colors.enumerated().map { index, color in
+ VPhoneHomePodMetalLED(position: SIMD4(x[index], y[index], 0, 0), color: SIMD4(color.x, color.y, color.z, 0))
+ }
+ let uniforms = VPhoneHomePodMetalUniforms(viewport: SIMD4(Float(size), Float(size), Float(size) / 2, Float(size) / 2), cap: SIMD4(304, Float(leds.count), plus, minus))
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
+ do {
+ try backend.render(texture: texture, drawable: nil, uniforms: uniforms, leds: leds) { error in
+ if let error { continuation.resume(throwing: VPhoneHomePodMetalError.unavailable(error)) }
+ else { continuation.resume() }
+ }
+ } catch { continuation.resume(throwing: error) }
+ }
+ var bytes = [UInt8](repeating: 0, count: size * size * 4)
+ texture.getBytes(&bytes, bytesPerRow: size * 4, from: MTLRegionMake2D(0, 0, size, size), mipmapLevel: 0)
+ var rgba = bytes
+ for i in stride(from: 0, to: bytes.count, by: 4) { rgba[i] = bytes[i + 2]; rgba[i + 2] = bytes[i] }
+ let provider = CGDataProvider(data: Data(rgba) as CFData)!
+ let image = CGImage(width: size, height: size, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: size * 4,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
+ provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)!
+ let destination = CGImageDestinationCreateWithURL(output.appendingPathComponent(name + ".png") as CFURL, "public.png" as CFString, 1, nil)!
+ CGImageDestinationAddImage(destination, image, nil)
+ precondition(CGImageDestinationFinalize(destination))
+ return bytes
+ }
+ func pixel(_ bytes: [UInt8], _ x: Int, _ y: Int) -> SIMD3<Int> {
+ let offset = (y * size + x) * 4
+ return SIMD3(Int(bytes[offset + 2]), Int(bytes[offset + 1]), Int(bytes[offset]))
+ }
+
+ let dark = try await render("off", colors: Array(repeating: .zero, count: 19))
+ let white = try await render("white", colors: Array(repeating: SIMD3(repeating: 0.75), count: 19), plus: 1, minus: 1)
+ let colored = try await render("multicolor", colors: (0 ..< 19).map { i in
+ let p = SIMD2(x[i] - 0.5, y[i] - 0.5)
+ let angle = atan2(p.y, p.x)
+ return SIMD3(0.30 + 0.28 * cos(angle), 0.28 + 0.26 * cos(angle + 2.1), 0.4 + 0.35 * cos(angle + 4.2))
+ })
+ let volume = try await render("volume", colors: (0 ..< 19).map { $0 >= 12 ? SIMD3(repeating: 0.7482) : .zero }, plus: 1, minus: 1)
+ let red = try await render("red", colors: Array(repeating: SIMD3(0.65, 0, 0), count: 19))
+ let redAgain = try await render("red-repeat", colors: Array(repeating: SIMD3(0.65, 0, 0), count: 19))
+ precondition(red == redAgain, "An unchanged guest frame must not acquire host animation.")
+ let centerDark = pixel(dark, 320, 320)
+ let centerWhite = pixel(white, 320, 320)
+ precondition(centerDark.max() < 24 && centerWhite.min() > 180, "Off/white optical output is incorrect.")
+ let centerRed = pixel(red, 320, 320)
+ precondition(centerRed.x > centerRed.y * 4 && centerRed.x > centerRed.z * 4, "RGB channels are crossed.")
+ precondition(pixel(white, 320, 320).x > pixel(white, 320, 24).x + 100, "The opaque rim is missing.")
+ precondition(pixel(white, 502, 320).x > pixel(dark, 502, 320).x + 120, "Independent plus illumination is missing.")
+ precondition(pixel(volume, 320, 320).x > 100, "Neighbouring emitters did not blend through the diffuser.")
+ precondition(colored != white && colored != dark)
+ // Queue all three owned frame slots without waiting between submissions,
+ // then repeat to exercise allocator reset and shared-input reuse.
+ for _ in 0 ..< 8 {
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
+ var remaining = 3
+ var firstError: String?
+ for channel in 0 ..< 3 {
+ let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm_srgb, width: size, height: size, mipmapped: false)
+ descriptor.storageMode = .shared
+ descriptor.usage = .renderTarget
+ let texture = device.makeTexture(descriptor: descriptor)!
+ var color = SIMD4<Float>.zero
+ color[channel] = 0.75
+ let leds = x.indices.map { VPhoneHomePodMetalLED(position: SIMD4(x[$0], y[$0], 0, 0), color: color) }
+ let uniforms = VPhoneHomePodMetalUniforms(viewport: SIMD4(640, 640, 320, 320), cap: SIMD4(304, 19, 0, 0))
+ do {
+ try backend.render(texture: texture, drawable: nil, uniforms: uniforms, leds: leds) { error in
+ firstError = firstError ?? error
+ var bytes = [UInt8](repeating: 0, count: size * size * 4)
+ texture.getBytes(&bytes, bytesPerRow: size * 4, from: MTLRegionMake2D(0, 0, size, size), mipmapLevel: 0)
+ let center = pixel(bytes, 320, 320)
+ if center[channel] < 180 || center[(channel + 1) % 3] > 30 {
+ firstError = "In-flight frame inputs overlapped."
+ }
+ remaining -= 1
+ if remaining == 0 {
+ if let firstError { continuation.resume(throwing: VPhoneHomePodMetalError.unavailable(firstError)) }
+ else { continuation.resume() }
+ }
+ }
+ } catch {
+ firstError = error.localizedDescription
+ remaining -= 1
+ if remaining == 0 { continuation.resume(throwing: error) }
+ }
+ }
+ }
+ }
+ backend = try VPhoneHomePodMetalLegacyBackend(device: device, format: .bgra8Unorm_srgb)
+ let compatible = try await render("metal3-compatibility", colors: Array(repeating: SIMD3(0.65, 0, 0), count: 19))
+ precondition(zip(red, compatible).allSatisfy { abs(Int($0.0) - Int($0.1)) <= 2 }, "Compatibility rendering differs from Metal 4.")
+ print("Metal 4 offscreen checks passed; PNGs: \(output.path)")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-metal-tests.sh b/VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-metal-tests.sh
new file mode 100755
index 00000000..283d0858
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/run-homepod-metal-tests.sh
@@ -0,0 +1,26 @@
+#!/bin/zsh
+set -euo pipefail
+
+tests="${0:a:h}"
+repo="${tests:h:h:h}"
+output="${1:-$repo/.build/homepod-metal-tests}"
+temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-homepod-metal.XXXXXX")"
+trap '/bin/rm -rf "$temporary"' EXIT
+/bin/mkdir -p "$output"
+
+# This probe uses the actual renderer and shader source. It compiles no .metal
+# file and invokes neither metal nor metallib, just like the product build.
+/usr/bin/xcrun --sdk macosx swiftc -swift-version 6 -strict-concurrency=complete \
+ -module-cache-path "$temporary/ModuleCache" -emit-library -emit-module \
+ -module-name VPhoneCoreKit -emit-module-path "$temporary/VPhoneCoreKit.swiftmodule" \
+ "$repo/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneHomePodDisplay.swift" \
+ -Xlinker -install_name -Xlinker '@rpath/libVPhoneCoreKit.dylib' \
+ -o "$temporary/libVPhoneCoreKit.dylib"
+/usr/bin/xcrun --sdk macosx swiftc -swift-version 6 -strict-concurrency=complete \
+ -module-cache-path "$temporary/ModuleCache" -I "$temporary" -L "$temporary" -lVPhoneCoreKit \
+ -Xlinker -rpath -Xlinker "$temporary" \
+ "$tests/HomePodMetalProbe.swift" \
+ "$tests:h/UI/UserInterface/HomePod/VPhoneHomePodMetalRenderer.swift" \
+ "$tests:h/UI/UserInterface/HomePod/VPhoneHomePodShader.swift" \
+ -o "$temporary/HomePodMetalProbe"
+"$temporary/HomePodMetalProbe" "$output"
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index f1a147c2..889d3693 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -58,6 +58,7 @@ final class VPhoneGuestControl {
@ObservationIgnored private var orderedInput: Task<Void, Never>?
@ObservationIgnored private var orderedLocation: Task<Void, Never>?
@ObservationIgnored private var locationGeneration: UInt64 = 0
+ @ObservationIgnored var isHomePodGuest = false
private(set) var isConnected = false
private(set) var guestCapabilities: [String] = []
private(set) var guestIPAddress: String?
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift
index b1a01dc4..f6faef8d 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodDisplayView.swift
@@ -26,6 +26,7 @@ final class VPhoneHomePodDisplayView: NSView {
private(set) var geometry: VPhoneHomePodDisplayGeometry?
private(set) var displayFrame: VPhoneHomePodDisplayFrame?
+ private let canvas = VPhoneHomePodMetalView(frame: .zero)
private let surface = VPhoneHomePodCapControl(control: .surface, label: "HomePod touch surface")
private let minus = VPhoneHomePodCapControl(control: .volumeDown, label: "Decrease volume")
private let plus = VPhoneHomePodCapControl(control: .volumeUp, label: "Increase volume")
@@ -33,6 +34,7 @@ final class VPhoneHomePodDisplayView: NSView {
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setAccessibilityElement(false)
+ addSubview(canvas)
for button in [surface, minus, plus] {
button.onChange = { [weak self] control, down, minimumHold in
self?.onControlChange?(control, down, minimumHold)
@@ -44,6 +46,17 @@ final class VPhoneHomePodDisplayView: NSView {
plus.nextKeyView = minus
surface.isHidden = true
surface.setAccessibilityElement(false)
+ if let error = canvas.renderingError {
+ let label = NSTextField(wrappingLabelWithString: "HomePod display unavailable: \(error)")
+ label.translatesAutoresizingMaskIntoConstraints = false
+ label.textColor = .secondaryLabelColor
+ addSubview(label)
+ NSLayoutConstraint.activate([
+ label.centerXAnchor.constraint(equalTo: centerXAnchor),
+ label.centerYAnchor.constraint(equalTo: centerYAnchor),
+ label.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -48),
+ ])
+ }
}
required init?(coder: NSCoder) { nil }
@@ -58,18 +71,14 @@ final class VPhoneHomePodDisplayView: NSView {
guard self.geometry != geometry || displayFrame != frame else { return }
self.geometry = geometry
displayFrame = frame
- minus.illumination = frame.minusBrightness * frame.brightness
- plus.illumination = frame.plusBrightness * frame.brightness
- needsDisplay = true
+ canvas.update(geometry: geometry, snapshot: frame)
}
func clearDisplay() {
releaseControls()
guard displayFrame != nil else { return }
displayFrame = nil
- minus.illumination = 0
- plus.illumination = 0
- needsDisplay = true
+ canvas.update(geometry: geometry, snapshot: nil)
}
func releaseControls() {
@@ -98,6 +107,7 @@ final class VPhoneHomePodDisplayView: NSView {
override func layout() {
super.layout()
+ canvas.frame = bounds
let cap = capRect
surface.frame = cap
let side = cap.width * 0.19
@@ -105,39 +115,6 @@ final class VPhoneHomePodDisplayView: NSView {
plus.frame = CGRect(x: cap.midX + cap.width * 0.30 - side / 2, y: cap.midY - side / 2, width: side, height: side)
}
- override func draw(_ dirtyRect: NSRect) {
- NSColor(calibratedWhite: 0.055, alpha: 1).setFill()
- dirtyRect.fill()
- let cap = capRect
- guard cap.width > 0 else { return }
- let path = NSBezierPath(ovalIn: cap)
- NSColor.black.setFill()
- path.fill()
- NSGraphicsContext.saveGraphicsState()
- path.addClip()
- if let geometry, let displayFrame, let context = NSGraphicsContext.current?.cgContext {
- // Add emitted light under the diffuser. Conversion from linear RGB
- // happens here, after multiplication by the guest's master level.
- context.setBlendMode(.screen)
- for (point, rgb) in zip(geometry.normalizedPoints, displayFrame.pixels) {
- let scaled = rgb.map { $0 * displayFrame.brightness }
- guard scaled.contains(where: { $0 > 0 }) else { continue }
- let center = CGPoint(x: cap.minX + point.x * cap.width, y: cap.minY + point.y * cap.height)
- let color = NSColor(srgbRed: Self.sRGB(scaled[0]), green: Self.sRGB(scaled[1]), blue: Self.sRGB(scaled[2]), alpha: 1)
- if let glow = NSGradient(colorsAndLocations: (color.withAlphaComponent(0.84), 0), (color.withAlphaComponent(0.32), 0.32), (color.withAlphaComponent(0), 1)) {
- glow.draw(fromCenter: center, radius: 0, toCenter: center, radius: cap.width * 0.24, options: [])
- }
- }
- }
- NSGraphicsContext.restoreGraphicsState()
- NSColor(calibratedWhite: 0.20, alpha: 1).setStroke()
- path.lineWidth = 1
- path.stroke()
- }
-
- private static func sRGB(_ linear: Double) -> Double {
- linear <= 0.0031308 ? linear * 12.92 : 1.055 * pow(linear, 1 / 2.4) - 0.055
- }
}
// MARK: - Capacitive Hit Areas
@@ -148,7 +125,6 @@ final class VPhoneHomePodDisplayView: NSView {
private final class VPhoneHomePodCapControl: NSButton {
let control: VPhoneHomePodDisplayView.Control
var onChange: ((VPhoneHomePodDisplayView.Control, Bool, Duration) -> Void)?
- var illumination: Double = 0 { didSet { needsDisplay = true } }
private var isPressed = false
init(control: VPhoneHomePodDisplayView.Control, label: String) {
@@ -233,23 +209,9 @@ private final class VPhoneHomePodCapControl: NSButton {
onChange?(control, false, minimumHold)
}
- override func draw(_ dirtyRect: NSRect) {
- guard control != .surface else { return }
- // The button LEDs are independent output channels, including off.
- let level = illumination <= 0.0031308 ? illumination * 12.92 : 1.055 * pow(illumination, 1 / 2.4) - 0.055
- NSColor(calibratedWhite: level, alpha: 1).setStroke()
- let path = NSBezierPath()
- let length = bounds.width * 0.40
- path.move(to: NSPoint(x: bounds.midX - length / 2, y: bounds.midY))
- path.line(to: NSPoint(x: bounds.midX + length / 2, y: bounds.midY))
- if control == .volumeUp {
- path.move(to: NSPoint(x: bounds.midX, y: bounds.midY - length / 2))
- path.line(to: NSPoint(x: bounds.midX, y: bounds.midY + length / 2))
- }
- path.lineWidth = max(1.5, bounds.width * 0.035)
- path.lineCapStyle = .round
- path.stroke()
- }
+ // Visual markings belong to the optical shader; these views supply native
+ // button semantics and the system focus ring above the Metal surface.
+ override func draw(_ dirtyRect: NSRect) {}
override func drawFocusRingMask() { NSBezierPath(ovalIn: bounds.insetBy(dx: 2, dy: 2)).fill() }
override var focusRingMaskBounds: NSRect { bounds }
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodMetalRenderer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodMetalRenderer.swift
new file mode 100644
index 00000000..06590dc7
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodMetalRenderer.swift
@@ -0,0 +1,324 @@
+import AppKit
+import MetalKit
+import VPhoneCoreKit
+
+// MARK: - Shader Inputs
+
+struct VPhoneHomePodMetalUniforms {
+ var viewport: SIMD4<Float>
+ var cap: SIMD4<Float>
+}
+
+struct VPhoneHomePodMetalLED {
+ var position: SIMD4<Float>
+ var color: SIMD4<Float>
+}
+
+enum VPhoneHomePodMetalError: Error, LocalizedError {
+ case unavailable(String)
+ var errorDescription: String? {
+ if case let .unavailable(message) = self { return message }
+ return nil
+ }
+}
+
+// MARK: - On-demand Metal View
+
+/// Rendering follows guest snapshots and window damage, never a host animation
+/// timer. At most three frames are in flight; GPU completion retries the newest
+/// pending snapshot if the GPU was busy when it arrived.
+@MainActor
+final class VPhoneHomePodMetalView: MTKView, MTKViewDelegate {
+ private var backend: (any VPhoneHomePodMetalBackend)?
+ private var geometry: VPhoneHomePodDisplayGeometry?
+ private var snapshot: VPhoneHomePodDisplayFrame?
+ private var pending = true
+ private(set) var renderingError: String?
+ var backendName: String? { backend?.name }
+
+ init(frame: NSRect) {
+ let device = MTLCreateSystemDefaultDevice()
+ super.init(frame: frame, device: device)
+ colorPixelFormat = .bgra8Unorm_srgb
+ clearColor = MTLClearColor(red: 0.0044, green: 0.0044, blue: 0.0044, alpha: 1)
+ framebufferOnly = true
+ isPaused = true
+ enableSetNeedsDisplay = true
+ autoResizeDrawable = true
+ setAccessibilityElement(false)
+ delegate = self
+ do {
+ guard let device else { throw VPhoneHomePodMetalError.unavailable("No Metal device is available.") }
+ if #available(macOS 26.0, *), device.supportsFamily(.metal4) {
+ backend = try VPhoneHomePodMetal4Backend(device: device, format: colorPixelFormat)
+ } else {
+ // The app still supports macOS 15. The same runtime-compiled
+ // optical shader uses Metal's older submission API there.
+ backend = try VPhoneHomePodMetalLegacyBackend(device: device, format: colorPixelFormat)
+ }
+ print("[homepod] \(backend!.name) top-cap renderer ready")
+ } catch {
+ renderingError = error.localizedDescription
+ print("[homepod] Metal renderer: \(error)")
+ }
+ }
+
+ @available(*, unavailable)
+ required init(coder: NSCoder) { fatalError("Create the HomePod Metal view programmatically.") }
+ override var isFlipped: Bool { true }
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ func update(geometry: VPhoneHomePodDisplayGeometry?, snapshot: VPhoneHomePodDisplayFrame?) {
+ if let geometry, let snapshot, !snapshot.matches(geometry) { return }
+ self.geometry = geometry
+ self.snapshot = snapshot
+ pending = true
+ needsDisplay = true
+ }
+
+ nonisolated func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
+ MainActor.assumeIsolated {
+ pending = true
+ needsDisplay = true
+ }
+ }
+
+ nonisolated func draw(in view: MTKView) {
+ MainActor.assumeIsolated { render() }
+ }
+
+ private func render() {
+ guard let backend, backend.hasFreeFrame, drawableSize.width > 0, drawableSize.height > 0,
+ let drawable = currentDrawable else { return }
+ let scale = drawableSize.width / max(bounds.width, 1)
+ let radius = max(0, (min(bounds.width, bounds.height) - 32) / 2) * scale
+ let count = geometry?.points.count ?? 0
+ let uniforms = VPhoneHomePodMetalUniforms(
+ viewport: SIMD4(Float(drawableSize.width), Float(drawableSize.height), Float(drawableSize.width / 2), Float(drawableSize.height / 2)),
+ cap: SIMD4(Float(radius), Float(count), Float((snapshot?.plusBrightness ?? 0) * (snapshot?.brightness ?? 0)), Float((snapshot?.minusBrightness ?? 0) * (snapshot?.brightness ?? 0))),
+ )
+ let leds: [VPhoneHomePodMetalLED] = (geometry?.points.enumerated().map { index, point in
+ let rgb = snapshot?.pixels[index] ?? [0, 0, 0]
+ let brightness = Float(snapshot?.brightness ?? 0)
+ return VPhoneHomePodMetalLED(
+ position: SIMD4(Float(point.x), Float(point.y), Float(point.ring), 0),
+ color: SIMD4(Float(rgb[0]) * brightness, Float(rgb[1]) * brightness, Float(rgb[2]) * brightness, 0),
+ )
+ }) ?? []
+ do {
+ pending = false
+ try backend.render(texture: drawable.texture, drawable: drawable, uniforms: uniforms, leds: leds) { [weak self] error in
+ guard let self else { return }
+ if let error {
+ renderingError = error
+ print("[homepod] Metal frame: \(error)")
+ }
+ if pending { needsDisplay = true }
+ }
+ } catch {
+ renderingError = error.localizedDescription
+ print("[homepod] Metal frame: \(error)")
+ }
+ }
+}
+
+// MARK: - Frame Ownership
+
+@MainActor
+protocol VPhoneHomePodMetalBackend: AnyObject {
+ var name: String { get }
+ var hasFreeFrame: Bool { get }
+ func render(texture: any MTLTexture, drawable: (any CAMetalDrawable)?, uniforms: VPhoneHomePodMetalUniforms,
+ leds: [VPhoneHomePodMetalLED], completion: @escaping @MainActor (String?) -> Void) throws
+}
+
+@MainActor
+private class VPhoneHomePodMetalFrame {
+ static let maximumLEDCount = 1024
+ let uniforms: any MTLBuffer
+ let leds: any MTLBuffer
+ var inFlight = false
+ var texture: (any MTLTexture)?
+ var drawable: (any CAMetalDrawable)?
+
+ init(device: any MTLDevice) throws {
+ guard let uniforms = device.makeBuffer(length: MemoryLayout<VPhoneHomePodMetalUniforms>.stride, options: .storageModeShared),
+ let leds = device.makeBuffer(length: MemoryLayout<VPhoneHomePodMetalLED>.stride * Self.maximumLEDCount, options: .storageModeShared)
+ else { throw VPhoneHomePodMetalError.unavailable("Could not allocate HomePod frame buffers.") }
+ self.uniforms = uniforms
+ self.leds = leds
+ }
+
+ func write(_ value: VPhoneHomePodMetalUniforms, leds values: [VPhoneHomePodMetalLED]) throws {
+ guard values.count <= Self.maximumLEDCount else { throw VPhoneHomePodMetalError.unavailable("Too many HomePod LEDs.") }
+ var value = value
+ withUnsafeBytes(of: &value) { uniforms.contents().copyMemory(from: $0.baseAddress!, byteCount: $0.count) }
+ values.withUnsafeBytes { bytes in
+ if let base = bytes.baseAddress, !bytes.isEmpty { leds.contents().copyMemory(from: base, byteCount: bytes.count) }
+ }
+ }
+
+ func finish() {
+ inFlight = false
+ texture = nil
+ drawable = nil
+ }
+}
+
+// MARK: - Metal 4
+
+@available(macOS 26.0, *)
+@MainActor
+final class VPhoneHomePodMetal4Backend: VPhoneHomePodMetalBackend {
+ let name = "Metal 4"
+ private let queue: any MTL4CommandQueue
+ private let pipeline: any MTLRenderPipelineState
+ private let frames: [Frame]
+ var hasFreeFrame: Bool { frames.contains { !$0.inFlight } }
+
+ private final class Frame: VPhoneHomePodMetalFrame {
+ let allocator: any MTL4CommandAllocator
+ let commands: any MTL4CommandBuffer
+ let arguments: any MTL4ArgumentTable
+ let residency: any MTLResidencySet
+
+ override init(device: any MTLDevice) throws {
+ guard let allocator = device.makeCommandAllocator(), let commands = device.makeCommandBuffer()
+ else { throw VPhoneHomePodMetalError.unavailable("Metal 4 command allocation failed.") }
+ self.allocator = allocator
+ self.commands = commands
+ let descriptor = MTL4ArgumentTableDescriptor()
+ descriptor.maxBufferBindCount = 2
+ descriptor.initializeBindings = true
+ arguments = try device.makeArgumentTable(descriptor: descriptor)
+ let residencyDescriptor = MTLResidencySetDescriptor()
+ residencyDescriptor.initialCapacity = 3
+ residency = try device.makeResidencySet(descriptor: residencyDescriptor)
+ try super.init(device: device)
+ arguments.setAddress(uniforms.gpuAddress, index: 0)
+ arguments.setAddress(leds.gpuAddress, index: 1)
+ }
+ }
+
+ init(device: any MTLDevice, format: MTLPixelFormat) throws {
+ guard let queue = device.makeMTL4CommandQueue() else { throw VPhoneHomePodMetalError.unavailable("Metal 4 queue creation failed.") }
+ self.queue = queue
+ let compiler = try device.makeCompiler(descriptor: MTL4CompilerDescriptor())
+ let libraryDescriptor = MTL4LibraryDescriptor()
+ libraryDescriptor.source = VPhoneHomePodShader.source
+ libraryDescriptor.name = "HomePod top-cap optics"
+ let options = MTLCompileOptions()
+ options.languageVersion = .version4_0
+ libraryDescriptor.options = options
+ let library = try compiler.makeLibrary(descriptor: libraryDescriptor)
+ func function(_ name: String) -> MTL4LibraryFunctionDescriptor {
+ let descriptor = MTL4LibraryFunctionDescriptor()
+ descriptor.library = library
+ descriptor.name = name
+ return descriptor
+ }
+ let descriptor = MTL4RenderPipelineDescriptor()
+ descriptor.label = "HomePod diffuser"
+ descriptor.vertexFunctionDescriptor = function("capVertex")
+ descriptor.fragmentFunctionDescriptor = function("capFragment")
+ descriptor.colorAttachments[0].pixelFormat = format
+ pipeline = try compiler.makeRenderPipelineState(descriptor: descriptor, compilerTaskOptions: nil)
+ frames = try (0 ..< 3).map { _ in try Frame(device: device) }
+ }
+
+ func render(texture: any MTLTexture, drawable: (any CAMetalDrawable)?, uniforms: VPhoneHomePodMetalUniforms,
+ leds: [VPhoneHomePodMetalLED], completion: @escaping @MainActor (String?) -> Void) throws {
+ guard let frame = frames.first(where: { !$0.inFlight }) else { return }
+ try frame.write(uniforms, leds: leds)
+ frame.texture = texture
+ frame.drawable = drawable
+ frame.residency.removeAllAllocations()
+ frame.residency.addAllocation(frame.uniforms)
+ frame.residency.addAllocation(frame.leds)
+ frame.residency.addAllocation(texture)
+ frame.residency.commit()
+ // Never reset command memory or rewrite inputs until feedback confirms
+ // GPU completion. Capturing the frame also retains every GPU resource.
+ frame.allocator.reset()
+ frame.commands.beginCommandBuffer(allocator: frame.allocator)
+ frame.commands.useResidencySet(frame.residency)
+ let pass = MTL4RenderPassDescriptor()
+ pass.colorAttachments[0].texture = texture
+ pass.colorAttachments[0].loadAction = .dontCare
+ pass.colorAttachments[0].storeAction = .store
+ guard let encoder = frame.commands.makeRenderCommandEncoder(descriptor: pass) else {
+ frame.commands.endCommandBuffer()
+ frame.finish()
+ throw VPhoneHomePodMetalError.unavailable("Metal 4 render encoder creation failed.")
+ }
+ encoder.setRenderPipelineState(pipeline)
+ encoder.setArgumentTable(frame.arguments, stages: .fragment)
+ encoder.setViewport(MTLViewport(originX: 0, originY: 0, width: Double(texture.width), height: Double(texture.height), znear: 0, zfar: 1))
+ encoder.drawPrimitives(primitiveType: .triangle, vertexStart: 0, vertexCount: 3)
+ encoder.endEncoding()
+ frame.commands.endCommandBuffer()
+ let options = MTL4CommitOptions()
+ options.addFeedbackHandler { feedback in
+ let error = feedback.error?.localizedDescription
+ Task { @MainActor in
+ frame.finish()
+ completion(error)
+ }
+ }
+ frame.inFlight = true
+ if let drawable { queue.waitForDrawable(drawable) }
+ queue.commit([frame.commands], options: options)
+ if let drawable {
+ queue.signalDrawable(drawable)
+ drawable.present()
+ }
+ }
+}
+
+// MARK: - macOS 15 Compatibility
+
+@MainActor
+final class VPhoneHomePodMetalLegacyBackend: VPhoneHomePodMetalBackend {
+ let name = "Metal (macOS 15 compatibility)"
+ private let queue: any MTLCommandQueue
+ private let pipeline: any MTLRenderPipelineState
+ private let frames: [VPhoneHomePodMetalFrame]
+ var hasFreeFrame: Bool { frames.contains { !$0.inFlight } }
+
+ init(device: any MTLDevice, format: MTLPixelFormat) throws {
+ guard let queue = device.makeCommandQueue() else { throw VPhoneHomePodMetalError.unavailable("Metal queue creation failed.") }
+ self.queue = queue
+ let options = MTLCompileOptions()
+ options.languageVersion = .version3_1
+ let library = try device.makeLibrary(source: VPhoneHomePodShader.source, options: options)
+ let descriptor = MTLRenderPipelineDescriptor()
+ descriptor.vertexFunction = library.makeFunction(name: "capVertex")
+ descriptor.fragmentFunction = library.makeFunction(name: "capFragment")
+ descriptor.colorAttachments[0].pixelFormat = format
+ pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
+ frames = try (0 ..< 3).map { _ in try VPhoneHomePodMetalFrame(device: device) }
+ }
+
+ func render(texture: any MTLTexture, drawable: (any CAMetalDrawable)?, uniforms: VPhoneHomePodMetalUniforms,
+ leds: [VPhoneHomePodMetalLED], completion: @escaping @MainActor (String?) -> Void) throws {
+ guard let frame = frames.first(where: { !$0.inFlight }), let commands = queue.makeCommandBuffer() else { return }
+ try frame.write(uniforms, leds: leds)
+ let pass = MTLRenderPassDescriptor()
+ pass.colorAttachments[0].texture = texture
+ pass.colorAttachments[0].loadAction = .dontCare
+ pass.colorAttachments[0].storeAction = .store
+ guard let encoder = commands.makeRenderCommandEncoder(descriptor: pass) else { throw VPhoneHomePodMetalError.unavailable("Metal render encoder creation failed.") }
+ encoder.setRenderPipelineState(pipeline)
+ encoder.setFragmentBuffer(frame.uniforms, offset: 0, index: 0)
+ encoder.setFragmentBuffer(frame.leds, offset: 0, index: 1)
+ encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
+ encoder.endEncoding()
+ frame.inFlight = true
+ commands.addCompletedHandler { commands in
+ let error = commands.error?.localizedDescription
+ Task { @MainActor in frame.finish(); completion(error) }
+ }
+ if let drawable { commands.present(drawable) }
+ commands.commit()
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodShader.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodShader.swift
new file mode 100644
index 00000000..661e4cad
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/HomePod/VPhoneHomePodShader.swift
@@ -0,0 +1,75 @@
+/// Kept as source, rather than a .metal build input: the system Metal compiler
+/// compiles this on the rendering Mac. Building VPhone needs no Metal toolchain.
+enum VPhoneHomePodShader {
+ static let source = #"""
+ #include <metal_stdlib>
+ using namespace metal;
+
+ struct CapUniforms {
+ float4 viewport; // pixel width/height, cap center x/y
+ float4 cap; // radius in pixels, LED count, plus/minus light
+ };
+ struct CapLED { float4 position; float4 color; };
+
+ vertex float4 capVertex(uint index [[vertex_id]]) {
+ constexpr float2 triangle[] = {float2(-1, -1), float2(3, -1), float2(-1, 3)};
+ return float4(triangle[index], 0, 1);
+ }
+
+ float stroke(float2 p, float2 center, bool plus, float aa) {
+ float2 q = abs(p - center);
+ float horizontal = max(q.x - 0.052, q.y - 0.0026);
+ float vertical = max(q.x - 0.0026, q.y - 0.052);
+ return 1.0 - smoothstep(-aa, aa, plus ? min(horizontal, vertical) : horizontal);
+ }
+
+ fragment float4 capFragment(float4 screen [[position]],
+ constant CapUniforms &u [[buffer(0)]],
+ device const CapLED *leds [[buffer(1)]]) {
+ float radius = max(u.cap.x, 1.0);
+ float2 p = (screen.xy - u.viewport.zw) / (radius * 2.0) + 0.5;
+ float r = length(p - 0.5) * 2.0;
+ float aa = 0.65 / radius;
+ // All values below are linear; the sRGB render target performs the
+ // display transfer exactly once, after optical mixing.
+ const float3 background = float3(0.0044);
+ if (r > 1.0 + aa * 2.0) return float4(background, 1);
+
+ // A broad point-spread function merges neighbouring emitters beneath
+ // the glass. Normalize the optical footprint, not the active colors:
+ // inactive LEDs continue to contribute zero, preserving guest patterns.
+ float3 light = 0;
+ float weightSum = 0;
+ for (uint i = 0; i < uint(u.cap.y); ++i) {
+ float2 d = p - leds[i].position.xy;
+ float d2 = dot(d, d);
+ float weight = 0.86 * exp(-d2 / (2.0 * 0.155 * 0.155))
+ + 0.14 * exp(-d2 / (2.0 * 0.29 * 0.29));
+ light += leds[i].color.rgb * weight;
+ weightSum += weight;
+ }
+ light /= max(weightSum, 0.001);
+ // The original mini's opaque edge masks scattered light; there are no
+ // visible LED points or time-based effects added by the host.
+ float edge = 1.0 - smoothstep(0.70, 0.985, r);
+ light *= edge * 1.55;
+ light = light / (1.0 + 0.45 * light);
+
+ float glass = 0.0014 + 0.0015 * pow(max(0.0, 1.0 - r * r), 3.0);
+ float reflection = 0.0022 * exp(-dot(p - float2(0.38, 0.24), p - float2(0.38, 0.24)) / 0.12);
+ float3 surface = light + glass + reflection;
+
+ float minus = stroke(p, float2(0.20, 0.5), false, aa * 0.5);
+ float plus = stroke(p, float2(0.80, 0.5), true, aa * 0.5);
+ // Etched markings remain faintly visible in reflected light. Their
+ // emitted white light is a separate, guest-controlled HID channel.
+ surface = mix(surface, float3(0.006) + surface * 0.12, max(minus, plus));
+ surface += float3(minus * u.cap.w + plus * u.cap.z) * 0.9;
+
+ float rim = exp(-pow((r - 0.992) / max(aa * 1.7, 0.002), 2.0));
+ surface += rim * 0.012;
+ float cover = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, r);
+ return float4(mix(background, surface, cover), 1);
+ }
+ """#
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneControlsView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneControlsView.swift
index 79064965..8f4b1146 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneControlsView.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneControlsView.swift
@@ -8,6 +8,9 @@ struct VPhoneControlsView: View {
Form {
displaySection
audioSection
+ if model.control.isHomePodGuest {
+ VPhoneHomePodDebugSection(control: model.control)
+ }
powerSection
buttonsSection
keyboardSection
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift
new file mode 100644
index 00000000..50dbaa55
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugModel.swift
@@ -0,0 +1,133 @@
+import Foundation
+
+/// SoundBoard supplies its fixed, ABI-checked debug catalog. Keeping the editor
+/// driven by that catalog avoids silently hiding operations when UI and daemon
+/// versions differ.
+@MainActor
+@Observable
+final class VPhoneHomePodDebugModel {
+ struct Argument: Decodable, Identifiable {
+ let name: String
+ let type: String
+ let initial: VPhoneHomePodDebugJSON
+ let help: String
+ var id: String { name }
+ }
+
+ struct Operation: Decodable, Identifiable {
+ let id: String
+ let title: String
+ let group: String
+ let arguments: [Argument]
+ let reply: String
+ let help: String
+ let available: Bool
+ }
+
+ struct Group: Identifiable {
+ let id: String
+ let operations: [Operation]
+ }
+
+ let control: VPhoneGuestControl
+ private(set) var groups: [Group] = []
+ private(set) var operations: [Operation] = []
+ private(set) var animations: [String] = []
+ private(set) var phases: [String] = []
+ var selectedID = "getAllDebugInfo:"
+ var values: [String: String] = [:]
+ private(set) var isBusy = false
+ private(set) var result = ""
+ private(set) var error: String?
+
+ var selected: Operation? { operations.first { $0.id == selectedID } }
+
+ init(control: VPhoneGuestControl) { self.control = control }
+
+ func load() async {
+ guard !isBusy, control.isConnected else { return }
+ guard control.guestCapabilities.contains("homepod_debug") else {
+ error = "The guest agent does not expose SoundBoard debugging. Update the guest environment to use these controls."
+ return
+ }
+ isBusy = true
+ defer { isBusy = false }
+ do {
+ let result = try await control.call("homepod.debug.catalog")
+ let data = try JSONSerialization.data(withJSONObject: result["operations"] ?? [])
+ operations = try JSONDecoder().decode([Operation].self, from: data)
+ animations = result["animations"] as? [String] ?? []
+ phases = result["phases"] as? [String] ?? []
+ var names: [String] = []
+ for operation in operations where !names.contains(operation.group) { names.append(operation.group) }
+ groups = names.map { name in Group(id: name, operations: operations.filter { $0.group == name }) }
+ if !operations.contains(where: { $0.id == selectedID }) { selectedID = operations.first?.id ?? "" }
+ resetArguments()
+ error = nil
+ } catch { self.error = String(describing: error) }
+ }
+
+ func resetArguments() {
+ values = Dictionary(uniqueKeysWithValues: (selected?.arguments ?? []).map { ($0.name, $0.initial.editorText) })
+ }
+
+ func execute() async {
+ guard !isBusy, control.isConnected, let operation = selected, operation.available else { return }
+ isBusy = true
+ error = nil
+ defer { isBusy = false }
+ do {
+ var arguments: [String: Any] = [:]
+ for argument in operation.arguments {
+ let text = values[argument.name] ?? ""
+ if argument.type == "string" { arguments[argument.name] = text; continue }
+ guard let data = text.data(using: .utf8) else { throw VPhoneHomePodDebugEditorError.invalid(argument.name) }
+ do { arguments[argument.name] = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) }
+ catch { throw VPhoneHomePodDebugEditorError.invalid(argument.name) }
+ }
+ let response = try await control.call("homepod.debug.call", params: ["operation": operation.id, "arguments": arguments])
+ let data = try JSONSerialization.data(withJSONObject: response, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ result = String(decoding: data, as: UTF8.self)
+ } catch { self.error = String(describing: error) }
+ }
+}
+
+private enum VPhoneHomePodDebugEditorError: Error, CustomStringConvertible {
+ case invalid(String)
+ var description: String {
+ switch self { case let .invalid(name): "\(name) must contain a valid JSON value." }
+ }
+}
+
+/// Codable JSON preserves the guest's typed argument defaults without an Any
+/// payload in observable state.
+indirect enum VPhoneHomePodDebugJSON: Decodable {
+ case string(String), number(Double), bool(Bool), array([Self]), object([String: Self]), null
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if container.decodeNil() { self = .null }
+ else if let value = try? container.decode(Bool.self) { self = .bool(value) }
+ else if let value = try? container.decode(Double.self) { self = .number(value) }
+ else if let value = try? container.decode(String.self) { self = .string(value) }
+ else if let value = try? container.decode([Self].self) { self = .array(value) }
+ else { self = try .object(container.decode([String: Self].self)) }
+ }
+
+ private var object: Any {
+ switch self {
+ case let .string(value): value
+ case let .number(value): value
+ case let .bool(value): value
+ case let .array(value): value.map(\.object)
+ case let .object(value): value.mapValues(\.object)
+ case .null: NSNull()
+ }
+ }
+
+ var editorText: String {
+ if case let .string(value) = self { return value }
+ guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.fragmentsAllowed, .prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else { return "null" }
+ return String(decoding: data, as: UTF8.self)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift
new file mode 100644
index 00000000..8bda0f59
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Controls/VPhoneHomePodDebugSection.swift
@@ -0,0 +1,173 @@
+import SwiftUI
+
+struct VPhoneHomePodDebugSection: View {
+ @State private var model: VPhoneHomePodDebugModel
+
+ init(control: VPhoneGuestControl) {
+ _model = State(initialValue: VPhoneHomePodDebugModel(control: control))
+ }
+
+ var body: some View {
+ Section("HomePod") {
+ Picker("SoundBoard Debug Control", selection: $model.selectedID) {
+ ForEach(model.groups) { group in
+ Section(group.id) {
+ ForEach(group.operations) { operation in
+ Text(verbatim: operation.title).tag(operation.id)
+ }
+ }
+ }
+ }
+ .disabled(model.isBusy || model.operations.isEmpty)
+ .onChange(of: model.selectedID) { _, _ in model.resetArguments() }
+
+ if let operation = model.selected {
+ VPhoneHomePodDebugOperationEditor(model: model, operation: operation)
+ .disabled(!model.control.guestCapabilities.contains("homepod_debug"))
+ }
+ if let error = model.error {
+ Text(verbatim: error)
+ .font(.callout)
+ .foregroundStyle(.red)
+ .textSelection(.enabled)
+ }
+ if !model.result.isEmpty {
+ DisclosureGroup("SoundBoard Reply") {
+ ScrollView([.horizontal, .vertical]) {
+ Text(verbatim: model.result)
+ .font(.system(size: 11, design: .monospaced))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(8)
+ }
+ .frame(minHeight: 80, maxHeight: 280)
+ HStack {
+ Spacer()
+ Button("Copy Reply") {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(model.result, forType: .string)
+ }
+ }
+ }
+ }
+ HStack {
+ Text("Commands without a reply report submission. SoundBoard applies them asynchronously.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ Spacer(minLength: 8)
+ Button("Reload Controls") { Task { await model.load() } }
+ .disabled(model.isBusy)
+ }
+ }
+ .task(id: model.control.isConnected && model.control.guestCapabilities.contains("homepod_debug")) {
+ await model.load()
+ }
+ }
+}
+
+private struct VPhoneHomePodDebugOperationEditor: View {
+ @Bindable var model: VPhoneHomePodDebugModel
+ let operation: VPhoneHomePodDebugModel.Operation
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(verbatim: operation.help)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ Text(verbatim: operation.id)
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ ForEach(operation.arguments) { argument in
+ VStack(alignment: .leading, spacing: 4) {
+ if operation.id == "render:" {
+ VPhoneHomePodAnimationEditor(
+ animations: model.animations,
+ phases: model.phases,
+ value: Binding {
+ model.values[argument.name] ?? "{}"
+ } set: { model.values[argument.name] = $0 }
+ )
+ } else {
+ VPhoneHomePodDebugArgumentEditor(
+ argument: argument,
+ value: Binding {
+ model.values[argument.name] ?? ""
+ } set: { model.values[argument.name] = $0 }
+ )
+ }
+ }
+ }
+ if !operation.available {
+ Text("This operation's native signature is unavailable on the guest firmware.")
+ .foregroundStyle(.secondary)
+ }
+ HStack {
+ Spacer()
+ if model.isBusy { ProgressView().controlSize(.small) }
+ Button(operation.reply == "none" ? "Send Command" : "Read") {
+ Task { await model.execute() }
+ }
+ .disabled(model.isBusy || !operation.available)
+ }
+ }
+ .disabled(model.isBusy)
+ }
+}
+
+private struct VPhoneHomePodAnimationEditor: View {
+ let animations: [String]
+ let phases: [String]
+ @Binding var value: String
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Picker("Animation", selection: selection("animation", fallback: "setup")) {
+ ForEach(animations, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ Picker("Phase", selection: selection("phase", fallback: "On")) {
+ ForEach(phases, id: \.self) { Text(verbatim: $0).tag($0) }
+ }
+ }
+ }
+
+ private func selection(_ key: String, fallback: String) -> Binding<String> {
+ Binding {
+ (try? JSONSerialization.jsonObject(with: Data(value.utf8)) as? [String: String])?[key] ?? fallback
+ } set: { newValue in
+ var options = (try? JSONSerialization.jsonObject(with: Data(value.utf8)) as? [String: String]) ?? [:]
+ options[key] = newValue
+ if let data = try? JSONSerialization.data(withJSONObject: options, options: [.sortedKeys]) {
+ value = String(decoding: data, as: UTF8.self)
+ }
+ }
+ }
+}
+
+private struct VPhoneHomePodDebugArgumentEditor: View {
+ let argument: VPhoneHomePodDebugModel.Argument
+ @Binding var value: String
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ if argument.type == "bool" {
+ Toggle(argument.name, isOn: Binding {
+ value == "true"
+ } set: { value = $0 ? "true" : "false" })
+ } else if ["array", "dictionary", "button", "replay"].contains(argument.type) {
+ Text(verbatim: argument.name)
+ TextEditor(text: $value)
+ .font(.system(size: 11, design: .monospaced))
+ .frame(minHeight: 80, maxHeight: 180)
+ .border(Color(nsColor: .separatorColor))
+ .accessibilityLabel(argument.name)
+ } else {
+ TextField(argument.name, text: $value)
+ .font(.system(size: 11, design: .monospaced))
+ }
+ Text(verbatim: argument.help)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index 3db01bea..dc2c96ba 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -112,6 +112,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
try await vm.start(forceDFU: command.dfu)
let control = VPhoneGuestControl()
+ control.isHomePodGuest = options.isHomePodGuest
self.control = control
if !command.dfu {
control.unlocksAtStartup = vm.unlocksAtStartup
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h
new file mode 100644
index 00000000..b0b770b7
--- /dev/null
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.h
@@ -0,0 +1,13 @@
+#import <Foundation/Foundation.h>
+#include <sys/types.h>
+
+typedef struct {
+ int (*listPIDs)(uint32_t, uint32_t, void *, int);
+ int (*processPath)(int, void *, uint32_t);
+ int (*signalProcess)(pid_t, int);
+} VPHomePodSetupProcessAPI;
+
+// Called only after the persisted/native completion transition. Only mobile's
+// exact Apple setup executable may receive SIGTERM. No escalation to SIGKILL.
+BOOL VPHomePodSetupStopProcesses(VPHomePodSetupProcessAPI api, uid_t user,
+ NSUInteger maximumPolls, void (^wait)(void), NSError **error);
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m
new file mode 100644
index 00000000..16dd5f45
--- /dev/null
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupProcesses.m
@@ -0,0 +1,78 @@
+#import "HomePodSetupProcesses.h"
+#include <errno.h>
+#include <limits.h>
+#include <signal.h>
+#include <string.h>
+
+// libproc.h / sys/proc_info.h: the tvOS SDK exports libproc.tbd but omits
+// these declarations. PROC_UID_ONLY filters by effective uid (not real uid).
+static const uint32_t VPProcUIDOnly = 4;
+static const char *VPSetupExecutable = "/Applications/HPSetup.app/HPSetup";
+
+static BOOL VPProcessError(NSError **error, NSString *description) {
+ if (error) *error = [NSError errorWithDomain:@"com.vphone.homepod-setup" code:4
+ userInfo:@{NSLocalizedDescriptionKey: description}];
+ return NO;
+}
+
+static NSArray<NSNumber *> *VPSetupProcesses(VPHomePodSetupProcessAPI api, uid_t user, NSError **error) {
+ int needed = api.listPIDs(VPProcUIDOnly, user, NULL, 0);
+ if (needed <= 0) { VPProcessError(error, @"Could not enumerate mobile's processes."); return nil; }
+ NSUInteger capacity = (NSUInteger)needed + 128 * sizeof(pid_t);
+ for (NSUInteger attempt = 0; attempt < 3 && capacity <= 1024 * 1024; attempt++, capacity *= 2) {
+ NSMutableData *data = [NSMutableData dataWithLength:capacity];
+ int bytes = api.listPIDs(VPProcUIDOnly, user, data.mutableBytes, (int)data.length);
+ if (bytes <= 0 || bytes % sizeof(pid_t)) {
+ VPProcessError(error, @"Invalid mobile process enumeration."); return nil;
+ }
+ if ((NSUInteger)bytes >= capacity) continue;
+ NSMutableArray *found = [NSMutableArray array];
+ const pid_t *pids = data.bytes;
+ for (NSUInteger index = 0; index < (NSUInteger)bytes / sizeof(pid_t); index++) {
+ if (pids[index] <= 0) continue;
+ char path[PATH_MAX] = {0};
+ errno = 0;
+ int length = api.processPath(pids[index], path, sizeof(path));
+ if (length <= 0) {
+ if (errno == EACCES || errno == EPERM) {
+ VPProcessError(error, @"Cannot verify an owned process's executable; refusing to claim setup teardown."); return nil;
+ }
+ continue; // Exited during enumeration, or no executable remains.
+ }
+ if ((size_t)length < sizeof(path) && strcmp(path, VPSetupExecutable) == 0) [found addObject:@(pids[index])];
+ }
+ return found;
+ }
+ VPProcessError(error, @"Mobile process enumeration did not stabilize within its bounds.");
+ return nil;
+}
+
+BOOL VPHomePodSetupStopProcesses(VPHomePodSetupProcessAPI api, uid_t user,
+ NSUInteger maximumPolls, void (^wait)(void), NSError **error) {
+ if (user != 501 || !api.listPIDs || !api.processPath || !api.signalProcess || !wait) {
+ return VPProcessError(error, @"HomePod setup teardown requires mobile and the native process APIs.");
+ }
+ NSMutableSet *signaled = [NSMutableSet set];
+ NSUInteger quietPolls = 0;
+ for (NSUInteger poll = 0; poll <= maximumPolls; poll++) {
+ NSArray<NSNumber *> *pids = VPSetupProcesses(api, user, error);
+ if (!pids) return NO;
+ // Observe a short quiet interval too: an app launch requested before
+ // completion may still have been in flight when the first scan ran.
+ quietPolls = pids.count ? 0 : quietPolls + 1;
+ if (quietPolls >= 5) return YES;
+ for (NSNumber *pid in pids) {
+ if ([signaled containsObject:pid]) continue;
+ char path[PATH_MAX] = {0};
+ int length = api.processPath(pid.intValue, path, sizeof(path));
+ if (length <= 0) continue;
+ if ((size_t)length >= sizeof(path) || strcmp(path, VPSetupExecutable)) continue;
+ if (api.signalProcess(pid.intValue, SIGTERM) != 0 && errno != ESRCH) {
+ return VPProcessError(error, @"Could not gracefully stop HomePod setup; no stronger signal was sent.");
+ }
+ [signaled addObject:pid];
+ }
+ if (poll < maximumPolls) wait();
+ }
+ return VPProcessError(error, @"HomePod setup is still running after its graceful completion deadline; journal retained.");
+}
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h
new file mode 100644
index 00000000..a6ce49f4
--- /dev/null
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.h
@@ -0,0 +1,13 @@
+#import <Foundation/Foundation.h>
+
+// Only these local completion flags belong to the bypass. Account, activation,
+// HomeKit and Wi-Fi state remain owned by their native services.
+NSArray<NSString *> *VPHomePodSetupKeys(void);
+BOOL VPHomePodSetupUpdate(BOOL enabled, NSURL *journalURL, NSDictionary<NSString *, id> *current,
+ void (^setValue)(NSString *, id), BOOL (^synchronize)(void), NSError **error);
+
+// Call after preferences synchronize. Native prepare publishes a new sentinel's
+// completion itself; only an already-completed state needs an explicit replay.
+BOOL VPHomePodSetupPrepare(BOOL enabled, BOOL expectedNeedsSetup, BOOL expectedCompleted,
+ BOOL (^needsSetup)(void), BOOL (^completed)(void), void (^prepare)(void),
+ BOOL (^publishFinished)(void), NSError **error);
diff --git a/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m
new file mode 100644
index 00000000..6c1fa643
--- /dev/null
+++ b/VPhoneGuestComponents/HomePodSetup/HomePodSetupState.m
@@ -0,0 +1,75 @@
+#import "HomePodSetupState.h"
+
+NSArray<NSString *> *VPHomePodSetupKeys(void) {
+ return @[@"SetupDone", @"SetupFinishedAllSteps"];
+}
+
+static BOOL VPSetupError(NSError **error, NSString *description) {
+ if (error) *error = [NSError errorWithDomain:@"com.vphone.homepod-setup" code:1
+ userInfo:@{NSLocalizedDescriptionKey: description}];
+ return NO;
+}
+
+BOOL VPHomePodSetupUpdate(BOOL enabled, NSURL *journalURL, NSDictionary<NSString *, id> *current,
+ void (^setValue)(NSString *, id), BOOL (^synchronize)(void), NSError **error) {
+ NSFileManager *files = NSFileManager.defaultManager;
+ NSDictionary *journal = nil;
+ if ([files fileExistsAtPath:journalURL.path]) {
+ NSData *data = [NSData dataWithContentsOfURL:journalURL options:0 error:error];
+ if (!data) return NO;
+ journal = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:error];
+ if (![journal isKindOfClass:NSDictionary.class] || ![journal[@"Version"] isEqual:@1]
+ || ![journal[@"Original"] isKindOfClass:NSDictionary.class]
+ || ![journal[@"Absent"] isKindOfClass:NSArray.class]) {
+ return VPSetupError(error, @"Refusing an invalid HomePod setup journal.");
+ }
+ NSMutableSet *recorded = [NSMutableSet setWithArray:[journal[@"Original"] allKeys]];
+ [recorded addObjectsFromArray:journal[@"Absent"]];
+ if (![recorded isEqualToSet:[NSSet setWithArray:VPHomePodSetupKeys()]]
+ || [[journal[@"Original"] allKeys] count] + [journal[@"Absent"] count] != recorded.count) {
+ return VPSetupError(error, @"HomePod setup journal contains unexpected or duplicate keys.");
+ }
+ }
+ if (!enabled && !journal) return YES;
+ if (enabled && !journal) {
+ NSMutableDictionary *original = [NSMutableDictionary dictionary];
+ NSMutableArray *absent = [NSMutableArray array];
+ for (NSString *key in VPHomePodSetupKeys()) {
+ if (current[key]) original[key] = current[key];
+ else [absent addObject:key];
+ }
+ journal = @{@"Version": @1, @"Original": original, @"Absent": absent};
+ if (![files createDirectoryAtURL:journalURL.URLByDeletingLastPathComponent
+ withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions: @0700} error:error]) return NO;
+ NSData *data = [NSPropertyListSerialization dataWithPropertyList:journal
+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:error];
+ // Persist the inverse before touching preferences. A failed write must
+ // never leave completion flags whose original values cannot be restored.
+ if (!data || ![data writeToURL:journalURL options:NSDataWritingAtomic error:error]) return NO;
+ if (![files setAttributes:@{NSFilePosixPermissions: @0600} ofItemAtPath:journalURL.path error:error]) return NO;
+ }
+ for (NSString *key in VPHomePodSetupKeys()) {
+ setValue(key, enabled ? @YES : journal[@"Original"][key]);
+ }
+ if (!synchronize()) return VPSetupError(error, @"Could not synchronize HomePod setup preferences; journal retained.");
+ // The caller must prepare and verify the native launch sentinel before
+ // deleting a restored journal. Preference synchronization alone is not
+ // proof that SoundBoard sees the new setup state.
+ return YES;
+}
+
+BOOL VPHomePodSetupPrepare(BOOL enabled, BOOL expectedNeedsSetup, BOOL expectedCompleted,
+ BOOL (^needsSetup)(void), BOOL (^completed)(void), void (^prepare)(void),
+ BOOL (^publishFinished)(void), NSError **error) {
+ // Read the native gate before prepare changes its sentinel. Reading only
+ // afterward would cause both prepare and our replay to initialize SoundBoard.
+ BOOL neededBeforePrepare = needsSetup();
+ prepare();
+ if (needsSetup() != expectedNeedsSetup || completed() != expectedCompleted) {
+ return VPSetupError(error, @"SetupAssistant did not accept the synchronized setup state; journal retained.");
+ }
+ if (enabled && !neededBeforePrepare && !publishFinished()) {
+ return VPSetupError(error, @"Could not publish native HomePod setup completion; journal retained.");
+ }
+ return YES;
+}
diff --git a/VPhoneGuestComponents/HomePodSetup/com.vphone.homepod-setup.plist b/VPhoneGuestComponents/HomePodSetup/com.vphone.homepod-setup.plist
new file mode 100644
index 00000000..94eb1aa4
--- /dev/null
+++ b/VPhoneGuestComponents/HomePodSetup/com.vphone.homepod-setup.plist
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+ <key>Label</key><string>com.vphone.homepod-setup</string>
+ <key>ProgramArguments</key><array><string>/usr/local/libexec/vphone-homepod-setup</string></array>
+ <key>UserName</key><string>mobile</string>
+ <key>GroupName</key><string>mobile</string>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
+ <key>ThrottleInterval</key><integer>15</integer>
+</dict></plist>
diff --git a/VPhoneGuestComponents/HomePodSetup/main.m b/VPhoneGuestComponents/HomePodSetup/main.m
new file mode 100644
index 00000000..7cf2f66f
--- /dev/null
+++ b/VPhoneGuestComponents/HomePodSetup/main.m
@@ -0,0 +1,102 @@
+// Run as mobile by launchd: the donor SoundBoard writes current-user values,
+// and SetupAssistant's launch sentinel is a per-user POSIX named semaphore.
+#import "HomePodSetupState.h"
+#import "HomePodSetupProcesses.h"
+#import <CoreFoundation/CoreFoundation.h>
+#import <dlfcn.h>
+#import <notify.h>
+#import <signal.h>
+#import <unistd.h>
+
+int main(void) {
+ @autoreleasepool {
+ if (getuid() != 501 || geteuid() != 501) {
+ NSLog(@"HomePod setup maintenance must run as mobile (501).");
+ return 1;
+ }
+ NSString *directory = @"/var/mobile/Library/Application Support/vphone";
+ NSURL *journal = [NSURL fileURLWithPath:[directory stringByAppendingPathComponent:@"HomePodSetupOriginal.plist"]];
+ NSDictionary *policy = [NSDictionary dictionaryWithContentsOfFile:@"/usr/share/vphone/HomePodSetup.plist"];
+ BOOL enabled = [policy[@"Enabled"] isEqual:@YES];
+ BOOL hadJournal = [NSFileManager.defaultManager fileExistsAtPath:journal.path];
+ if (!enabled && !hadJournal) return 0;
+
+ void *framework = dlopen("/System/Library/PrivateFrameworks/SetupAssistant.framework/SetupAssistant", RTLD_NOW);
+ void (*prepare)(void) = framework ? dlsym(framework, "BYSetupAssistantPrepareLaunchSentinel") : NULL;
+ BOOL (*needsSetup)(void) = framework ? dlsym(framework, "BYSetupAssistantNeedsToRun") : NULL;
+ BOOL (*completed)(void) = framework ? dlsym(framework, "BYSetupAssistantHasCompletedInitialRun") : NULL;
+ CFStringRef *finishedNotification = framework ? dlsym(framework, "BYSetupAssistantFinishedDarwinNotification") : NULL;
+ NSError *error = nil;
+ BOOL success = NO;
+ if (!prepare || !needsSetup || !completed || !finishedNotification || !*finishedNotification) {
+ error = [NSError errorWithDomain:@"com.vphone.homepod-setup" code:2
+ userInfo:@{NSLocalizedDescriptionKey: @"Donor SetupAssistant completion APIs are unavailable."}];
+ } else {
+ CFStringRef domain = CFSTR("com.apple.purplebuddy");
+ CFPreferencesSynchronize(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+ NSMutableDictionary *current = [NSMutableDictionary dictionary];
+ for (NSString *key in VPHomePodSetupKeys()) {
+ id value = CFBridgingRelease(CFPreferencesCopyValue((__bridge CFStringRef)key, domain,
+ kCFPreferencesCurrentUser, kCFPreferencesAnyHost));
+ if (value) current[key] = value;
+ }
+ success = VPHomePodSetupUpdate(enabled, journal, current, ^(NSString *key, id value) {
+ CFPreferencesSetValue((__bridge CFStringRef)key, (__bridge CFPropertyListRef)value, domain,
+ kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+ }, ^BOOL {
+ return CFPreferencesSynchronize(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
+ }, &error);
+ if (success) {
+ // The stock function publishes the setup state notification and
+ // prepares/clears the semaphore. SoundBoard then uses its own
+ // setup-gated initialization; do not fake a HomeKit home here.
+ BOOL setupDone = CFPreferencesGetAppBooleanValue(CFSTR("SetupDone"), domain, NULL);
+ BOOL allSteps = CFPreferencesGetAppBooleanValue(CFSTR("SetupFinishedAllSteps"), domain, NULL);
+ BOOL forceNoBuddy = CFPreferencesGetAppBooleanValue(CFSTR("ForceNoBuddy"), domain, NULL);
+ BOOL expectedNeedsSetup = enabled ? NO : !setupDone && !forceNoBuddy;
+ BOOL expectedCompleted = enabled ? YES : allSteps || forceNoBuddy;
+ success = VPHomePodSetupPrepare(enabled, expectedNeedsSetup, expectedCompleted,
+ ^BOOL { return needsSetup(); }, ^BOOL { return completed(); }, ^{ prepare(); }, ^BOOL {
+ // Prepare already publishes when creating the sentinel.
+ // Only replay an existing sentinel's event, using the
+ // donor export rather than duplicating its notification.
+ char name[512];
+ return CFStringGetCString(*finishedNotification, name, sizeof(name), kCFStringEncodingUTF8)
+ && notify_post(name) == NOTIFY_STATUS_OK;
+ }, &error);
+ if (success) {
+ if (enabled) {
+ // A pending HPSetup session owns separate assistant/
+ // voice-trigger assertions; native _setupFinished does
+ // not tear that process down, so finish it gracefully.
+ void *processLibrary = dlopen("/usr/lib/libproc.dylib", RTLD_NOW);
+ VPHomePodSetupProcessAPI api = {
+ .listPIDs = processLibrary ? dlsym(processLibrary, "proc_listpids") : NULL,
+ .processPath = processLibrary ? dlsym(processLibrary, "proc_pidpath") : NULL,
+ .signalProcess = kill,
+ };
+ success = VPHomePodSetupStopProcesses(api, getuid(), 50, ^{
+ NSDate *until = [NSDate dateWithTimeIntervalSinceNow:0.1];
+ [NSRunLoop.currentRunLoop runUntilDate:until];
+ NSTimeInterval remaining = until.timeIntervalSinceNow;
+ if (remaining > 0) [NSThread sleepForTimeInterval:remaining];
+ }, &error);
+ } else {
+ // Keep the inverse through the native sentinel transition,
+ // including failures that need a later launchd retry.
+ success = [NSFileManager.defaultManager removeItemAtURL:journal error:&error];
+ }
+ }
+ }
+ }
+ [NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES
+ attributes:@{NSFilePosixPermissions: @0700} error:NULL];
+ NSMutableDictionary *status = [@{@"Enabled": @(enabled), @"Succeeded": @(success), @"Updated": NSDate.date} mutableCopy];
+ if (needsSetup) status[@"NeedsSetup"] = @(needsSetup());
+ if (completed) status[@"CompletedInitialRun"] = @(completed());
+ if (error) status[@"Error"] = error.localizedDescription;
+ [status writeToFile:[directory stringByAppendingPathComponent:@"HomePodSetupStatus.plist"] atomically:YES];
+ NSLog(@"HomePod setup maintenance: %@", status);
+ return success ? 0 : 1;
+ }
+}
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 793037d4..444ae37c 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -97,6 +97,9 @@ ATTITUDE_SOURCES := $(call find_sources,Attitude)
ATTITUDE_INPUTS := $(call find_headers,Attitude) $(call find_folders,Attitude) Shared/AttitudeProcess.h
HOMEPODDISPLAY := $(STAGE)/homepoddisplay/libvphonehomepoddisplay.dylib
HOMEPODDISPLAY_SOURCES := $(call find_sources,HomePodDisplay)
+HOMEPODSETUP := $(STAGE)/homepodsetup/vphone-homepod-setup
+HOMEPODSETUP_SOURCES := $(call find_sources,HomePodSetup)
+HOMEPODSETUP_INPUTS := $(call find_headers,HomePodSetup) HomePodSetup/com.vphone.homepod-setup.plist
GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib
GPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)
GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)
@@ -130,7 +133,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driver
VIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)
VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd
-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(GPU_PLUGIN) $(VIRTIOSOUND)
+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(HOMEPODSETUP) $(GPU_PLUGIN) $(VIRTIOSOUND)
PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \
$(STAGE)/misfix/libmisfix.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
@@ -152,7 +155,7 @@ gpu: $(GPU_PLUGIN)
package: all
@rm -f $(ARCHIVE)
- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay gpu virtiosound
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay homepodsetup gpu virtiosound
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -352,6 +355,23 @@ $(HOMEPODDISPLAY): $(HOMEPODDISPLAY_SOURCES)
-o $@ $(HOMEPODDISPLAY_SOURCES) -framework Foundation -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
+$(HOMEPODSETUP): $(HOMEPODSETUP_SOURCES) $(HOMEPODSETUP_INPUTS)
+ @mkdir -p $(STAGE)/homepodsetup
+ xcrun --sdk appletvos clang -arch arm64e -mtvos-version-min=27.0 -Os -fobjc-arc \
+ -Wall -Wextra -Werror -o $@ $(HOMEPODSETUP_SOURCES) -framework Foundation
+ @cp HomePodSetup/com.vphone.homepod-setup.plist $(STAGE)/homepodsetup/
+ @codesign --force --sign - $@
+
+.PHONY: test-homepod-setup
+test-homepod-setup:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHomePodSetup \
+ -o $(OUT)/HomePodSetupTests Tests/HomePodSetupTests.m HomePodSetup/HomePodSetupState.m -framework Foundation
+ @$(OUT)/HomePodSetupTests
+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHomePodSetup \
+ -o $(OUT)/HomePodSetupProcessTests Tests/HomePodSetupProcessTests.m HomePodSetup/HomePodSetupProcesses.m -framework Foundation
+ @$(OUT)/HomePodSetupProcessTests
+
.PHONY: test-attitude
test-attitude:
@mkdir -p $(OUT)
diff --git a/VPhoneGuestComponents/README.md b/VPhoneGuestComponents/README.md
index 4e744cd9..ee9c7744 100644
--- a/VPhoneGuestComponents/README.md
+++ b/VPhoneGuestComponents/README.md
@@ -16,6 +16,7 @@ tweak filter plists, and the GPU provenance note:
| Gravity accelerometer | `accelerometer/libvphoneaccelerometer.dylib` |
| Device attitude | `attitude/libvphoneattitude.dylib` |
| HomePod display identity | `homepoddisplay/libvphonehomepoddisplay.dylib` |
+| HomePod setup maintenance | `homepodsetup/vphone-homepod-setup`, `homepodsetup/com.vphone.homepod-setup.plist` |
| Launchd hook | `launchhook/launchdhook-vphone.dylib` |
| Process injection bridge | `systemhook/SystemHook-vphone.dylib` |
| iOS 27 app registrar | `vpregister/vpregister` |
diff --git a/VPhoneGuestComponents/Tests/HomePodSetupProcessTests.m b/VPhoneGuestComponents/Tests/HomePodSetupProcessTests.m
new file mode 100644
index 00000000..fc742fcb
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/HomePodSetupProcessTests.m
@@ -0,0 +1,82 @@
+#import "HomePodSetupProcesses.h"
+#include <assert.h>
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+
+static BOOL running, initialLaunchInFlight, wrongPath, identityChanges, denied, refusesSignal, enumerationFails;
+static NSUInteger ticks, signals, pathReads;
+
+static int listPIDs(uint32_t type, uint32_t user, void *buffer, int capacity) {
+ assert(type == 4 && user == 501); // Never enumerate arbitrary users.
+ if (enumerationFails) return 0;
+ pid_t pids[] = {7, 188}; // mobile's unrelated process and HPSetup.
+ int bytes = (running || initialLaunchInFlight) ? sizeof(pids) : sizeof(pid_t);
+ if (!buffer) return bytes;
+ assert(capacity >= bytes);
+ memcpy(buffer, pids, (size_t)bytes);
+ return bytes;
+}
+static int processPath(int pid, void *buffer, uint32_t capacity) {
+ const char *path = "/usr/bin/unrelated";
+ if (pid == 188) {
+ pathReads++;
+ if (denied) { errno = EPERM; return 0; }
+ if (!running) { errno = ESRCH; return 0; }
+ path = wrongPath || (identityChanges && pathReads > 1)
+ ? "/tmp/HPSetup" : "/Applications/HPSetup.app/HPSetup";
+ }
+ assert(strlen(path) + 1 < capacity);
+ strcpy(buffer, path);
+ return (int)strlen(path);
+}
+static int signalProcess(pid_t pid, int signal) {
+ assert(pid == 188 && signal == SIGTERM); // No other process or stronger signal.
+ signals++;
+ if (!refusesSignal) running = NO;
+ return 0;
+}
+static void reset(void) {
+ running = initialLaunchInFlight = wrongPath = identityChanges = denied = refusesSignal = enumerationFails = NO;
+ ticks = signals = pathReads = 0;
+}
+
+int main(void) {
+ @autoreleasepool {
+ VPHomePodSetupProcessAPI api = {listPIDs, processPath, signalProcess};
+ NSError *error = nil;
+ void (^wait)(void) = ^{
+ ticks++;
+ if (initialLaunchInFlight && ticks == 2) { running = YES; initialLaunchInFlight = NO; }
+ };
+ reset();
+ assert(VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 0 && ticks == 4); // Helper first: bounded quiet interval.
+ reset(); running = YES;
+ assert(VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 1 && !running); // SoundBoard/HPSetup first: graceful exit observed.
+ reset(); initialLaunchInFlight = YES;
+ assert(VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 1 && !running); // Already-requested launch appears during quiet interval.
+ reset(); running = YES; wrongPath = YES;
+ assert(VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 0); // Basename alone cannot authorize termination.
+ reset(); running = YES; identityChanges = YES;
+ assert(VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 0); // Revalidate identity immediately before signal.
+ reset(); running = YES; denied = YES;
+ assert(!VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 0 && error); // An unreadable identity is not proof setup is gone.
+ reset(); running = YES; refusesSignal = YES;
+ assert(!VPHomePodSetupStopProcesses(api, 501, 6, wait, &error));
+ assert(signals == 1 && ticks == 6 && running); // Timeout; never escalate/repeatedly signal.
+ reset(); enumerationFails = YES;
+ assert(!VPHomePodSetupStopProcesses(api, 501, 10, wait, &error));
+ assert(signals == 0);
+ reset();
+ assert(!VPHomePodSetupStopProcesses(api, 0, 10, wait, &error));
+ assert(signals == 0); // Root/arbitrary-user execution refused.
+ NSLog(@"HomePod setup process ordering and identity tests passed");
+ }
+ return 0;
+}
diff --git a/VPhoneGuestComponents/Tests/HomePodSetupTests.m b/VPhoneGuestComponents/Tests/HomePodSetupTests.m
new file mode 100644
index 00000000..f4e97f66
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/HomePodSetupTests.m
@@ -0,0 +1,98 @@
+#import "HomePodSetupState.h"
+#import <sys/stat.h>
+
+#define CHECK(condition) do { if (!(condition)) { NSLog(@"Failed at line %d: %s", __LINE__, #condition); abort(); } } while (0)
+
+int main(void) {
+ @autoreleasepool {
+ NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:NSUUID.UUID.UUIDString];
+ NSURL *journal = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:@"state/original.plist"]];
+ NSMutableDictionary *preferences = [@{@"SetupDone": @NO, @"Unrelated": @"unchanged"} mutableCopy];
+ __block NSUInteger writes = 0;
+ void (^set)(NSString *, id) = ^(NSString *key, id value) {
+ writes++;
+ if (value) preferences[key] = value;
+ else [preferences removeObjectForKey:key];
+ };
+ NSError *error = nil;
+ CHECK(VPHomePodSetupUpdate(NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK(writes == 0);
+ CHECK(VPHomePodSetupUpdate(YES, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK([preferences[@"SetupDone"] isEqual:@YES]);
+ CHECK([preferences[@"SetupFinishedAllSteps"] isEqual:@YES]);
+ CHECK([preferences[@"Unrelated"] isEqual:@"unchanged"]);
+ NSData *originalJournal = [NSData dataWithContentsOfURL:journal];
+ struct stat metadata;
+ CHECK(stat(journal.path.fileSystemRepresentation, &metadata) == 0 && (metadata.st_mode & 0777) == 0600);
+ // Updating an enabled VM must retain the pre-bypass values rather than
+ // snapshotting the values already written by an earlier boot.
+ CHECK(VPHomePodSetupUpdate(YES, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK([[NSData dataWithContentsOfURL:journal] isEqual:originalJournal]);
+ preferences[@"Unrelated"] = @"edited after enable";
+ CHECK(VPHomePodSetupUpdate(NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK([preferences[@"SetupDone"] isEqual:@NO]);
+ CHECK(preferences[@"SetupFinishedAllSteps"] == nil);
+ CHECK([preferences[@"Unrelated"] isEqual:@"edited after enable"]);
+ // A native sentinel failure after preference synchronization still
+ // needs the journal on the next attempt. Only main removes it after
+ // the stock framework reports the expected state.
+ CHECK([NSFileManager.defaultManager fileExistsAtPath:journal.path]);
+ CHECK(VPHomePodSetupUpdate(NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK([preferences[@"SetupDone"] isEqual:@NO] && preferences[@"SetupFinishedAllSteps"] == nil);
+ CHECK([NSFileManager.defaultManager removeItemAtURL:journal error:&error]);
+ // Failed synchronization retains the inverse so a retry or disable can
+ // still recover. The failure does not silently become an applied state.
+ CHECK(!VPHomePodSetupUpdate(YES, journal, preferences, set, ^BOOL { return NO; }, &error));
+ CHECK(error != nil && [NSFileManager.defaultManager fileExistsAtPath:journal.path]);
+ CHECK(VPHomePodSetupUpdate(NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK([preferences[@"SetupDone"] isEqual:@NO] && preferences[@"SetupFinishedAllSteps"] == nil);
+ // Refuse a corrupted/expanded journal without writing any preferences.
+ [@{@"Version": @1, @"Original": @{@"Unexpected": @YES}, @"Absent": @[]} writeToURL:journal atomically:YES];
+ NSUInteger before = writes;
+ CHECK(!VPHomePodSetupUpdate(NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK(writes == before);
+ // Both keys appearing in the union is insufficient: a duplicate in
+ // Absent or overlap with Original must not be accepted as an inverse.
+ for (NSDictionary *invalid in @[
+ @{@"Version": @1, @"Original": @{@"SetupDone": @NO}, @"Absent": @[@"SetupFinishedAllSteps", @"SetupFinishedAllSteps"]},
+ @{@"Version": @1, @"Original": @{@"SetupDone": @NO}, @"Absent": @[@"SetupDone", @"SetupFinishedAllSteps"]},
+ ]) {
+ CHECK([invalid writeToURL:journal atomically:YES]);
+ CHECK(!VPHomePodSetupUpdate(NO, journal, preferences, set, ^BOOL { return YES; }, &error));
+ CHECK(writes == before);
+ }
+ [NSFileManager.defaultManager removeItemAtPath:path error:NULL];
+ // Model the donor: needsSetup reads the semaphore, while prepare reads
+ // synchronized completion flags and emits only on sentinel creation.
+ __block BOOL sentinel = NO, persistedComplete = YES, prepareFails = NO;
+ __block NSUInteger nativeEvents = 0, replayEvents = 0, prepared = 0;
+ BOOL (^needs)(void) = ^BOOL { return !sentinel; };
+ BOOL (^completed)(void) = ^BOOL { return persistedComplete; };
+ void (^prepare)(void) = ^{
+ prepared++;
+ if (prepareFails) return;
+ if (persistedComplete && !sentinel) nativeEvents++;
+ sentinel = persistedComplete;
+ };
+ BOOL (^publish)(void) = ^BOOL {
+ CHECK(prepared > 0 && sentinel && persistedComplete);
+ replayEvents++;
+ return YES;
+ };
+ CHECK(VPHomePodSetupPrepare(YES, NO, YES, needs, completed, prepare, publish, &error));
+ CHECK(nativeEvents == 1 && replayEvents == 0); // First completion: exactly one native event.
+ CHECK(VPHomePodSetupPrepare(YES, NO, YES, needs, completed, prepare, publish, &error));
+ CHECK(nativeEvents == 1 && replayEvents == 1); // Existing sentinel: recover the event explicitly.
+ persistedComplete = NO;
+ CHECK(VPHomePodSetupPrepare(NO, YES, NO, needs, completed, prepare, publish, &error));
+ CHECK(!sentinel && nativeEvents == 1 && replayEvents == 1); // Opt-out cannot publish completion.
+ persistedComplete = YES; prepareFails = YES;
+ CHECK(!VPHomePodSetupPrepare(YES, NO, YES, needs, completed, prepare, publish, &error));
+ CHECK(!sentinel && nativeEvents == 1 && replayEvents == 1); // Verify before any explicit event.
+ prepareFails = NO; sentinel = YES;
+ CHECK(!VPHomePodSetupPrepare(YES, NO, YES, needs, completed, prepare, ^BOOL { return NO; }, &error));
+ CHECK(error != nil); // Existing-state publication failure must remain retryable.
+ NSLog(@"HomePod setup journal and native transition tests passed");
+ }
+ return 0;
+}