Run a virtual iPhone on an Apple Silicon Mac.
Swift
HomePod welcome experience
Guilherme Rambocb198e43cb9f
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 2fef4792..386a4ebc 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,43 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **HomePod Siri speech policy (2026-10-22, repair runtime unverified).**+> New optional `system-homepod-exp-siri_speech` generates+> `/usr/share/vphone/HomePodSiriSpeech.plist` with `Enabled=true`, restricted to+> 27.x HomePod guests and selected by default only in `homepod-mini`. Installation+> requires vphoned, the top-cap adapter and virtio sound; welcome additionally+> requires this speech policy. Opt-out removes only the selected policy.+> The native branch supports an output-only auxiliary AVAudioSession ID carried+> on a normal type 13 SVXSystemEvent, allowing SoundBoard's existing Siri lifecycle+> and completion to handle speech without entering physical recording setup.+> The candidate repair is scoped to the existing SoundBoard adapter; global+> product identity, audio route and microphone capability flags remain intact.+> Native branch analysis is verified; repair playback remains unverified.+> See [welcome and speech policy](Firmware/homepod_welcome.md).++> **HomePod welcome policy (2026-10-22, runtime validation pending).**+> New optional `system-homepod-exp-welcome` is restricted to 27.x and admitted+> only for HomePod guests. Only `homepod-mini` selects it by default. The guest+> installer checks that vphoned, the HomePod top cap, local setup completion and+> virtio sound and native Siri speech are selected, then generates+> `/usr/share/vphone/HomePodWelcome.plist` with `Enabled=true`. Opt-out removes+> only that policy; once-only Data state remains owned by the guest runtime.+> The coordinator runs in SoundBoard's existing injected HomePod adapter, using+> native tone completion, a coordinated Identify activity and Siri finalization+> after boot readiness. A durable guest-identity claim prevents replay across+> restarts and updates while allowing each template clone its own welcome.+> Catalogue and standalone runtime/state tests pass. Audible synthesis, native+> flourish and end-to-end first-boot behavior still require live validation.+> See [welcome policy and pending native behavior](Firmware/homepod_welcome.md).++> **HomePod welcome pre-live ABI audit (2026-10-23).**+> Direct 24J361 donor-cache metadata establishes UInt32 tone playback+> (`SBUITonePlaybackManager play:completion:`, `v28@0:8I16@?20`). The candidate's+> initial UInt64 mock and guard agreed with each other but would reject the real+> guest method. Both are corrected, with an independent donor-signature fixture+> and rejection coverage for the old shape. Native Siri state/selector analysis+> also confirms a presenting-state activity path separate from microphone audio+> activation; live animation, metering and audibility remain pending.+> **HomePod audio-only identity correction (2026-10-22, live validation).**> An A/B boot of the same installed bundle, changing only the validated donor> product token back to its prior virtual value, restores the native red replay;diff --git a/Research/Firmware/homepod_welcome.md b/Research/Firmware/homepod_welcome.mdnew file mode 100644index 00000000..5e8ba320--- /dev/null+++ b/Research/Firmware/homepod_welcome.md@@ -0,0 +1,218 @@+# HomePod mini first-boot welcome++The guest policies, SoundBoard welcome coordinator, isolated Siri playback+adapter and durable once state are implemented. Local tests pass. No updated+bundle has been installed; audible Siri speech and the full welcome still need+live validation.++## Patch policies++Both patches are optional, apply to 27.x and are admitted only for HomePod guests.+Only the `homepod-mini` preset selects them by default; Standard, Experimental+and both Apple TV presets leave them off. Built-in selections and shipped+preset plists agree.++| Patch | Generated guest policy | Required selections |+| --- | --- | --- |+| `system-homepod-exp-siri_speech` | `/usr/share/vphone/HomePodSiriSpeech.plist` | vphoned, HomePod top cap, virtio sound |+| `system-homepod-exp-welcome` | `/usr/share/vphone/HomePodWelcome.plist` | Those three, local setup completion, native Siri speech |++The exact prerequisites are `system-vphoned-boot-install`,+`system-homepod-exp-top_cap`, `system-virtiosound-cfw-hal_plugin`, and for the+welcome also `system-homepod-exp-setup_bypass` and `system-homepod-exp-siri_speech`.+The installer checks dependencies before guest filesystem writes, then generates+root-owned, mode `0644` binary plists containing `Enabled=true`. Opt-out removes+only the selected policy and preserves guest Data state. Speech can be selected+without welcome or setup bypass; welcome cannot keep a missing prerequisite.++## Guest runtime++The existing HomePodDisplay dylib is injected only into SoundBoard by the top-cap+patch. The Siri adapter validates native method ABIs and installs only while its+policy is enabled. The welcome lifecycle hook installs only after that succeeds.+After Apple's `_applicationsModuleInitComplete` returns, a main-queue timer waits+for `SBSetupController.deviceNeedsSetup=false`, completed native display startup,+`DrawingEnabled=true`, enabled Siri and Siri UI, and an idle Siri session. It+leaves other foreground activities and active media alone; idle `NowPlayingCap`+is a normal foreground activity and does not block the welcome. It never forces+SoundBoard's singleton into existence from the dylib constructor.++After a durable claim the coordinator activates the existing Identify activity+through `setLocalSessionActive:YES`, then plays native tone 1 through+`SBUITonePlaybackManager play:completion:`. Tone 1 resolves to+`HomePodReadyToSetUp-b238.m4a`; the debug selector is `playTone:`.+The native manager takes UInt32 (`v28@0:8I16@?20`), not UInt64. A direct donor+cache audit caught the initial mock/guard mismatch before installation; the+regression harness now compares its tone mock against that independent encoding+and verifies that the old UInt64 shape is rejected.+`HPACoordinatedSession.setActive:` is an error/no-op, so it must not be used.+Identify's `launchWithOptions:` would also play tone 6, so the welcome does not+use that entry point. Apple's Identify renderer supplies the animation;+`endLocalSessionActivity` releases it when the tone finishes or fails.++After successful tone completion and a 650 ms pause, the coordinator rechecks+policy and Siri idleness, then calls the native Siri manager with exactly:++> Hi, I'm Siri. It sure is great to be running in a virtual machine!++The normal type 13 SiriVOX session drives HPASiri's animated display state. The+speech adapter supplies a real active auxiliary playback-session ID so SiriVOX+can use its existing external-session path. The request retains the auxiliary+manager through synthesis finalization, then deactivates/releases it exactly+once and forwards the native NSError. Disabling policy restores original+`say:completion:` dispatch. Neither AVAudioSession's shared instance nor global+product identity, audio routing or microphone capability flags are changed.+There is no host playback timer, generated LED replay or new LaunchDaemon.++## Once-only state++The first eligible ready boot exclusively creates and fsyncs `Claim.plist` under+`/var/mobile/Library/Application Support/vphone/HomePodWelcome/<UniqueDeviceID>`+before its first audiovisual side effect. Identity comes from a read-only+MobileGestalt query. Keying by guest identity lets a clone of an already-booted+template receive its own welcome. The immutable claim survives SoundBoard+restarts, reboots and bundle/environment updates. Neither a new OS nor a new+bundle version resets it. Waiting for readiness leaves it unconsumed.++This provides at-most-once behavior. A crash after the durable claim may leave+the sequence incomplete; it must not replay an already-started welcome. Empty,+partial and malformed existing claims also prevent replay. I/O or symlink+failures fail before playback. New directory entries, the claim and its+containing directory are synced before playback can begin.++`Status.plist` is replaced separately and records `TonePlaying`, `ToneFinished`,+`SpeechRequested`, `SpeechFinalized`, cancellation, timeouts or native failures.+Error domain/code/description are retained. `say:completion:` reaches SiriVOX's+synthesis finalizer, which supplies the result's error. The API omits the result+type, including cancellation, so a nil error is recorded as finalized rather+than asserted as audible speech. The debug XPC endpoint acknowledges submission+without exposing this completion. Keeping the claim through opt-out prevents+re-enabling the patch from replaying the welcome.++## Native speech evidence++The 27.0 24J361 donor is the authority. Extracted `SoundBoardFramework` SHA-256:+`a352a2ba4025e714ca8b7208490991d821f63387aeb5268c7937974029246749`;+`SiriVOX` SHA-256:+`84726d96209afc6f1bb9272e18c7fcd9a0e043e7589cb0b87b2b8494d7969dd9`.+Addresses below identify these artifacts, never patch offsets.++- `SBSiriManager say:completion:` (`0x1a6c0297c`) builds a normal type 13+ `SVXSystemEvent` containing an `SVXSpeechSynthesisRequest` (priority 2,+ speakable text, options 0), then activates it through SiriVOX.+- With a zero event audioSessionID, SiriVOX forces audio-session activation+ (options 0, reason 3). The installed guest fails here with AF 221, underlying+ OSStatus -11795, before `sirittsd` receives synthesis work.+- CoreSpeech reports `No input routes. AQ engine couldnt find routes since+ VSPD is not present!`, a nil record route and failed `prepareRecordForStream`.+ Native recording setup requests a physical 14-channel HomePod path. A missing+ voice asset has not been demonstrated.+- A nonzero event audioSessionID follows the existing external-session branch+ and forwards that real session ID to synthesis. The adapter uses+ `SBAudioSessionConfiguration initWithCategory:categoryOptions:`,+ `SBAudioSessionManager auxiliaryAudioSessionManagerWithConfiguration:name:`,+ `activateAndReturnError:` and the returned AVAudioSession's UInt32+ `opaqueSessionID`. It does not invent a bypass ID or relabel a microphone port.+- The early nil callback in SiriVOX's speech-start block is its+ `postActivationHandler`, distinct from the original caller completion. The+ latter flows through synthesis finalization and `SVXSpeechSynthesisResult.error`.+ Earcon `didStopSoundWithID:` callbacks are not utterance-completion signals.++Focused disassembly, donor method encodings, REA snapshots and live diagnostics+are retained locally under `.build/homepod-welcome-research/`. They are diagnostic+artifacts; the shipped guest runtime uses framework APIs and runtime metadata.++### External-session animation audit (2026-10-23)++Static native evidence supports leaving Apple's display lifecycle in control:++- SiriVOX's external-session preparation block (`0x1a68f4a88`) sets its internal+ lifecycle active and calls+ `session:didBecomeActiveWithActivationContext:activityUUID:turnID:`. This is+ distinct from the public Siri UI state enum. REA evidence:+ `ev_a7edd03019e050ef20daec94b05d8b0bb2ce04c206916e8a4cd9dedb406ed2f5`.+- `HPASiri siriSessionService:didChangeStateFrom:to:` (`0x1a6b7aaa4`) updates its+ renderer state, then activates its local coordinated session for listening,+ thinking or presenting (2 through 4), except for native alarm/skip cases.+ Type 13 is not the type-12 bypass. This route does not require the separate+ `audioSessionDidBecomeActive` flag used by `_updateSessionsActive`. REA evidence:+ `ev_c9b20b00458acfa58b52242028a8f32c38c556701a8f5304d7cb18d6caee99b3`.+- Native `drawSurface` (`0x1a6bc7d5c`) sends the current state to+ `renderTransitionToSiriUIState:siriUIRenderState:` when the legacy renderer is+ selected and `_shouldAnimate` permits it; SAE uses the corresponding native+ animation/descriptor route. REA evidence:+ `ev_b82d1f359c74898ffe1695552a1df6bcb2256696fc5f3e3d44f75b1bf7d9b261`.++The direct donor-cache probe resolves those shared selector stubs and verifies+the welcome's native readiness signatures, including the UInt32 tone argument.+Its source/results are `audit-welcome-native.swift` and+`welcome-native-abi-audit.txt` in the local research folder. Numeric branches are+checked against decoded instructions: Hopper's pseudocode loses the unsigned+subtract/range test in the Siri state callback and must not be read literally.+Snapshots are `soundboard-animation-audit-rea.json` and+`sirivox-external-animation-audit-rea.json`. These establish native control flow,+not actual frame delivery, speech metering or audibility in the installed guest.++## Verification and remaining live checks++Catalogue/resolution tests pass (43 tests), covering version/preset selection,+TV rejection, both policy targets, missing dependencies and independent opt-out.+The complete `VPhone` Debug bundle builds successfully and passes bundle+admission. Xcode's connector lists the owning test scheme but omits the aggregate+`VPhone` scheme, so the catalogue tests ran through Xcode MCP and the finished+bundle used the repository's documented `xcodebuild` command with the selected+`/Applications/Xcode.app` toolchain. The built CLI also emits the updated patch+catalogue successfully.+The standalone harnesses run with:++```zsh+make -C VPhoneGuestComponents test-homepod-welcome test-homepod-siri-speech test-homepod-display+```++They cover native readiness ordering, idle NowPlayingCap versus active media,+exact phrase/tone ordering, failures, cancellation, changed ABIs, restart/no+replay, 32 concurrent claims, nested directory durability, malformed/partial+claims, symlinks, real write failures, native speech event fields, auxiliary+session lifetime and cleanup, duplicate completion and original dispatch when+disabled. The display harness checks the existing MiniDisplay identity adapter.+Mock tests establish control flow and ABI handling, not audible synthesis.++Live proof must establish exactly one tone/flourish sequence, the exact spoken+sentence, native Siri animation, completion ordering and no replay after cold+boot. It must also repeat direct debug `siriSay:` and verify display and ordinary+tone playback with the original product token intact. Bundle installation and+these end-to-end checks are deferred until the user is available to authorize+updates. The prior installed audio/display build remains in place.++### Live validation order when authorization is available++1. Install the candidate with `bundle install-local <path> --keep-default`.+ Use its returned version when rebinding `homepod-mini`; preserve the library+ default and other machines. The last read-only inventory still has this VM+ running host/guest bundle `2.11.0-local.40cd1d45`.+2. Inspect the machine's current patch selection. For an initial speech-only+ comparison, block welcome while keeping native Siri speech selected, then+ stop/rebind with `vm set-bundle ... --update-environment`. Do not weaken any+ boot-volume protections or edit the root-owned installed bundle manually.+3. Clear the earlier research-only Buddy debug override before the comparison.+ The existing VM retained `HomePodBuddyConnection` with a simulated+ `siriThinking` activity; this is absent from the default template. Reset that+ default through SoundBoard's native debug interface and restart SoundBoard+ normally (or apply it before the planned VM reboot). Do not replace it with+ another debug override or an LED replay to make the welcome visible.+4. On the speech-only boot, capture SoundBoard/SiriHeadlessService/sirittsd logs,+ native activity diagnostics and top-cap frames while issuing `siriSay:` with+ the exact sentence. Confirm audible speech, presenting-to-idle rendering,+ native finalization, isolated-session cleanup and continued ordinary tone+ output. A submitted debug RPC alone is not a pass.+5. Re-enable welcome, update the guest environment through Launchpad and boot+ with the listener ready. Verify native tone 1 and Identify animation first,+ then the short pause, exact Siri sentence and its native speech animation.+ Inspect the guest's identity-scoped claim/status after playback.+6. Cold boot again and restart SoundBoard: the welcome must not repeat. Verify+ that standalone `siriSay:` remains usable and display frames still arrive.+ Retain the consumption marker; do not add a production reset/replay trigger.++These are planned checks, not completed live results. Administrator authorization+is needed for bundle installation and guest-environment deployment; it has not+been requested while the user is unavailable.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftindex 87cc610e..6b588de2 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -52,13 +52,42 @@ public enum FirmwareGuestPatchResolution {public static let homePodSupportedGuestPatches = tvSupportedGuestPatches.subtracting([FirmwareGuestSystemPatchSet.tvTPRO]).union([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass,- FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.virtioSoundDriver])+ FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome,+ FirmwareGuestSystemPatchSet.homePodSiriSpeech,+ FirmwareGuestSystemPatchSet.virtioSoundDriver]).union(FirmwarePatchSetCatalog.tvOS27UserlandPatches)public static func unvalidatedHomePodGuestPatches(enabled: Set<String>) -> [String] {enabled.intersection(guestTargetIdentifiers).subtracting(homePodSupportedGuestPatches).sorted()}+ public static let homePodWelcomeDependencies: Set<String> = [+ "system-vphoned-boot-install",+ FirmwareGuestSystemPatchSet.homePodTopCap,+ FirmwareGuestSystemPatchSet.homePodSetupBypass,+ FirmwareGuestSystemPatchSet.virtioSoundDriver,+ FirmwareGuestSystemPatchSet.homePodSiriSpeech,+ ]++ /// A welcome opt-out remains installable when any prerequisite is also off.+ /// This checks the current guest selection before any filesystem writes;+ /// the guest runtime must still verify readiness before consuming its claim.+ public static func missingHomePodWelcomeDependencies(enabled: Set<String>) -> [String] {+ guard enabled.contains(FirmwareGuestSystemPatchSet.homePodWelcome) else { return [] }+ return homePodWelcomeDependencies.subtracting(enabled).sorted()+ }++ public static let homePodSiriSpeechDependencies: Set<String> = [+ "system-vphoned-boot-install",+ FirmwareGuestSystemPatchSet.homePodTopCap,+ FirmwareGuestSystemPatchSet.virtioSoundDriver,+ ]++ public static func missingHomePodSiriSpeechDependencies(enabled: Set<String>) -> [String] {+ guard enabled.contains(FirmwareGuestSystemPatchSet.homePodSiriSpeech) else { return [] }+ return homePodSiriSpeechDependencies.subtracting(enabled).sorted()+ }+/// Every bundled-set patch whose bytes the guest half of an install writes —/// the dyld shared cache, a guest Mach-O, its entitlements, a guest file, or/// the Preboot device tree. The complement is the boot chain, which `fwdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 760c886a..50671b16 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -331,6 +331,20 @@ public enum FirmwareGuestSystemPatchSet {target: .guestFile(path: homePodSetupPath),applicability: VPhonePatchApplicability(iOSBase: .major(27)),),+ VPhonePatchDeclaration(+ identifier: homePodSiriSpeech,+ title: "HomePod native Siri speech",+ summary: "Enables the HomePod guest's output-only auxiliary audio session on native Siri speech events, using the existing SoundBoard adapter. Requires vphoned, the HomePod top cap and virtio sound. Turning it off removes only this policy. The native branch is verified; repair playback remains pending runtime validation.",+ target: .guestFile(path: homePodSiriSpeechPath),+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),+ ),+ VPhonePatchDeclaration(+ identifier: homePodWelcome,+ title: "HomePod first-boot welcome",+ summary: "Enables a guest-owned, one-time welcome after HomePod setup, display and audio services become ready. Requires vphoned, the HomePod top cap, local setup completion, virtio sound and native Siri speech. Turning it off removes the policy and preserves the guest's once-only state. Native welcome playback remains pending runtime validation.",+ target: .guestFile(path: homePodWelcomePath),+ applicability: VPhonePatchApplicability(iOSBase: .major(27)),+ ),VPhonePatchDeclaration(identifier: "system-launchdaemons-boot-environment",title: "Guest environment",@@ -595,6 +609,10 @@ public enum FirmwareGuestSystemPatchSet {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 homePodWelcome = "system-homepod-exp-welcome"+ public static let homePodWelcomePath = "/usr/share/vphone/HomePodWelcome.plist"+ public static let homePodSiriSpeech = "system-homepod-exp-siri_speech"+ public static let homePodSiriSpeechPath = "/usr/share/vphone/HomePodSiriSpeech.plist"public static let prebootBoardAudio = "preboot-cfw-devicetree_board_audio"public static let homePodAudioProduct = "preboot-homepod-exp-audio_product"diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex f26ae38f..7d4182f9 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, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct])+ .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech]).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, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct]),+ selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech]),)/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no@@ -326,7 +326,7 @@ public enum FirmwarePatchSetCatalog {summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion and virtio audio using an audio-only B520 route, without changing the VM product token or adding Apple TV OTA replacement or iPhone display, camera and routing hooks.",patchSets: bundledReferences,selection: .block(- manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass])+ manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech]).union(tvOSBlockedPatches.subtracting(tvOS27UserlandPatches).subtracting([FirmwareGuestSystemPatchSet.virtioSoundDriver])),),)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftindex 2b39faf0..9ce8ea71 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -26,7 +26,8 @@ struct FirmwareGuestPatchResolutionTests {#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true) == [identifier])}- @Test(arguments: [FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct])+ @Test(arguments: [FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct,+ FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech])func `HomePod optional guest repairs are version gated and never selected for other devices`(identifier: String) throws {for base in ["26.4", "27.0", "27.1"] {for preset in FirmwarePatchSetCatalog.builtInPresets {@@ -45,6 +46,59 @@ struct FirmwareGuestPatchResolutionTests {#expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: []).contains(identifier))}+ @Test func `HomePod welcome requires every selected runtime prerequisite but opt out is independent`() throws {+ let welcome = FirmwareGuestSystemPatchSet.homePodWelcome+ let dependencies = FirmwareGuestPatchResolution.homePodWelcomeDependencies+ #expect(dependencies == ["system-vphoned-boot-install", FirmwareGuestSystemPatchSet.homePodTopCap,+ FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.virtioSoundDriver,+ FirmwareGuestSystemPatchSet.homePodSiriSpeech])+ let complete = dependencies.union([welcome])+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: complete).isEmpty)+ for dependency in dependencies {+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: complete.subtracting([dependency])) == [dependency])+ }+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: [welcome]) == dependencies.sorted())+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: []).isEmpty)+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: dependencies).isEmpty)+ let plan = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.homePodMiniPreset, patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("27.0"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(plan.isEnabled(welcome))+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: plan.enabled).isEmpty)+ let declaration = try #require(FirmwarePatchSetCatalog.allDeclarations.first { $0.identifier == welcome })+ #expect(declaration.target == .guestFile(path: "/usr/share/vphone/HomePodWelcome.plist"))+ #expect(!declaration.bootEssential)+ }++ @Test func `HomePod Siri speech requires its native output dependencies and can be disabled independently`() throws {+ let speech = FirmwareGuestSystemPatchSet.homePodSiriSpeech+ let dependencies = FirmwareGuestPatchResolution.homePodSiriSpeechDependencies+ #expect(dependencies == ["system-vphoned-boot-install", FirmwareGuestSystemPatchSet.homePodTopCap,+ FirmwareGuestSystemPatchSet.virtioSoundDriver])+ let complete = dependencies.union([speech])+ #expect(FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: complete).isEmpty)+ for dependency in dependencies {+ #expect(FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: complete.subtracting([dependency])) == [dependency])+ }+ #expect(FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: [speech]) == dependencies.sorted())+ #expect(FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: []).isEmpty)+ #expect(FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: dependencies).isEmpty)+ #expect(!dependencies.contains(FirmwareGuestSystemPatchSet.homePodSetupBypass))+ #expect(!dependencies.contains(FirmwareGuestSystemPatchSet.homePodWelcome))+ let plan = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.homePodMiniPreset, patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("27.0"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(plan.isEnabled(speech))+ #expect(FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: plan.enabled).isEmpty)+ let declaration = try #require(FirmwarePatchSetCatalog.allDeclarations.first { $0.identifier == speech })+ #expect(declaration.target == .guestFile(path: "/usr/share/vphone/HomePodSiriSpeech.plist"))+ #expect(!declaration.bootEssential)+ // Welcome cannot remain enabled after opting out of its speech repair.+ #expect(FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: plan.enabled.subtracting([speech])) == [speech])+ }+@Testfunc `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.swiftindex f963463f..e588c520 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -198,6 +198,8 @@ struct FirmwarePatchSetCatalogTests {FirmwarePatchSetCatalog.manualOnlyPatches.contains($0.identifier)&& $0.identifier != FirmwareGuestSystemPatchSet.homePodTopCap&& $0.identifier != FirmwareGuestSystemPatchSet.homePodSetupBypass+ && $0.identifier != FirmwareGuestSystemPatchSet.homePodWelcome+ && $0.identifier != FirmwareGuestSystemPatchSet.homePodSiriSpeech&& $0.identifier != FirmwareGuestSystemPatchSet.homePodAudioProduct&& $0.applicability.matches(iOSBase: version, cloudOS: cloud)}.map(\.identifier))diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex d68a88ea..2cc23ecd 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -209,6 +209,20 @@ struct VPhoneCustomFirmwareInstaller {if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodAudioProduct), device.family != .homePod {throw ValidationError("The HomePod audio-product patch is supported only for a HomePod guest.")}+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodWelcome), device.family != .homePod {+ throw ValidationError("The HomePod welcome patch is supported only for a HomePod guest.")+ }+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodSiriSpeech), device.family != .homePod {+ throw ValidationError("The HomePod Siri-speech patch is supported only for a HomePod guest.")+ }+ let missingSpeechDependencies = FirmwareGuestPatchResolution.missingHomePodSiriSpeechDependencies(enabled: effectiveEnabled)+ guard missingSpeechDependencies.isEmpty else {+ throw ValidationError("The HomePod Siri-speech patch requires these selected guest patches: \(missingSpeechDependencies.joined(separator: ", ")).")+ }+ let missingWelcomeDependencies = FirmwareGuestPatchResolution.missingHomePodWelcomeDependencies(enabled: effectiveEnabled)+ guard missingWelcomeDependencies.isEmpty else {+ throw ValidationError("The HomePod welcome patch requires these selected guest patches: \(missingWelcomeDependencies.joined(separator: ", ")).")+ }// 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@@ -1380,6 +1394,34 @@ struct VPhoneCustomFirmwareInstaller {} else {try system.removeItem(setupPath)}+ let speech = FirmwareGuestSystemPatchSet.homePodSiriSpeech+ let speechPath = String(FirmwareGuestSystemPatchSet.homePodSiriSpeechPath.dropFirst())+ if plan?.isEnabled(speech) == true {+ guard guestDevice.family == .homePod else {+ throw ValidationError("HomePod Siri speech 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(speechPath, contents: policy, mode: 0o644, owner: Self.guestOwner)+ live.insert(speech)+ } else {+ try system.removeItem(speechPath)+ }+ let welcome = FirmwareGuestSystemPatchSet.homePodWelcome+ let welcomePath = String(FirmwareGuestSystemPatchSet.homePodWelcomePath.dropFirst())+ if plan?.isEnabled(welcome) == true {+ guard guestDevice.family == .homePod else {+ throw ValidationError("HomePod welcome 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(welcomePath, contents: policy, mode: 0o644, owner: Self.guestOwner)+ live.insert(welcome)+ } else {+ // Once-only state belongs to the guest's writable Data volume and+ // survives opt-out, re-enabling and bundle/environment updates.+ try system.removeItem(welcomePath)+ }for (identifier, library) in [(FirmwareGuestSystemPatchSet.gyroscope, "libvphonegyro.dylib"),(FirmwareGuestSystemPatchSet.accelerometer, "libvphoneaccelerometer.dylib"),diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plistindex 08fb8fe7..cbb44136 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist@@ -89,6 +89,8 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>system-homepod-exp-welcome</string>+ <string>system-homepod-exp-siri_speech</string><string>preboot-homepod-exp-audio_product</string></array></dict>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex bc88604f..1dbdab4f 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -69,6 +69,8 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>system-homepod-exp-welcome</string>+ <string>system-homepod-exp-siri_speech</string><string>preboot-homepod-exp-audio_product</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-exp-frida_vm_map_delete_immutable_code</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex 727f3bc7..00e5da51 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -69,6 +69,8 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>system-homepod-exp-welcome</string>+ <string>system-homepod-exp-siri_speech</string><string>preboot-homepod-exp-audio_product</string><string>system-exp-ota_userland</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex a37de04a..02ecf8ba 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -69,6 +69,8 @@<array><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string>+ <string>system-homepod-exp-welcome</string>+ <string>system-homepod-exp-siri_speech</string><string>preboot-homepod-exp-audio_product</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-cfw-paravirt_gpu_task3</string>diff --git a/VPhoneGuestComponents/HomePodDisplay/VPHomePodSiriSpeech.h b/VPhoneGuestComponents/HomePodDisplay/VPHomePodSiriSpeech.hnew file mode 100644index 00000000..82fb2de3--- /dev/null+++ b/VPhoneGuestComponents/HomePodDisplay/VPHomePodSiriSpeech.h@@ -0,0 +1,6 @@+#import <Foundation/Foundation.h>++// Installs only in SoundBoard when HomePodSiriSpeech.plist enables the adapter.+// The native say:completion: NSError contract remains unchanged. A nil error+// means native finalization, and does not assert that a person heard the speech.+BOOL VPHomePodSiriSpeechInstall(void);diff --git a/VPhoneGuestComponents/HomePodDisplay/VPHomePodSiriSpeech.m b/VPhoneGuestComponents/HomePodDisplay/VPHomePodSiriSpeech.mnew file mode 100644index 00000000..af6677e3--- /dev/null+++ b/VPhoneGuestComponents/HomePodDisplay/VPHomePodSiriSpeech.m@@ -0,0 +1,179 @@+#import "VPHomePodSiriSpeech.h"+#import <objc/runtime.h>+#include <mach/mach_time.h>++@protocol VPHomePodSiriNative+@optional+- (id)initWithCategory:(NSString *)category categoryOptions:(NSUInteger)options;++ (id)auxiliaryAudioSessionManagerWithConfiguration:(id)configuration name:(NSString *)name;+- (BOOL)activateAndReturnError:(NSError **)error;+- (BOOL)deactivateWithOptions:(NSUInteger)options deactivateImmediately:(BOOL)immediately error:(NSError **)error;+- (id)audioSession;+- (uint32_t)opaqueSessionID;+- (id)initWithPriority:(NSInteger)priority options:(NSUInteger)options speakableText:(NSString *)text+ speakableContext:(id)context localizationKey:(id)key presynthesizedAudio:(id)audio streamID:(id)stream;++ (id)newWithBuilder:(void (^)(id))builder;+- (void)setTimestamp:(uint64_t)timestamp;+- (void)setType:(NSInteger)type;+- (void)setSpeechSynthesisRequest:(id)request;+- (void)setAudioSessionID:(uint32_t)sessionID;+- (id)siriClientInterface;+- (id)activationService;+- (void)activateWithSystemEvent:(id)event userInfo:(NSDictionary *)info completion:(void (^)(NSError *))completion;+@end++static Class VPSiriClass(NSString *name) {+#ifdef VP_HOMEPOD_SIRI_SPEECH_TESTING+ if ([name isEqualToString:@"AVAudioSession"]) return NSClassFromString(@"VPSiriMockAudioSession");+#endif+ return NSClassFromString(name);+}++static NSString *const VPSiriSpeechPolicy = @"/usr/share/vphone/HomePodSiriSpeech.plist";+static void (*VPSiriOriginalSay)(id, SEL, NSString *, void (^)(NSError *));++static BOOL VPSiriSpeechEnabled(void) {+#ifdef VP_HOMEPOD_SIRI_SPEECH_TESTING+ extern BOOL VPSiriSpeechTestEnabled;+ return VPSiriSpeechTestEnabled;+#else+ return [NSProcessInfo.processInfo.processName isEqualToString:@"SoundBoard"] &&+ [[NSDictionary dictionaryWithContentsOfFile:VPSiriSpeechPolicy][@"Enabled"] isEqual:@YES];+#endif+}++static BOOL VPSiriSignature(Class cls, BOOL classMethod, SEL selector, const char *result,+ NSArray<NSString *> *arguments) {+ Method method = classMethod ? class_getClassMethod(cls, selector) : class_getInstanceMethod(cls, selector);+ if (!method) return NO;+ NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:method_getTypeEncoding(method)];+ if (signature.numberOfArguments != arguments.count + 2 || strcmp(signature.methodReturnType, result)) return NO;+ for (NSUInteger i = 0; i < arguments.count; i++) {+ if (strcmp([signature getArgumentTypeAtIndex:i + 2], arguments[i].UTF8String)) return NO;+ }+ return YES;+}++static BOOL VPSiriSpeechABI(void) {+ return VPSiriSignature(VPSiriClass(@"SBSiriManager"), NO, NSSelectorFromString(@"say:completion:"), "v", @[@"@", @"@?"]) &&+ VPSiriSignature(VPSiriClass(@"SBSiriManager"), NO, @selector(siriClientInterface), "@", @[]) &&+ VPSiriSignature(VPSiriClass(@"SVXClientServiceConnection"), NO, @selector(activationService), "@", @[]) &&+ VPSiriSignature(VPSiriClass(@"SVXClientActivationService"), NO, @selector(activateWithSystemEvent:userInfo:completion:), "v", @[@"@", @"@", @"@?"]) &&+ VPSiriSignature(VPSiriClass(@"SBAudioSessionConfiguration"), NO, @selector(initWithCategory:categoryOptions:), "@", @[@"@", @"Q"]) &&+ VPSiriSignature(VPSiriClass(@"SBAudioSessionManager"), YES, @selector(auxiliaryAudioSessionManagerWithConfiguration:name:), "@", @[@"@", @"@"]) &&+ VPSiriSignature(VPSiriClass(@"SBAudioSessionManager"), NO, @selector(activateAndReturnError:), "B", @[@"^@"]) &&+ VPSiriSignature(VPSiriClass(@"SBAudioSessionManager"), NO, @selector(deactivateWithOptions:deactivateImmediately:error:), "B", @[@"Q", @"B", @"^@"]) &&+ VPSiriSignature(VPSiriClass(@"SBAudioSessionManager"), NO, @selector(audioSession), "@", @[]) &&+ VPSiriSignature(VPSiriClass(@"AVAudioSession"), NO, @selector(opaqueSessionID), "I", @[]) &&+ VPSiriSignature(VPSiriClass(@"SVXSpeechSynthesisRequest"), NO, @selector(initWithPriority:options:speakableText:speakableContext:localizationKey:presynthesizedAudio:streamID:), "@", @[@"q", @"Q", @"@", @"@", @"@", @"@", @"@"]) &&+ VPSiriSignature(VPSiriClass(@"SVXSystemEvent"), YES, @selector(newWithBuilder:), "@", @[@"@?"]) &&+ VPSiriSignature(VPSiriClass(@"_SVXSystemEventMutation"), NO, @selector(setTimestamp:), "v", @[@"Q"]) &&+ VPSiriSignature(VPSiriClass(@"_SVXSystemEventMutation"), NO, @selector(setType:), "v", @[@"q"]) &&+ VPSiriSignature(VPSiriClass(@"_SVXSystemEventMutation"), NO, @selector(setSpeechSynthesisRequest:), "v", @[@"@"]) &&+ VPSiriSignature(VPSiriClass(@"_SVXSystemEventMutation"), NO, @selector(setAudioSessionID:), "v", @[@"I"]);+}++static NSError *VPSiriSpeechError(NSString *message) {+ return [NSError errorWithDomain:@"com.vphone.homepod.siri-speech" code:1+ userInfo:@{NSLocalizedDescriptionKey: message}];+}++// The completion block owns this object through native synthesis finalization.+// Keep a separate auxiliary session; never change AVAudioSession.sharedInstance.+@interface VPHomePodSiriSpeechRequest : NSObject+@property (strong) id<VPHomePodSiriNative> audioManager;+@property (copy) void (^completion)(NSError *);+@property BOOL finished;+@property BOOL active;+- (void)finish:(NSError *)error;+@end++@implementation VPHomePodSiriSpeechRequest+- (void)finish:(NSError *)error {+ @synchronized (self) {+ if (self.finished) return;+ self.finished = YES;+ }+ if (self.active) {+ NSError *cleanupError = nil;+ if (![self.audioManager deactivateWithOptions:0 deactivateImmediately:YES error:&cleanupError]) {+ NSLog(@"vphone HomePod Siri speech: auxiliary session cleanup failed: %@", cleanupError);+ }+ self.active = NO;+ }+ self.audioManager = nil;+ void (^completion)(NSError *) = self.completion;+ self.completion = nil;+ if (completion) completion(error);+}+@end++static void VPSiriSpeechSay(id<VPHomePodSiriNative> manager, SEL selector, NSString *text,+ void (^completion)(NSError *)) {+ if (!VPSiriSpeechEnabled()) {+ VPSiriOriginalSay(manager, selector, text, completion);+ return;+ }+ VPHomePodSiriSpeechRequest *lifetime = [VPHomePodSiriSpeechRequest new];+ lifetime.completion = completion;+ @try {+ id<VPHomePodSiriNative> configuration = [(id<VPHomePodSiriNative>)[VPSiriClass(@"SBAudioSessionConfiguration") alloc]+ initWithCategory:@"AVAudioSessionCategoryPlayback" categoryOptions:0];+ if (!configuration) {+ [lifetime finish:VPSiriSpeechError(@"Unable to create auxiliary playback configuration")];+ return;+ }+ lifetime.audioManager = [(id<VPHomePodSiriNative>)VPSiriClass(@"SBAudioSessionManager")+ auxiliaryAudioSessionManagerWithConfiguration:configuration name:@"vphone Siri speech"];+ NSError *activationError = nil;+ if (!lifetime.audioManager || ![lifetime.audioManager activateAndReturnError:&activationError]) {+ [lifetime finish:activationError ?: VPSiriSpeechError(@"Unable to activate auxiliary playback session")];+ return;+ }+ lifetime.active = YES;+ uint32_t sessionID = [[lifetime.audioManager audioSession] opaqueSessionID];+ if (!sessionID) {+ [lifetime finish:VPSiriSpeechError(@"Auxiliary playback session has no session ID")];+ return;+ }+ // SoundBoard 24J361 uses priority 2, options 0 and event type 13.+ // SVXSession's native External path accepts this real session ID,+ // avoiding its own microphone/record-route activation while retaining+ // normal Siri activation, HPASiri rendering and synthesis finalization.+ id request = [(id<VPHomePodSiriNative>)[VPSiriClass(@"SVXSpeechSynthesisRequest") alloc]+ initWithPriority:2 options:0 speakableText:text speakableContext:nil localizationKey:nil+ presynthesizedAudio:nil streamID:nil];+ id event = [(id<VPHomePodSiriNative>)VPSiriClass(@"SVXSystemEvent") newWithBuilder:^(id<VPHomePodSiriNative> builder) {+ [builder setTimestamp:mach_absolute_time()];+ [builder setType:13];+ [builder setSpeechSynthesisRequest:request];+ [builder setAudioSessionID:sessionID];+ }];+ id<VPHomePodSiriNative> service = [[manager siriClientInterface] activationService];+ if (!request || !event || !service) {+ [lifetime finish:VPSiriSpeechError(@"Native Siri speech service is unavailable")];+ return;+ }+ [service activateWithSystemEvent:event userInfo:@{} completion:^(NSError *error) {+ // SVXSession passes result.error here after finalization. Its+ // separate postActivationHandler is invoked before enqueueing.+ [lifetime finish:error];+ }];+ } @catch (NSException *exception) {+ [lifetime finish:VPSiriSpeechError(exception.reason ?: @"Native Siri speech request failed")];+ }+}++BOOL VPHomePodSiriSpeechInstall(void) {+ static BOOL installed;+ if (!VPSiriSpeechEnabled()) return NO;+ if (!VPSiriSpeechABI()) {+ NSLog(@"vphone HomePod Siri speech: native playback/event ABI unavailable");+ return NO;+ }+ if (installed) return YES;+ Method method = class_getInstanceMethod(VPSiriClass(@"SBSiriManager"), NSSelectorFromString(@"say:completion:"));+ VPSiriOriginalSay = (void *)method_setImplementation(method, (IMP)VPSiriSpeechSay);+ installed = YES;+ return YES;+}diff --git a/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcome.m b/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcome.mnew file mode 100644index 00000000..071a0d32--- /dev/null+++ b/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcome.m@@ -0,0 +1,276 @@+#import <Foundation/Foundation.h>+#import <objc/runtime.h>+#include <dlfcn.h>+#import "VPHomePodWelcomeState.h"++// Runs in SoundBoard, beside the MiniDisplay identity adapter. All rendering,+// playback, Siri session ownership and speech synthesis remain Apple's. See+// Research/Firmware/homepod_welcome.md for the donor APIs and live-test limits.+@protocol VPHomePodWelcomeNative+@optional+- (id)activityManager;+- (id)displayService;+- (id)siriManager;+- (id)uiTonePlaybackManager;+- (id)activityWithName:(NSString *)name;+- (id)foregroundedActivity;+- (NSString *)activityName;+- (NSUInteger)activeMediaCount;+- (NSDictionary *)diagnosticsInfo;+- (BOOL)startupComplete;+- (BOOL)siriEnabled;+- (BOOL)deviceNeedsSetup;+- (BOOL)localSessionActive;+- (BOOL)remoteSessionActive;+- (BOOL)siriUIEnabled;+- (NSInteger)currentSessionState;+- (void)setLocalSessionActive:(BOOL)active;+- (void)play:(uint32_t)tone completion:(void (^)(NSError *))completion;+- (void)say:(NSString *)text completion:(void (^)(NSError *))completion;+@end++static NSString *const VPHomePodWelcomePhrase = @"Hi, I'm Siri. It sure is great to be running in a virtual machine!";+static NSString *(*VPWelcomeSessionStateName)(NSInteger);++static BOOL VPWelcomeSignature(id object, SEL selector, const char *result, NSArray<NSString *> *arguments) {+ NSMethodSignature *signature = [object methodSignatureForSelector:selector];+ if (!signature || strcmp(signature.methodReturnType, result) || signature.numberOfArguments != arguments.count + 2) return NO;+ for (NSUInteger i = 0; i < arguments.count; i++) {+ if (strcmp([signature getArgumentTypeAtIndex:i + 2], arguments[i].UTF8String)) return NO;+ }+ return YES;+}++static BOOL VPWelcomeObjectGetter(id object, SEL selector) {+ return VPWelcomeSignature(object, selector, @encode(id), @[]);+}++static BOOL VPWelcomeBoolGetter(id object, SEL selector) {+ return VPWelcomeSignature(object, selector, @encode(BOOL), @[]);+}++typedef NS_ENUM(NSUInteger, VPHomePodWelcomePhase) {+ VPHomePodWelcomeWaiting, VPHomePodWelcomeTone, VPHomePodWelcomePause,+ VPHomePodWelcomeSpeech, VPHomePodWelcomeStopped,+};++@interface VPHomePodWelcome : NSObject+@property (nonatomic, weak) id<VPHomePodWelcomeNative> board;+@property (nonatomic, strong) id<VPHomePodWelcomeNative> siri;+@property (nonatomic, strong) id<VPHomePodWelcomeNative> flourish;+@property (nonatomic, strong) VPHomePodWelcomeState *state;+@property (nonatomic, copy) NSString *policyPath;+@property (nonatomic, strong) dispatch_source_t timer;+@property (nonatomic) VPHomePodWelcomePhase phase;+- (instancetype)initWithBoard:(id)board directory:(NSString *)directory policy:(NSString *)policy;+- (void)poll;+@end++@implementation VPHomePodWelcome+- (instancetype)initWithBoard:(id)board directory:(NSString *)directory policy:(NSString *)policy {+ if ((self = [super init])) {+ _board = board;+ _state = [[VPHomePodWelcomeState alloc] initWithDirectory:directory];+ _policyPath = [policy copy];+ }+ return self;+}++- (BOOL)enabled {+ NSDictionary *policy = [NSDictionary dictionaryWithContentsOfFile:self.policyPath];+ return [policy[@"Enabled"] isEqual:@YES];+}++- (void)record:(NSString *)status error:(NSError *)error {+ NSMutableDictionary *fields = NSMutableDictionary.dictionary;+ if (error) {+ fields[@"ErrorDomain"] = error.domain;+ fields[@"ErrorCode"] = @(error.code);+ fields[@"ErrorDescription"] = error.localizedDescription;+ }+ NSError *writeError = nil;+ if (![self.state writeStatus:status fields:fields error:&writeError]) {+ NSLog(@"vphone HomePod welcome: cannot record %@: %@", status, writeError);+ }+ NSLog(@"vphone HomePod welcome: %@%@", status, error ? [@": " stringByAppendingString:error.description] : @"");+}++- (void)stop:(NSString *)status error:(NSError *)error {+ self.phase = VPHomePodWelcomeStopped;+ if (self.timer) { dispatch_source_cancel(self.timer); self.timer = nil; }+ if (self.flourish) {+ // The coordinated setter clears ownership and invokes Identify's+ // endLocalSessionActivity cleanup. Calling that callback directly+ // leaves the activity active and it resurfaces after Siri finishes.+ [self.flourish setLocalSessionActive:NO];+ self.flourish = nil;+ }+ [self record:status error:error];+}++- (BOOL)nativeReady {+ id<VPHomePodWelcomeNative> board = self.board;+ Class setup = NSClassFromString(@"SBSetupController");+ if (!VPWelcomeBoolGetter(setup, @selector(deviceNeedsSetup)) ||+ [(id<VPHomePodWelcomeNative>)setup deviceNeedsSetup]) return NO;+ for (NSString *name in @[@"activityManager", @"displayService", @"siriManager", @"uiTonePlaybackManager"]) {+ if (!VPWelcomeObjectGetter(board, NSSelectorFromString(name))) return NO;+ }+ id<VPHomePodWelcomeNative> display = [board displayService];+ if (!VPWelcomeBoolGetter(display, @selector(startupComplete)) || ![display startupComplete] ||+ !VPWelcomeObjectGetter(display, @selector(diagnosticsInfo)) ||+ ![[display diagnosticsInfo][@"DrawingEnabled"] boolValue]) return NO;+ id<VPHomePodWelcomeNative> manager = [board activityManager];+ if (!VPWelcomeSignature(manager, @selector(activityWithName:), @encode(id), @[@(@encode(id))]) ||+ !VPWelcomeObjectGetter(manager, @selector(foregroundedActivity))) return NO;+ id<VPHomePodWelcomeNative> foreground = [manager foregroundedActivity];+ // NowPlayingCap is present even while idle. Leave live media and all other+ // foreground activities alone; our native Identify activity has priority 22.+ if (foreground && (!VPWelcomeObjectGetter(foreground, @selector(activityName)) ||+ ![[foreground activityName] isEqual:@"NowPlayingCap"] ||+ !VPWelcomeSignature(manager, @selector(activeMediaCount), @encode(NSUInteger), @[]) || [manager activeMediaCount])) return NO;+ id<VPHomePodWelcomeNative> identify = [manager activityWithName:@"Identify"];+ id<VPHomePodWelcomeNative> siriActivity = [manager activityWithName:@"Siri"];+ if (!VPWelcomeBoolGetter(identify, @selector(localSessionActive)) || [identify localSessionActive] ||+ !VPWelcomeBoolGetter(identify, @selector(remoteSessionActive)) || [identify remoteSessionActive] ||+ !VPWelcomeSignature(identify, @selector(setLocalSessionActive:), @encode(void), @[@(@encode(BOOL))]) ||+ !VPWelcomeBoolGetter(siriActivity, @selector(siriUIEnabled)) || ![siriActivity siriUIEnabled]) return NO;+ id<VPHomePodWelcomeNative> siri = [board siriManager];+ if (!VPWelcomeBoolGetter(siri, @selector(siriEnabled)) || ![siri siriEnabled] ||+ !VPWelcomeSignature(siri, @selector(currentSessionState), @encode(NSInteger), @[]) ||+ !VPWelcomeSessionStateName || ![VPWelcomeSessionStateName([siri currentSessionState]) isEqual:@"idle"] ||+ !VPWelcomeSignature(siri, @selector(say:completion:), @encode(void), @[@(@encode(id)), @"@?"]) ||+ !VPWelcomeSignature([board uiTonePlaybackManager], @selector(play:completion:), @encode(void), @[@(@encode(uint32_t)), @"@?"])) return NO;+ self.siri = siri;+ // Do not enable Buddy's debug-only renderer. Identify's normal coordinated+ // activity supplies a native animated ring, without its separate tone 6.+ self.flourish = identify;+ return YES;+}++- (void)poll {+ if (self.phase != VPHomePodWelcomeWaiting) return;+ if (![self enabled]) {+ self.phase = VPHomePodWelcomeStopped;+ if (self.timer) { dispatch_source_cancel(self.timer); self.timer = nil; }+ return; // Opt-out must not create or replace any consumption state.+ }+ if (![self nativeReady]) return;+ NSError *claimError = nil;+ if (![self.state claimWithError:&claimError]) {+ self.phase = VPHomePodWelcomeStopped;+ if (self.timer) { dispatch_source_cancel(self.timer); self.timer = nil; }+ self.flourish = nil;+ if (claimError) NSLog(@"vphone HomePod welcome: cannot claim: %@", claimError);+ return;+ }+ if (self.timer) { dispatch_source_cancel(self.timer); self.timer = nil; }+ self.phase = VPHomePodWelcomeTone;+ [self record:@"TonePlaying" error:nil];+ [self.flourish setLocalSessionActive:YES];+ __weak VPHomePodWelcome *weakSelf = self;+ [[self.board uiTonePlaybackManager] play:1 completion:^(NSError *error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ VPHomePodWelcome *welcome = weakSelf;+ if (!welcome || welcome.phase != VPHomePodWelcomeTone) return;+ [welcome.flourish setLocalSessionActive:NO];+ welcome.flourish = nil;+ if (error) { [welcome stop:@"ToneFailed" error:error]; return; }+ welcome.phase = VPHomePodWelcomePause;+ [welcome record:@"ToneFinished" error:nil];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 650 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{+ [weakSelf speak];+ });+ });+ }];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ VPHomePodWelcome *welcome = weakSelf;+ if (welcome && welcome.phase == VPHomePodWelcomeTone) [welcome stop:@"ToneTimedOut" error:nil];+ });+}++- (void)speak {+ if (self.phase != VPHomePodWelcomePause) return;+ if (![self enabled]) { [self stop:@"Cancelled" error:nil]; return; }+ if (![self.siri siriEnabled] || ![VPWelcomeSessionStateName([self.siri currentSessionState]) isEqual:@"idle"]) {+ [self stop:@"SpeechUnavailable" error:nil];+ return;+ }+ self.phase = VPHomePodWelcomeSpeech;+ [self record:@"SpeechRequested" error:nil];+ __weak VPHomePodWelcome *weakSelf = self;+ [self.siri say:VPHomePodWelcomePhrase completion:^(NSError *error) {+ dispatch_async(dispatch_get_main_queue(), ^{+ VPHomePodWelcome *welcome = weakSelf;+ if (!welcome || welcome.phase != VPHomePodWelcomeSpeech) return;+ if (error) { [welcome stop:@"SpeechFailed" error:error]; return; }+ // SiriVOX's synthesis finalizer returns its NSError here. The API+ // omits the result type (including cancellation), so record that+ // exact boundary rather than claiming the sentence was audible.+ [welcome stop:@"SpeechFinalized" error:nil];+ });+ }];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 90 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ VPHomePodWelcome *welcome = weakSelf;+ if (welcome && welcome.phase == VPHomePodWelcomeSpeech) [welcome stop:@"SpeechTimedOut" error:nil];+ });+}++@end++#if !defined(VP_HOMEPOD_DISPLAY_TESTING) && !defined(VP_HOMEPOD_WELCOME_TESTING)+static VPHomePodWelcome *VPWelcomeController;+static void (*VPWelcomeOriginalApplicationsReady)(id, SEL);++static NSString *VPWelcomeGuestIdentity(void) {+ void *gestalt = dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_NOW);+ CFTypeRef (*copyAnswer)(CFStringRef) = gestalt ? dlsym(gestalt, "MGCopyAnswer") : NULL;+ id identity = copyAnswer ? CFBridgingRelease(copyAnswer(CFSTR("UniqueDeviceID"))) : nil;+ // Scope the durable claim to this guest, including when its Data volume was+ // cloned from a previously booted template. Read identity, never override it.+ if (![identity isKindOfClass:NSString.class] || [identity length] == 0 || [identity length] > 128) return nil;+ NSCharacterSet *invalid = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF-"] invertedSet];+ return [identity rangeOfCharacterFromSet:invalid].location == NSNotFound ? [identity lowercaseString] : nil;+}++static void VPWelcomeApplicationsReady(id board, SEL selector) {+ VPWelcomeOriginalApplicationsReady(board, selector);+ // Observe Apple's constructed instance. Never force sharedInstance from a+ // dylib constructor, which could initialize SoundBoard before its OS setup.+ dispatch_async(dispatch_get_main_queue(), ^{+ if (VPWelcomeController) return;+ NSString *identity = VPWelcomeGuestIdentity();+ if (!identity) { NSLog(@"vphone HomePod welcome: stable guest identity unavailable"); return; }+ NSString *directory = [@"/var/mobile/Library/Application Support/vphone/HomePodWelcome" stringByAppendingPathComponent:identity];+ VPWelcomeController = [[VPHomePodWelcome alloc] initWithBoard:board+ directory:directory policy:@"/usr/share/vphone/HomePodWelcome.plist"];+ dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());+ VPWelcomeController.timer = timer;+ dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC, 250 * NSEC_PER_MSEC);+ dispatch_source_set_event_handler(timer, ^{ [VPWelcomeController poll]; });+ dispatch_resume(timer);+ });+}++void VPHomePodWelcomeInstall(void) {+ static BOOL installed;+ if (installed) return;+ NSDictionary *policy = [NSDictionary dictionaryWithContentsOfFile:@"/usr/share/vphone/HomePodWelcome.plist"];+ if (![policy[@"Enabled"] isEqual:@YES]) return;+ VPWelcomeSessionStateName = dlsym(RTLD_DEFAULT, "SVXSessionStateGetName");+ if (!VPWelcomeSessionStateName) {+ NSLog(@"vphone HomePod welcome: native Siri state API unavailable");+ return;+ }+ Class board = NSClassFromString(@"SBSoundBoard");+ SEL selector = NSSelectorFromString(@"_applicationsModuleInitComplete");+ Method method = class_getInstanceMethod(board, selector);+ NSMethodSignature *signature = method ? [NSMethodSignature signatureWithObjCTypes:method_getTypeEncoding(method)] : nil;+ if (!signature || signature.numberOfArguments != 2 || strcmp(signature.methodReturnType, @encode(void))) {+ NSLog(@"vphone HomePod welcome: native lifecycle ABI unavailable");+ return;+ }+ VPWelcomeOriginalApplicationsReady = (void *)method_setImplementation(method, (IMP)VPWelcomeApplicationsReady);+ installed = YES;+}+#endifdiff --git a/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcomeState.h b/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcomeState.hnew file mode 100644index 00000000..2470f222--- /dev/null+++ b/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcomeState.h@@ -0,0 +1,21 @@+#import <Foundation/Foundation.h>++NS_ASSUME_NONNULL_BEGIN++/// Guest Data state for one welcome. A successful claim must precede every+/// audiovisual side effect; progress updates never replace or remove it.+@interface VPHomePodWelcomeState : NSObject+- (instancetype)initWithDirectory:(NSString *)directory NS_DESIGNATED_INITIALIZER;+- (instancetype)init NS_UNAVAILABLE;++/// YES only after creating and durably recording a new exclusive claim.+/// An existing claim returns NO without an error, regardless of its contents.+/// I/O and symlink failures return NO with an error and never permit playback.+- (BOOL)claimWithError:(NSError * _Nullable * _Nullable)error;++/// Replaces only Status.plist. Fields must be property-list values; State and+/// Updated are reserved and always supplied by this method.+- (BOOL)writeStatus:(NSString *)status fields:(NSDictionary *)fields error:(NSError * _Nullable * _Nullable)error;+@end++NS_ASSUME_NONNULL_ENDdiff --git a/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcomeState.m b/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcomeState.mnew file mode 100644index 00000000..b687bdbf--- /dev/null+++ b/VPhoneGuestComponents/HomePodDisplay/VPHomePodWelcomeState.m@@ -0,0 +1,199 @@+#import "VPHomePodWelcomeState.h"+#include <errno.h>+#include <fcntl.h>+#include <stdio.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++static BOOL VPWelcomeError(NSError **error, int code, NSString *operation, NSString *path) {+ if (error) *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:code+ userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@: %s", operation, strerror(code)],+ NSFilePathErrorKey: path}];+ return NO;+}++static BOOL VPWelcomeWrite(int descriptor, NSData *data, NSError **error, NSString *path) {+ const uint8_t *bytes = data.bytes;+ NSUInteger remaining = data.length;+ while (remaining) {+ ssize_t count = write(descriptor, bytes, remaining);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) return VPWelcomeError(error, count < 0 ? errno : EIO, @"Write welcome state", path);+ bytes += count;+ remaining -= (NSUInteger)count;+ }+ return YES;+}++static BOOL VPWelcomeSync(int descriptor, NSError **error, NSString *path) {+ int result;+ do { result = fsync(descriptor); } while (result != 0 && errno == EINTR);+ return result == 0 || VPWelcomeError(error, errno, @"Persist welcome state", path);+}++@implementation VPHomePodWelcomeState {+ NSString *_directory;+}++- (instancetype)initWithDirectory:(NSString *)directory {+ if ((self = [super init])) _directory = [directory copy];+ return self;+}++- (int)openDirectoryWithError:(NSError **)error {+ if (!_directory.isAbsolutePath || [_directory rangeOfString:@"\0"].location != NSNotFound) {+ VPWelcomeError(error, EINVAL, @"Invalid welcome state directory", _directory);+ return -1;+ }+ int flags = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC;+ int descriptor = open(_directory.fileSystemRepresentation, flags);+ int openError = descriptor < 0 ? errno : 0;+ BOOL created = openError == ENOENT;+ NSMutableArray<NSString *> *parentsToSync = NSMutableArray.array;+ if (created) {+ // Capture the missing chain before recursive mkdir makes every level+ // appear to exist. Each new directory's entry belongs to its parent;+ // syncing only the final identity directory's parent misses newly+ // created HomePodWelcome/vphone entries farther up the chain.+ NSString *cursor = _directory;+ for (;;) {+ struct stat ancestor;+ if (stat(cursor.fileSystemRepresentation, &ancestor) == 0) {+ if (!S_ISDIR(ancestor.st_mode)) {+ VPWelcomeError(error, ENOTDIR, @"Inspect welcome state ancestor", cursor);+ return -1;+ }+ break;+ }+ int code = errno;+ if (code != ENOENT) {+ VPWelcomeError(error, code, @"Inspect welcome state ancestor", cursor);+ return -1;+ }+ NSString *parent = cursor.stringByDeletingLastPathComponent;+ if (!parent.length || [parent isEqual:cursor]) {+ VPWelcomeError(error, EINVAL, @"Invalid welcome state ancestor", cursor);+ return -1;+ }+ [parentsToSync addObject:parent];+ cursor = parent;+ }+ // Only directory creation uses a pathname. All control-file operations+ // use the pinned, non-symlink directory descriptor below.+ [NSFileManager.defaultManager createDirectoryAtPath:_directory withIntermediateDirectories:YES+ attributes:@{NSFilePosixPermissions: @0700} error:NULL];+ descriptor = open(_directory.fileSystemRepresentation, flags);+ openError = descriptor < 0 ? errno : 0;+ }+ if (descriptor < 0) {+ VPWelcomeError(error, openError, @"Open welcome state directory", _directory);+ return -1;+ }+ struct stat metadata;+ if (fstat(descriptor, &metadata) != 0) {+ VPWelcomeError(error, errno, @"Inspect welcome state directory", _directory);+ close(descriptor);+ return -1;+ }+ if (!S_ISDIR(metadata.st_mode) || metadata.st_uid != geteuid()) {+ VPWelcomeError(error, EPERM, @"Welcome state directory must belong to the current user", _directory);+ close(descriptor);+ return -1;+ }+ if (fchmod(descriptor, 0700) != 0) {+ VPWelcomeError(error, errno, @"Protect welcome state directory", _directory);+ close(descriptor);+ return -1;+ }+ for (NSString *parent in parentsToSync) {+ // Follow ordinary ancestor aliases such as /var. The control directory+ // itself and its claim remain pinned with O_NOFOLLOW independently.+ int parentDescriptor = open(parent.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_CLOEXEC);+ if (parentDescriptor < 0) {+ VPWelcomeError(error, errno, @"Open welcome state parent", parent);+ close(descriptor);+ return -1;+ }+ BOOL persisted = VPWelcomeSync(parentDescriptor, error, parent);+ close(parentDescriptor);+ if (!persisted) { close(descriptor); return -1; }+ }+ return descriptor;+}++- (BOOL)claimWithError:(NSError **)error {+ if (error) *error = nil;+ int directory = [self openDirectoryWithError:error];+ if (directory < 0) return NO;+ int descriptor = openat(directory, "Claim.plist", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);+ if (descriptor < 0) {+ int code = errno;+ if (code == EEXIST) {+ struct stat entry;+ if (fstatat(directory, "Claim.plist", &entry, AT_SYMLINK_NOFOLLOW) != 0) code = errno;+ else if (S_ISLNK(entry.st_mode)) code = ELOOP;+ else { close(directory); return NO; } // Never parse, repair or overwrite a prior claim.+ }+ close(directory);+ return VPWelcomeError(error, code, @"Create exclusive welcome claim", _directory);+ }+ NSData *claim = [NSPropertyListSerialization dataWithPropertyList:@{@"Version": @1, @"Claimed": NSDate.date}+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:error];+ BOOL success = YES;+ if (fchmod(descriptor, 0600) != 0) success = VPWelcomeError(error, errno, @"Protect welcome claim", _directory);+ success = success && claim && VPWelcomeWrite(descriptor, claim, error, _directory)+ && VPWelcomeSync(descriptor, error, _directory) && VPWelcomeSync(directory, error, _directory);+ if (close(descriptor) != 0 && success) success = VPWelcomeError(error, errno, @"Close welcome claim", _directory);+ close(directory);+ // A failed write or sync may leave an empty/partial claim. Keep it: the+ // caller cannot safely treat an uncertain durable claim as replayable.+ return success;+}++- (BOOL)writeStatus:(NSString *)status fields:(NSDictionary *)fields error:(NSError **)error {+ if (error) *error = nil;+ if (![status isKindOfClass:NSString.class] || !status.length || ![fields isKindOfClass:NSDictionary.class]) {+ return VPWelcomeError(error, EINVAL, @"Invalid welcome status", _directory);+ }+ NSMutableDictionary *record = [fields mutableCopy];+ record[@"State"] = status;+ record[@"Updated"] = NSDate.date;+ if (![NSPropertyListSerialization propertyList:record isValidForFormat:NSPropertyListBinaryFormat_v1_0]) {+ return VPWelcomeError(error, EINVAL, @"Welcome status fields must be property-list values", _directory);+ }+ NSData *data = [NSPropertyListSerialization dataWithPropertyList:record format:NSPropertyListBinaryFormat_v1_0 options:0 error:error];+ if (!data) return NO;+ int directory = [self openDirectoryWithError:error];+ if (directory < 0) return NO;+ struct stat entry;+ if (fstatat(directory, "Status.plist", &entry, AT_SYMLINK_NOFOLLOW) == 0) {+ if (!S_ISREG(entry.st_mode)) {+ close(directory);+ return VPWelcomeError(error, ELOOP, @"Refuse non-regular welcome status", _directory);+ }+ } else if (errno != ENOENT) {+ int code = errno;+ close(directory);+ return VPWelcomeError(error, code, @"Inspect welcome status", _directory);+ }+ NSString *temporary = [NSString stringWithFormat:@".Status.%@.tmp", NSUUID.UUID.UUIDString];+ int descriptor = openat(directory, temporary.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);+ if (descriptor < 0) {+ int code = errno;+ close(directory);+ return VPWelcomeError(error, code, @"Create welcome status", _directory);+ }+ BOOL success = YES;+ if (fchmod(descriptor, 0600) != 0) success = VPWelcomeError(error, errno, @"Protect welcome status", _directory);+ success = success && VPWelcomeWrite(descriptor, data, error, _directory) && VPWelcomeSync(descriptor, error, _directory);+ if (close(descriptor) != 0 && success) success = VPWelcomeError(error, errno, @"Close welcome status", _directory);+ if (success && renameat(directory, temporary.fileSystemRepresentation, directory, "Status.plist") != 0) {+ success = VPWelcomeError(error, errno, @"Replace welcome status", _directory);+ }+ if (success) success = VPWelcomeSync(directory, error, _directory);+ if (!success) unlinkat(directory, temporary.fileSystemRepresentation, 0);+ close(directory);+ return success;+}+@enddiff --git a/VPhoneGuestComponents/HomePodDisplay/libvphonehomepoddisplay.m b/VPhoneGuestComponents/HomePodDisplay/libvphonehomepoddisplay.mindex 87b75b37..2518165b 100644--- a/VPhoneGuestComponents/HomePodDisplay/libvphonehomepoddisplay.m+++ b/VPhoneGuestComponents/HomePodDisplay/libvphonehomepoddisplay.m@@ -1,6 +1,9 @@#import <Foundation/Foundation.h>#import <objc/runtime.h>#include <dlfcn.h>+#import "VPHomePodSiriSpeech.h"++void VPHomePodWelcomeInstall(void);// IOHIDUserDevice deliberately rejects reserved IOKit properties, including// IOClass. MiniDisplay's HW3 path tests that property before reading MDHWVersion.@@ -167,6 +170,10 @@ __attribute__((constructor)) static void VPHomePodDisplayInitialize(void) {NSLog(@"vphone HomePod display: MiniDisplay identity adapter unavailable");} else {NSLog(@"vphone HomePod display: virtual MiniDisplay identity adapter ready");+ if (VPHomePodSiriSpeechInstall()) {+ NSLog(@"vphone HomePod Siri speech: isolated playback session adapter ready");+ VPHomePodWelcomeInstall();+ }}}}diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex 444ae37c..3b7d1714 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -97,6 +97,7 @@ ATTITUDE_SOURCES := $(call find_sources,Attitude)ATTITUDE_INPUTS := $(call find_headers,Attitude) $(call find_folders,Attitude) Shared/AttitudeProcess.hHOMEPODDISPLAY := $(STAGE)/homepoddisplay/libvphonehomepoddisplay.dylibHOMEPODDISPLAY_SOURCES := $(call find_sources,HomePodDisplay)+HOMEPODDISPLAY_INPUTS := $(call find_headers,HomePodDisplay) $(call find_folders,HomePodDisplay)HOMEPODSETUP := $(STAGE)/homepodsetup/vphone-homepod-setupHOMEPODSETUP_SOURCES := $(call find_sources,HomePodSetup)HOMEPODSETUP_INPUTS := $(call find_headers,HomePodSetup) HomePodSetup/com.vphone.homepod-setup.plist@@ -151,6 +152,23 @@ test-homepod-display:-o $(OUT)/HomePodDisplayIdentityTests Tests/HomePodDisplayIdentityTests.m $(HOMEPODDISPLAY_SOURCES) -framework Foundation@$(OUT)/HomePodDisplayIdentityTests+.PHONY: test-homepod-welcome+test-homepod-welcome:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHomePodDisplay \+ -o $(OUT)/HomePodWelcomeStateTests Tests/HomePodWelcomeStateTests.m HomePodDisplay/VPHomePodWelcomeState.m -framework Foundation+ @$(OUT)/HomePodWelcomeStateTests+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror -IHomePodDisplay \+ -o $(OUT)/HomePodWelcomeTests Tests/HomePodWelcomeTests.m HomePodDisplay/VPHomePodWelcomeState.m -framework Foundation+ @$(OUT)/HomePodWelcomeTests++.PHONY: test-homepod-siri-speech+test-homepod-siri-speech:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -fobjc-arc -Wall -Wextra -Werror \+ -o $(OUT)/HomePodSiriSpeechTests Tests/HomePodSiriSpeechTests.m -framework Foundation+ @$(OUT)/HomePodSiriSpeechTests+gpu: $(GPU_PLUGIN)package: all@@ -348,7 +366,7 @@ $(ATTITUDE): $(ATTITUDE_SOURCES) $(ATTITUDE_INPUTS) | $(STAGE)/attitude-framework Foundation -framework CoreMotion -Wl,-not_for_dyld_shared_cache@codesign --force --sign - $@-$(HOMEPODDISPLAY): $(HOMEPODDISPLAY_SOURCES)+$(HOMEPODDISPLAY): $(HOMEPODDISPLAY_SOURCES) $(HOMEPODDISPLAY_INPUTS)@mkdir -p $(STAGE)/homepoddisplayxcrun --sdk appletvos clang -arch arm64e -mtvos-version-min=27.0 -Os -fobjc-arc \-Wall -Wextra -Werror -dynamiclib -install_name /usr/lib/libvphonehomepoddisplay.dylib \diff --git a/VPhoneGuestComponents/Tests/HomePodSiriSpeechTests.m b/VPhoneGuestComponents/Tests/HomePodSiriSpeechTests.mnew file mode 100644index 00000000..acf28130--- /dev/null+++ b/VPhoneGuestComponents/Tests/HomePodSiriSpeechTests.m@@ -0,0 +1,181 @@+#define VP_HOMEPOD_SIRI_SPEECH_TESTING 1+#import "../HomePodDisplay/VPHomePodSiriSpeech.m"+#include <assert.h>++BOOL VPSiriSpeechTestEnabled;+static NSUInteger sharedSessionRequests, originalRequests, auxiliaryRequests;+static BOOL failActivation, zeroSessionID;+static NSError *nativeError;++@interface VPSiriMockAudioSession : NSObject+@property uint32_t opaqueSessionID;++ (id)sharedInstance;+@end+@implementation VPSiriMockAudioSession++ (id)sharedInstance { sharedSessionRequests++; return [self new]; }+@end++@interface SBAudioSessionConfiguration : NSObject+@property (copy) NSString *category;+@property NSUInteger options;+- (id)initWithCategory:(NSString *)category categoryOptions:(NSUInteger)options;+@end+@implementation SBAudioSessionConfiguration+- (id)initWithCategory:(NSString *)category categoryOptions:(NSUInteger)options {+ if ((self = [super init])) { _category = category; _options = options; }+ return self;+}+@end++@interface SBAudioSessionManager : NSObject+@property (strong) VPSiriMockAudioSession *audioSession;+@property (strong) SBAudioSessionConfiguration *configuration;+@property NSUInteger activations, deactivations;++ (id)auxiliaryAudioSessionManagerWithConfiguration:(id)configuration name:(NSString *)name;+- (BOOL)activateAndReturnError:(NSError **)error;+- (BOOL)deactivateWithOptions:(NSUInteger)options deactivateImmediately:(BOOL)immediately error:(NSError **)error;+@end+static __weak SBAudioSessionManager *lastAuxiliary;+@implementation SBAudioSessionManager++ (id)auxiliaryAudioSessionManagerWithConfiguration:(id)configuration name:(NSString *)name {+ assert([name isEqual:@"vphone Siri speech"]);+ auxiliaryRequests++;+ SBAudioSessionManager *manager = [self new];+ manager.configuration = configuration;+ manager.audioSession = [VPSiriMockAudioSession new];+ manager.audioSession.opaqueSessionID = zeroSessionID ? 0 : 47;+ lastAuxiliary = manager;+ return manager;+}+- (BOOL)activateAndReturnError:(NSError **)error {+ self.activations++;+ if (failActivation) { if (error) *error = nativeError; return NO; }+ return YES;+}+- (BOOL)deactivateWithOptions:(NSUInteger)options deactivateImmediately:(BOOL)immediately error:(NSError **)error {+ assert(options == 0 && immediately);+ (void)error;+ self.deactivations++;+ return YES;+}+@end++@interface SVXSpeechSynthesisRequest : NSObject+@property NSInteger priority;+@property NSUInteger options;+@property (copy) NSString *speakableText;+- (id)initWithPriority:(NSInteger)priority options:(NSUInteger)options speakableText:(NSString *)text+ speakableContext:(id)context localizationKey:(id)key presynthesizedAudio:(id)audio streamID:(id)stream;+@end+@implementation SVXSpeechSynthesisRequest+- (id)initWithPriority:(NSInteger)priority options:(NSUInteger)options speakableText:(NSString *)text+ speakableContext:(id)context localizationKey:(id)key presynthesizedAudio:(id)audio streamID:(id)stream {+ assert(!context && !key && !audio && !stream);+ if ((self = [super init])) { _priority = priority; _options = options; _speakableText = text; }+ return self;+}+@end++@interface _SVXSystemEventMutation : NSObject+@property uint64_t timestamp;+@property NSInteger type;+@property (strong) SVXSpeechSynthesisRequest *speechSynthesisRequest;+@property uint32_t audioSessionID;+@end+@implementation _SVXSystemEventMutation+@end+@interface SVXSystemEvent : _SVXSystemEventMutation++ (id)newWithBuilder:(void (^)(id))builder;+@end+@implementation SVXSystemEvent++ (id)newWithBuilder:(void (^)(id))builder { id event = [self new]; builder(event); return event; }+@end++@interface SVXClientActivationService : NSObject+@property (strong) SVXSystemEvent *event;+@property (copy) void (^completion)(NSError *);+- (void)activateWithSystemEvent:(id)event userInfo:(NSDictionary *)info completion:(void (^)(NSError *))completion;+@end+@implementation SVXClientActivationService+- (void)activateWithSystemEvent:(id)event userInfo:(NSDictionary *)info completion:(void (^)(NSError *))completion {+ assert(info.count == 0);+ self.event = event; self.completion = completion;+}+@end+@interface SVXClientServiceConnection : NSObject+@property (strong) id activationService;+@end+@implementation SVXClientServiceConnection+@end+@interface SBSiriManager : NSObject+@property (strong) id siriClientInterface;+- (void)say:(NSString *)text completion:(void (^)(NSError *))completion;+@end+@implementation SBSiriManager+- (void)say:(NSString *)text completion:(void (^)(NSError *))completion {+ (void)text;+ originalRequests++;+ if (completion) completion(nil);+}+@end++int main(void) {+ @autoreleasepool {+ nativeError = [NSError errorWithDomain:@"NativeFailure" code:42 userInfo:nil];+ assert(VPSiriSpeechABI());+ assert(!VPSiriSignature(VPSiriMockAudioSession.class, NO, @selector(opaqueSessionID), "Q", @[]));+ assert(!VPSiriSignature(SBSiriManager.class, NO, @selector(siriClientInterface), "@", @[@"I"]));+ assert(!VPSiriSignature(Nil, NO, @selector(siriClientInterface), "@", @[]));+ assert(!VPHomePodSiriSpeechInstall());+ SBSiriManager *siri = [SBSiriManager new];+ SVXClientServiceConnection *client = [SVXClientServiceConnection new];+ SVXClientActivationService *service = [SVXClientActivationService new];+ client.activationService = service; siri.siriClientInterface = client;+ VPSiriSpeechTestEnabled = YES;+ assert(VPHomePodSiriSpeechInstall());+ assert(VPHomePodSiriSpeechInstall());+ __block NSUInteger completions = 0;+ __block NSError *received = nil;+ @autoreleasepool {+ [siri say:@"Native Siri phrase" completion:^(NSError *error) { completions++; received = error; }];+ }+ SBAudioSessionManager *aux = lastAuxiliary;+ assert(aux && aux.activations == 1 && aux.deactivations == 0 && completions == 0);+ assert([aux.configuration.category isEqual:@"AVAudioSessionCategoryPlayback"] && aux.configuration.options == 0);+ assert(service.event.type == 13 && service.event.timestamp && service.event.audioSessionID == 47);+ assert(service.event.speechSynthesisRequest.priority == 2 && service.event.speechSynthesisRequest.options == 0);+ assert([service.event.speechSynthesisRequest.speakableText isEqual:@"Native Siri phrase"]);+ // Submission does not release the auxiliary session. The native final+ // callback, including a failure, is the lifetime boundary.+ service.completion(nativeError);+ assert(completions == 1 && received == nativeError && aux.deactivations == 1);+ service.completion(nil);+ assert(completions == 1 && aux.deactivations == 1);+ service.completion = nil; aux = nil;+ assert(!lastAuxiliary);+ [siri say:@"Second" completion:^(NSError *error) { completions++; received = error; }];+ aux = lastAuxiliary;+ assert(aux.deactivations == 0);+ service.completion(nil);+ assert(completions == 2 && received == nil && aux.deactivations == 1);+ service.completion = nil;+ failActivation = YES;+ [siri say:@"Failure" completion:^(NSError *error) { completions++; received = error; }];+ assert(completions == 3 && received == nativeError && lastAuxiliary.activations == 1 && lastAuxiliary.deactivations == 0);+ failActivation = NO; zeroSessionID = YES;+ [siri say:@"Missing ID" completion:^(NSError *error) { completions++; received = error; }];+ assert(completions == 4 && received && lastAuxiliary.deactivations == 1);+ zeroSessionID = NO;+ client.activationService = nil;+ [siri say:@"Disconnected" completion:^(NSError *error) { completions++; received = error; }];+ assert(completions == 5 && received && lastAuxiliary.deactivations == 1);+ NSUInteger beforeDisabled = auxiliaryRequests;+ VPSiriSpeechTestEnabled = NO;+ assert(!VPHomePodSiriSpeechInstall());+ [siri say:@"Original" completion:^(NSError *error) { completions++; received = error; }];+ assert(originalRequests == 1 && auxiliaryRequests == beforeDisabled && received == nil);+ assert(sharedSessionRequests == 0);+ puts("HomePod Siri speech tests passed");+ }+ return 0;+}diff --git a/VPhoneGuestComponents/Tests/HomePodWelcomeStateTests.m b/VPhoneGuestComponents/Tests/HomePodWelcomeStateTests.mnew file mode 100644index 00000000..c35a261c--- /dev/null+++ b/VPhoneGuestComponents/Tests/HomePodWelcomeStateTests.m@@ -0,0 +1,171 @@+#import "VPHomePodWelcomeState.h"+#include <dispatch/dispatch.h>+#include <signal.h>+#include <stdlib.h>+#include <sys/resource.h>+#include <sys/stat.h>+#include <unistd.h>++#define CHECK(...) do { if (!(__VA_ARGS__)) { NSLog(@"Failed at line %d: %s", __LINE__, #__VA_ARGS__); abort(); } } while (0)++static NSString *directory(NSString *root, NSString *name) {+ return [root stringByAppendingPathComponent:name];+}++static void makeDirectory(NSString *path) {+ CHECK([NSFileManager.defaultManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL]);+}++static BOOL withWritesPrevented(BOOL (^operation)(void)) {+ // Force a real regular-file persistence failure, including when the test+ // runs as root. Restore the process limit/handler before inspecting errors.+ struct rlimit original;+ CHECK(getrlimit(RLIMIT_FSIZE, &original) == 0);+ struct rlimit limited = original;+ limited.rlim_cur = 0;+ void (*handler)(int) = signal(SIGXFSZ, SIG_IGN);+ CHECK(handler != SIG_ERR && setrlimit(RLIMIT_FSIZE, &limited) == 0);+ BOOL result = operation();+ CHECK(setrlimit(RLIMIT_FSIZE, &original) == 0);+ CHECK(signal(SIGXFSZ, handler) != SIG_ERR);+ return result;+}++int main(void) {+ @autoreleasepool {+ NSString *root = [NSTemporaryDirectory() stringByAppendingPathComponent:NSUUID.UUID.UUIDString];+ makeDirectory(root);+ NSError *error = nil;++ // Production adds an identity directory below HomePodWelcome. Every+ // newly-created ancestor entry must persist before the claim succeeds.+ NSString *nestedPath = directory(root, @"new-vphone/HomePodWelcome/device-identity");+ VPHomePodWelcomeState *nested = [[VPHomePodWelcomeState alloc] initWithDirectory:nestedPath];+ CHECK([nested claimWithError:&error] && !error);+ for (NSString *path in @[directory(root, @"new-vphone"), directory(root, @"new-vphone/HomePodWelcome"), nestedPath]) {+ struct stat metadata;+ CHECK(stat(path.fileSystemRepresentation, &metadata) == 0 && S_ISDIR(metadata.st_mode));+ }+ CHECK(![[[VPHomePodWelcomeState alloc] initWithDirectory:nestedPath] claimWithError:&error] && !error);++ // An existing containing ancestor can be a system alias (/var on+ // Apple platforms). It is not the control directory and may be followed.+ NSString *ancestor = directory(root, @"existing-ancestor");+ NSString *alias = directory(root, @"ancestor-alias");+ makeDirectory(ancestor);+ CHECK(symlink(ancestor.fileSystemRepresentation, alias.fileSystemRepresentation) == 0);+ NSString *aliasedNestedPath = directory(alias, @"HomePodWelcome/device-identity");+ VPHomePodWelcomeState *aliasedNested = [[VPHomePodWelcomeState alloc] initWithDirectory:aliasedNestedPath];+ CHECK([aliasedNested claimWithError:&error] && !error);+ CHECK([NSFileManager.defaultManager fileExistsAtPath:directory(ancestor, @"HomePodWelcome/device-identity/Claim.plist")]);++ NSString *oncePath = directory(root, @"once");+ VPHomePodWelcomeState *once = [[VPHomePodWelcomeState alloc] initWithDirectory:oncePath];+ CHECK([once claimWithError:&error] && !error);+ NSString *claimPath = directory(oncePath, @"Claim.plist");+ NSData *claim = [NSData dataWithContentsOfFile:claimPath];+ CHECK(claim.length > 0);+ struct stat claimMetadata, controlMetadata;+ CHECK(lstat(claimPath.fileSystemRepresentation, &claimMetadata) == 0);+ CHECK((claimMetadata.st_mode & 0777) == 0600 && claimMetadata.st_uid == geteuid());+ CHECK(lstat(oncePath.fileSystemRepresentation, &controlMetadata) == 0);+ CHECK((controlMetadata.st_mode & 0777) == 0700 && controlMetadata.st_uid == geteuid());+ CHECK(![once claimWithError:&error] && !error);+ VPHomePodWelcomeState *restarted = [[VPHomePodWelcomeState alloc] initWithDirectory:oncePath];+ CHECK(![restarted claimWithError:&error] && !error); // Process/boot restart preserves consumption.++ CHECK([once writeStatus:@"playing" fields:@{@"Tone": @1, @"State": @"cannot override", @"Updated": @0} error:&error]);+ NSString *statusPath = directory(oncePath, @"Status.plist");+ NSDictionary *status = [NSDictionary dictionaryWithContentsOfFile:statusPath];+ CHECK([status[@"State"] isEqual:@"playing"] && [status[@"Updated"] isKindOfClass:NSDate.class]);+ CHECK([status[@"Tone"] isEqual:@1]);+ CHECK([once writeStatus:@"failed" fields:@{@"Error": @"speech unavailable"} error:&error]);+ status = [NSDictionary dictionaryWithContentsOfFile:statusPath];+ CHECK([status[@"State"] isEqual:@"failed"] && [status[@"Error"] isEqual:@"speech unavailable"]);+ CHECK(![once writeStatus:@"failed" fields:@{@"Invalid": [NSObject new]} error:&error] && error);+ CHECK([[NSDictionary dictionaryWithContentsOfFile:statusPath] isEqual:status]);+ CHECK([[NSData dataWithContentsOfFile:claimPath] isEqual:claim]);+ struct stat afterStatus;+ CHECK(lstat(claimPath.fileSystemRepresentation, &afterStatus) == 0 && afterStatus.st_ino == claimMetadata.st_ino);+ CHECK(lstat(statusPath.fileSystemRepresentation, &afterStatus) == 0 && (afterStatus.st_mode & 0777) == 0600);+ CHECK(![restarted claimWithError:&error] && !error); // Progress cannot clear or replace the claim.++ for (NSData *malformed in @[[NSData data], [@"partial plist" dataUsingEncoding:NSUTF8StringEncoding]]) {+ NSString *path = directory(root, NSUUID.UUID.UUIDString);+ makeDirectory(path);+ CHECK([malformed writeToFile:directory(path, @"Claim.plist") atomically:YES]);+ VPHomePodWelcomeState *state = [[VPHomePodWelcomeState alloc] initWithDirectory:path];+ CHECK(![state claimWithError:&error] && !error);+ CHECK([[NSData dataWithContentsOfFile:directory(path, @"Claim.plist")] isEqual:malformed]);+ }++ NSString *target = directory(root, @"symlink-target");+ makeDirectory(target);+ NSString *linkedDirectory = directory(root, @"linked-directory");+ CHECK(symlink(target.fileSystemRepresentation, linkedDirectory.fileSystemRepresentation) == 0);+ VPHomePodWelcomeState *linked = [[VPHomePodWelcomeState alloc] initWithDirectory:linkedDirectory];+ CHECK(![linked claimWithError:&error] && error);+ CHECK(![linked writeStatus:@"waiting" fields:@{} error:&error] && error);+ CHECK(![NSFileManager.defaultManager fileExistsAtPath:directory(target, @"Claim.plist")]);+ CHECK(![NSFileManager.defaultManager fileExistsAtPath:directory(target, @"Status.plist")]);++ NSString *sentinel = directory(root, @"sentinel");+ NSData *untouched = [@"untouched" dataUsingEncoding:NSUTF8StringEncoding];+ CHECK([untouched writeToFile:sentinel atomically:YES]);+ NSString *linkedClaimPath = directory(root, @"linked-claim");+ makeDirectory(linkedClaimPath);+ CHECK(symlink(sentinel.fileSystemRepresentation, directory(linkedClaimPath, @"Claim.plist").fileSystemRepresentation) == 0);+ VPHomePodWelcomeState *linkedClaim = [[VPHomePodWelcomeState alloc] initWithDirectory:linkedClaimPath];+ CHECK(![linkedClaim claimWithError:&error] && error);+ CHECK([[NSData dataWithContentsOfFile:sentinel] isEqual:untouched]);+ NSString *linkedStatusPath = directory(root, @"linked-status");+ makeDirectory(linkedStatusPath);+ CHECK(symlink(sentinel.fileSystemRepresentation, directory(linkedStatusPath, @"Status.plist").fileSystemRepresentation) == 0);+ VPHomePodWelcomeState *linkedStatus = [[VPHomePodWelcomeState alloc] initWithDirectory:linkedStatusPath];+ CHECK(![linkedStatus writeStatus:@"waiting" fields:@{} error:&error] && error);+ CHECK([[NSData dataWithContentsOfFile:sentinel] isEqual:untouched]);++ NSString *failedPath = directory(root, @"failed-write");+ VPHomePodWelcomeState *failed = [[VPHomePodWelcomeState alloc] initWithDirectory:failedPath];+ CHECK([failed writeStatus:@"waiting" fields:@{} error:&error]);+ __block NSError *writeError = nil;+ CHECK(!withWritesPrevented(^BOOL { return [failed claimWithError:&writeError]; }));+ CHECK(writeError && [NSFileManager.defaultManager fileExistsAtPath:directory(failedPath, @"Claim.plist")]);+ CHECK(![[[VPHomePodWelcomeState alloc] initWithDirectory:failedPath] claimWithError:&error] && !error);+ NSData *priorStatus = [NSData dataWithContentsOfFile:directory(failedPath, @"Status.plist")];+ CHECK(!withWritesPrevented(^BOOL { return [failed writeStatus:@"completed" fields:@{} error:&writeError]; }));+ CHECK(writeError && [[NSData dataWithContentsOfFile:directory(failedPath, @"Status.plist")] isEqual:priorStatus]);+ CHECK(![failed claimWithError:&error] && !error); // Failed persistence is fail-closed, never a retry permission.++ NSString *notDirectory = directory(root, @"regular-file");+ CHECK([untouched writeToFile:notDirectory atomically:YES]);+ VPHomePodWelcomeState *invalid = [[VPHomePodWelcomeState alloc] initWithDirectory:notDirectory];+ CHECK(![invalid claimWithError:&error] && error);+ CHECK(![[[VPHomePodWelcomeState alloc] initWithDirectory:@"relative"] claimWithError:&error] && error);++ NSString *concurrentPath = directory(root, @"concurrent/HomePodWelcome/device-identity");+ dispatch_group_t group = dispatch_group_create();+ NSObject *lock = [NSObject new];+ __block NSUInteger winners = 0, failures = 0;+ for (NSUInteger index = 0; index < 32; index++) {+ dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{+ @autoreleasepool {+ VPHomePodWelcomeState *state = [[VPHomePodWelcomeState alloc] initWithDirectory:concurrentPath];+ NSError *failure = nil;+ BOOL claimed = [state claimWithError:&failure];+ @synchronized (lock) {+ winners += claimed ? 1 : 0;+ failures += failure ? 1 : 0;+ }+ }+ });+ }+ CHECK(dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)) == 0);+ CHECK(winners == 1 && failures == 0);+ CHECK(![[[VPHomePodWelcomeState alloc] initWithDirectory:concurrentPath] claimWithError:&error] && !error);++ CHECK([NSFileManager.defaultManager removeItemAtPath:root error:&error]);+ NSLog(@"HomePod welcome durable claim and status tests passed");+ }+ return 0;+}diff --git a/VPhoneGuestComponents/Tests/HomePodWelcomeTests.m b/VPhoneGuestComponents/Tests/HomePodWelcomeTests.mnew file mode 100644index 00000000..7036dbdb--- /dev/null+++ b/VPhoneGuestComponents/Tests/HomePodWelcomeTests.m@@ -0,0 +1,204 @@+#define VP_HOMEPOD_WELCOME_TESTING 1+#import "../HomePodDisplay/VPHomePodWelcome.m"+#include <assert.h>++static BOOL needsSetup;+@interface SBSetupController : NSObject++ (BOOL)deviceNeedsSetup;+@end+@implementation SBSetupController++ (BOOL)deviceNeedsSetup { return needsSetup; }+@end++@interface WelcomeDisplay : NSObject+@property BOOL startupComplete;+@property BOOL drawing;+- (NSDictionary *)diagnosticsInfo;+@end+@implementation WelcomeDisplay+- (NSDictionary *)diagnosticsInfo { return @{@"DrawingEnabled": @(self.drawing)}; }+@end++@interface WelcomeActivity : NSObject+@property BOOL localSessionActive;+@property BOOL remoteSessionActive;+@property BOOL siriUIEnabled;+@property (copy) NSString *activityName;+@property NSUInteger stops;+- (void)endLocalSessionActivity;+@end+@implementation WelcomeActivity+@synthesize localSessionActive = _localSessionActive;+- (void)setLocalSessionActive:(BOOL)active {+ if (_localSessionActive == active) return;+ _localSessionActive = active;+ if (!active) [self endLocalSessionActivity];+}+// Native Identify only stops its tone/animation in this subclass callback.+// The coordinated setter owns the active flag and foreground dismissal.+- (void)endLocalSessionActivity { self.stops++; }+@end++@interface WelcomeActivities : NSObject+@property (strong) WelcomeActivity *identify;+@property (strong) WelcomeActivity *siri;+@property (strong) id foregroundedActivity;+@property NSUInteger activeMediaCount;+- (id)activityWithName:(NSString *)name;+@end+@implementation WelcomeActivities+- (id)activityWithName:(NSString *)name {+ return [name isEqual:@"Identify"] ? self.identify : [name isEqual:@"Siri"] ? self.siri : nil;+}+@end++@interface WelcomeSiri : NSObject+@property BOOL siriEnabled;+@property NSInteger currentSessionState;+@property (copy) NSString *phrase;+@property (copy) void (^completion)(NSError *);+@property NSUInteger requests;+- (void)say:(NSString *)text completion:(void (^)(NSError *))completion;+@end+@implementation WelcomeSiri+- (void)say:(NSString *)text completion:(void (^)(NSError *))completion {+ self.phrase = text; self.completion = completion; self.requests++;+}+@end++@interface WelcomeTone : NSObject+@property uint32_t tone;+@property NSUInteger requests;+@property (copy) void (^completion)(NSError *);+- (void)play:(uint32_t)tone completion:(void (^)(NSError *))completion;+@end+@implementation WelcomeTone+- (void)play:(uint32_t)tone completion:(void (^)(NSError *))completion {+ self.tone = tone; self.completion = completion; self.requests++;+}+@end+@interface WrongToneABI : NSObject+- (void)play:(uint64_t)tone completion:(void (^)(NSError *))completion;+@end+@implementation WrongToneABI+- (void)play:(uint64_t)tone completion:(void (^)(NSError *))completion { (void)tone; (void)completion; abort(); }+@end++@interface WelcomeBoard : NSObject+@property (strong) WelcomeActivities *activityManager;+@property (strong) WelcomeDisplay *displayService;+@property (strong) WelcomeSiri *siriManager;+@property (strong) id uiTonePlaybackManager;+@end+@implementation WelcomeBoard+@end++static NSString *root;+static NSString *policy;+static WelcomeBoard *board;+static WelcomeTone *tone;+static NSString *directory;++static NSString *stateName(NSInteger state) { return state == 1 ? @"idle" : @"presenting"; }++static VPHomePodWelcome *fresh(void) {+ directory = [root stringByAppendingPathComponent:NSUUID.UUID.UUIDString];+ needsSetup = NO;+ board = WelcomeBoard.new;+ board.activityManager = WelcomeActivities.new;+ board.activityManager.identify = WelcomeActivity.new;+ board.activityManager.siri = WelcomeActivity.new;+ board.activityManager.siri.siriUIEnabled = YES;+ board.displayService = WelcomeDisplay.new;+ board.displayService.startupComplete = YES; board.displayService.drawing = YES;+ board.siriManager = WelcomeSiri.new; board.siriManager.siriEnabled = YES; board.siriManager.currentSessionState = 1;+ tone = WelcomeTone.new; board.uiTonePlaybackManager = tone;+ assert([@{@"Enabled": @YES} writeToFile:policy atomically:YES]);+ return [[VPHomePodWelcome alloc] initWithBoard:board directory:directory policy:policy];+}++static NSDictionary *status(void) {+ return [NSDictionary dictionaryWithContentsOfFile:[directory stringByAppendingPathComponent:@"Status.plist"]];+}+static void spin(NSTimeInterval duration) {+ NSDate *until = [NSDate dateWithTimeIntervalSinceNow:duration];+ while (until.timeIntervalSinceNow > 0) [NSRunLoop.mainRunLoop runMode:NSDefaultRunLoopMode beforeDate:until];+}++int main(void) { @autoreleasepool {+ VPWelcomeSessionStateName = stateName;+ // Independent donor metadata: SBUITonePlaybackManager on 24J361 is UInt32,+ // v28@0:8I16@?20. A UInt64 mock used to agree with a wrong production guard+ // and concealed that every real guest would wait for readiness forever.+ NSMethodSignature *donorTone = [NSMethodSignature signatureWithObjCTypes:"v28@0:8I16@?20"];+ NSMethodSignature *mockTone = [WelcomeTone instanceMethodSignatureForSelector:@selector(play:completion:)];+ assert(strcmp(mockTone.methodReturnType, donorTone.methodReturnType) == 0);+ assert(mockTone.numberOfArguments == donorTone.numberOfArguments);+ for (NSUInteger i = 0; i < donorTone.numberOfArguments; i++) {+ assert(strcmp([mockTone getArgumentTypeAtIndex:i], [donorTone getArgumentTypeAtIndex:i]) == 0);+ }+ root = [NSTemporaryDirectory() stringByAppendingPathComponent:NSUUID.UUID.UUIDString];+ assert([NSFileManager.defaultManager createDirectoryAtPath:root withIntermediateDirectories:YES attributes:nil error:NULL]);+ policy = [root stringByAppendingPathComponent:@"Policy.plist"];++ // Readiness can arrive in either order. Waiting never consumes the claim.+ VPHomePodWelcome *welcome = fresh();+ needsSetup = YES; [welcome poll]; assert(tone.requests == 0);+ needsSetup = NO; board.displayService.startupComplete = NO; [welcome poll]; assert(tone.requests == 0);+ board.displayService.startupComplete = YES; board.displayService.drawing = NO; [welcome poll]; assert(tone.requests == 0);+ board.displayService.drawing = YES; board.siriManager.siriEnabled = NO; [welcome poll]; assert(tone.requests == 0);+ board.siriManager.siriEnabled = YES; board.siriManager.currentSessionState = 4; [welcome poll]; assert(tone.requests == 0);+ board.siriManager.currentSessionState = 1; board.activityManager.siri.siriUIEnabled = NO; [welcome poll]; assert(tone.requests == 0);+ board.activityManager.siri.siriUIEnabled = YES;+ WelcomeActivity *foreground = WelcomeActivity.new; foreground.activityName = @"HPSetup";+ board.activityManager.foregroundedActivity = foreground; [welcome poll]; assert(tone.requests == 0);+ foreground.activityName = @"NowPlayingCap"; board.activityManager.activeMediaCount = 1; [welcome poll]; assert(tone.requests == 0);+ assert(![NSFileManager.defaultManager fileExistsAtPath:directory]);+ board.activityManager.activeMediaCount = 0; [welcome poll]; assert(tone.requests == 1 && tone.tone == 1);+ assert(board.activityManager.identify.localSessionActive);+ assert(board.siriManager.requests == 0);+ [welcome poll]; assert(tone.requests == 1);+ tone.completion(nil); spin(0.1);+ assert(!board.activityManager.identify.localSessionActive && board.activityManager.identify.stops == 1);+ assert(board.siriManager.requests == 0); // Wait for tone completion, then the pause.+ spin(0.7);+ assert(board.siriManager.requests == 1);+ assert([board.siriManager.phrase isEqual:@"Hi, I'm Siri. It sure is great to be running in a virtual machine!"]);+ board.siriManager.completion(nil); spin(0.05);+ assert([status()[@"State"] isEqual:@"SpeechFinalized"]);+ VPHomePodWelcome *restart = [[VPHomePodWelcome alloc] initWithBoard:board directory:directory policy:policy];+ [restart poll]; assert(tone.requests == 1 && board.siriManager.requests == 1);++ // Native tone failure releases only our flourish and prevents speech/replay.+ welcome = fresh(); [welcome poll];+ NSError *failure = [NSError errorWithDomain:@"NativeTone" code:42 userInfo:nil];+ tone.completion(failure); spin(0.05);+ assert([status()[@"State"] isEqual:@"ToneFailed"] && board.siriManager.requests == 0);+ assert([status()[@"ErrorDomain"] isEqual:@"NativeTone"]);+ assert(!board.activityManager.identify.localSessionActive);++ // Opt-out before readiness leaves Data untouched; during the pause it cancels+ // speech while retaining the already-consumed claim.+ welcome = fresh(); assert([@{@"Enabled": @NO} writeToFile:policy atomically:YES]);+ [welcome poll]; assert(tone.requests == 0 && ![NSFileManager.defaultManager fileExistsAtPath:directory]);+ welcome = fresh(); [welcome poll]; tone.completion(nil); spin(0.1);+ assert([@{@"Enabled": @NO} writeToFile:policy atomically:YES]); spin(0.7);+ assert(board.siriManager.requests == 0 && [status()[@"State"] isEqual:@"Cancelled"]);+ assert([NSFileManager.defaultManager fileExistsAtPath:[directory stringByAppendingPathComponent:@"Claim.plist"]]);++ welcome = fresh(); [welcome poll]; tone.completion(nil); spin(0.8);+ board.siriManager.completion([NSError errorWithDomain:@"NativeSiri" code:221 userInfo:nil]); spin(0.05);+ assert([status()[@"State"] isEqual:@"SpeechFailed"]);+ assert([status()[@"ErrorCode"] isEqual:@221]);+ board.siriManager.completion(nil); spin(0.05);+ assert([status()[@"State"] isEqual:@"SpeechFailed"]); // Late callbacks cannot erase failure.++ // A changed donor ABI or unavailable Data volume fails before side effects.+ welcome = fresh(); board.uiTonePlaybackManager = WrongToneABI.new; [welcome poll]; assert(tone.requests == 0);+ assert(![NSFileManager.defaultManager fileExistsAtPath:directory]);+ welcome = fresh(); assert([@"not a directory" writeToFile:directory atomically:YES encoding:NSUTF8StringEncoding error:NULL]);+ [welcome poll]; assert(tone.requests == 0 && !board.activityManager.identify.localSessionActive);++ assert([NSFileManager.defaultManager removeItemAtPath:root error:NULL]);+ puts("HomePod welcome ordering, readiness, cancellation and native failure tests passed");+} return 0; }