import AppKit import Carbon import Foundation import ParcelPlatform import RealityDriverSupport @MainActor func requireVoiceOverOwnership() throws { guard ProcessInfo.processInfo.environment["PARCEL_REALITY_VOICEOVER"] == "1" else { throw RealitySkip("Set PARCEL_REALITY_VOICEOVER=1 to own and restore a temporary VoiceOver session") } try TabViewConsoleSession.requireUnlockedConsole() guard !VoiceOverStatus.isRunning else { throw RealitySkip("VoiceOver is already running; this lane will not change an existing screen-reader session") } guard NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.VoiceOverQuickstart").isEmpty else { throw RealitySkip("An existing VoiceOver first-use assistant is open; this lane will not control it") } } @MainActor func withOwnedVoiceOver(_ session: RealitySession, operation: @MainActor () async throws -> Void) async throws { try requireVoiceOverOwnership() let preference = try VoiceOverPreference() try preference.requireRestorableSession() let configuration = NSWorkspace.OpenConfiguration() configuration.activates = false let voiceOver: NSRunningApplication do { voiceOver = try await NSWorkspace.shared.openApplication( at: URL(fileURLWithPath: "/System/Library/CoreServices/VoiceOver.app"), configuration: configuration) } catch { let launchFailure = error do { try preference.restore() } catch { throw RealityError( "Safety stop: VoiceOver launch failed: \(launchFailure); preference restoration failed: \(error)") } throw launchFailure } do { try await waitForVoiceOver(true) try await operation() } catch { var failure = error do { try encodeJSON( VoiceOverSessionEvidence( ownedPID: voiceOver.processIdentifier, ownedProcessTerminated: voiceOver.isTerminated, ownedProcessFinishedLaunching: voiceOver.isFinishedLaunching, voiceOverRunning: VoiceOverStatus.isRunning, originalPreference: preference.original, frontmostPID: NSWorkspace.shared.frontmostApplication?.processIdentifier, parcelPanels: try FrameOracle.read(allLayers: true, onScreenOnly: true).filter { $0.pid == session.parcel?.processIdentifier }), to: session.directory.appendingPathComponent("voiceover-failure-state.json")) } catch { failure = RealityError("\(failure); VoiceOver failure-state capture failed: \(error)") } do { try await stopOwnedVoiceOver(voiceOver, preference: preference, session: session) } catch { throw RealityError("Safety stop: \(failure); VoiceOver restoration failed: \(error)") } throw failure } try await stopOwnedVoiceOver(voiceOver, preference: preference, session: session) } @MainActor func checkTabViewVoiceOver(_ session: RealitySession) async throws { try requireVoiceOverOwnership() try session.configure() let owned = try await session.startingWindows([.textEdit, .textEdit]) try await session.start() try await session.tiles(owned) let frames = try session.readFrames(owned) try await session.apps.focus(owned[0]) try await withOwnedVoiceOver(session) { let initialIDs = Set(try FrameOracle.read(allLayers: true).filter(\.onscreen).map(\.id)) try TabViewConsoleSession.requireUnlockedConsole() try await session.driver.key(RealityInputDefaults.tabView) guard let parcel = session.parcel else { throw RealityError("No tested Parcel process") } let display = try RealityDisplays.primaryFrame() @MainActor func panelOwnsFocus() throws -> Bool { let rows = try FrameOracle.read(allLayers: true) let currentFrames = try FrameOracle.frames(rows, ids: owned.map(\.id)) return VoiceOverStatus.isRunning && TabViewVoiceOverOracle.panelIsFrontmost( rows, initialIDs: initialIDs, parcelPID: parcel.processIdentifier, display: display, frontmostPID: NSWorkspace.shared.frontmostApplication?.processIdentifier) && currentFrames == frames } try await session.expect("VoiceOver switcher remains open after releasing its opening modifier") { _ in try panelOwnsFocus() } let panelIDs = Set( TabViewRealityOracle.newPanels( try FrameOracle.read(allLayers: true), initialIDs: initialIDs, pid: parcel.processIdentifier, display: display ).map(\.id)) for flags: CGEventFlags in [[], [.maskControl, .maskAlternate]] { for code in [kVK_LeftArrow, kVK_RightArrow, kVK_UpArrow, kVK_DownArrow] { try TabViewConsoleSession.requireUnlockedConsole() let response = try await session.driver.send(.key(virtualKey: UInt16(code), flags: flags.rawValue)) try TabViewVoiceOverOracle.requirePanelReceipt( response, parcelPID: parcel.processIdentifier, panelIDs: panelIDs, virtualKey: UInt16(code)) try await session.expect( "VoiceOver arrow \(code), modifiers \(flags.rawValue), preserves native panel foreground and document frames" ) { _ in try panelOwnsFocus() } } } session.recordExpectation( "Real VoiceOver ran with verified bare and Control-Option arrow receipts; Parcel stayed foreground and document frames stayed unchanged" ) session.recordExpectation( "Owner still validates spoken Quick Nav selection and physical Caps Lock; the driver never toggles Caps Lock" ) try TabViewConsoleSession.requireUnlockedConsole() let cancel = try await session.driver.send(.key(virtualKey: UInt16(kVK_Escape), flags: 0)) try TabViewVoiceOverOracle.requirePanelReceipt( cancel, parcelPID: parcel.processIdentifier, panelIDs: panelIDs, virtualKey: UInt16(kVK_Escape)) try await session.expect("Cancel closes the panel and returns focus to the exact original document") { _ in let rows = try FrameOracle.read(allLayers: true, onScreenOnly: true) return try TabViewVoiceOverOracle.cancelled( rows, initialIDs: initialIDs, parcelPID: parcel.processIdentifier, display: display, frontmostPID: NSWorkspace.shared.frontmostApplication?.processIdentifier, original: owned[0], ownedIDs: owned.map(\.id), frames: frames) } } } enum TabViewVoiceOverOracle { static func requirePanelReceipt( _ response: DriverResponse, parcelPID: Int32, panelIDs: Set, virtualKey: UInt16 ) throws { guard response.error == nil, let receipts = response.input, receipts.count == 1, let receipt = receipts.first, receipt.virtualKey == virtualKey, receipt.target.pid == parcelPID, receipt.target.panel, !receipt.target.fixture, panelIDs.contains(receipt.target.windowID) else { throw RealityError("Safety stop: VoiceOver input lacks an exact observed Parcel panel receipt") } switch receipt.delivery { case .intercepted, .panel, .voiceOverPanel: break default: throw RealityError("Safety stop: VoiceOver panel input has an unverified or unexpected delivery outcome") } } static func panelIsFrontmost( _ rows: [RealWindow], initialIDs: Set, parcelPID: Int32, display: ScreenRect, frontmostPID: Int32? ) -> Bool { frontmostPID == parcelPID && !TabViewRealityOracle.newPanels(rows, initialIDs: initialIDs, pid: parcelPID, display: display).isEmpty } static func cancelled( _ rows: [RealWindow], initialIDs: Set, parcelPID: Int32, display: ScreenRect, frontmostPID: Int32?, original: OwnedWindow, ownedIDs: [UInt32], frames: [ScreenRect] ) throws -> Bool { guard frontmostPID == original.pid, ownedIDs.count == frames.count, rows.first(where: { $0.pid == original.pid && $0.layer == 0 && $0.onscreen })?.id == original.id, TabViewRealityOracle.newPanels(rows, initialIDs: initialIDs, pid: parcelPID, display: display).isEmpty else { return false } return try FrameOracle.frames(rows, ids: ownedIDs) == frames } } @MainActor private func stopOwnedVoiceOver( _ app: NSRunningApplication, preference: VoiceOverPreference, session: RealitySession ) async throws { var inputBalance = RealityInputBalance(baseline: session.inputBaseline) inputBalance.observe(DriverInputState.capture(), stage: "Before owned VoiceOver key release") var releaseFailure: (any Error)? do { _ = try await session.driver.send(.releaseOwnedKeys) } catch { releaseFailure = error } do { let assistants = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.VoiceOverQuickstart") guard assistants.count <= 1 else { throw RealityError("Ambiguous VoiceOver first-use assistant ownership") } for assistant in assistants { guard let launched = assistant.launchDate, let started = app.launchDate, launched >= started else { throw RealityError("Refusing to close a VoiceOver assistant not launched by our session") } try await terminate(assistant) } try await terminate(app) try await waitForVoiceOver(false) try preference.restore() inputBalance.observe(DriverInputState.capture(), stage: "After owned VoiceOver stopped") _ = try await session.driver.send(.releaseOwnedKeys) inputBalance.observe(DriverInputState.capture(), stage: "After final VoiceOver key release") try encodeJSON(inputBalance, to: session.directory.appendingPathComponent("voiceover-input-restoration.json")) try inputBalance.requireRestored() } catch { throw RealityError( "Safety stop: VoiceOver restoration failed: \(error); owned key release failure: \(String(describing: releaseFailure))" ) } if let releaseFailure { throw RealityError("Safety stop: VoiceOver stopped but owned key release failed: \(releaseFailure)") } do { try encodeJSON( [ "voiceOverRestored": true, "preferenceRestored": true, "firstUseAssistantRestored": true, "ownedKeysReleased": true, ], to: session.directory.appendingPathComponent("voiceover-restoration.json")) } catch { throw RealityError("Safety stop: VoiceOver restoration receipt failed: \(error)") } } @MainActor private func waitForVoiceOver(_ enabled: Bool) async throws { let deadline = ContinuousClock.now.advanced(by: .seconds(10)) while VoiceOverStatus.isRunning != enabled { if enabled, !NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.VoiceOverQuickstart").isEmpty { throw RealitySkip( "VoiceOver requires its first-use assistant; complete setup before live keyboard validation") } guard ContinuousClock.now < deadline else { throw RealityError( "VoiceOver did not reach enabled=\(enabled); inspect the owned session before proceeding") } try await Task.sleep(for: .milliseconds(50)) } }