Run a virtual iPhone on an Apple Silicon Mac.
Swift
Apple TV remote, native 4th gen setup
Guilherme Ramboc8d8be57bc16
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex aa4bc404..7fbf067a 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,56 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **Apple TV remote and native Setup (2026-10-24).** The current+> `tvos-4k` preset selects `system-setupbackground-exp-pineboard_lookup` on+> 27.2 and blocks `system-tv-exp-legacy_setup`. The environment update+> restores the original CompanionServices flags from their backup, returning+> to the new Setup app. Live debugger inspection localized Select's failure:+> Hello's native focus target exists but is deferred; a directional press+> commits it, after which Select executes the ordinary Hello callback and+> opens Language. `system-setup-exp-deferred_focus` installs a tvOS dylib into+> Setup via `/tf`, preserving its original entitlements and a reversible backup.+> Its adapter uses native TV button-focus policy (`0`) only for an active key+> Setup window whose WaffleIron system has default deferral (`3`) and no explicit+> override. It observes scene/key/focus updates, preserves other overrides, and+> uses UIKit's own preferred-focus machinery and eligibility checks. Earlier+> focus-initialization prototypes expired after the native 60-second idle timer.+> A live policy-0 test retained focus past 80 seconds and Select entered the+> native country picker. The adapter changes no+> pairing, drawing, ScenePhase, window suppression or setup-completion state.+> This patch is selected only by `tvos-4k` on 27.2; legacy setup remains off.+> Installed cold-boot testing passes the first Select after more than 65 seconds+> idle at Hello, without directional priming or a debugger. Completed+> AX/button taps now survive panel focus loss; pending holds are cancelled and+> neither may cross a guest reconnection. The actual AX-button/queue harness+> covers this live-discovered delivery failure. See the+> [input investigation](Firmware/tvos_27_setup_input.md). Remote clicks, holds,+> Home/Settings navigation and Control Center have passed live testing.+>+> Native Setup then reached manual activation and failed with -71136. The+> matching tvOS mobileactivationd retains the existing `should_hactivate`+> local-state path, but the TV preset had excluded it. The new declaration+> `system-mobileactivationd-exp-tv_activation` reuses that unchanged patcher+> with an exact 27.2 applicability gate, selected only by `tvos-4k` and admitted+> only for arm64e Apple TV. The installer uses one activation declaration per+> device, retaining the existing backup/revert path. Installed native Manual+> setup now advances past activation to room choice and Terms & Conditions.+> Cold boot of `a4b9ffc4` exposed a packaging failure: the final Setup bundle+> seal discarded the entitlements preserved by `patchMachO`, causing native+> TCC Bluetooth usage-description crashes. Both applying the focus adapter+> and restoring its backup now preserve original entitlements through bundle+> sealing. Corrected bundle `da14d7a4` retains the full pristine entitlement set+> byte-identically and passes the idle/AX input test. After user-confirmed Terms,+> native Setup completes to Home with its own SetupDone/TVBuddy completion+> flags true and TVSetupVersion=15. The original VM is also updated, with its+> prior setup and data preserved. Navigation, Control Center, Siri search,+> Power sleep and TV wake pass; audio effects without active media remain+> unverified. A final read-only daemon correction uses TV version/completion+> policy instead of the iOS setup version; 376 logic checks pass. Its bundle+> `9ffd2d6e` is installed on both machines. Final cold boots report TV setup+> and current versions 15, pending=false, and no Setup process. The clone+> returns directly to Home; the original remains running with its data intact.+> Both receipts have zero pending changes and legacy setup off.+> **HomePod local app installation (2026-10-23).**> `system-installd-exp-homepod_adhoc` is selected only by `homepod-mini` on> HomePod 27. It loads a dedicated TVOS arm64e build of the existing MISdiff --git a/Research/Firmware/tvos_27_setup_input.md b/Research/Firmware/tvos_27_setup_input.mdnew file mode 100644index 00000000..9a5270ef--- /dev/null+++ b/Research/Firmware/tvos_27_setup_input.md@@ -0,0 +1,800 @@+# tvOS 27.2 Setup input investigation++## Scope and result++Static and live inspection of the native 27.2 beta `Setup` executable (SHA-256+`52815e2959731c961cd259e74c98d6d46263b13a4daca7d9789ee734fea4e44c`),+plus the matching pristine UIKitCore dyld-cache image. Live diagnostics used+the separate `tv4k4-native-setup` clone, preserving the user's configured VM.+Test preparation used `vm clone --new-identity` and reset only the clone's+SetupDone, SetupFinishedAllSteps, and TVBuddyCompletedSuccessfully to false+to exercise the assistant. No tool forced those values to completed; the+source VM's preferences were never reset.+The new assistant remains the intended path;+selecting legacy TVSetup is not a solution to this input issue.++The ordinary consumer Select event has the correct native press type. No+Bluetooth-pairing requirement, HID sender-ID test, or service-identity test was+found in the Hello tap callback or the inspected window delivery code. The+failure is now localized to deferred focus. At actual Select delivery, the+key window is foreground-active, `dropsEvents` is false, and the press is type+4, phase began, force 1. The focus system has no focused item, but its deferred+target is the native Hello SwiftUI focusable item. One normal Up commits that+target; the next Select hits the verified Hello callback and opens Language.+The native `_performDeferredFocusUpdateIfAvailable` method also returns YES+and commits the same target without an arrow. That initialization alone expires+after the native 60-second idle timer; timestamps explain the delayed first-+Select prototype failures. An immediate Select hits the native callback.+The live behavior is `_UIFocusBehavior_WaffleIron`, effective deferral 3, with+no explicit override. Native TV behavior's deferral is 0. Setting the native+override to 0 retains focus past 80 seconds and allows selection of English+and entry to the country picker without an arrow.++The adapter applies that native TV button-focus policy only to an active key+`Setup.EventDroppingWindow` with WaffleIron/default-3/no-override state. It+preserves other explicit policies and uses UIKit's native setter, preference+search and eligibility checks. Scene/key/focus notifications recheck after+native updates finish; there are no private-ivar writes, swizzles, polling+timers or changes to Setup's actual input/readiness/step callbacks. Installed+bundle `da14d7a4` passes the first actual panel Select after more than 65 seconds+idle at Hello; native Manual setup then passes activation and completes to Home+after user-confirmed Terms. Native TV completion/version preferences are set by+Setup itself; no tool forces the completed state.++A separate host transport issue was isolated on Language: an AX panel tap+left English focused, while the identical direct `input.hid` Select entered+Country or Region. Cancelling queued input on panel key loss also cancelled+already-completed AX taps. Press tickets now preserve completed taps across+focus changes while cancelling unfinished holds; a separate connection epoch+prevents any old tap reaching a later guest. The host harness exercises the+actual AX button and view release order for both cases.++## Hello gesture and readiness++`TVHelloView`'s body (`0x100044ba0`, call sites `0x100045418` and+`0x100045528`) attaches `.focusable(true)` and `.onTapGesture(count: 1)`.+Its callback thunk `0x1000496b4` reaches `0x100047600`. There is no+`onMoveCommand` modifier in this Hello body; that modifier is used by other+Setup screens.++Before logging `Remote pressed.` and invoking `remotePairedHandler`, the+callback requires both:++1. `TVHelloManager._hasDrawingStarted == true` (byte at instance offset `0x28`).+2. The installed SwiftUI `Environment<ScenePhase>` equals `.active`.++These checks do not inspect the paired-remote state. A different asynchronous+path can advance after a remote becomes paired, but it does not make pairing a+prerequisite for the local tap path. The eventual parent callback+`0x100077520` checks the server is still in `.hello` before sending+`CSKStepHelloServer.Command.helloAnswered`.++The drawing flag is a real rendering lifecycle signal, not a pairing flag:++- `CursiveHelloViewController` configures+ `SASBookendCallbackConfiguration.onAnimationWillBegin` in `0x10010afd8`.+- Its closure reaches `0x10010b280`, which yields+ `DrawingProgress.started(languageCode:)` to `drawingContinuation`.+- `TVHelloManager` consumes that AsyncStream in `0x100040f7c`; the started+ case sets the `0x28` byte through Observation mutation (and retains `true`+ on subsequent starts).+- `TVHelloView`'s drawing-state `onChange` reaches `0x100048c04`, which+ invokes the distinct `drawingStartedHandler` when the flag becomes true.++`0x1001ba1f4` reads the installed ScenePhase environment. Its fallback emits+SwiftUI's runtime warning about reading an Environment outside an installed+View; it does not query an XPC service or entitlement. Static inspection does+not establish the actual guest's phase or focus at the failed press.++## Window suppression boundary++`Setup.EventDroppingWindow.sendEvent:` reaches `0x10010cce4`. For press events+it tracks press identities so a sequence rejected at its beginning does not+later deliver an orphan release. It uses the window's `dropsEvents` gate and+press phases, without a sender/service-ID check in the inspected code.++The useful debug message is already shipped:++```text+sendEvent presses dropsEvents=%{bool}d dropped=%ld deliver=%{bool}d phases=[%s]+```++Its logger is subsystem `CompanionSetup`, category `EventDroppingWindow`.+The exact subsystem is independently confirmed by the matching cache's+`CSKConstants.logSubsystem` getter at `0x1d2c7b13c`, which returns that Swift+small string. Hello's logger uses the same subsystem, category `TVHelloView`.++**The window message is conditional, not an event trace.** A full control-flow+recheck after enabling debug and cold-booting the setup-test clone establishes+that `dropsEvents == false` together with an empty `droppedPressIDs` set skips+the logger entirely. At `0x10010d088`, a set drops flag reaches the logger at+`0x10010d0bc`; otherwise the stored dropped-set count is tested at+`0x10010d0b4`. Zero branches to `0x10010d614`, then `0x10010d3cc`, bypassing+both logger initialization and `os_log_type_enabled`. Normal delivery can+therefore produce no `EventDroppingWindow` message even with debug enabled.+The eventual call to `super.sendEvent:` remains conditional on the computed+delivery Boolean at `0x10010d5d8` / `0x10010d5f0`.++The window logger constructor `0x10010cc78` uses the exact category literal+`EventDroppingWindow` at `0x10027b3e0` and the CSK subsystem getter. The log+level is explicitly Debug (`0x10010d198`). It is neither a nil-logger fallback+nor compiled-out logging. Hello's constructor `0x1000443b0` independently+encodes `CompanionSetup` / `TVHelloView` as Swift small strings; its+`Remote pressed.` message uses **Default** at `0x1000478fc`, after both the+drawing-started and active-scene guards. Absence of the window message cannot+localize the input failure; absence of `Remote pressed.` remains consistent+with missing tap focus or an unmet Hello guard.++Two callers control suppression:++- `TVMainSetupView` observes+ `server.uiState.restartImminent || server.uiState.isShowingScreenSaver`.+ `0x1000602e0` gates the scene's EventDroppingWindows. When the observed+ condition becomes false, its task clears suppression after 0.25 seconds+ (`0x100060f48` / `0x1000610cc`).+- During `.hello`, `0x100061834` detects `.pairing` → `.paired` and briefly+ gates delivery before its clear task (`0x1000623e0` / `0x100062564`).++The main view also installs FocusState binding and default focus with+`DefaultFocusEvaluationPriority.userInitiated`. Neither existence of the+rendered animation nor a healthy PBS display-state query proves that the+intended Hello view has input focus.++## Native remote mapping, verified on 27.2++UIKitCore's `__UIEventHIDPressTypeForKeyboardHIDEvent` at `0x194776f54`+reads only keyboard usage page (`0x30000`) and usage (`0x30001`). It maps:++| Consumer page `0x0C` usage | UIKit press type | Intended control |+| --- | --- | --- |+| `0x41` | 4 | Select |+| `0x42`, `0x43`, `0x44`, `0x45` | 0, 1, 2, 3 | Up, Down, Left, Right |+| `0x46` | 5 | Siri Remote Back / Menu |+| `0x224` | 7 | Different Back press; not the Menu mapping |+| `0x40` | 17 | TV / Home |+| `0xCD` | 6 | Play/Pause |+| `0xE2` | 20 | Mute |+| `0xE9`, `0xEA` | 102, 103 | Volume Up, Down |+| `0x30` | 104 | Power |+| `0xCF` | 504 | Voice Command |++Keyboard Return (`0x07/0x28`) is not Select in this conversion; a UI may+separately handle its keyboard event. Thus Return alone is not a decisive+comparison for the consumer Select gesture path. This conversion does not+prove all earlier backboard or focus routing accepts an arbitrary event sender.++`GuestAPI` routes ordinary `input.hid` requests to `hidEvent`/`hidPress`.+`vp_hid_keyboard_hold` and its explicit KeyboardLongPress field are used only+when `long_press: true` is requested. Earlier ordinary Select trials did not+take that branch; the hold helper does not explain their failure.++## PineBoard's actual routing and activation gates++`-[PBHIDEventDeliveryManager _lock_enableNormalHIDEventDelivery]` installs+two BKS discrete-dispatch rules: a system predicate to `systemTarget`, and a+keyboard-focus predicate to `keyboardFocusTarget`. Both predicate constructors+explicitly clear `senderDescriptors`.++The keyboard-focus predicate removes the system press set, then adds+`[30, 31, 4, 0, 3, 1, 2, 32, 33]`. Select (4) and arrows (0–3) therefore+take the ordinary keyboard-focus route. The system predicate removes that set+and retains such controls as Menu (5), AC Back (7), Home (17), power and volume.+This is shipped PineBoard behavior, independent of the SDK usage labels.++`-[PBSceneManager _eventsCanBeDeferredToSceneHandle:]` requires:++- A scene exists and is valid.+- Its settings are foreground and `contentState == 2`.+- For `UIApplicationSceneSpecification`, `isUISubclass` is true and+ `(deactivationReasons & ~0x20) == 0`.++Every rejected case has a `Will not defer events to … scene` log, including+the scene identifier; the deactivation case logs the reason mask description.+`_updateFocusDeferralsIfNeeded` creates a BKS target with PID and scene token,+installs it with reason `PineBoardFocusDeferral`, and logs+`Updated events to new focused scene … pid: …`.++The scene layout's event-focus acceptance also follows readiness:+`PBApplicationSceneView.canBecomeFocused` requires effective presentation+mode 3, `_eligibleForFocus`, and `sceneHandle.isContentReady`.+`PBSceneLayoutViewController.setFocusedSceneLayoutElement:` calls+`setAcceptsEventFocus:` with the element's readiness.++These checks give a concrete scene/focus boundary to measure. They do not prove+the failed new Setup run had a bad scene or require altering any readiness gate.++## Original live diagnostic plan++Use the unmodified new Setup path and a normal consumer Select down/up pair+with one stable sender and a short physical-style hold. Do not synthesize+pairing or send `helloAnswered` directly. Capture these boundaries for that+single press:++1. Backboard/PineBoard HID routing and the foreground scene receiving the event.+2. `EventDroppingWindow` debug message, plus the actual press type and phase.+3. If delivered, Hello's focused view, `_hasDrawingStarted`, and ScenePhase at+ `0x100047600`. Prefer read-only logging of these values to modifying them.+4. The normal `Remote pressed.` then `Hello view remote paired. Going next.`+ messages and the next setup screen.++This separates a transport/device-metadata fix from a scene/focus fix. The+offline evidence supported normal Select and Menu event mappings for the new+remote panel, but did not then establish a fix for Hello. Do not+restore legacy feature overrides, force drawing/paired state, broaden Setup+entitlements, or remove readiness checks to make the test pass.++### Observer-only diagnostic hook design++The first useful hook needs no private Swift ABI or fixed image offset:++1. Restrict injection to `com.apple.Setup`; resolve+ `_TtC5Setup19EventDroppingWindow` by Objective-C runtime name and wrap+ `sendEvent:` using the project's chosen runtime-hook facility. Always call+ the original exactly once with the original event.+2. For the bounded test press, record window class, key-window status,+ `windowScene.activationState`, scene session identifier, and each+ `UIPress`'s type, phase and timestamp before and after the original call.+ Read `dropsEvents` with `class_getInstanceVariable`/`ivar_getOffset` and a+ byte load; do not write it. Query the scene's current focus through an+ public read-only `window.windowScene.focusSystem.focusedItem` accessor.+ Log numbers and runtime class names, not typed text or account content.+3. Wrap `SASBookendCallbackConfiguration`'s verified Objective-C methods+ `initOnAnimationWillBegin:onAnimationDidFinish:` and+ `setOnAnimationUIUpdateSignal:` to add logging while preserving and invoking+ the supplied blocks unchanged. Check method encodings and block ABI before+ implementing wrappers. This distinguishes a drawn background from delivery+ of the Cursive Hello lifecycle callbacks.+4. If the window receives and delivers Select but Hello remains inert, measure+ the two actual gates. `_hasDrawingStarted` is an Objective-C ivar on+ `Setup.TVHelloManager`; resolve its offset dynamically on a captured live+ instance, using a weak reference and main-thread access. Do not heap-scan or+ hardcode `0x28` in shipped compatibility code. The SwiftUI ScenePhase is a+ value-type environment, so `windowScene.activationState` is useful context+ but is not a substitute for reading the callback's installed environment.+ Capturing those Swift values requires a Swift-ABI-aware diagnostic or a+ debugger at the semantically found tap callback; do not cast it to an+ ordinary C function pointer.+ Matching metadata exposes no Objective-C methods on+ `_TtC5Setup14TVHelloManager`, so there is no concrete Objective-C `init`+ hook for capturing this instance. Do not assume NSObject initialization or+ KVC support on its `_SwiftObject` superclass. A debugger can inspect focus+ without changing it through `[UIFocusDebugger status]`,+ `preferredFocusEnvironmentsForEnvironment:`, and+ `checkFocusabilityForItem:` on the main thread; these declarations are in+ the selected tvOS SDK's public UIKit headers.+5. In PineBoard, observer wrappers on+ `PBSceneManager._eventsCanBeDeferredToSceneHandle:` and+ `_updateFocusDeferralsIfNeeded` should log the original result, scene PID,+ readiness/foreground/deactivation values and selected target. Preserve the+ original result and all original routing calls.++Enable debug for only `CompanionSetup` / `EventDroppingWindow` and+`CompanionSetup` / `TVHelloView` during the bounded capture. Producer+preferences and live-reader flags are separate controls; both must be checked.++### Scoped logging validation, 2026-10-24++The guest has no `/usr/bin/log`. Matching tvOS 27.2 `LoggingSupport` exposes+`OSLogPreferencesSubsystem.initWithName:` and+`OSLogPreferencesCategory.initWithName:subsystem:`. Retain the subsystem while+using categories: the latter store it weakly. Category `enabledLevel`,+`persistedLevel`, `effectiveEnabledLevel`, and `effectivePersistedLevel` use+signed 64-bit values (`Tq`); `isLocked` is `BOOL`. `setEnabledLevel:4` selects+the preferences enum's `debug` value, rather than `os_log_type_t`. The setter+sends a synchronous preferences-type-3 install to `com.apple.logd.admin` but+discards installation errors. Verify persistence with a newly initialized+subsystem and its on-disk category dictionary, not only the mutated instance.++A temporary native helper initially failed readback without logging-admin+authorization. Signing that diagnostic helper with `platform-application` and+`com.apple.private.logging.admin` allowed the two category entries to persist+as `Level.Enable = debug`; a fresh helper also reported+`os_log_type_enabled(..., OS_LOG_TYPE_DEBUG) == true`. These are temporary+diagnostic privileges, not additions to the product. Before mutation, both+category entries were absent. The helper saves rollback state, refuses+preexisting target entries, and restores absent entries through category+`reset`; `_resetCategory:` removes the subsystem preferences file when its last+entry is removed. It reloads between mutations to preserve unrelated entries+and refuses a changed target entry during rollback. Restore after capture.++The existing icli live reader creates `OSLogEventLiveStream`, installs its+event handler, and activates it without setting flags. Matching framework+analysis shows the default flags are zero. The host `/usr/bin/log` live path+proves bit 0 includes Info and bit 1 includes Debug: its `_log_flags_s` metadata+orders `show_backtrace`, `show_info`, `show_debug`, and its live path reads+offsets `+4` / `+8` before OR-ing stream flags `1` / `2`. Matching tvOS+`_activateLiveStream` maps those bits to diagnosticd request flags `0x100` /+`0x20`. Set `flags = flags | 3` **before** `activate` to include both. These+reader flags do not alter producer preferences.++A separate temporary native capture, bounded to 30 seconds / 5,000 entries and+filtered to Setup and PineBoard, then received real Info and Debug events+(one capture: 4,579 entries, including 1,497 Debug). This proves the previous+notice-only captures did not cover all severities. No `CompanionSetup` events+appeared in that capture, so absence alone still does not establish which+Setup gate failed. Event proxy properties must be sent directly through+Objective-C dispatch, as icli does: a forwarding proxy may return false from+`respondsToSelector:` for getters it nevertheless implements through+forwarding.++The subsystem spelling was independently rechecked in matching+`CompanionSetupKit`: `CSKConstants.logSubsystem` at `0x1d2c7b13c` returns Swift+small-string words `0x6f696e61706d6f43` and `0xee0070757465536e`. Their+little-endian payload is exactly `CompanionSetup` (14 bytes), without a+`com.apple.` prefix. LoggingSupport's setter has no explicit app-relaunch or+notification call beyond its logd request; propagation to existing producer+handles belongs to logd/libsystem_trace and was not established by this static+analysis. A cold boot of the disposable setup-test clone with the scoped+preferences installed disambiguates producer initialization.++Temporary evidence artifacts: `/private/tmp/tvremote-logging-cache-objc.txt`,+`/private/tmp/tvremote-logging-analysis.json`,+`/private/tmp/tvremote-logging-stream-analysis.json`, and+`/private/tmp/tvremote-host-log-ipswdisasm.txt`. Host CLI evidence used native+ipsw disassembly because the separate host REA provider startup timed out.++| Scoped logging observation | REA evidence ID |+| --- | --- |+| `debug` maps to preferences level 4 | `ev_e1398c4765ff2551f63f1c839ed84477a300026e7f30852da869a5ff28eb5198` |+| Category weak subsystem reference | `ev_1cece862c7cae3586c1289ae621e336e05cdbebc059d55b9cc7cd479fe9f4c64` |+| Per-category enabled setter/install | `ev_807b6898c67b7fa596836c62e8100457b944fff83199dd6422da2fd43545e7af` |+| Category reset removes entry / last file | `ev_540c83a12ace2814151c9af46986f04858750948ec64f630399e7a9821c4387a` |+| Synchronous logd admin transport | `ev_d5b61b5cd11b0339a98c3a1bac761bfb7f1ff4815904371ea5a58876986f2c8c` |+| Stream base init leaves zero flags | `ev_2be86dcf343a27119ddeed73d15519bfac0813017d1ce63ab73f353f48c038e3` |+| Matching tvOS stream flag remapping | `ev_7b92ad0bc997c0ce5252e2c0c2a5e8c858a417f90fd087e988fc93fe8033934d` |+| Complete window flow / clean-delivery log bypass | `ev_df2b9ea001b7353bf0e2822377cdf45c0d41ca3b3da61f7568526cd6bc2d5637` |+| Exact window logger constructor/category | `ev_42a1cb84ae3001d4b3061d238107ef62eeeaa9bf9be86085daebb113962f9012` |+| Exact Hello logger constructor/category | `ev_895590a11e2c40c9575904eb7acf345a8214491ec42eac832556e56520ae1b43` |+| Hello guards followed by Default-level remote log | `ev_8154a42aa29e8fd2f77d0e3f97a3f517eccc474ba272f98eca725f1552b03f15` |++## Evidence ledger++REA/Hopper decompilation is recovered pseudocode, not original source. Addresses+are analysis anchors for this build, not offsets to hardcode in a patch.++| Observation | REA evidence ID |+| --- | --- |+| Hello focusable + single tap body | `ev_a9ece8c1ed9df8b26c04a621f8451e76e44aef08c853899eaf3475501bfb7b09` |+| Tap callback drawing + active gates | `ev_a4b76a7a8aab038818e1cc5e14ff40bc473d1aa01b1654115a73e0ee62812830` |+| Exact byte load in callback assembly | `ev_2be14fc1b527e3c79040a4a437af3a70eeac4f5a359c2312043c4bbe22dbc353` |+| Parent normal hello command | `ev_4fe49dbb67bd216fdf32bda6a79a09d2d6fd330a5a9a799c0eedfb1301256a90` |+| Cursive callback registration | `ev_1088553f6e867e4df03f84d43d5a4cf4c9ac98e0c91048210bf054876a36de99` |+| Drawing started producer | `ev_89e78278c021bd0e37af362b92a73adc79c32dfb8b89f41db1920d118186bad9` |+| Drawing flag mutation consumer | `ev_b6303d4b283779ea431c6dca7564798d7c4e910ded02feff94c1caca9111e683` |+| Drawing-state view callback | `ev_5fc359a948d6c02bdffc2b7f0c7a4bd4c885458870e6bbb37bf9104697e83a5a` |+| ScenePhase environment read | `ev_efe7ddbbff8d970a0446d5729d725e9d8fd77397491a2eb3698040d40049e17f` |+| EventDroppingWindow delivery | `ev_f10ddc6196da767beae2ff919d918bf48760bd4b26ae2b90e469983e39479ab5` |+| Event logger category | `ev_358aed1a3dec665597b2e84848e7da548fbcbf5eaa36ae4b55479c07ef3d6706` |+| Main view gate conditions and default focus | `ev_24b2a147e021a95956e0ea6acf639b3d3533da77396043183889560fd442b643` |+| Restart/screensaver suppression | `ev_527f04a8b4dfb104d9a52eed3c4e8f1e493f31d8560c2749fe0ee3c3ab4ca3d5` |+| Pairing transition suppression | `ev_257280584ea93df966f312c9af31b27d8d41980ef6d439b77666c536c7f113ac` |+| Normal BKS dispatch rules | `ev_5ae109cec8fadd72f4ff461375fc61e378aa365f3d9bcf4627605787a6ebb488` |+| Keyboard-focus predicate without sender restriction | `ev_20db42f4d5b9602d1c76c36f6444d9dfd65af194ebdfa7dd4b12d85a1552242c` |+| Actual keyboard-focus press set | `ev_b91122666e8b5f9b93823757535f1bf6cdeb9c3ef010085d0f7cdee5eb103384` |+| Scene deferral readiness/activation gate | `ev_7acdd185b56827c2a53626aa0075b56d26e1f54e31fa7259def0e4ffb63da588` |+| Scene focus target and deferral update | `ev_a88ddfab6667d556462d7a885f0db790507a3090780a8b030657229b810ebc61` |+| Scene view focus eligibility | `ev_6550afe210ea5b9c1f624dac068095f89b0807eac41c40890e32e8f7fe1f039d` |+| Layout accepts event focus when ready | `ev_745c06e3e8e8d89e6bf5344f5a2175955abf0b03874552bc38c42cddfc680fa0` |++Local matching-cache disassemblies (ipsw, explicit unslid addresses, no guest+execution): `/private/tmp/tv4k4-tvos27-hidpress-disassembly.txt`,+`/private/tmp/tv4k4-tvos27-tap-press-disassembly.txt`, and+`/private/tmp/tv4k4-tvos27-tap-shouldreceive-disassembly.txt`.++## Native focus-deferral implementation evidence++Matching-cache UIKitCore was extracted with ipsw to+`/private/tmp/tvremote-uikit/UIKitCore`, SHA-256+`5ebe74b705bcb0260446ee45a58c94c82dace11d1ad7d488b20aca04b28d45dc`.+The following findings come from native ipsw symbol, Objective-C metadata,+disassembly, and cross-reference inspection. A separate REA/Hopper startup+timed out for this large image; these findings do not have REA evidence IDs.+All addresses below are unslid reveal anchors, not product offsets.++`-[UIFocusSystem _performDeferredFocusUpdateIfAvailable]` (`0x193b136a0`)+returns false if the focus system is disabled, its weak deferred target is+nil, or its effective deferral behavior equals 2. Otherwise it:++1. Preserves the existing deferred item locally and clears the stored target+ through `_setDeferredFocusUpdateTarget:nil`.+2. Builds a context with+ `_simulatedNonDeferredProgrammaticFocusUpdateToEnvironment:` using that+ preserved item; it does not select a replacement target.+3. Marks the context with `_setDeferredUpdate:YES`.+4. Returns `_updateFocusImmediatelyWithContext:`'s Boolean result.++The matching live runtime separately reported Objective-C return encoding `B`.+The method does not create, forward, consume, or replay a `UIPress`. Its true+return describes a successful focus update, not consumption of the caller's+Select event. Eligibility and focus-update handling remain in UIKit's native+context path.++The optimized Objective-C dispatch stub for this selector is `0x198065f10`.+An ipsw xref search across matching UIKitCore finds exactly two call sites:++| Caller | Call site | Native use |+| --- | --- | --- |+| `_UIFocusMovementPerformer.performFocusMovement:` | `0x193b1bd40` | Before ordinary movement, perform an available deferred update unless the request suppresses this path; a true return takes the successful-movement path at `0x193b1be1c`. This accounts for a directional press activating the already chosen item. |+| `UIFocusSystem._setOverrideFocusDeferralBehavior:` | `0x193b13e80` | When the new effective behavior becomes zero, try the deferred update before requesting an ordinary fallback focus update. |++The same dispatch-stub xref search in matching SwiftUI found no call sites.+This is a bounded direct-call result; it does not rule out dynamic dispatch+through another route or other framework images.++`_effectiveFocusDeferralBehavior` (`0x193b13db8`) returns the numeric override+when `_overrideFocusDeferralBehavior` is nonnil, otherwise+`behavior.focusDeferral`. `_UIFocusBehavior_TV.focusDeferral`+(`0x1945b21ac`) returns zero. Do not assign an invented enum name to the live+value 3, infer its source without inspecting the actual override/behavior, or+change that policy to repair input. In the value-3 branch of+`_prefersDeferralForFocusUpdateInContext:` (`0x193b1325c`), UIKit consults the+request's `allowsDeferral`, the next item's deferral mode, and the system's+`hasSeenFocusedItem` state.++The independent `waitingForFocusMovementAction` property is a Boolean. Its+getter (`0x193b190b0`) reads the byte at `0x3c` and its setter+(`0x193b190b8`) writes it. Runtime inspection should use the selector or+resolved ivar `_waitingForFocusMovementAction`, never that offset. A false+value does not imply the separate deferred target is empty.++Matching SwiftUI Objective-C metadata declares+`_TtC7SwiftUI28UIKitSelectGestureRecognizer` as a subclass of+`_TtC7SwiftUI22UIKitGestureRecognizer`, with its own+`pressesBegan:withEvent:`, `pressesChanged:withEvent:`,+`pressesEnded:withEvent:`, and `pressesCancelled:withEvent:` methods. Its+`pressesBegan:` Objective-C thunk (`0x1c1e086b4`, shared bridge+`0x1c1e086e4`) accepts `self`, `_cmd`, `NSSet<UIPress *> *`, and+`UIEvent *`, and returns void. The Swift body (`0x1c1e08e18`) converts real+presses to select-listener events, sends them through the event bridge, and+sets the recognizer's state. A compatibility wrapper should retain that+original call exactly once, including when the deferred-focus attempt returns+false, and leave change/end/cancel delivery unchanged.++Bounded UIKit focus logging is also source-backed. The `UIFocus` category's+override table includes key `UIFocusLoggingEnabled` from both UIKit's+`NSUserDefaults` suite `com.apple.UIKit` and the process's standard defaults.+Using the latter can scope a temporary diagnostic to Setup, with its prior+value restored afterward. Category refresh is registered under Darwin+notification `com.apple.UIKit.LoggingPreferences`; the exported+`__UILogSyncCategories()` function (`0x194542a68`, Mach-O symbol+`___UILogSyncCategories`) synchronizes associated category flags directly.+These logging controls are diagnostic only and are not part of the input fix.++Reproducible local evidence files:+`/private/tmp/tvremote-focus-system-disasm.txt`,+`/private/tmp/tvremote-focus-deferred-callers.txt`,+`/private/tmp/tvremote-focus-movement-deferred.txt`,+`/private/tmp/tvremote-uikit-objc.txt`,+`/private/tmp/tvremote-swiftui-objc.txt`,+`/private/tmp/tvremote-swiftui-select-thunk.txt`, and+`/private/tmp/tvremote-swiftui-select-began.txt`.++### Native focus-policy and idle-expiry evidence++Runtime inspection on the setup-test clone identified the actual behavior as+`_UIFocusBehavior_WaffleIron`, with effective deferral value 3 and a nil+override. The scene's public `focusSystem`, `window._focusSystem`, and+`window._focusSystem._preferredFirstResponderFocusSystem` were the same+instance. WaffleIron's `focusDeferral` getter (`0x194546db0`) reads its+configured `_focusDeferral` field; the ordinary `_UIFocusBehavior_TV` getter+(`0x1945b21ac`) returns zero. The earlier possibility of an explicit scene+override producing the observed 3 was therefore ruled out for this live+instance.++`_setOverrideFocusDeferralBehavior:` (`0x193b13e24`) is a void method with one+`NSNumber *` argument. It stores the override and then evaluates the native+effective policy. A nonzero effective policy invokes+`_startDeferringFocusIfSupported`. Zero first attempts+`_performDeferredFocusUpdateIfAvailable`; if that does not succeed, it calls+`requestFocusUpdateToEnvironment:self` and `updateFocusIfNeeded`. It does not+write Setup state, select a hardcoded leaf, synthesize input, or bypass the+ordinary focus eligibility path. Existing nonnil overrides must be preserved+by a compatibility adapter rather than overwritten indiscriminately.++The timer is material to testing this policy. `_tickHasSeenFocusedItemTimer:`+(`0x193b13818`) invalidates its previous timer and, for effective policy 3+with a focused item, schedules a one-shot timer for **60 seconds**. Its Boolean+argument controls whether to mark `hasSeenFocusedItem` first. A successful+focus update derives that argument from the context's `_isDeferredUpdate`+(`0x193b16e50`–`0x193b16e60`, or a direct true branch when appropriate).+The native deferred-update method marks its context as deferred, so both a+lifecycle activation and the corresponding first-directional-input activation+can start this timer naturally.++When the timer fires, `_hasSeenFocusedItemDidExpire` (`0x193b13d20`) invokes+`_startDeferringFocusIfSupported`. That method resets the seen-item bookkeeping+and, when the effective policy and item mode permit, drops the current focus+and stores the old item as the deferred target. Thus a lifecycle-only focus+activation can appear successful and still leave the first later Select+without a focused item after the idle interval. One prototype's initialization+log preceded the user-interface capture by more than 60 seconds; an immediate+native activation followed by a real Select reached the unmodified Hello+callback. Neither observation proves that a lifecycle-only adapter remains+effective after idle.++`_startDeferringFocusIfSupported` performs the drop using+`_dropFocusAndStartDeferring:NO suppressUpdate:YES`. The suppression does+**not** suppress `UIFocusDidUpdateNotification`: normal focus-update callbacks+still reach `_UIFocusSystemSceneComponent._focusSystem:didUpdateFocusInContext:`+(`0x193bbdfc0`), which posts the public notification with the focus system as+its object at `0x193bbe080`–`0x193bbe090`. Suppression skips only the fallback+focus request in the completion block at `0x193b17a68`–`0x193b17a9c`.+The old focus item is stored as the deferred target only after this drop and+synchronous notification return (`0x193b13ccc`). An observer that needs that+target must therefore defer its work to the main queue and recheck the current+window, scene, focus-system identity, and policy there.++The scene component can replace an explicit override during+`_updateFocusSystemState` (`0x193bbb2ec`). If replacing zero with nil changes+the effective policy back to 3 while an item is focused, the native drop posts+the notification above. If focus was already nil, no new focus notification is+guaranteed; scene-activation and key-window notifications provide separate+lifecycle opportunities. Under effective policy zero, expiry of an existing+timer may reset bookkeeping, but `_startDeferringFocusIfSupported` does not+drop focus.++A manual diagnostic call setting the native override to zero kept the normal+Language focus through more than 80 seconds of idle, after which a real Select+RPC advanced to Region. This validates the native setter's policy behavior in+that test; validation of the final installed product bundle is a separate+step. The source adapter is intended to apply the same native button-focus+policy only to an active, visible, key `Setup.EventDroppingWindow` with+WaffleIron behavior, effective value 3, and no existing override. It leaves+Setup's drawing, scene, press-suppression, pairing, and completion gates intact.++Additional native evidence files:+`/private/tmp/tvremote-focus-immediate-env.txt`,+`/private/tmp/tvremote-focus-send-notifications.txt`,+`/private/tmp/tvremote-focus-scene-notification.txt`,+`/private/tmp/tvremote-focus-startdefer-callers.txt`,+`/private/tmp/tvremote-focus-override-callers.txt`,+`/private/tmp/tvremote-focus-scene-state.txt`, and+`/private/tmp/tvremote-focus-preferred-system.txt`.++## Final policy component trial and native activation boundary++At 20:50:58 UTC on 2026-10-24, the exact final built+`libvphonetvsetupfocus.dylib` was loaded into the newly relaunched Setup+process 342 on the diagnostic clone. No manual policy setter was called in+that process. Its initialization log reported the native TV button-focus+policy, and read-only inspection confirmed effective policy 0, override 0,+and a native focused item. Ordinary remote input selected Set Up Manually+from Quick Start and entered Activating Apple TV. English and United States+were preserved. This is an in-memory payload trial, not an installed+load-command/cold-boot validation.++Activation then displayed Activation Error. Dismissing OK returned to Quick+Start. One normal retry, captured in+`/private/tmp/tvremote-activation-retry-setup.json` and+`/private/tmp/tvremote-activation-retry-daemon.json`, logged five native+activation attempts failing with `NSOSStatusErrorDomain` code -71136, while+mobileactivationd received `createTunnel1SessionInfoWithCompletionBlock:`+requests from Setup. No agreements, accounts, or privacy permissions were+accepted; setup completion remains false.++The live mobileactivationd was pulled to+`/private/tmp/tvremote-live-mobileactivationd`. The existing activation patch+resolves its getter through agreeing symbol-table and Objective-C metadata+anchors, and its scratch-copy trial finds the original Boolean-field getter,+not an already patched getter. Both the TV preset and TV guest admission+currently exclude this patch. Whether enabling it covers the new assistant's+activation path requires matching binary inspection and live validation.+The debugger was detached, its temporary launch job unloaded, and the clone+stopped before further environment changes. The original VM was not reset.++## Native activation-state path and bounded TV admission++Offline inspection of that pulled tvOS 27.2 mobileactivationd establishes+that the existing patch targets a real native local-activation path in this+daemon. Its SHA-256 is+`4393ac6c559340933ab28b627c0cb96af4ce8b8f7b4c30d2f1884252a9e9b367`.+`-[DeviceType should_hactivate]` (`0x100017a14`) reads its original Boolean+field. `_use_hactivation` (`0x10001800c`) calls that getter on the shared+DeviceType. In `_dealwith_activation` (`0x10001ed48`), a true result logs+`Hactivation is enabled, short circuiting activation state to Activated.`,+writes DataArk `ActivationState = Activated`, `BrickState = false`, and+`ActivationExpired = false`, and returns successfully before activation-record+validation. The normal migration block (`0x10001cf00`, call site+`0x10001da70`) invokes this operation after its migration/registration work;+`_handle_unbrick` is another caller. The XPC method+`getActivationStateWithCompletionBlock:` (`0x100053ebc`) reads that same+DataArk ActivationState after migration and returns it in its result+dictionary. Missing state defaults to Unactivated; incomplete migration returns+Unavailable. This is native daemon state handling, not a Setup completion+override.++REA evidence: getter+`ev_114d4b4b985de1005eef1553e1244cd7e6b136971431d8c514a35a050a1fb3ee`,+use-hactivation wrapper+`ev_96a884a1e699df95851e7c5d108aa6fa9e44a84fbf8c89a1d59fed4cf7f62885`,+activation operation+`ev_b26592343ade26d74c66270bcf0a797e16bbc1f2f4613b0ee2043acb028d5ad8`,+XPC state result+`ev_4651dc76599f0a106990a77cf003629b10c2fbb39fba433196dfe84b418cce5b`,+and migration block+`ev_b5465951756c117b161ea10e77b13b68ca2f6e631eb310461e0c76c1feac8b9d`.+The provider-neutral snapshot is+`/private/tmp/tvremote-mobileactivationd-rea.json`.++The new assistant's matching CompanionSetupKit client also checks this native+activation state before creating a session. The extracted framework SHA-256 is+`a74b8220cc6419bcc66a4d2e8f9c42d2f97a951591dd51c6e763a807e2cca81e`.+Its checking phase logs `activation state checking` at `0x1d27f4460`, calls+the CSKMAEGetActivationState wrapper (`0x1d27fe4c4`) at `0x1d27f4638`, and+awaits its result. The wrapper's callback calls+`MAEGetActivationStateWithError` at `0x1d27fea5c`. The continuation logs the+result at `0x1d27f4978`, then compares it to+`kMAActivationStateActivated` and `kMAActivationStateFactoryActivated`.+The matching cache identifies the imported constant pointers at+`0x1e0141d58` and `0x1e0141d68`, respectively (`ipsw dyld a2s`). Either+equality reaches the normal nil-error async return at `0x1d27f4aa4` through+`0x1d27f4c60`. Only nonmatching states reach the later+`session request create` log at `0x1d27f4e98` and session-request wrapper.+Therefore the daemon's existing Activated state is accepted by the new native+client without editing that client's activation or completion decisions.++REA string/xref evidence:+`ev_0a9860e7983b0c477aa9f4734ebf27091cfb9466c338ebdc3ffcd16000ae5360`,+`ev_158fb534529ab7e451e6344f031905304716ad0dc1490f4f26f676cba4cd5ad2`,+and `ev_b36b585cfcfe82afff402182e9a1019e7e70d64b705b814bcc96b50d3aade663`.+Function dossier+`ev_2a41bd6918d78f3eaa09a2dbf8b830598d16c42a10b95afc7ecea81c302a16f8`+corroborates the state-comparison path. Hopper merged multiple Swift async+continuations into an oversized function; the bounded branch conclusion was+checked against native instruction disassembly, saved in+`/private/tmp/tvremote-csk-activation-state.asm` and+`/private/tmp/tvremote-csk-activation-wrapper.asm`. The REA snapshot is+`/private/tmp/tvremote-csk-rea.json`; the native provider was closed after this+inspection. These addresses are research evidence, not patch offsets.++The TV admission uses a separate declaration,+`system-mobileactivationd-exp-tv_activation`, gated to tvOS 27.2 and admitted+only for arm64e Apple TV. It reuses the unchanged `patch-mobileactivationd`+implementation. The installer selects one activation declaration per device+family for the shared file and reversible backup. The old global activation+declaration remains excluded from TV, preserving older TV preset behavior.+Static review found no routing blocker. A scratch trial using the pulled+binary successfully patched and re-signed it with its original entitlements+preserved; code-signature verification passed and a second patch was a no-op.+The re-signed scratch SHA-256 is+`999d10f1cd33e06a3ebd5000127022453b91c45ede55708d7d17a0bbf930c73b`.++This establishes the proposed fix's native state path and offline patch+compatibility. It does not prove that the final installed daemon boots,+reports Activated to Setup, or completes the assistant. Those remain live+cold-boot validation steps after bundle installation and environment update.+The observed -71136 failures alone do not establish the numerical error's+underlying meaning or prove that this omission is the only activation issue.++## Read-only TV completion reporting++A completed TV guest can have `SetupDone = true` while the iPhone+`SetupVersion` key is absent. The daemon previously interpreted that absence+as version zero and compared it with `BYBuddyIOSCurrentVersion` (11), falsely+reporting setup pending. The matching tvOS SetupAssistant framework uses a+different version key and an additional completion condition.++Inspection of the matching extracted SetupAssistant (SHA-256+`51aa489f9d09ce8a78b267394276356df101a7db64d2fcf83c66c27994d636f6`)+finds the TV path in `_Internal_BYSetupAssistantNeedsToRun`+(`0x1a7033aa8`). After its general supported-device and audio-accessory gates,+the TV rule reports pending when any of these is true: `SetupDone` is false,+`TVSetupVersion` is below the native TV version, or+`TVBuddyCompletedSuccessfully` is false. At `0x1a7033c40` it reads+`TVSetupVersion`, accepts values above 14, and at `0x1a7033d30` checks the TV+completion Boolean. The exported Int32 `BYBuddyTVOSCurrentVersion` at+`0x1a705a7c4` contains 15 in this build; the adjacent iOS constant contains+11. Its exported `BYBuddyTVOSVersionKey` is `TVSetupVersion`.+The native integer preference reader uses `com.apple.purplebuddy`, user+`mobile`, and any host. Its Apple TV discriminator compares MobileGestalt+`DeviceClassNumber` with 4 (`0x1a7035150`).++REA evidence:+`ev_89652f73c821f5e89e1a7e48711fc5958d466174b7df65871be6a56b81fc8587`+and integer reader+`ev_35d80a3e106c7f22bd95d6256a017818b9f251576de010066175d2a865f43997`.+Bounded native disassembly is+`/private/tmp/tvremote-native-tv-status.asm`; the snapshot is+`/private/tmp/tvremote-setupassistant-status-rea.json`. The provider is closed.++The minimal status correction is a runtime TV-specific preference policy:+read the TV version key, load the TV current-version constant, and retain both+native completion conditions. iPhone and HomePod should keep their existing+status path. The exported `BYSetupAssistantNeedsToRun` wrapper additionally+consults its launch sentinel/cache; duplicating the verified preference rule+keeps the daemon health check cheap and avoids importing that process-dependent+cache behavior. This reporting correction must not write completion keys or+silently extend the existing iPhone setup-skip operation to TV. Native Setup+completion and observed post-completion preferences remain live evidence to+record separately.++## Installed cold-boot validation, 2026-10-24++Administrator authorization installed `8e456731`, followed by activation build+`a4b9ffc4`. Both patches were recorded applied with zero pending patches and+legacy TVSetup disabled. The first cold boot exposed a packaging defect:+`patchMachO` preserved the original Setup entitlements, but the later outer+bundle seal used the default `preserveEntitlements: false` and removed them.+Setup repeatedly terminated with TCC's missing+`NSBluetoothAlwaysUsageDescription` diagnosis. The pulled installed executable+had no entitlements, compared with the pristine executable's complete set.+This was an installation defect, not evidence that Setup needs a new Bluetooth+permission, a usage-description edit, or a TCC bypass.++Corrected build `2.13.0-local.da14d7a4` preserves entitlements at both the final+apply seal and the backup-restoration seal. Its full bundle build and admission+passed. After redeploying from the pristine backup and cold booting, the actual+installed Setup's entitlements compare byte-identically with pristine Setup.+The pulled executable verifies with the actual Info.plist and CodeResources+using host resource-content verification disabled; the focus payload and+activation daemon signatures also verify. A separate scratch restoration seal+of the pristine executable preserves its exact entitlement XML and passes full+signature verification for that scratch bundle.++Hello was visible at 21:23:00 UTC. The first guest input was one actual remote+panel AX Select at approximately 21:24:16, after more than 65 seconds idle.+It advanced to native Quick Start by 21:24:19 without directional input, direct+RPC priming, a debugger, or manual policy calls. This validates persistent+focus initialization, idle behavior, and the installed completed-tap queue fix.+The previous English and United States choices persisted, so their pickers did+not reappear on that boot.++Using only the installed remote, Down focused Set Up Manually and Select+advanced through activation to native room choice, then Office, Data & Privacy,+and Terms & Conditions. No activation error appeared. Terms initially remained unaccepted:+the computer-use tool's runtime confirmation policy requires action-time user+confirmation to accept Terms of Service or an EULA, even with prior approval.+The user was asked at the displayed screen; no completion preferences or native+step callbacks were changed while awaiting that confirmation.++The original configured VM was never reset. Its update to the corrected bundle+was started independently while the clone remained at Terms. Launchpad's+administrator authorization expires after 300 seconds; any new credential+prompt must be completed by the user before that environment update can run.++At 00:25 UTC on 2026-10-25 the user explicitly authorized the displayed Agree+action and completed the new administrator prompt. Native Setup then skipped+account sign-in through its offered route, declined optional Siri/location and+both analytics choices, preserved America/Sao_Paulo through native city search,+and advanced Welcome to Home. English/US remained unchanged; Office is only+the clone's room. Read-only checks find SetupDone=true,+TVBuddyCompletedSuccessfully=true, TVSetupVersion=15, and no running Setup.+The clone was stopped after this capture. The original VM was updated to+`da14d7a4`, booted to Home/screensaver with its prior completed state intact,+and passed actual remote navigation/Settings/Back, held TV Control Center,+Siri search/dictation UI, held Power sleep, and TV wake. Volume and mute events+were balanced, but audible volume/mute/playback effects are not claimed with+no active media. Home was restored and all inputs released.++The completed TV still made the old status API report pending, because it used+the iOS version namespace. The final read-only reporting correction separates+TVSetupVersion/BYBuddyTVOSCurrentVersion/TVBuddyCompletedSuccessfully from the+unchanged iOS/HomePod policy and existing skip operation. Its logic harness+passes 376 checks, including missing/stale/current TV state and non-TV model+boundaries; the complete bundle builds and passes admission. Candidate+`9ffd2d6e` was prepared in Launchpad, awaiting macOS administrator authentication+before live status verification. At that point both VMs remained bound to+working `da14d7a4`; the original was running and the completed clone stopped. Unused defective+intermediate bundles `8e456731` and `a4b9ffc4` were removed from the store.++At 02:08:25 UTC on 2026-10-25 the final status bundle installed successfully,+including policy and host preflight. Both VM environments were updated before+the authorization timeout. Cold boot of the completed native-Setup clone+answered vphoned in five seconds and returned this actual status:++```json+{"current_version":15,"setup_version":15,"setup_done":true,"pending":false,"running":false,"pid":0}+```++The actual UI capture `/private/tmp/tv-remote-live-9ffd-clone-reboot-home.jpg`+shows Home without Setup returning; no input was needed. The clone was then+stopped. Cold boot of the original VM also answered in five seconds and+returned the same completed TV status. Both are bound to and report the guest+environment `2.13.0-local.9ffd2d6e`; their receipts have zero pending patches,+the native focus and local-activation patches applied, and legacy setup off.+No preference resets, setup completion writes, or debugger intervention were+used for these final boots. The original VM remains running.+Its final UI capture `/private/tmp/tv-remote-live-9ffd-source-home-after.jpg`+shows Home without Setup. The actual final remote exposes all 13 enabled+controls, and Back followed by Right moves native Home focus successfully.+The original VM was left at Home with every input released.diff --git a/Research/Firmware/tvos_support.md b/Research/Firmware/tvos_support.mdindex 733e67ba..9489b421 100644--- a/Research/Firmware/tvos_support.md+++ b/Research/Firmware/tvos_support.md@@ -30,8 +30,11 @@ would choose the HD preset for this new product type. The CLI/catalog schemais unchanged; the new series keeps that preset decision paired with the newdevice catalog. Firmware patch discovery now preserves any recorded OTA boardwith a restore base, so the HD manifest cannot replace J265's guest identity.-The 27.2 setup compatibility patch described below is selected by `tvos-4k`;-there is no new instruction patch or preset.+The current `tvos-4k` preset retains the new 27.2 Setup app and selects its+SetupBackground display lookup repair. The legacy TVSetup fallback used in+the earlier validation below is now off in every preset. The new setup's+input issue remains under investigation; see [native Setup and remote+panel](#native-setup-and-remote-panel). There is no new instruction patch or preset.Validation completed without admin privileges:@@ -160,6 +163,123 @@ verification uses direct screenshots and the native VM window.Logs, the watchdog report, a guest spindump and screenshots are retained under`/private/tmp/vphone-appletv18-*` and `.build/appletv18-validation/`.+## Native Setup and remote panel++Current source, 2026-10-24: `tvos-4k` blocks+`system-tv-exp-legacy_setup` and enables the existing 27.2+`system-setupbackground-exp-pineboard_lookup` and+`system-setup-exp-deferred_focus`. An environment update restores+the original CompanionServices feature flags from their `.bak`, then applies+the single display-service lookup entitlement repair and the native button-+focus policy adapter in Setup. This returns an earlier+test VM to `com.apple.Setup`, without changing setup completion or choices.+The current bundle is `2.13.0-local.9ffd2d6e`. Its installed focus adapter+passes cold-boot input testing, and native manual setup advances past activation.++The new panel is available only for Apple TV guests under **Device > Apple TV+Remote** (Option-Command-R). Its silver remote face has a directional clickpad+and Select, Back, TV/Control Center, Play/Pause, Mute, volume rocker, side Siri+and Power buttons. Native buttons expose accessibility labels and keyboard+focus. Click/hold sends distinct consumer HID down/up events, so the guest can+interpret taps, multiple clicks and holds. Closing, minimizing, losing focus+or disconnecting releases held controls; a failed release is retried before+new input on reconnection. A cancelled queued press cannot reach a later+connection. Remote controls are disabled while the agent is unavailable.++Arrow keys, Return and Escape in the panel send the remote's directional,+Select and Menu events. Space activates a focused button, or Play/Pause when+the remote face has focus. H, M, +/-, S and P map to TV, Mute, Volume, Siri and+Power. The HID consumer MenuEscape usage (`0x46`) is Back; ACBack (`0x224`)+is a different UIKit press type. These mappings are verified against the+matching tvOS 27.2 UIKitCore, rather than inferred from keyboard behavior.+The control layout and hold semantics follow Apple's+[Siri Remote guide](https://support.apple.com/en-us/102337).++Offline validation uses `Tests/run-tv-remote-tests.sh`, a host-only AppKit+harness with no guest connection. It exercises all 13 accessible buttons,+directional hit areas, pointer holds, overlapping keyboard/pointer sources,+modifier-safe releases, cancellation while the shared queue is suspended,+and release recovery after disconnection. Completed AX/button taps survive+panel key loss, unfinished holds are cancelled before releasing the view, and+a connection epoch keeps old taps out of a later guest. The harness exercises+the actual AX button through that cancellation sequence. It renders the native+view to a PNG for visual review. The focused patch suites pass 63 tests and+the patch model suites pass 32. The finished bundle builds and passes bundle+admission. Live remote tests passed Home/Settings navigation, Select, Back and+a held TV button opening Control Center. The new focus/preset checks passed+54 focused tests; the activation declaration's version/preset matrix then passed+49 selected tests. Installed cold-boot focus and completed-tap delivery pass:+Hello appeared at 21:23:00 UTC, and the first actual remote AX Select after+more than 65 seconds idle advanced to Quick Start at 21:24:19. No directional+input, RPC priming, or debugger was used. Siri/audio integration remains outside+that validation.++Live inspection localized Hello's failure to native deferred focus. Select+reaches the active key window as UIPress type 4 with window suppression off,+but no item is focused. UIKit already holds Hello's preferred item as a+deferred target. A normal Up commits it and the next Select enters Language;+the native deferred-focus method also commits it without an arrow. Initial+focus-operation prototypes expired after the native 60-second idle timeout.+The final adapter instead uses native TV button-focus policy (`0`) only for+an active key Setup window with WaffleIron/default-3/nil-override state;+explicit unrelated overrides are preserved. Native preferred focus and+eligibility still choose the item. Scene/key/focus notifications recheck+asynchronously, with no swizzles or polling. A manual policy-0 trial retained+focus beyond 80 seconds, and ordinary Select advanced English to the country+picker, then United States to Quick Start. [The investigation](tvos_27_setup_input.md)+records the exact boundaries and installed test. No pairing,+drawing, scene-phase or setup-completion state is fabricated, and no Hello+command or readiness check is bypassed.++The exact built focus adapter was then loaded into a fresh native Setup+process without a manual policy call. It initialized native focus and ordinary+remote input advanced Quick Start to Set Up Manually. Activation failed with+`NSOSStatusErrorDomain` -71136. The matching tvOS mobileactivationd retains+the same local-activation path as the existing iPhone patch; its getter was+unpatched because TV excluded it. `system-mobileactivationd-exp-tv_activation`+now reuses that patch under an exact 27.2 gate, selected only by `tvos-4k` and+admitted only for arm64e Apple TV. Older TV releases and HomePod keep their+existing selection. The complete bundle builds and 49 focused tests pass.+After administrator authorization, cold boot of `a4b9ffc4` exposed a sealing+bug: final bundle signing dropped Setup's original entitlements and caused+TCC Bluetooth usage-description crashes before Hello. `da14d7a4` preserves+those entitlements during both application and reversal of the focus adapter.+The actual installed executable's full entitlements compare byte-identically+to pristine Setup. Its signature verifies with the pulled Info.plist and+CodeResources (resource contents excluded from that host check). Both new+patches are recorded applied, with zero pending patches and legacy setup off.+The corrected cold boot reaches Hello; the actual remote's Manual selection+advances through activation to room choice, Data & Privacy, and Terms &+Conditions. After the user's action-time confirmation, Terms were accepted,+account sign-in was skipped, and optional Siri, location, and analytics were+declined. Native Welcome then advanced to the Home Screen. Native preferences+now contain SetupDone=true, TVBuddyCompletedSuccessfully=true, and+TVSetupVersion=15; Setup itself wrote these completion values and exited.+English/United States and America/Sao_Paulo were preserved; Office was chosen+only on the diagnostic clone. The original VM was also updated to `da14d7a4`,+cold-booted in five seconds, and retained its prior completed setup and data.++Final original-VM remote tests pass navigation, Select/Back, Control Center,+Siri search/dictation UI, Power hold to sleep and TV to wake. Volume Up/Down,+Mute (twice), and Play/Pause were exercised without active media; audible+effects remain unverified. All inputs were released and Home restored. The+two unused builds with the sealing defect (`8e456731`, `a4b9ffc4`) were removed.++Completion exposed an additional read-only reporting bug: vphoned compared the+absent iOS SetupVersion against BYBuddyIOSCurrentVersion even on Apple TV.+`9ffd2d6e` uses TVSetupVersion, dynamic BYBuddyTVOSCurrentVersion, SetupDone,+and TVBuddyCompletedSuccessfully for runtime Apple TV models. iPhone/HomePod+and the existing skip operation retain their previous behavior. No completion+state is written. The full bundle builds and its 376-check logic harness passes.+After administrator installation, both machines' guest environments match+`9ffd2d6e`. Each cold boot answers vphoned in five seconds and reports native+setup/current version 15, SetupDone=true, pending=false, and no Setup process.+The clone returns directly to Home without running Setup again and is then+stopped. The original VM remains running with its data and completed setup+preserved. Both patch receipts have zero pending changes and legacy setup off.+The final original-VM Home capture and actual remote Back/Right test also pass;+all 13 controls are enabled and the VM is left at Home with input released.+## Earlier Apple TV validationValidated on 2026-10-15: AppleTV5,3 tvOS 26.4 beta 1 (23L5208m) on thediff --git a/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swift b/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swiftindex b669edfa..c47f3bef 100644--- a/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+SetupAssistant.swift@@ -34,15 +34,19 @@ extension GuestAPI {private static let buddyDomain = "com.apple.purplebuddy"- /// `BYBuddyIOSCurrentVersion`, a 32-bit integer: 11 on iOS 26.4 and 27.0.- /// Nil when the framework does not export it.- static let setupAssistantCurrentVersion: Int? = {+ /// Keep the iOS constant for the existing skip operation. TV status is+ /// read independently; this correction never writes TV completion state.+ static let setupAssistantCurrentVersion = setupAssistantVersion(symbol: "BYBuddyIOSCurrentVersion")+ private static let tvSetupAssistantCurrentVersion = setupAssistantVersion(symbol: "BYBuddyTVOSCurrentVersion")+ private static let usesTVSetupState = GuestSetupAssistantState.usesTVPolicy(machine: GuestVirtualAudioProduct.machine())++ private static func setupAssistantVersion(symbol name: String) -> Int? {let path = "/System/Library/PrivateFrameworks/SetupAssistant.framework/SetupAssistant"guard let handle = dlopen(path, RTLD_LAZY),- let symbol = dlsym(handle, "BYBuddyIOSCurrentVersion")+ let symbol = dlsym(handle, name)else { return nil }return Int(symbol.assumingMemoryBound(to: Int32.self).pointee)- }()+ }private static func buddyValue(_ key: String) -> Any? {CFPreferencesCopyValue(key as CFString, buddyDomain as CFString, "mobile" as CFString, kCFPreferencesAnyHost)@@ -52,24 +56,31 @@ extension GuestAPI {(buddyValue("SetupVersion") as? NSNumber)?.intValue}- /// True when SpringBoard will run Setup the next time it starts. Two- /// preference reads, cheap enough for `/v1/health`.- static func setupAssistantPending() -> Bool {- guard buddyValue("SetupDone") as? Bool == true else { return true }- guard let current = setupAssistantCurrentVersion else { return false }- return (buddySetupVersion ?? 0) < current+ private static var setupAssistantState: GuestSetupAssistantState {+ GuestSetupAssistantState(+ setupDone: buddyValue("SetupDone") as? Bool ?? false,+ version: usesTVSetupState ? (buddyValue("TVSetupVersion") as? NSNumber)?.intValue : buddySetupVersion,+ currentVersion: usesTVSetupState ? tvSetupAssistantCurrentVersion : setupAssistantCurrentVersion,+ requiresTVCompletion: usesTVSetupState,+ tvCompleted: usesTVSetupState && (buddyValue("TVBuddyCompletedSuccessfully") as? Bool == true),+ )}+ /// Native preference policy, cheap enough for `/v1/health`. PineBoard+ /// requires the TV version and completion flag, not BYBuddyIOSCurrentVersion.+ static func setupAssistantPending() -> Bool { setupAssistantState.pending }+private static func setupAssistantStatus() throws -> [String: Any] {let processes = try listProcesses(filter: "Setup")["processes"] as? [[String: Any]] ?? []let pid = processes.first { $0["executable"] as? String == "/Applications/Setup.app/Setup" }?["pid"]+ let state = setupAssistantStatereturn [- "pending": setupAssistantPending(),+ "pending": state.pending,"running": pid != nil,"pid": pid ?? 0,- "setup_done": buddyValue("SetupDone") as? Bool ?? false,- "setup_version": buddySetupVersion.map { $0 as Any } ?? NSNull(),- "current_version": setupAssistantCurrentVersion.map { $0 as Any } ?? NSNull(),+ "setup_done": state.setupDone,+ "setup_version": state.version.map { $0 as Any } ?? NSNull(),+ "current_version": state.currentVersion.map { $0 as Any } ?? NSNull(),"data_migration_done": dataMigrationDone().map { $0 as Any } ?? NSNull(),]}diff --git a/VPhoneDaemon/Daemon/GuestSetupAssistantState.swift b/VPhoneDaemon/Daemon/GuestSetupAssistantState.swiftnew file mode 100644index 00000000..2736574a--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestSetupAssistantState.swift@@ -0,0 +1,18 @@+/// Read-only completion policy. Apple TV uses its TV setup version and+/// completion flag; iPhone and HomePod retain the existing iOS-version policy.+struct GuestSetupAssistantState {+ static func usesTVPolicy(machine: String) -> Bool { machine.hasPrefix("AppleTV") }++ let setupDone: Bool+ let version: Int?+ let currentVersion: Int?+ let requiresTVCompletion: Bool+ let tvCompleted: Bool++ var pending: Bool {+ guard setupDone else { return true }+ if requiresTVCompletion && (currentVersion == nil || !tvCompleted) { return true }+ if let currentVersion, (version ?? 0) < currentVersion { return true }+ return false+ }+}diff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swiftindex 5877f3cb..522b3ddc 100644--- a/VPhoneDaemon/Tests/LogicTests.swift+++ b/VPhoneDaemon/Tests/LogicTests.swift@@ -36,10 +36,37 @@ enum LogicTests {dataMigrationRecord()deviceNameRule()pointerScroll()+ setupAssistantState()print("\(checks) checks, \(failures) failures")exit(failures == 0 ? 0 : 1)}+ // MARK: - Setup Assistant++ static func setupAssistantState() {+ for machine in ["AppleTV5,3", "AppleTV18,1"] {+ expect(GuestSetupAssistantState.usesTVPolicy(machine: machine), "TV policy for \(machine)")+ }+ for machine in ["iPhone17,3", "iPad16,1", "AudioAccessory5,1", ""] {+ expect(!GuestSetupAssistantState.usesTVPolicy(machine: machine), "existing policy for \(machine)")+ }+ func state(_ done: Bool, _ version: Int?, _ current: Int?, tv: Bool = true, completed: Bool = true) -> GuestSetupAssistantState {+ GuestSetupAssistantState(setupDone: done, version: version, currentVersion: current, requiresTVCompletion: tv, tvCompleted: completed)+ }+ expect(!state(true, 15, 15).pending, "native TV completion with its current version")+ expect(!state(true, 16, 15).pending, "newer recorded TV version")+ expect(state(false, 15, 15).pending, "TV SetupDone remains required")+ expect(state(true, 14, 15).pending, "TV update setup remains pending")+ expect(state(true, nil, 15).pending, "missing TV version is pending")+ expect(state(true, 15, 15, completed: false).pending, "native TV success flag remains required")+ expect(state(true, 15, nil).pending, "unknown TV current version cannot prove completion")+ expect(!state(true, 11, 11, tv: false, completed: false).pending, "iPhone ignores the TV flag")+ expect(state(false, 11, 11, tv: false).pending, "iPhone SetupDone remains required")+ expect(state(true, 10, 11, tv: false).pending, "iPhone update version remains required")+ expect(!state(true, nil, nil, tv: false).pending, "existing unknown-version fallback")+ expect(state(true, nil, 11, tv: false).pending, "HomePod keeps its existing version policy")+ }+// MARK: - Service Profilestatic let labelPattern = "^[A-Za-z0-9][A-Za-z0-9._:\\[\\]-]{0,200}$"diff --git a/VPhoneDaemon/Tests/run-logic-tests.sh b/VPhoneDaemon/Tests/run-logic-tests.shindex 597bba25..f24fa3ec 100755--- a/VPhoneDaemon/Tests/run-logic-tests.sh+++ b/VPhoneDaemon/Tests/run-logic-tests.sh@@ -16,6 +16,7 @@ trap '/bin/rm -rf "$temporary"' EXIT"$daemon/Daemon/GuestFirstBootSettle.swift" \"$daemon/Daemon/GuestDeviceNameRule.swift" \"$daemon/Daemon/GuestPointerScroll.swift" \+ "$daemon/Daemon/GuestSetupAssistantState.swift" \"$daemon/Tests/LogicTests.swift" \-o "$temporary/logic-tests"diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftindex c78431f0..6d1d8ad6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -41,6 +41,8 @@ public enum FirmwareGuestPatchResolution {"system-extensions-boot-gpu_bundle",FirmwareGuestSystemPatchSet.tvOTAUserland,FirmwareGuestSystemPatchSet.tvSetupDisplayLookup,+ FirmwareGuestSystemPatchSet.tvSetupFocus,+ FirmwareGuestSystemPatchSet.tvLocalActivation,FirmwareGuestSystemPatchSet.tvLegacySetup,]).union(FirmwarePatchSetCatalog.tvOS27UserlandPatches)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 54c6fa4a..2ea81446 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -45,6 +45,9 @@ public enum FirmwareGuestSystemPatchSet {public static let tvTPRO = "system-dyld-exp-tv_tpro"public static let tvSetupDisplayLookup = "system-setupbackground-exp-pineboard_lookup"public static let tvLegacySetup = "system-tv-exp-legacy_setup"+ public static let tvSetupFocus = "system-setup-exp-deferred_focus"+ public static let tvSetupFocusLibrary = "/usr/lib/libvphonetvsetupfocus.dylib"+ public static let tvLocalActivation = "system-mobileactivationd-exp-tv_activation"/// Replaces the restored System volume with an Apple TV 4K userland/// staged from its OTA. Research only: no IPSW exists for that device.public static let tvOTAUserland = "system-tv-exp-ota_userland"@@ -130,11 +133,25 @@ public enum FirmwareGuestSystemPatchSet {),VPhonePatchDeclaration(identifier: tvLegacySetup,- title: "TV setup virtual remote compatibility",- summary: "Selects the native TVSetup app retained in tvOS 27.2 by disabling TVSetupV2 and TVSetupV2HW. Its language screen accepts virtual keyboard and consumer remote input. Setup choices and completion remain under user control.",+ title: "Legacy TV setup (research)",+ summary: "Research fallback: selects the legacy TVSetup app in tvOS 27.2 by disabling TVSetupV2 and TVSetupV2HW. Off in every preset; disabling restores the original flags and the new Setup flow.",target: .guestFile(path: "/" + CustomFirmwareTVSetup.relativePath),applicability: VPhonePatchApplicability(iOSBase: .release(major: 27, minor: 2)),),+ VPhonePatchDeclaration(+ identifier: tvLocalActivation,+ title: "TV local activation",+ summary: "Uses mobileactivationd’s existing local activation path for the tvOS 27.2 research guest, allowing the native Setup assistant to proceed without an Apple activation record.",+ target: .guestExecutable(path: "/usr/libexec/mobileactivationd"),+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 27, minor: 2)),+ ),+ VPhonePatchDeclaration(+ identifier: tvSetupFocus,+ title: "TV setup button focus",+ summary: "Uses native TV button-focus policy in the new tvOS 27.2 Setup window, so Consumer Select works without indirect-touch activity, including after idle. Preserves explicit focus overrides, eligibility and all Setup readiness checks.",+ target: .guestExecutable(path: "/Applications/Setup.app/Setup"),+ applicability: VPhonePatchApplicability(iOSBase: .release(major: 27, minor: 2)),+ ),VPhonePatchDeclaration(identifier: tvSetupDisplayLookup,title: "TV setup display connection",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 4aee5869..8bfb1a9b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -69,7 +69,7 @@ public enum FirmwarePatchSetCatalog {.union(hypervisorConcealmentPatches).union(experimentalIdentityPatches).union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall])- .union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvLegacySetup])+ .union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.tvLegacySetup])/// ProMotion: the 120 Hz timing for the paravirtual display.///@@ -226,7 +226,7 @@ public enum FirmwarePatchSetCatalog {freshly restored 26.4 guest does not survive. The HomePod-only top cap is off.""",patchSets: bundledReferences,- selection: .block([FirmwareGuestSystemPatchSet.tvLegacySetup, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]),+ selection: .block([FirmwareGuestSystemPatchSet.tvLegacySetup, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass, FirmwareGuestSystemPatchSet.homePodAdHocInstall]),)/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no@@ -318,7 +318,7 @@ public enum FirmwarePatchSetCatalog {patchSets: bundledReferences,selection: .block(manualOnlyPatches- .subtracting([FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvLegacySetup])+ .subtracting([FirmwareGuestSystemPatchSet.tvOTAUserland, FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation]).union(tvOSBlockedPatches.subtracting(["system-extensions-boot-gpu_bundle"]).subtracting(tvOS27UserlandPatches)),),)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftindex 6aa75303..7e38308e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -12,24 +12,26 @@ import VPhonePatchKit@Suite("Guest patch resolution")struct FirmwareGuestPatchResolutionTests {- @Test func `TV legacy setup is limited to the 27 point 2 4K preset`() throws {- let identifier = FirmwareGuestSystemPatchSet.tvLegacySetup- for version in ["26.6", "27.0", "27.1", "27.2", "27.3"] {- for preset in FirmwarePatchSetCatalog.builtInPresets {- let plan = try VPhonePatchPlan.resolve(- preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,- iOSBase: VPhoneVersion(version), cloudOS: VPhoneVersion("26.4"),- )- #expect(plan.isEnabled(identifier) == (version == "27.2" && preset.identifier == VPhonePatchPreset.tvOS4KIdentifier))+ @Test func `native TV setup adapters are limited to the 27 point 2 4K preset`() throws {+ for identifier in [FirmwareGuestSystemPatchSet.tvSetupDisplayLookup, FirmwareGuestSystemPatchSet.tvSetupFocus, FirmwareGuestSystemPatchSet.tvLocalActivation] {+ for version in ["26.6", "27.0", "27.1", "27.2", "27.3"] {+ for preset in FirmwarePatchSetCatalog.builtInPresets {+ let plan = try VPhonePatchPlan.resolve(+ preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion(version), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(plan.isEnabled(identifier) == (version == "27.2" && preset.identifier == VPhonePatchPreset.tvOS4KIdentifier))+ }}+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true).isEmpty)+ #expect(FirmwareGuestPatchResolution.unvalidatedHomePodGuestPatches(enabled: [identifier]) == [identifier])+ #expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: []).contains(identifier))+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier]) == [identifier])}- #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true).isEmpty)- #expect(FirmwareGuestPatchResolution.unvalidatedHomePodGuestPatches(enabled: [identifier]) == [identifier])- #expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: []).contains(identifier))}- @Test func `new TV setup display repair remains opt in`() throws {- let identifier = FirmwareGuestSystemPatchSet.tvSetupDisplayLookup+ @Test func `legacy TV setup is not selected by any preset`() throws {+ let identifier = FirmwareGuestSystemPatchSet.tvLegacySetupfor preset in FirmwarePatchSetCatalog.builtInPresets {let plan = try VPhonePatchPlan.resolve(preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex 2848faad..987f72c4 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -243,6 +243,8 @@ struct FirmwarePatchSetCatalogTests {&& $0.identifier != FirmwareGuestSystemPatchSet.homePodOTAUserland&& $0.identifier != FirmwareGuestSystemPatchSet.homePodSoundGlow&& $0.identifier != FirmwareGuestSystemPatchSet.tvSetupDisplayLookup+ && $0.identifier != FirmwareGuestSystemPatchSet.tvSetupFocus+ && $0.identifier != FirmwareGuestSystemPatchSet.tvLocalActivation&& $0.identifier != FirmwareGuestSystemPatchSet.tvLegacySetup&& $0.identifier != FirmwareGuestSystemPatchSet.homePodCryptexStaging&& $0.identifier != FirmwareGuestSystemPatchSet.homePodCryptexClassdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex ff2474c6..58514bd8 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -217,6 +217,12 @@ struct VPhoneCustomFirmwareInstaller {if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.tvSetupDisplayLookup), device.family != .appleTV {throw ValidationError("The TV setup display-connection patch is supported only for an Apple TV guest.")}+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.tvLocalActivation), device.family != .appleTV {+ throw ValidationError("The TV local-activation patch is supported only for an Apple TV guest.")+ }+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.tvSetupFocus), device.family != .appleTV {+ throw ValidationError("The TV setup focus adapter is supported only for an Apple TV guest.")+ }if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodTopCap), device.family != .homePod {throw ValidationError("The HomePod top-cap patch is supported only for a HomePod guest.")}@@ -1774,7 +1780,11 @@ struct VPhoneCustomFirmwareInstaller {}machO("system-launchd_cache_loader-boot-unsecure_cache_gate", path: "usr/libexec/launchd_cache_loader", verbs: ["patch-launchd-cache-loader"], codeIdentifier: "com.apple.launchd_cache_loader")- machO("system-mobileactivationd-boot-should_hactivate", path: "usr/libexec/mobileactivationd", verbs: ["patch-mobileactivationd"])+ // The TV declaration has its own 27.2 gate and preset selection; the+ // implementation and reversible backup are shared with iPhone.+ let activation = guestDevice.family == .appleTV+ ? FirmwareGuestSystemPatchSet.tvLocalActivation : "system-mobileactivationd-boot-should_hactivate"+ machO(activation, path: "usr/libexec/mobileactivationd", verbs: ["patch-mobileactivationd"])isolate(["system-watchdogd-exp-hv_vmm_cache"]) {if on("system-watchdogd-exp-hv_vmm_cache") {@@ -2014,6 +2024,37 @@ struct VPhoneCustomFirmwareInstaller {}}+ let tvSetupFocus = FirmwareGuestSystemPatchSet.tvSetupFocus+ isolate([tvSetupFocus]) {+ let executable = "Applications/Setup.app/Setup"+ let library = FirmwareGuestSystemPatchSet.tvSetupFocusLibrary+ let path = String(library.dropFirst())+ if on(tvSetupFocus), guestDevice.family == .appleTV,+ version == "27.2" || version.hasPrefix("27.2.") {+ let payload = try VPhoneGuestBinaries.resolve((library as NSString).lastPathComponent)+ try system.replaceFile(path, fromFileAt: payload, mode: 0o755, owner: Self.guestOwner)+ try installLibraryAlias(system: system, alias: "tf", target: library)+ try patchMachO(system: system, work: work, path: executable,+ preserveEntitlements: true, injectedDylibPath: "/tf")+ try sealGuestBundle(system: system, bundle: "Applications/Setup.app", preserveEntitlements: true)+ live.insert(tvSetupFocus)+ } else {+ if try revertMachO(system: system, work: work, path: executable, bundle: "Applications/Setup.app", preserveEntitlements: true) {+ print(" [+] \(tvSetupFocus): restored Setup from backup")+ } else if priorGuest.contains(tvSetupFocus) {+ live.insert(tvSetupFocus)+ throw ValidationError("TV setup focus adapter has no Setup backup; cannot safely remove its library.")+ }+ if try system.exists("tf") {+ guard try system.readLink("tf") == library else {+ throw ValidationError("Another file uses /tf; leaving it intact.")+ }+ try system.removeItem("tf")+ }+ try system.removeItem(path)+ }+ }+let tvSetupLookup = FirmwareGuestSystemPatchSet.tvSetupDisplayLookuplet tvSetupBackground = "Applications/SetupBackground.app/SetupBackground"isolate([tvSetupLookup]) {@@ -2173,6 +2214,7 @@ struct VPhoneCustomFirmwareInstaller {work: WorkDirectory,path: String,bundle: String? = nil,+ preserveEntitlements: Bool = false,) throws -> Bool {let backup = "\(path).bak"guard try system.exists(backup) else { return false }@@ -2182,7 +2224,7 @@ struct VPhoneCustomFirmwareInstaller {try system.replaceFile(path, fromFileAt: work.file(name), mode: 0o755, owner: Self.guestOwner)try system.removeItem(backup)if let bundle {- try sealGuestBundle(system: system, bundle: bundle)+ try sealGuestBundle(system: system, bundle: bundle, preserveEntitlements: preserveEntitlements)}return true}diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 22a623b5..27248b03 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -104,6 +104,7 @@ guest_compatibility_library="$(/usr/bin/xcrun swift-stdlib-tool --print \/bin/cp "$guest_products/homepodpersona/libvphoneinstallpersona.dylib" "$guest/libvphoneinstallpersona.dylib"/bin/cp "$guest_products/homepodmisfix/libvphonehomepodmisfix.dylib" "$guest/libvphonehomepodmisfix.dylib"/bin/cp "$guest_products/homepoddisplay/libvphonehomepoddisplay.dylib" "$guest/libvphonehomepoddisplay.dylib"+/bin/cp "$guest_products/tvsetupfocus/libvphonetvsetupfocus.dylib" "$guest/libvphonetvsetupfocus.dylib"/bin/cp "$guest_products/homepodsetup/vphone-homepod-setup" "$guest/vphone-homepod-setup"/bin/cp "$guest_products/homepodsetup/com.vphone.homepod-setup.plist" "$guest/com.vphone.homepod-setup.plist"/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex 0592a7ec..940b2e78 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -148,7 +148,7 @@ if /usr/bin/grep -q 'AVPSEPBooter-' "$resources/OpenSEP/OpenSEP.bin"; thenexit 1fi-for name in vphoned vphoned-tvos vphoned-watchos libswiftCompatibilitySpan.dylib launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \+for name in vphoned vphoned-tvos vphoned-watchos libvphonetvsetupfocus.dylib libswiftCompatibilitySpan.dylib launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneaccelerometer.dylib libvphoneattitude.dylib libvphonehomepoddisplay.dylib libvphonecryptexstaging.dylib libvphoneinstallpersona.dylib libvphonehomepodmisfix.dylib vphone-homepod-setup libAppleParavirtCompilerPluginIOGPUFamily.dylib; dorequire_signed_macho "$guest/$name"@@ -220,7 +220,7 @@ while IFS= read -r file; do"$frameworks/"*)[[ "$platform" != IOS ]] || { print -u2 "iOS binary in Contents/Frameworks: ${file#$bundle/}"; exit 1; };;- "$guest/vphoned-tvos"|"$guest/libvphonehomepoddisplay.dylib"|"$guest/libvphonecryptexstaging.dylib"|"$guest/libvphoneinstallpersona.dylib"|"$guest/libvphonehomepodmisfix.dylib"|"$guest/vphone-homepod-setup")+ "$guest/vphoned-tvos"|"$guest/libvphonetvsetupfocus.dylib"|"$guest/libvphonehomepoddisplay.dylib"|"$guest/libvphonecryptexstaging.dylib"|"$guest/libvphoneinstallpersona.dylib"|"$guest/libvphonehomepodmisfix.dylib"|"$guest/vphone-homepod-setup")# tvOS dyld refuses an iOS-platform daemon on an Apple TV guest.[[ "$platform" == TVOS ]] || { print -u2 "Non-tvOS binary: ${file#$bundle/}"; exit 1; };;diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstringsindex 60582a84..f0b31266 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings@@ -1,6 +1,26 @@{"sourceLanguage" : "en","strings" : {+ "Apple TV Remote" : {+ },+ "Click or hold. Arrow keys navigate.\nReturn selects. Esc goes back." : {+ },+ "Down" : {+ },+ "Left" : {+ },+ "Play / Pause" : {+ },+ "Right" : {+ },+ "Select" : {+ },+ "Siri" : {+ },+ "TV / Control Center" : {+ },+ "Up" : {+ },"%lld of %lld defaults · %lld unsaved changes" : {"localizations": {"en": {diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plistindex 8bcfc19b..c782e473 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist@@ -95,6 +95,8 @@<array><string>system-homepod-exp-top_cap</string><string>system-setupbackground-exp-pineboard_lookup</string>+ <string>system-setup-exp-deferred_focus</string>+ <string>system-mobileactivationd-exp-tv_activation</string><string>system-tv-exp-legacy_setup</string><string>system-homepod-exp-setup_bypass</string><string>system-homepod-exp-welcome</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plistindex ef66455f..9bacb3a9 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist@@ -115,6 +115,8 @@<string>system-extensions-boot-gpu_bundle</string><string>system-tv-exp-ota_userland</string><string>system-setupbackground-exp-pineboard_lookup</string>+ <string>system-setup-exp-deferred_focus</string>+ <string>system-mobileactivationd-exp-tv_activation</string><string>system-tv-exp-legacy_setup</string><string>system-fsck-boot-arm64e_x1_bootstrap</string><string>system-jetsamproperties-cfw-disable_allowed</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex c09fa6c8..df8f06b2 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -106,6 +106,8 @@<string>kernel-exp-tv_tpro_pagers</string><string>system-tv-exp-ota_userland</string><string>system-setupbackground-exp-pineboard_lookup</string>+ <string>system-setup-exp-deferred_focus</string>+ <string>system-mobileactivationd-exp-tv_activation</string><string>system-tv-exp-legacy_setup</string><string>system-exp-ota_userland</string></array>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex cec02f3e..80022dd5 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -73,7 +73,7 @@<string>Block</string><key>Patches</key><array>- <string>system-setupbackground-exp-pineboard_lookup</string>+ <string>system-tv-exp-legacy_setup</string><string>system-homepod-exp-top_cap</string><string>system-homepod-exp-setup_bypass</string><string>system-homepod-exp-welcome</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex 47dbcb70..632dc358 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -148,6 +148,8 @@<string>system-virtualaudio-cfw-volume_mode_precondition</string><string>system-tv-exp-ota_userland</string><string>system-setupbackground-exp-pineboard_lookup</string>+ <string>system-setup-exp-deferred_focus</string>+ <string>system-mobileactivationd-exp-tv_activation</string><string>system-tv-exp-legacy_setup</string><string>system-exp-ota_userland</string></array>diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/TVRemoteTests.swift b/VPhoneExecutable/VPhoneVirtualization/Tests/TVRemoteTests.swiftnew file mode 100644index 00000000..46c4de6c--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/TVRemoteTests.swift@@ -0,0 +1,177 @@+import AppKit++// The standalone host harness supplies only localization, with no VM or guest.+enum VPhoneLocalization { static let bundle = Bundle.main }++@main+struct TVRemoteTests {+ @MainActor+ static func main() async throws {+ _ = NSApplication.shared+ let view = VPhoneTVRemoteView(frame: NSRect(origin: .zero, size: VPhoneTVRemoteView.preferredSize))+ view.needsLayout = true+ view.layoutSubtreeIfNeeded()+ view.enabled = true+ var events: [VPhoneTVRemoteEvent] = []+ view.onEvent = { events.append($0) }+ let expected: [VPhoneTVRemoteControl: UInt32] = [+ .up: 0x42, .down: 0x43, .left: 0x44, .right: 0x45, .select: 0x41,+ .back: 0x46, .tv: 0x40, .playPause: 0xCD, .mute: 0xE2,+ .volumeUp: 0xE9, .volumeDown: 0xEA, .siri: 0xCF, .power: 0x30,+ ]+ for control in VPhoneTVRemoteControl.allCases {+ precondition(control.hid.page == 12 && control.hid.usage == expected[control])+ let button = try require(view.buttons[control])+ precondition(button.isAccessibilityElement() && button.accessibilityLabel()?.isEmpty == false)+ precondition(button.accessibilityPerformPress())+ precondition(events.suffix(2) == [.init(control: control, down: true), .init(control: control, down: false)])+ }+ precondition(events.count == 26)++ // Ring sectors do not overlap the center or reverse horizontal arrows.+ for (point, control) in [+ (NSPoint(x: 140, y: 90), VPhoneTVRemoteControl.up),+ (NSPoint(x: 140, y: 200), .down), (NSPoint(x: 85, y: 145), .left),+ (NSPoint(x: 195, y: 145), .right), (NSPoint(x: 140, y: 145), .select),+ ] {+ let hit = view.hitTest(view.convert(point, to: view.superview)) as? VPhoneTVRemoteButton+ precondition(hit?.control == control, "Hit area for \(control): \(String(describing: hit?.control))")+ }++ let down = try require(NSEvent.mouseEvent(with: .leftMouseDown, location: .zero, modifierFlags: [],+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 1, clickCount: 1, pressure: 1))+ let up = try require(NSEvent.mouseEvent(with: .leftMouseUp, location: .zero, modifierFlags: [],+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 2, clickCount: 1, pressure: 0))+ let select = try require(view.buttons[.select])+ events.removeAll()+ select.mouseDown(with: down)+ select.mouseDown(with: down) // Repeats must not create extra downs.+ try await Task.sleep(for: .milliseconds(80))+ precondition(events == [.init(control: .select, down: true)])+ // A simultaneous Return retains the press after pointer release.+ view.keyDown(with: try key(36, down: true))+ select.mouseUp(with: up)+ precondition(events.count == 1)+ view.keyUp(with: try key(36, down: false))+ precondition(events == [.init(control: .select, down: true), .init(control: .select, down: false)])++ events.removeAll()+ view.keyDown(with: try key(123, down: true))+ view.keyDown(with: try key(123, down: true))+ view.keyUp(with: try key(123, down: false))+ precondition(events == [.init(control: .left, down: true), .init(control: .left, down: false)])+ events.removeAll()+ let commandDown = try key(4, down: true, modifiers: .command)+ let commandUp = try key(4, down: false, modifiers: .command)+ precondition(!view.handleKey(commandDown, down: true))+ view.keyDown(with: try key(4, down: true))+ precondition(view.handleKey(commandUp, down: false))+ precondition(events == [.init(control: .tv, down: true), .init(control: .tv, down: false)])+ view.keyDown(with: try key(126, down: true))+ view.enabled = false // Same release path as connection loss.+ precondition(events.suffix(2) == [.init(control: .up, down: true), .init(control: .up, down: false)])+ let count = events.count+ view.releaseControls()+ precondition(!select.accessibilityPerformPress() && events.count == count)++ // Queued input cancelled before dispatch never reaches the next session.+ var delivered: [VPhoneTVRemoteEvent] = []+ let input = VPhoneTVRemoteInput { delivered.append($0) }+ input.connectionChanged(true)+ input.enqueue(.init(control: .tv, down: true))+ input.cancelPresses()+ await input.flush()+ precondition(delivered.isEmpty)+ input.enqueue(.init(control: .tv, down: true))+ input.enqueue(.init(control: .tv, down: false))+ await input.flush()+ precondition(delivered == [.init(control: .tv, down: true), .init(control: .tv, down: false)])++ // Closing while another input producer owns the queue invalidates a+ // waiting down, even though the transport task has already started.+ var waiting: CheckedContinuation<Void, Never>?+ var prepared = false+ var late: [VPhoneTVRemoteEvent] = []+ let suspended = VPhoneTVRemoteInput(prepare: {+ prepared = true+ await withCheckedContinuation { waiting = $0 }+ }) { late.append($0) }+ suspended.connectionChanged(true)+ suspended.enqueue(.init(control: .power, down: true))+ while !prepared { await Task.yield() }+ suspended.cancelPresses()+ waiting?.resume()+ await suspended.flush()+ precondition(late.isEmpty && suspended.needsRelease.isEmpty)++ // An AX activation is a completed tap before AppKit can change key+ // windows. Focus loss must preserve it, while cancelling a held key.+ var taps: [VPhoneTVRemoteEvent] = []+ let activated = VPhoneTVRemoteInput { taps.append($0) }+ activated.connectionChanged(true)+ view.enabled = true+ view.onEvent = { activated.enqueue($0) }+ precondition(select.accessibilityPerformPress())+ activated.cancelPresses()+ view.releaseControls()+ await activated.flush()+ precondition(taps == [.init(control: .select, down: true), .init(control: .select, down: false)])+ taps.removeAll()+ view.keyDown(with: try key(126, down: true))+ activated.cancelPresses() // Controller cancels before releasing the view.+ view.releaseControls()+ await activated.flush()+ precondition(taps.isEmpty)+ precondition(select.accessibilityPerformPress())+ activated.connectionChanged(false)+ activated.connectionChanged(true)+ await activated.flush()+ precondition(taps.isEmpty) // Completed taps cannot reach a later guest.++ // A failed release is remembered, retried first on reconnect, then+ // removed only after acknowledgement. Cancellation sends no orphan up.+ var failRelease = true+ var recovery: [VPhoneTVRemoteEvent] = []+ let reconnecting = VPhoneTVRemoteInput { event in+ if !event.down && failRelease { throw URLError(.networkConnectionLost) }+ recovery.append(event)+ }+ reconnecting.connectionChanged(true)+ reconnecting.enqueue(.init(control: .siri, down: true))+ reconnecting.enqueue(.init(control: .siri, down: false))+ await reconnecting.flush()+ precondition(reconnecting.needsRelease == [.siri])+ reconnecting.connectionChanged(false)+ failRelease = false+ reconnecting.connectionChanged(true)+ reconnecting.enqueue(.init(control: .select, down: true))+ reconnecting.enqueue(.init(control: .select, down: false))+ await reconnecting.flush()+ precondition(recovery == [.init(control: .siri, down: true), .init(control: .siri, down: false),+ .init(control: .select, down: true), .init(control: .select, down: false)])+ precondition(reconnecting.needsRelease.isEmpty)+ reconnecting.cancelPresses()+ await reconnecting.flush()+ precondition(recovery.count == 4)++ if CommandLine.arguments.count > 1 {+ view.enabled = true+ let bitmap = try require(view.bitmapImageRepForCachingDisplay(in: view.bounds))+ view.cacheDisplay(in: view.bounds, to: bitmap)+ try require(bitmap.representation(using: .png, properties: [:]))+ .write(to: URL(fileURLWithPath: CommandLine.arguments[1]))+ }+ print("TV remote HID mapping, all 13 buttons, ring hit areas, holds, keyboard, cancellation and reconnect tests passed")+ }++ static func key(_ code: UInt16, down: Bool, modifiers: NSEvent.ModifierFlags = []) throws -> NSEvent {+ try require(NSEvent.keyEvent(with: down ? .keyDown : .keyUp, location: .zero, modifierFlags: modifiers,+ timestamp: 0, windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: "",+ isARepeat: false, keyCode: code))+ }++ static func require<T>(_ value: T?) throws -> T {+ guard let value else { throw NSError(domain: "TVRemoteTests", code: 1) }+ return value+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/Tests/run-tv-remote-tests.sh b/VPhoneExecutable/VPhoneVirtualization/Tests/run-tv-remote-tests.shnew file mode 100755index 00000000..c939962b--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/Tests/run-tv-remote-tests.sh@@ -0,0 +1,13 @@+#!/bin/zsh+set -euo pipefail++tests="${0:a:h}"+remote="$tests:h/UI/UserInterface/Panels/TVRemote"+temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-tv-remote.XXXXXX")"+trap '/bin/rm -rf "$temporary"' EXIT++/usr/bin/xcrun --sdk macosx swiftc -swift-version 6 -strict-concurrency=complete \+ -module-cache-path "$temporary/ModuleCache" \+ "$remote/VPhoneTVRemoteInput.swift" "$remote/VPhoneTVRemoteView.swift" \+ "$tests/TVRemoteTests.swift" -o "$temporary/TVRemoteTests"+"$temporary/TVRemoteTests" "$@"diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 80b94a33..7f04ed99 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -545,6 +545,10 @@ final class VPhoneGuestControl {/// Calls one vphoned operation after the input events already queued, so a/// key or text request cannot overtake a tap sent before it.+ /// A cancellable input producer must drain first, then check that its+ /// interaction is still current immediately before submitting a new RPC.+ func waitForQueuedInput() async { await orderedInput?.value }+func callAfterQueuedInput(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {await orderedInput?.valuereturn try await call(method, params: params)diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swiftindex ee26e019..41e3c01b 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift@@ -23,10 +23,16 @@ class VPhoneMenuController {var hardwareKeyboardItem: NSMenuItem?var tvControlCenterItem: NSMenuItem?+ var tvRemoteItem: NSMenuItem?+ lazy var tvRemoteWindowController = VPhoneTVRemoteWindowController(control: control)/// An Apple TV guest has a TV button that opens Control Center when held.var showsTVControls = false {- didSet { tvControlCenterItem?.isHidden = !showsTVControls }+ didSet {+ tvControlCenterItem?.isHidden = !showsTVControls+ tvRemoteItem?.isHidden = !showsTVControls+ if oldValue && !showsTVControls { tvRemoteWindowController.close() }+ }}var watchSideButtonItem: NSMenuItem?diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swiftindex ccf10462..2eb14d1a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift@@ -13,6 +13,13 @@ extension VPhoneMenuController {let menu = NSMenu(title: "Device")menu.autoenablesItems = falsemenu.addItem(makePanelItem(.controls, "Controls", keyEquivalent: "k", symbol: "slider.horizontal.3"))+ let remote = makeItem(+ "Apple TV Remote", action: #selector(showTVRemote),+ keyEquivalent: "r", modifiers: [.command, .option], symbol: "appletvremote.gen2",+ )+ remote.isHidden = true+ tvRemoteItem = remote+ menu.addItem(remote)menu.addItem(NSMenuItem.separator())menu.addItem(makeItem("Home Screen",@@ -140,6 +147,11 @@ extension VPhoneMenuController {return item}+ @objc func showTVRemote() {+ guard showsTVControls else { return }+ tvRemoteWindowController.show()+ }+@objc func sendHome() {keySender.sendHome()}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swiftindex 0b2c8a15..72dcbb1a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDiagnostics.swift@@ -73,6 +73,7 @@ extension VPhoneMenuController {/// disconnect, disables them all.func updatePanelAvailability(capabilities: [String]) {guestPanelsWindowController.attitudeConnectionChanged()+ if showsTVControls { tvRemoteWindowController.connectionChanged() }for (panel, item) in panelMenuItems {item.isEnabled = capabilities.contains(panel.capability)}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteInput.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteInput.swiftnew file mode 100644index 00000000..e832c351--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteInput.swift@@ -0,0 +1,174 @@+import Foundation+import IOKit.hid++// MARK: - Remote Events++enum VPhoneTVRemoteControl: String, CaseIterable, Hashable {+ case up, down, left, right, select, back, tv, playPause, mute, volumeUp, volumeDown, siri, power++ /// Consumer usages verified against tvOS 27.2 UIKitCore's+ /// __UIEventHIDPressTypeForKeyboardHIDEvent. MenuEscape is remote Back;+ /// ACBack maps to a different press type.+ var hid: (page: UInt32, usage: UInt32) {+ let usage: Int = switch self {+ case .up: kHIDUsage_Csmr_MenuUp+ case .down: kHIDUsage_Csmr_MenuDown+ case .left: kHIDUsage_Csmr_MenuLeft+ case .right: kHIDUsage_Csmr_MenuRight+ case .select: kHIDUsage_Csmr_MenuPick+ case .tv: kHIDUsage_Csmr_Menu+ case .playPause: kHIDUsage_Csmr_PlayOrPause+ case .mute: kHIDUsage_Csmr_Mute+ case .volumeUp: kHIDUsage_Csmr_VolumeIncrement+ case .volumeDown: kHIDUsage_Csmr_VolumeDecrement+ case .siri: kHIDUsage_Csmr_VoiceCommand+ case .power: kHIDUsage_Csmr_Power+ case .back: kHIDUsage_Csmr_MenuEscape+ }+ return (UInt32(kHIDPage_Consumer), UInt32(usage))+ }++ var symbol: String {+ switch self {+ case .up: "chevron.up"+ case .down: "chevron.down"+ case .left: "chevron.left"+ case .right: "chevron.right"+ case .select: "circle.fill"+ case .back: "chevron.left"+ case .tv: "tv"+ case .playPause: "playpause.fill"+ case .mute: "speaker.slash.fill"+ case .volumeUp: "plus"+ case .volumeDown: "minus"+ case .siri: "mic.fill"+ case .power: "power"+ }+ }++ var label: String.LocalizationValue {+ switch self {+ case .up: "Up"+ case .down: "Down"+ case .left: "Left"+ case .right: "Right"+ case .select: "Select"+ case .back: "Back"+ case .tv: "TV / Control Center"+ case .playPause: "Play / Pause"+ case .mute: "Mute"+ case .volumeUp: "Volume Up"+ case .volumeDown: "Volume Down"+ case .siri: "Siri"+ case .power: "Power"+ }+ }++ static func keyboard(_ code: UInt16) -> Self? {+ switch code {+ case 126: .up+ case 125: .down+ case 123: .left+ case 124: .right+ case 36, 76: .select+ case 53: .back+ case 49: .playPause+ case 4: .tv // H+ case 46: .mute // M+ case 24, 69: .volumeUp+ case 27, 78: .volumeDown+ case 1: .siri // S+ case 35: .power // P+ default: nil+ }+ }+}++struct VPhoneTVRemoteEvent: Equatable {+ let control: VPhoneTVRemoteControl+ let down: Bool+}++// MARK: - Ordered Delivery++/// Preserves down/up ordering without blocking AppKit. A disconnected release+/// is retried before new input when the agent reconnects. Queued downs from a+/// cancelled interaction can never reach a later guest connection.+@MainActor+final class VPhoneTVRemoteInput {+ typealias Send = @MainActor (VPhoneTVRemoteEvent) async throws -> Void+ private let send: Send+ private let prepare: (@MainActor () async -> Void)?+ private var queue: Task<Void, Never>?+ private var generation: UInt64 = 0+ private var connectionGeneration: UInt64 = 0+ private final class PressTicket { var completed = false }+ private var pendingPresses: [VPhoneTVRemoteControl: PressTicket] = [:]+ private(set) var connected = false+ private(set) var needsRelease: Set<VPhoneTVRemoteControl> = []+ var onError: ((Error) -> Void)?++ init(prepare: (@MainActor () async -> Void)? = nil, send: @escaping Send) {+ self.prepare = prepare+ self.send = send+ }++ func connectionChanged(_ connected: Bool) {+ guard self.connected != connected else { return }+ self.connected = connected+ generation &+= 1+ connectionGeneration &+= 1+ pendingPresses.removeAll()+ if connected {+ for control in VPhoneTVRemoteControl.allCases where needsRelease.contains(control) {+ enqueue(.init(control: control, down: false))+ }+ }+ }++ func enqueue(_ event: VPhoneTVRemoteEvent) {+ guard !event.down || connected else { return }+ let ticket: PressTicket?+ if event.down {+ let press = PressTicket()+ pendingPresses[event.control] = press+ ticket = press+ } else {+ pendingPresses.removeValue(forKey: event.control)?.completed = true+ ticket = nil+ }+ let previous = queue+ let generation = generation+ let connectionGeneration = connectionGeneration+ queue = Task { [self] in+ await previous?.value+ await prepare?()+ guard connected else { return }+ if event.down {+ // A completed AX/button tap remains intentional after panel+ // focus changes. An unfinished hold is cancelled; neither may+ // cross a guest connection boundary.+ guard connectionGeneration == self.connectionGeneration,+ generation == self.generation || ticket?.completed == true else { return }+ }+ guard event.down || needsRelease.contains(event.control) else { return }+ if event.down { needsRelease.insert(event.control) }+ do {+ try await send(event)+ if !event.down { needsRelease.remove(event.control) }+ } catch {+ onError?(error)+ }+ }+ }++ func cancelPresses() {+ generation &+= 1+ pendingPresses.removeAll()+ for control in VPhoneTVRemoteControl.allCases where needsRelease.contains(control) {+ enqueue(.init(control: control, down: false))+ }+ }++ func flush() async { await queue?.value }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteView.swiftnew file mode 100644index 00000000..ba28f673--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteView.swift@@ -0,0 +1,290 @@+import AppKit++// MARK: - Remote Face++/// Native buttons provide hit testing and AX activation above the remote face.+/// Holds are real down/up transitions; changing focus or connection releases all.+@MainActor+final class VPhoneTVRemoteView: NSView {+ static let preferredSize = NSSize(width: 280, height: 680)+ var onEvent: ((VPhoneTVRemoteEvent) -> Void)?+ var enabled = false {+ didSet {+ if !enabled { releaseControls() }+ for button in buttons.values { button.isEnabled = enabled }+ status.stringValue = enabled ? "" : String(localized: "Guest Not Connected", bundle: VPhoneLocalization.bundle)+ needsDisplay = true+ }+ }++ private(set) var buttons: [VPhoneTVRemoteControl: VPhoneTVRemoteButton] = [:]+ private var sources: [VPhoneTVRemoteControl: Set<String>] = [:]+ private let status = NSTextField(wrappingLabelWithString: "")+ private let hint = NSTextField(wrappingLabelWithString: String(+ localized: "Click or hold. Arrow keys navigate.\nReturn selects. Esc goes back.",+ bundle: VPhoneLocalization.bundle,+ ))++ override init(frame: NSRect) {+ super.init(frame: frame)+ setAccessibilityElement(false)+ for control in VPhoneTVRemoteControl.allCases {+ let button = VPhoneTVRemoteButton(control: control)+ button.remote = self+ buttons[control] = button+ addSubview(button)+ }+ for label in [status, hint] {+ label.alignment = .center+ label.textColor = NSColor(calibratedWhite: 0.7, alpha: 1)+ label.font = .monospacedSystemFont(ofSize: 11, weight: .regular)+ addSubview(label)+ }+ let order: [VPhoneTVRemoteControl] = [+ .power, .up, .left, .select, .right, .down, .back, .tv,+ .playPause, .mute, .volumeUp, .volumeDown, .siri,+ ]+ for (index, control) in order.enumerated() {+ buttons[control]?.nextKeyView = buttons[order[(index + 1) % order.count]]+ }+ enabled = false+ }++ required init?(coder: NSCoder) { nil }+ override var isFlipped: Bool { true }+ override var acceptsFirstResponder: Bool { true }+ override var intrinsicContentSize: NSSize { Self.preferredSize }++ private var scale: CGFloat { min(bounds.width / 280, bounds.height / 680) }+ private func rect(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> NSRect {+ NSRect(x: bounds.midX + (x - 140) * scale, y: bounds.midY + (y - 340) * scale,+ width: width * scale, height: height * scale)+ }++ override func layout() {+ super.layout()+ let pad = rect(77, 82, 126, 126)+ for control in [VPhoneTVRemoteControl.up, .down, .left, .right] {+ buttons[control]?.frame = pad+ }+ buttons[.select]?.frame = rect(108, 113, 64, 64)+ buttons[.power]?.frame = rect(182, 38, 23, 23)+ buttons[.back]?.frame = rect(83, 237, 46, 46)+ buttons[.tv]?.frame = rect(151, 237, 46, 46)+ buttons[.playPause]?.frame = rect(83, 303, 46, 46)+ buttons[.mute]?.frame = rect(83, 369, 46, 46)+ buttons[.volumeUp]?.frame = rect(151, 303, 46, 56)+ buttons[.volumeDown]?.frame = rect(151, 359, 46, 56)+ buttons[.siri]?.frame = rect(216, 223, 15, 70)+ status.frame = rect(16, 620, 248, 18)+ hint.frame = rect(16, 642, 248, 32)+ for label in [status, hint] { label.font = .monospacedSystemFont(ofSize: 11 * scale, weight: .regular) }+ for button in buttons.values { button.needsDisplay = true }+ }++ override func draw(_ dirtyRect: NSRect) {+ NSColor(calibratedWhite: 0.10, alpha: 1).setFill()+ bounds.fill()+ let body = NSBezierPath(roundedRect: rect(64, 20, 152, 590), xRadius: 28 * scale, yRadius: 28 * scale)+ NSColor(calibratedWhite: 0.82, alpha: 1).setFill()+ body.fill()+ NSColor(calibratedWhite: 0.56, alpha: 1).setStroke()+ body.lineWidth = scale+ body.stroke()+ NSColor(calibratedWhite: 0.18, alpha: 1).setFill()+ NSBezierPath(ovalIn: rect(138, 45, 4, 4)).fill()+ // The volume rocker is one capsule, with independent upper/lower hits.+ NSBezierPath(roundedRect: rect(151, 303, 46, 112), xRadius: 23 * scale, yRadius: 23 * scale).fill()+ NSColor(calibratedWhite: 0.5, alpha: 1).setFill()+ NSBezierPath(roundedRect: rect(132, 597, 16, 3), xRadius: scale, yRadius: scale).fill()+ }++ func change(_ control: VPhoneTVRemoteControl, source: String, down: Bool) {+ guard enabled || !down else { return }+ var held = sources[control] ?? []+ let wasPressed = !held.isEmpty+ if down { held.insert(source) } else { held.remove(source) }+ sources[control] = held.isEmpty ? nil : held+ let pressed = !held.isEmpty+ guard pressed != wasPressed else { return }+ buttons[control]?.pressed = pressed+ onEvent?(.init(control: control, down: pressed))+ }++ func releaseControls() {+ for control in VPhoneTVRemoteControl.allCases where sources[control]?.isEmpty == false {+ sources[control] = nil+ buttons[control]?.pressed = false+ onEvent?(.init(control: control, down: false))+ }+ }++ func showError(_ error: Error) {+ status.stringValue = error.localizedDescription+ status.toolTip = error.localizedDescription+ }++ func handleKey(_ event: NSEvent, down: Bool) -> Bool {+ guard let control = VPhoneTVRemoteControl.keyboard(event.keyCode) else { return false }+ let source = "key-\(event.keyCode)"+ if down {+ guard event.modifierFlags.intersection([.command, .control, .option]).isEmpty else { return false }+ } else {+ // A modifier pressed after key-down must not strand the release.+ guard sources[control]?.contains(source) == true else { return false }+ }+ change(control, source: source, down: down)+ return true+ }++ override func keyDown(with event: NSEvent) {+ if !handleKey(event, down: true) { super.keyDown(with: event) }+ }++ override func keyUp(with event: NSEvent) {+ if !handleKey(event, down: false) { super.keyUp(with: event) }+ }+}++// MARK: - Physical Button++@MainActor+final class VPhoneTVRemoteButton: NSButton {+ let control: VPhoneTVRemoteControl+ weak var remote: VPhoneTVRemoteView?+ var pressed = false { didSet { needsDisplay = true } }++ init(control: VPhoneTVRemoteControl) {+ self.control = control+ super.init(frame: .zero)+ title = ""+ // Each rocker half draws the shared capsule; bound its pressed fill.+ clipsToBounds = true+ isBordered = false+ setButtonType(.momentaryPushIn)+ target = self+ action = #selector(activate)+ setAccessibilityElement(true)+ setAccessibilityRole(.button)+ let label = String(localized: control.label, bundle: VPhoneLocalization.bundle)+ setAccessibilityLabel(label)+ setAccessibilityIdentifier("tv-remote-\(control.rawValue)")+ toolTip = label+ }++ required init?(coder: NSCoder) { nil }+ override var acceptsFirstResponder: Bool { true }+ override var canBecomeKeyView: Bool { true }+ override var isFlipped: Bool { true }+ override var focusRingType: NSFocusRingType { get { .none } set {} }++ private var angle: CGFloat? {+ switch control {+ case .up: -.pi / 2+ case .down: .pi / 2+ case .left: .pi+ case .right: 0+ default: nil+ }+ }++ private var shape: NSBezierPath {+ if let angle {+ let path = NSBezierPath()+ let radius = bounds.width / 2+ for (index, step) in (0...24).enumerated() {+ let a = angle - .pi / 4 + CGFloat(step) / 24 * .pi / 2+ let point = NSPoint(x: bounds.midX + cos(a) * radius, y: bounds.midY + sin(a) * radius)+ if index == 0 { path.move(to: point) } else { path.line(to: point) }+ }+ for step in (0...24).reversed() {+ let a = angle - .pi / 4 + CGFloat(step) / 24 * .pi / 2+ path.line(to: NSPoint(x: bounds.midX + cos(a) * radius * 0.51, y: bounds.midY + sin(a) * radius * 0.51))+ }+ path.close()+ return path+ }+ if control == .volumeUp || control == .volumeDown {+ let rocker = NSRect(x: 1, y: control == .volumeUp ? 1 : -bounds.height + 1,+ width: bounds.width - 2, height: bounds.height * 2 - 2)+ return NSBezierPath(roundedRect: rocker, xRadius: bounds.width / 2, yRadius: bounds.width / 2)+ }+ return NSBezierPath(roundedRect: bounds.insetBy(dx: 1, dy: 1),+ xRadius: min(bounds.width, bounds.height) / 2,+ yRadius: min(bounds.width, bounds.height) / 2)+ }++ override func hitTest(_ point: NSPoint) -> NSView? {+ shape.contains(convert(point, from: superview)) ? super.hitTest(point) : nil+ }++ override func mouseDown(with event: NSEvent) {+ guard isEnabled else { return }+ window?.makeFirstResponder(self)+ remote?.change(control, source: "pointer", down: true)+ }++ override func mouseUp(with event: NSEvent) {+ remote?.change(control, source: "pointer", down: false)+ }++ override func keyDown(with event: NSEvent) {+ if event.keyCode == 48 {+ if event.modifierFlags.contains(.shift) { window?.selectPreviousKeyView(self) }+ else { window?.selectNextKeyView(self) }+ } else if event.keyCode == 49 {+ remote?.change(control, source: "button-space", down: true)+ } else if remote?.handleKey(event, down: true) != true { super.keyDown(with: event) }+ }++ override func keyUp(with event: NSEvent) {+ if event.keyCode == 49 { remote?.change(control, source: "button-space", down: false) }+ else if remote?.handleKey(event, down: false) != true { super.keyUp(with: event) }+ }++ override func resignFirstResponder() -> Bool {+ remote?.change(control, source: "pointer", down: false)+ remote?.change(control, source: "button-space", down: false)+ return super.resignFirstResponder()+ }++ override func accessibilityPerformPress() -> Bool {+ guard isEnabled else { return false }+ activate()+ return true+ }++ @objc private func activate() {+ remote?.change(control, source: "activation", down: true)+ remote?.change(control, source: "activation", down: false)+ }++ override func draw(_ dirtyRect: NSRect) {+ let path = shape+ if control != .volumeUp && control != .volumeDown || pressed {+ NSColor(calibratedWhite: pressed ? 0.34 : 0.13, alpha: 1).setFill()+ path.fill()+ }+ if window?.firstResponder === self {+ NSColor.keyboardFocusIndicatorColor.setStroke()+ path.lineWidth = 2+ path.stroke()+ }+ if control == .select { return }+ let pointSize = min(bounds.width, bounds.height) * (control == .siri ? 0.75 : angle == nil ? 0.42 : 0.11)+ let color = NSColor.white.withAlphaComponent(isEnabled ? 1 : 0.35)+ let configuration = NSImage.SymbolConfiguration(pointSize: pointSize, weight: .medium)+ .applying(.init(paletteColors: [color]))+ guard let image = NSImage(systemSymbolName: control.symbol, accessibilityDescription: nil)?+ .withSymbolConfiguration(configuration)+ else { return }+ let size = image.size+ var center = NSPoint(x: bounds.midX, y: bounds.midY)+ if let angle {+ center.x += cos(angle) * bounds.width * 0.39+ center.y += sin(angle) * bounds.height * 0.39+ }+ image.draw(in: NSRect(x: center.x - size.width / 2, y: center.y - size.height / 2,+ width: size.width, height: size.height))+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteWindowController.swiftnew file mode 100644index 00000000..2f5c9315--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/TVRemote/VPhoneTVRemoteWindowController.swift@@ -0,0 +1,86 @@+import AppKit++/// One remote per VM process. Opening it never changes guest setup or pairing.+@MainActor+final class VPhoneTVRemoteWindowController: NSWindowController, NSWindowDelegate {+ private let control: VPhoneGuestControl+ private var face: VPhoneTVRemoteView?+ private let input: VPhoneTVRemoteInput++ init(control: VPhoneGuestControl) {+ self.control = control+ input = VPhoneTVRemoteInput(prepare: { [weak control] in+ await control?.waitForQueuedInput()+ }) { [weak control] event in+ guard let control else { throw VPhoneGuestControl.ControlError.notConnected }+ let hid = event.control.hid+ _ = try await control.call("input.hid", params: [+ "page": hid.page, "usage": hid.usage, "down": event.down,+ ])+ // Keep an AX tap visible even when down/up share a run-loop turn.+ if event.down { try await Task.sleep(for: .milliseconds(60)) }+ }+ super.init(window: nil)+ }++ required init?(coder: NSCoder) { nil }++ func show() {+ if window == nil { makeWindow() }+ connectionChanged()+ showWindow(nil)+ window?.makeKeyAndOrderFront(nil)+ NSApp.activate(ignoringOtherApps: true)+ }++ func connectionChanged() {+ let connected = control.isConnected && control.guestCapabilities.contains("hid")+ input.connectionChanged(connected)+ face?.enabled = connected+ }++ private func makeWindow() {+ let face = VPhoneTVRemoteView(frame: NSRect(origin: .zero, size: VPhoneTVRemoteView.preferredSize))+ face.onEvent = { [weak self] in self?.input.enqueue($0) }+ input.onError = { [weak face] in face?.showError($0) }+ self.face = face++ let panel = NSPanel(+ contentRect: face.frame,+ styleMask: [.titled, .closable, .miniaturizable, .resizable, .utilityWindow],+ backing: .buffered, defer: false,+ )+ panel.title = String(localized: "Apple TV Remote", bundle: VPhoneLocalization.bundle)+ panel.isReleasedWhenClosed = false+ panel.hidesOnDeactivate = false+ panel.contentView = face+ panel.contentMinSize = NSSize(width: 240, height: 582)+ panel.contentAspectRatio = VPhoneTVRemoteView.preferredSize+ panel.setFrameAutosaveName("vphone-panel-tv-remote")+ panel.delegate = self+ if !panel.setFrameUsingName("vphone-panel-tv-remote") { panel.center() }+ window = panel+ }++ private func releaseControls() {+ input.cancelPresses()+ face?.releaseControls()+ }++ nonisolated func windowDidResignKey(_ notification: Notification) {+ MainActor.assumeIsolated { releaseControls() }+ }++ nonisolated func windowDidMiniaturize(_ notification: Notification) {+ MainActor.assumeIsolated { releaseControls() }+ }++ nonisolated func windowWillClose(_ notification: Notification) {+ MainActor.assumeIsolated { releaseControls() }+ }++ override func close() {+ releaseControls()+ super.close()+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swiftindex 01e37035..2c2b3828 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneApplication.swift@@ -37,6 +37,15 @@ final class VPhoneApplication: NSApplication {private static let homeKeyCode: UInt16 = 0x73override func sendEvent(_ event: NSEvent) {+ // The remote's Return/Esc are consumer Select/Menu, including while+ // AppKit would otherwise match the Device menu's bare Escape item.+ if (event.type == .keyDown || event.type == .keyUp),+ event.keyCode != 49, // Space activates the focused native button.+ event.window?.attachedSheet == nil,+ let remote = event.window?.contentView as? VPhoneTVRemoteView,+ remote.handleKey(event, down: event.type == .keyDown) {+ return+ }// While a sheet is up, its keys are its own: Esc must reach its// Cancel button, not the guest's back gesture.guard event.type == .keyDown || event.type == .keyUp || event.type == .flagsChanged,diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 60db9723..2507af8b 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -535,6 +535,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {cameraServer?.disconnect()menuController?.stopBatteryMonitoring()menuController?.guestPanelsWindowController.closeAttitudeDials()+ menuController?.tvRemoteWindowController.close()windowController?.closeForRestart()// Tool windows belong to the old guest connection too.for window in NSApp.windows {diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex 3024c545..cb1148df 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -108,6 +108,9 @@ HOMEPODMISFIX_INPUTS := $(HOMEPODMISFIX_SOURCES) MISFix/MISFixDetour.h MISFix/MIHOMEPODSETUP := $(STAGE)/homepodsetup/vphone-homepod-setupHOMEPODSETUP_SOURCES := $(call find_sources,HomePodSetup)HOMEPODSETUP_INPUTS := $(call find_headers,HomePodSetup) HomePodSetup/com.vphone.homepod-setup.plist+TVSETUPFOCUS := $(STAGE)/tvsetupfocus/libvphonetvsetupfocus.dylib+TVSETUPFOCUS_SOURCES := $(call find_sources,TVSetupFocus)+TVSETUPFOCUS_INPUTS := $(call find_headers,TVSetupFocus) $(call find_folders,TVSetupFocus)GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylibGPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)@@ -141,7 +144,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driverVIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(CRYPTEXSTAGING) $(HOMEPODPERSONA) $(HOMEPODMISFIX) $(HOMEPODSETUP) $(GPU_PLUGIN) $(VIRTIOSOUND)+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(CRYPTEXSTAGING) $(HOMEPODPERSONA) $(HOMEPODMISFIX) $(HOMEPODSETUP) $(TVSETUPFOCUS) $(GPU_PLUGIN) $(VIRTIOSOUND)PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \$(STAGE)/misfix/libmisfix.plistGPU_PROVENANCE := $(STAGE)/gpu/README.md@@ -187,7 +190,7 @@ gpu: $(GPU_PLUGIN)package: all@rm -f $(ARCHIVE)- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay cryptexstaging homepodpersona homepodmisfix homepodsetup gpu virtiosound+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay cryptexstaging homepodpersona homepodmisfix homepodsetup tvsetupfocus gpu virtiosound@echo "Packaged $(ARCHIVE)"test-loader-links:@@ -418,6 +421,13 @@ test-cryptex-staging:-o $(OUT)/CryptexStagingTests Tests/CryptexStagingTests.c -framework CoreFoundation@$(OUT)/CryptexStagingTests+$(TVSETUPFOCUS): $(TVSETUPFOCUS_SOURCES) $(TVSETUPFOCUS_INPUTS)+ @mkdir -p $(STAGE)/tvsetupfocus+ xcrun --sdk appletvos clang -arch arm64e -mtvos-version-min=27.2 -Os -fobjc-arc \+ -Wall -Wextra -Werror -dynamiclib -install_name /usr/lib/libvphonetvsetupfocus.dylib \+ -o $@ $(TVSETUPFOCUS_SOURCES) -framework UIKit -framework Foundation -Wl,-not_for_dyld_shared_cache+ @codesign --force --sign - $@+$(HOMEPODSETUP): $(HOMEPODSETUP_SOURCES) $(HOMEPODSETUP_INPUTS)@mkdir -p $(STAGE)/homepodsetupxcrun --sdk appletvos clang -arch arm64e -mtvos-version-min=27.0 -Os -fobjc-arc \diff --git a/VPhoneGuestComponents/TVSetupFocus/libvphonetvsetupfocus.m b/VPhoneGuestComponents/TVSetupFocus/libvphonetvsetupfocus.mnew file mode 100644index 00000000..cdd0b367--- /dev/null+++ b/VPhoneGuestComponents/TVSetupFocus/libvphonetvsetupfocus.m@@ -0,0 +1,64 @@+#import <UIKit/UIKit.h>+#import <objc/runtime.h>+#import <os/log.h>++@interface UIFocusSystem (VPhoneTVSetupFocus)+- (id)behavior;+- (NSNumber *)_overrideFocusDeferralBehavior;+- (NSInteger)_effectiveFocusDeferralBehavior;+- (void)_setOverrideFocusDeferralBehavior:(NSNumber *)behavior;+@end++static void VPApplyPolicy(UIFocusSystem *changedSystem) {+ Class setupWindow = NSClassFromString(@"Setup.EventDroppingWindow");+ if (!setupWindow) return;+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {+ if (![scene isKindOfClass:UIWindowScene.class] ||+ scene.activationState != UISceneActivationStateForegroundActive) continue;+ for (UIWindow *window in ((UIWindowScene *)scene).windows) {+ if (!window.isKeyWindow || window.hidden || window.alpha <= 0 ||+ ![window isKindOfClass:setupWindow]) continue;+ UIFocusSystem *system = window.windowScene.focusSystem;+ if (!system || (changedSystem && system != changedSystem)) continue;+ if (![NSStringFromClass(object_getClass([system behavior])) isEqualToString:@"_UIFocusBehavior_WaffleIron"] ||+ [system _overrideFocusDeferralBehavior] || [system _effectiveFocusDeferralBehavior] != 3) continue;+ // The new assistant's WaffleIron policy defers focus after 60s.+ // Consumer Select does not restore that deferred target.+ // Use the native TV button-focus policy (TV.focusDeferral == 0).+ // The setter performs UIKit's normal preferred-focus and eligibility+ // checks; Setup's press, drawing, scene and completion logic is intact.+ [system _setOverrideFocusDeferralBehavior:@0];+ os_log(OS_LOG_DEFAULT, "[TVSetupFocus] Enabled native TV button-focus policy");+ }+ }+}++static void VPSchedulePolicy(UIFocusSystem *changedSystem) {+ // A focus-drop notification precedes storage of the deferred target.+ // Recheck current windows after that native update completes.+ dispatch_async(dispatch_get_main_queue(), ^{ VPApplyPolicy(changedSystem); });+}++static void VPInstall(void) {+ Method setter = class_getInstanceMethod(UIFocusSystem.class, @selector(_setOverrideFocusDeferralBehavior:));+ Method override = class_getInstanceMethod(UIFocusSystem.class, @selector(_overrideFocusDeferralBehavior));+ Method effective = class_getInstanceMethod(UIFocusSystem.class, @selector(_effectiveFocusDeferralBehavior));+ Method behavior = class_getInstanceMethod(UIFocusSystem.class, @selector(behavior));+ if (!setter || method_getNumberOfArguments(setter) != 3 || method_getTypeEncoding(setter)[0] != 'v' ||+ !override || method_getTypeEncoding(override)[0] != '@' ||+ !effective || (method_getTypeEncoding(effective)[0] != 'q' && method_getTypeEncoding(effective)[0] != 'Q') ||+ !behavior || method_getTypeEncoding(behavior)[0] != '@') return;+ for (NSNotificationName name in @[UISceneDidActivateNotification, UIWindowDidBecomeKeyNotification, UIFocusDidUpdateNotification]) {+ [NSNotificationCenter.defaultCenter addObserverForName:name object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {+ VPSchedulePolicy([note.name isEqualToString:UIFocusDidUpdateNotification] ? note.object : nil);+ }];+ }+ VPSchedulePolicy(nil);+}++__attribute__((constructor)) static void VPInitialize(void) {+ NSOperatingSystemVersion version = NSProcessInfo.processInfo.operatingSystemVersion;+ if (version.majorVersion != 27 || version.minorVersion != 2 ||+ ![NSBundle.mainBundle.bundleIdentifier isEqualToString:@"com.apple.Setup"]) return;+ dispatch_async(dispatch_get_main_queue(), ^{ VPInstall(); });+}