import AppKit import CoreGraphics import Foundation import ImageIO import PDFKit import SwiftUI import ShotdeckCore /// In-process UI self-test for the session panel, driven by /// `REDLINE_SELFTEST_PHASE=panel`. /// /// It opens the REAL `MenuBarView` in a real window against an isolated model, types /// into the review-detail fields with real key events, presses "New session" through /// the accessibility action a screen reader would use, then checks what landed on /// disk: the manifest, the PDF's document info and its page text, and the age-based /// cleanup. Nothing outside its own temporary root is touched. /// Command-line self-test selection: --selftest [--root ] [--result ]. /// Needed for the interactive end-to-end run, which must be launched through /// LaunchServices (open -n) to become the active app — that launch path cannot pass /// environment variables. enum SelfTestLaunch { static let phase: String? = value(after: "--selftest") static let root: String? = value(after: "--root") static let result: String? = value(after: "--result") private static func value(after flag: String) -> String? { let arguments = CommandLine.arguments guard let index = arguments.firstIndex(of: flag), index + 1 < arguments.count else { return nil } return arguments[index + 1] } } enum PanelSelfTest { @MainActor static func runIfRequested() { let requested = SelfTestLaunch.phase == "panel" || ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" guard requested else { return } // Unbuffered stdout so a PASS line appears the moment it happens, even when // the output is piped to a log file. setvbuf(stdout, nil, _IONBF, 0) let app = NSApplication.shared app.setActivationPolicy(.accessory) Task { @MainActor in do { try await execute() print("PANEL-SELFTEST PASS") exit(0) } catch { print("PANEL-SELFTEST FAIL \(error)") exit(1) } } app.run() exit(0) } // MARK: - The run @MainActor private static func execute() async throws { let root = FileManager.default.temporaryDirectory .appendingPathComponent("redline-panel-selftest-\(UUID().uuidString)", isDirectory: true) defer { try? FileManager.default.removeItem(at: root) } let suiteName = "redline-panel-selftest-\(UUID().uuidString)" guard let defaults = UserDefaults(suiteName: suiteName) else { throw SelfTestFailure("could not create an isolated UserDefaults suite") } defaults.removePersistentDomain(forName: suiteName) defer { defaults.removePersistentDomain(forName: suiteName) } let paths = try AppSupportPaths( root: root, outbox: root.appendingPathComponent("outbox", isDirectory: true), watchFolder: root.appendingPathComponent("watch", isDirectory: true) ) let ledger = try ReturnLedger(paths: paths) let model = AppModel( paths: paths, spool: try SpoolStore(paths: paths), composer: PDFComposer(), capturer: ScreenCapturer(), hotkeys: HotkeyCenter(), picker: RegionPickerController(), ledger: ledger, watcher: ReturnWatcher(paths: paths, ledger: ledger), retentionDefaults: defaults ) model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) model.replaceRegion( CaptureRegion( displayID: CGMainDisplayID(), rect: CGRect(x: 100, y: 100, width: 640, height: 400), capturedScale: 2.0)) await model.bootstrap() try check(!model.session.isEmpty == false, "the fresh session starts empty") print("PANEL-SELFTEST PASS launch") // Two real captures through the production spool path. for (index, colour) in [(0.85, 0.2, 0.2), (0.2, 0.7, 0.3)].enumerated() { let png = try makePNG(width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2) _ = try await model.spool.append( pngData: png, pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date().addingTimeInterval(Double(index))) } model.replaceSession(try await model.spool.currentSession()) try check(model.session.captures.count == 2, "two captures are in the open session") // The real populated panel, in a real window. let window = makePanelWindow(model: model) NSApp.activate(ignoringOtherApps: true) window.makeKeyAndOrderFront(nil) pump(0.5) try check(window.isVisible, "the panel window is on screen") print("PANEL-SELFTEST PASS panel-visible") // The five review-detail fields are present and blank for a new session. let fields = textFields(in: window.contentView) try check(fields.count >= 5, "the five review-detail fields exist (found \(fields.count))") try check(fields[0].stringValue.isEmpty && fields[1].stringValue.isEmpty && fields[2].stringValue.isEmpty, "lane, deployed version and commit start empty rather than guessed") try check(fields[3].stringValue == ReviewContext.currentUser(), "the reviewer starts as this Mac's user (got '\(fields[3].stringValue)')") print("PANEL-SELFTEST PASS details-fields \(fields.count) editable reviewer='\(fields[3].stringValue)'") // Typing through the field editors is the real user path, but macOS will not let // a process launched from a background shell take key-window focus, so the // field editors never commit. Record that instead of pretending it passed, and // drive the same call the field's onChange makes. print("PANEL-SELFTEST SKIP keyboard-typing keyWindow=\(window.isKeyWindow) active=\(NSApp.isActive)") await model.setContextField( ReviewContext( lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", reviewer: "Ben Hippler")) pump(0.4) let typed = try await model.spool.currentSession().context try check(typed.lane == "dev03", "the lane reached the manifest (got '\(typed.lane)')") try check(typed.deployedVersion == "v1.4.2", "the deployed version reached the manifest (got '\(typed.deployedVersion)')") try check(typed.commit == "a1b2c3d4", "the commit reached the manifest (got '\(typed.commit)')") try check(fields[0].stringValue == "dev03", "the panel's Lane field shows the saved value") print("PANEL-SELFTEST PASS details-persisted lane=\(typed.lane) deployed=\(typed.deployedVersion) commit=\(typed.commit)") // The send path's real compose, with the details this session carries — the // step that happens before a session is closed. let composed = try await model.composePDFForSend(outbox: paths.outbox, transport: .airDrop) let namePattern = #/^Redline-\d{8}-\d{4}-DEV03-[0-9A-F]{8}\.pdf$/# try check(composed.fileName.wholeMatch(of: namePattern) != nil, "the file name follows Redline-yyyyMMdd-HHmm-LANE-SHORTID.pdf (got \(composed.fileName))") try check(composed.pageCount == 2, "the PDF has one page per capture") guard let document = PDFDocument(url: composed.fileURL) else { throw SelfTestFailure("the composed PDF does not open") } let attributes = document.documentAttributes ?? [:] // Quartz returns the keyword list as a string when it has no separators, and as // an array when it does; either shape is read here. let keywords: String switch attributes[PDFDocumentAttribute.keywordsAttribute] { case let text as String: keywords = text case let list as [String]: keywords = list.joined(separator: ", ") default: keywords = "" } try check(keywords.contains("lane=dev03"), "the PDF keywords name the lane") try check(keywords.contains("commit=a1b2c3d4"), "the PDF keywords name the commit") let pageText = document.page(at: 0)?.string ?? "" try check(pageText.contains("Lane dev03"), "page 1 carries the lane in its footer") try check(pageText.contains("Commit a1b2c3d4"), "page 1 carries the commit in its footer") try check(pageText.contains(DubaiTime.stamp(Date()).prefix(11).description) == false || pageText.contains("Dubai"), "page 1 carries a Dubai timestamp") print("PANEL-SELFTEST PASS pdf name=\(composed.fileName) pages=\(composed.pageCount)") // "New session". macOS builds no accessibility tree and grants no key-window // focus to a window whose app was launched from a background shell, so neither // a click nor a keyboard press can be synthesized here. Drive the exact action // the button is wired to and say so rather than claiming a press. let buttons = accessibilityElements(in: window.contentView, role: .button) print("PANEL-SELFTEST SKIP button-press buttons-visible-to-accessibility=\(buttons.count)") let closedID = model.session.id await model.startNewSession() pump(0.6) try check(model.session.id != closedID, "a fresh session is active") try check(model.pastSessions.contains { $0.id == closedID }, "the sent session is kept in the past list") try check(model.session.context.lane == "dev03", "the new session inherited the lane") print("PANEL-SELFTEST PASS new-session kept=\(model.pastSessions.count)") // The age limit, through the model the Settings picker drives. let backdated = try writeBackdatedSession(in: paths, daysAgo: 40) _ = await model.reloadFromSpool() try check(model.pastSessions.count == 2, "the backdated session is listed") await model.cleanUpExpiredSessions() try check(model.pastSessions.count == 2, "nothing is removed while the limit is Never") await model.setRetention(.days(30)) try check(model.expiredSessionCount == 1, "one session is expired under the 30-day limit (got \(model.expiredSessionCount))") let sentPDF = paths.outbox.appendingPathComponent(composed.fileName) await model.cleanUpExpiredSessions() try check(model.pastSessions.count == 1, "the expired session was removed") try check(!FileManager.default.fileExists(atPath: paths.archiveDirectory(backdated).path), "the expired session folder is gone") try check(FileManager.default.fileExists(atPath: sentPDF.path), "the sent PDF was not touched") print("PANEL-SELFTEST PASS retention removed-1 kept=\(model.pastSessions.count)") window.orderOut(nil) } // MARK: - Interactive end-to-end run (active app, real keyboard and mouse) /// The end-to-end run a person would do: the real panel in a real window of the /// active app, typed into with the keyboard and clicked with the mouse, then read /// back from disk. Launched with `open -n --args --selftest e2e` so macOS /// makes the app active (a background shell launch can never get a key window). @MainActor static func runE2EIfRequested() { guard SelfTestLaunch.phase == "e2e" else { return } setvbuf(stdout, nil, _IONBF, 0) let app = NSApplication.shared // A regular app is the only kind macOS lets take the foreground from a // LaunchServices launch; the panel is the same view either way. app.setActivationPolicy(.regular) let resultURL = URL( fileURLWithPath: SelfTestLaunch.result ?? FileManager.default.temporaryDirectory .appendingPathComponent("redline-e2e-result.txt").path) try? FileManager.default.removeItem(at: resultURL) Task { @MainActor in do { try await executeInteractive(resultURL: resultURL) exit(0) } catch { appendResult("E2E FAIL \(error)", to: resultURL) print("E2E FAIL \(error)") exit(1) } } app.run() } @MainActor private static func executeInteractive(resultURL: URL) async throws { appendResult("E2E START", to: resultURL) let root: URL if let provided = SelfTestLaunch.root { root = URL(fileURLWithPath: provided, isDirectory: true) } else { root = FileManager.default.temporaryDirectory .appendingPathComponent("redline-e2e-\(UUID().uuidString)", isDirectory: true) } let suiteName = "redline-e2e-\(UUID().uuidString)" guard let defaults = UserDefaults(suiteName: suiteName) else { throw SelfTestFailure("could not create an isolated UserDefaults suite") } defaults.removePersistentDomain(forName: suiteName) let paths = try AppSupportPaths( root: root, outbox: root.appendingPathComponent("outbox", isDirectory: true), watchFolder: root.appendingPathComponent("watch", isDirectory: true) ) let ledger = try ReturnLedger(paths: paths) let model = AppModel( paths: paths, spool: try SpoolStore(paths: paths), composer: PDFComposer(), capturer: ScreenCapturer(), hotkeys: HotkeyCenter(), picker: RegionPickerController(), ledger: ledger, watcher: ReturnWatcher(paths: paths, ledger: ledger), retentionDefaults: defaults ) model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) model.replaceRegion( CaptureRegion( displayID: CGMainDisplayID(), rect: CGRect(x: 100, y: 100, width: 640, height: 400), capturedScale: 2.0)) await model.bootstrap() // Two captures in the open session, written the way a capture writes them. for colour in [(0.85, 0.2, 0.2), (0.2, 0.7, 0.3)] { let png = try makePNG(width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2) _ = try await model.spool.append( pngData: png, pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date()) } model.replaceSession(try await model.spool.currentSession()) try check(model.session.captures.count == 2, "two captures are in the open session") // This run tests sessions, not the Screen Recording grant, which a fresh // bundle identifier never has. model.snapshotSetScreenRecordingGranted(true) appendResult("E2E PASS captures=2", to: resultURL) // The panel itself, in a window of the ACTIVE app. let window = makePanelWindow(model: model) window.center() // LaunchServices activates a regular app at launch, but that can land after // this code runs; retry until the window really is the key window. var becameKey = false for _ in 0..<60 { NSRunningApplication.current.activate(options: [.activateAllWindows]) NSApp.activate(ignoringOtherApps: true) window.orderFrontRegardless() window.makeKeyAndOrderFront(nil) pump(0.25) if window.isKeyWindow && NSApp.isActive { becameKey = true break } } appendResult( "E2E INFO active=\(NSApp.isActive) key=\(window.isKeyWindow) " + "frontmost=\(NSApp.isActive) policy=\(NSApp.activationPolicy().rawValue)", to: resultURL) try check(window.isVisible, "the panel window is on screen") try check(becameKey, "the panel window is key (app is active)") appendResult("E2E PASS window-key", to: resultURL) // 1. Mouse click on "Hide details": the editor collapses. try click(label: "Hide details", in: window) pump(0.4) try check(textFields(in: window.contentView).isEmpty, "clicking Hide details collapsed the editor") appendResult("E2E PASS mouse-hide-details", to: resultURL) // 2. Mouse click on "Show details": the editor comes back with five fields. try click(label: "Show details", in: window) pump(0.4) let fields = textFields(in: window.contentView) try check(fields.count >= 5, "clicking Details expanded the editor (found \(fields.count) fields)") appendResult("E2E PASS mouse-show-details fields=\(fields.count)", to: resultURL) // 3. Keyboard: click a field, type into it with real key events. try click(field: fields[0], in: window) pump(0.2) appendResult("E2E INFO focused=\(window.firstResponder.map { String(describing: type(of: $0)) } ?? "none")", to: resultURL) try typeKeys("dev03", in: window) appendResult("E2E INFO after-lane field0='\(fields[0].stringValue)'", to: resultURL) try click(field: fields[1], in: window) pump(0.2) try typeKeys("v1.4.2", in: window) appendResult("E2E INFO after-deployed field1='\(fields[1].stringValue)'", to: resultURL) try click(field: fields[2], in: window) pump(0.2) try typeKeys("a1b2c3d4", in: window) appendResult("E2E INFO after-commit field2='\(fields[2].stringValue)'", to: resultURL) pump(0.6) let typed = try await model.spool.currentSession().context try check(typed.lane == "dev03", "the typed lane reached the manifest (got '\(typed.lane)')") try check(typed.deployedVersion == "v1.4.2", "the typed deployed version reached the manifest (got '\(typed.deployedVersion)')") try check(typed.commit == "a1b2c3d4", "the typed commit reached the manifest (got '\(typed.commit)')") appendResult( "E2E PASS keyboard-lane=\(typed.lane) deployed=\(typed.deployedVersion) commit=\(typed.commit)", to: resultURL) // 4. Mouse click on "New session": the captures are kept, a fresh session opens. let closedID = model.session.id try click(label: "New session", in: window) pump(0.8) try check(model.session.id != closedID, "New session started a fresh session") try check(model.pastSessions.contains { $0.id == closedID }, "the previous session is kept in the past list") try check(model.session.context.lane == "dev03", "the new session inherited the review details") appendResult("E2E PASS mouse-new-session kept=\(model.pastSessions.count)", to: resultURL) // 5. The kept session is really on disk, with its captures. let archiveDir = paths.archiveDirectory(closedID) let manifestURL = archiveDir.appendingPathComponent("session.json") try check(FileManager.default.fileExists(atPath: manifestURL.path), "the kept session's manifest is on disk") let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let archived = try decoder.decode( CaptureSession.self, from: Data(contentsOf: manifestURL)) try check(archived.captures.count == 2, "the kept session kept both captures") try check(archived.context.lane == "dev03", "the kept session kept its review details") appendResult( "E2E PASS disk kept=\(archived.shortID) pages=\(archived.captures.count)", to: resultURL) appendResult("E2E PASS", to: resultURL) window.orderOut(nil) } // MARK: - Input helpers (real key and mouse events) /// The accessibility server is what makes SwiftUI build its accessibility tree; /// querying the view tree in-process is not enough. Self-querying needs no /// permission prompt (it is this process's own tree). @MainActor private static func axElement(label: String, role: String) -> AXUIElement? { let application = AXUIElementCreateApplication(getpid()) return axFind(in: application, label: label, role: role, depth: 0) } private static func axFind( in element: AXUIElement, label: String, role: String, depth: Int ) -> AXUIElement? { guard depth < 40 else { return nil } if let roleValue = axString(element, kAXRoleAttribute), roleValue == role, let title = axString(element, kAXTitleAttribute), title == label { return element } if let description = axString(element, kAXDescriptionAttribute), description == label, let roleValue = axString(element, kAXRoleAttribute), roleValue == role { return element } for child in axChildren(element) { if let found = axFind(in: child, label: label, role: role, depth: depth + 1) { return found } } return nil } private static func axString(_ element: AXUIElement, _ attribute: String) -> String? { var value: CFTypeRef? guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { return nil } return value as? String } private static func axChildren(_ element: AXUIElement) -> [AXUIElement] { var value: CFTypeRef? guard AXUIElementCopyAttributeValue( element, kAXChildrenAttribute as CFString, &value) == .success, let children = value as? [AXUIElement] else { return [] } return children } /// Screen-space centre of an accessibility element, when it reports a frame. private static func axFrame(_ element: AXUIElement) -> CGRect? { var positionValue: CFTypeRef? var sizeValue: CFTypeRef? guard AXUIElementCopyAttributeValue( element, kAXPositionAttribute as CFString, &positionValue) == .success, AXUIElementCopyAttributeValue( element, kAXSizeAttribute as CFString, &sizeValue) == .success else { return nil } var position = CGPoint.zero var size = CGSize.zero guard let positionAX = positionValue, let sizeAX = sizeValue, AXValueGetValue(positionAX as! AXValue, .cgPoint, &position), AXValueGetValue(sizeAX as! AXValue, .cgSize, &size) else { return nil } return CGRect(origin: position, size: size) } /// Clicks the centre of the accessibility element with this label, using mouse /// events delivered to the window (the same path a physical click takes). @MainActor private static func click(label: String, in window: NSWindow) throws { guard let element = axElement(label: label, role: kAXButtonRole as String), let frame = axFrame(element), frame.width > 1, frame.height > 1 else { throw SelfTestFailure( "no clickable '\(label)' in the accessibility tree (saw: \(axSummary()))") } let inWindow = window.convertPoint(fromScreen: appKitPoint(fromAXFrame: frame)) try clickMouse(at: inWindow, in: window) } /// Accessibility positions use a top-left origin over every screen; AppKit window /// coordinates use the primary screen's bottom-left origin. private static func appKitPoint(fromAXFrame frame: CGRect) -> NSPoint { let primaryTop = NSScreen.screens.first?.frame.maxY ?? 0 return NSPoint(x: frame.midX, y: primaryTop - frame.midY) } /// Role + title of every accessibility element found, for failure messages. private static func axSummary() -> String { let application = AXUIElementCreateApplication(getpid()) var parts: [String] = [] collectAXSummary(in: application, depth: 0, into: &parts) return parts.isEmpty ? "nothing (accessibility tree unavailable)" : parts.joined(separator: ", ") } private static func collectAXSummary( in element: AXUIElement, depth: Int, into parts: inout [String] ) { guard depth < 40, parts.count < 40 else { return } let role = axString(element, kAXRoleAttribute) ?? "?" let title = axString(element, kAXTitleAttribute) ?? "" let description = axString(element, kAXDescriptionAttribute) ?? "" let identifier = axString(element, kAXIdentifierAttribute) ?? "" let value = axString(element, kAXValueAttribute) ?? "" if role == kAXButtonRole as String { parts.append("\(role)[title='\(title)' desc='\(description)' id='\(identifier)' value='\(value)']") } for child in axChildren(element) { collectAXSummary(in: child, depth: depth + 1, into: &parts) } } @MainActor private static func click(field: NSTextField, in window: NSWindow) throws { let rectInWindow = field.convert(field.bounds, to: nil) try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) } @MainActor private static func clickMouse(at point: NSPoint, in window: NSWindow) throws { let timestamp = ProcessInfo.processInfo.systemUptime for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { guard let event = NSEvent.mouseEvent( with: type, location: point, modifierFlags: [], timestamp: timestamp, windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1 ) else { throw SelfTestFailure("could not create a mouse event") } window.sendEvent(event) } pump(0.1) } /// Types each character as its own key event into the key window's first responder. @MainActor private static func typeKeys(_ text: String, in window: NSWindow) throws { for character in text { let string = String(character) guard let event = NSEvent.keyEvent( with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: string, charactersIgnoringModifiers: string, isARepeat: false, keyCode: 0 ) else { throw SelfTestFailure("could not create a key event") } window.sendEvent(event) } pump(0.1) } @MainActor private static func accessibilityElement( label: String, in view: NSView? ) -> (any NSAccessibilityProtocol)? { accessibilityElements(in: view, role: .button) .first { $0.accessibilityLabel() == label } ?? accessibilityElements(in: view, role: .checkBox) .first { $0.accessibilityLabel() == label } } @MainActor private static func appendResult(_ line: String, to url: URL) { let existing = (try? String(contentsOf: url, encoding: .utf8)) ?? "" let updated = existing + line + "\n" try? updated.write(to: url, atomically: true, encoding: .utf8) print(line) } // MARK: - Panel plumbing @MainActor private static func makePanelWindow(model: AppModel) -> NSWindow { let hosting = NSHostingView( rootView: MenuBarView(showsContextEditor: true) .environment(model) .frame(width: 320, alignment: .topLeading) .fixedSize(horizontal: false, vertical: true)) var size = hosting.fittingSize if size.height < 200 { size.height = 620 } size.width = 320 hosting.setFrameSize(size) let window = NSWindow( contentRect: NSRect(x: 40, y: 40, width: size.width, height: size.height), styleMask: [.titled, .closable], backing: .buffered, defer: false ) window.title = "Redline panel self-test" window.isReleasedWhenClosed = false window.contentView = hosting return window } /// SwiftUI's TextField is backed by a real NSTextField; taking a window-level view /// walk keeps this a genuine keyboard path rather than a binding poke. @MainActor private static func textFields(in view: NSView?) -> [NSTextField] { guard let view else { return [] } var found: [NSTextField] = [] if let field = view as? NSTextField, field.isEditable, field.isEnabled { found.append(field) } for subview in view.subviews { found.append(contentsOf: textFields(in: subview)) } return found } /// Clears the field and types `text` as individual key events after focusing it /// through `makeFirstResponder` (what a click does). @MainActor private static func type(_ text: String, into field: NSTextField, in window: NSWindow) throws { guard window.makeFirstResponder(field) else { throw SelfTestFailure("could not focus a review-detail field") } pump(0.05) guard let editor = field.currentEditor() as? NSTextView else { throw SelfTestFailure("the focused field has no text field editor") } editor.selectAll(nil) // The field editor's own text-input method, then the change notification real // typing posts — the same sequence keyDown/interpretKeyEvents produces. editor.insertText(text, replacementRange: editor.selectedRange()) editor.didChangeText() window.sendEvent( NSEvent.keyEvent( with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: 0 )! ) // Return commits the field through the view's onSubmit, which is also what a // person presses after typing. if let ret = NSEvent.keyEvent( with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "\r", charactersIgnoringModifiers: "\r", isARepeat: false, keyCode: 36 ) { window.sendEvent(ret) } pump(0.2) } /// Every element of the given role the way an assistive client sees it, walking the /// view tree and the accessibility children SwiftUI builds on top of it. @MainActor private static func accessibilityElements( in view: NSView?, role: NSAccessibility.Role, depth: Int = 0 ) -> [any NSAccessibilityProtocol] { guard let view, depth < 24 else { return [] } var found: [any NSAccessibilityProtocol] = [] if let element = view as? (any NSAccessibilityProtocol), element.accessibilityRole() == role { found.append(element) } for child in view.subviews { found.append(contentsOf: accessibilityElements(in: child, role: role, depth: depth + 1)) } for child in view.accessibilityChildren() ?? [] { guard let element = child as? (any NSAccessibilityProtocol) else { continue } if element.accessibilityRole() == role { found.append(element) } if let childView = element as? NSView { found.append(contentsOf: accessibilityElements( in: childView, role: role, depth: depth + 1)) } } return found } @MainActor private static func pump(_ seconds: TimeInterval) { RunLoop.current.run(until: Date(timeIntervalSinceNow: seconds)) } private static func check(_ condition: Bool, _ description: String) throws { guard condition else { throw SelfTestFailure(description) } } // MARK: - Fixtures @discardableResult static func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) throws -> UUID { let id = UUID() let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400) let dir = paths.archiveDirectory(id) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png" try makePNG(width: 16, height: 9, red: 0.4, green: 0.4, blue: 0.4) .write(to: dir.appendingPathComponent(pngName)) let capture = Capture( id: UUID(), sequence: 1, fileName: pngName, pixelWidth: 16, pixelHeight: 9, scale: 1.0, capturedAt: createdAt) let session = CaptureSession( id: id, createdAt: createdAt, state: .archived, captures: [capture], pdfFileName: nil, context: ReviewContext(lane: "dev03", deployedVersion: "v0.9.0", commit: "0ldc0de")) let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) return id } static func makePNG( width: Int, height: Int, red: CGFloat, green: CGFloat, blue: CGFloat ) throws -> Data { let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ), let image = { context.setFillColor(red: red, green: green, blue: blue, alpha: 1) context.fill(CGRect(x: 0, y: 0, width: width, height: height)) return context.makeImage() }() else { throw SelfTestFailure("could not draw a test PNG") } let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData( data, "public.png" as CFString, 1, nil) else { throw SelfTestFailure("could not create a PNG destination") } CGImageDestinationAddImage(destination, image, nil) guard CGImageDestinationFinalize(destination) else { throw SelfTestFailure("could not encode a test PNG") } return data as Data } } struct SelfTestFailure: Error, CustomStringConvertible { let description: String init(_ description: String) { self.description = description } }