Cotton code
235 lines · 14.3 KB · SwiftRaw
// The VoiceOver walk over Chat Dev's invented chats: each Warm page is audited// the way Accessibility Inspector audits it (every control named, hit regions,// text that grows with the person's size, nothing clipped), at the default// size and at the largest accessibility size.import XCTestfinal class ChatWarmVoiceOverTests: XCTestCase {    private let asha = "11111111-1111-4111-8111-0000000000a1"    private let hillTrip = "11111111-1111-4111-8111-0000000000b1"    private let ravi = "11111111-1111-4111-8111-0000000000d1"    private func launched(_ extra: [String], large: Bool = false) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-chat-warm-seed", "YES"] + extra        if large { app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"] }        app.launch()        return app    }    /// Audit what stands, ignoring the shell's own cards (the approval and    /// sign-in slips, drawn by the shell for every app) and the Dev build's stamp.    private func audit(_ app: XCUIApplication, _ page: String) throws {        let found = Found()        let types: XCUIAccessibilityAuditType = [.dynamicType, .sufficientElementDescription, .hitRegion, .textClipped, .trait]        // The audit can refuse an app that has only just come up ("Invalid target app"): again, after a moment.        Thread.sleep(forTimeInterval: 2)        for _ in 0..<4 {            do {                try app.performAccessibilityAudit(for: types) { _ in true }                break            } catch {                Thread.sleep(forTimeInterval: 4)            }        }        try app.performAccessibilityAudit(for: types) { issue in            let id = issue.element?.identifier ?? ""            let label = issue.element?.label ?? ""            if id.hasPrefix("shell-") || id.hasPrefix("card-") || label.hasPrefix("Cotton Comms 1.") { return true }            found.lines.append("\(page): \(issue.compactDescription) [\(issue.element?.elementType.rawValue ?? 0)] id=\(id) label=\(label) at \(issue.element?.frame ?? .zero) " + String((issue.element?.debugDescription ?? "").prefix(1200)))            return true        }        for line in found.lines { XCTFail("AUDIT " + line) }    }    // RULE: every Chat page passes the audit at the default size.    func testEveryPageAtTheDefaultSize() throws {        try walk(large: false)    }    // RULE: every Chat page passes the audit at the largest accessibility size.    func testEveryPageAtTheLargestSize() throws {        try walk(large: true)    }    /// One page of the walk: launched with `args`, standing once `standing` does; `then` brings up what is audited    /// (a panel, a scrolled place), standing once `shown` does.    private struct Page {        let name: String        let args: [String]        let standing: String        var then: ((XCUIApplication) -> Void)? = nil        var shown: String? = nil    }    private func tap(_ id: String) -> (XCUIApplication) -> Void {        { app in            let element = app.descendants(matching: .any)[id].firstMatch            for _ in 0..<4 where !element.isHittable { app.swipeUp() }            element.tap()        }    }    /// Taps a voice note's round: the chat is flipped, so a pull down brings it below the header and the "Not on    /// Cotton Comms yet" card (both tall at the largest text), clear of the writing box.    private func play(_ id: String) -> (XCUIApplication) -> Void {        { app in            let round = app.buttons[id]            let table = app.tables["chat-thread"]            func clear() -> Bool {                let reach = app.scrollViews["chat-reach"]                let top = max(app.buttons["chat-back"].frame.maxY, reach.exists ? reach.frame.maxY : 0)                let foot = app.otherElements["chat-composer"].frame.minY                return round.isHittable && round.frame.minY > top + 8 && round.frame.maxY < foot - 8            }            for _ in 0..<8 where !clear() {                let from = table.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))                let down = round.frame.midY < app.windows.firstMatch.frame.midY                from.press(forDuration: 0.05, thenDragTo: from.withOffset(CGVector(dx: 0, dy: down ? 160 : -160)),                           withVelocity: .slow, thenHoldForDuration: 0.3)            }            round.tap()        }    }    private func walk(large: Bool) throws {        let person = ["-chat-warm-open", asha, "-chat-warm-person", "YES"]        let you = ["-chat-warm-place", "you"]        let pages: [Page] = [            Page(name: "chats", args: [], standing: "chat-filter-unread"),            Page(name: "conversation", args: ["-chat-warm-open", asha], standing: "chat-attach"),            // The imported group: Read only, the call line, Picture not available, one picture per run, at the chat's top.            Page(name: "imported group", args: ["-chat-warm-open", hillTrip], standing: "chat-thread", then: { app in                app.tables["chat-thread"].swipeDown(velocity: .slow)                app.tables["chat-thread"].swipeDown(velocity: .slow)            }, shown: "chat-bubble-m-w7"),            // The header over rows scrolled up under it.            Page(name: "scrolled header", args: ["-chat-warm-long", "400", "-chat-warm-open", "chat-warm-long"], standing: "chat-thread", then: { app in                for _ in 0..<3 { app.tables["chat-thread"].swipeDown(velocity: .slow) }            }, shown: "chat-person"),            // The voice player (voice-player.html): Ravi's notes at rest, not played, gone, then one playing, its place            // and its speed their own controls.            Page(name: "voice player", args: ["-chat-warm-open", ravi], standing: "chat-voice-play-m-r3"),            Page(name: "voice player, playing", args: ["-chat-warm-open", ravi], standing: "chat-voice-play-m-r3",                 then: play("chat-voice-play-m-r3"), shown: "chat-voice-speed-m-r3"),            Page(name: "person", args: person, standing: "chat-person-block"),            Page(name: "person's Mute", args: person, standing: "chat-person-mute", then: tap("chat-person-mute"), shown: "chat-person-mute-always"),            // The safety number (CONTRACT.md "Safety number"), opened from the person's page, and after a scan that matched.            Page(name: "safety number", args: person, standing: "chat-person-safety", then: tap("chat-person-safety"), shown: "chat-safety-scan"),            Page(name: "safety number, scanned", args: person + ["-chat-safety-scan", "theirs"], standing: "chat-person-safety", then: { app in                self.tap("chat-person-safety")(app)                _ = app.descendants(matching: .any)["chat-safety-scan"].firstMatch.waitForExistence(timeout: 15)                self.tap("chat-safety-scan")(app)            }, shown: "chat-safety-verified"),            Page(name: "group", args: ["-chat-warm-open", hillTrip, "-chat-warm-person", "YES"], standing: "chat-group-add"),            Page(name: "new", args: ["-chat-warm-new", "YES"], standing: "chat-new-group"),            // You, grouped: the rows, then each page.            Page(name: "you", args: you, standing: "you-row-about"),            Page(name: "you's Profile", args: you + ["-chat-warm-you", "profile"], standing: "you-picture"),            Page(name: "you's Sync", args: you + ["-chat-warm-you", "sync", "-chat-warm-unreachable", "YES"], standing: "you-sync-now"),            Page(name: "you's Claude", args: you + ["-chat-warm-you", "claude"], standing: "you-claude-group-files"),            Page(name: "you's Privacy", args: you + ["-chat-warm-you", "privacy"], standing: "you-safety-line"),            Page(name: "you's Notifications", args: you + ["-chat-warm-you", "notifications"], standing: "you-notifications-phone"),            Page(name: "you's Storage", args: you + ["-chat-warm-you", "storage"], standing: "settings-free-up"),            Page(name: "you's Help", args: you + ["-chat-warm-you", "help"], standing: "you-write-us"),            Page(name: "you's About", args: you + ["-chat-warm-you", "about"], standing: "settings-about-version"),            Page(name: "you's Blocked", args: you + ["-chat-warm-you", "privacy"], standing: "you-blocked", then: tap("you-blocked"), shown: "you-blocked-sheet"),            Page(name: "you's Change picture", args: you + ["-chat-warm-you", "profile"], standing: "you-picture", then: tap("you-picture"), shown: "look-ask-choose"),            Page(name: "you's report", args: you + ["-chat-warm-you", "help"], standing: "settings-share-report", then: tap("settings-share-report"), shown: "settings-report-preview"),            Page(name: "calls", args: ["-chat-warm-place", "calls"], standing: "chat-calls"),            Page(name: "ringing", args: ["-chat-warm-call", "ring"], standing: "chat-call-answer"),            Page(name: "in-call", args: ["-chat-warm-call", "live"], standing: "chat-call-end"),        ]        for page in pages {            let app = launched(page.args, large: large)            defer { app.terminate() }            guard app.descendants(matching: .any)[page.standing].firstMatch.waitForExistence(timeout: 30) else {                XCTFail("\(page.name) did not stand: " + String(app.debugDescription.prefix(4000)))                continue            }            if let then = page.then {                then(app)                if let shown = page.shown, !app.descendants(matching: .any)[shown].firstMatch.waitForExistence(timeout: 10) {                    XCTFail("\(page.name) did not come up: " + String(app.debugDescription.prefix(4000)))                    continue                }                Thread.sleep(forTimeInterval: 0.6)            }            try audit(app, page.name + (large ? " (largest)" : ""))        }    }}extension ChatWarmVoiceOverTests {    /// What VoiceOver reads, in its order: the leaves of the accessibility tree a finger can land on, depth first,    /// those standing on the screen.    fileprivate struct Read { let type: XCUIElement.ElementType; let id: String; let label: String; let frame: CGRect }    @MainActor fileprivate func reading(_ app: XCUIApplication) throws -> [Read] {        let screen = app.windows.firstMatch.frame        let read: Set<XCUIElement.ElementType> = [.button, .staticText, .cell, .image, .textField, .switch, .link, .slider]        var out: [Read] = []        func walk(_ node: XCUIElementSnapshot) {            if read.contains(node.elementType), !node.frame.isEmpty, node.frame.intersects(screen) {                out.append(Read(type: node.elementType, id: node.identifier, label: node.label, frame: node.frame))                if node.elementType != .cell { return }            }            for child in node.children { walk(child) }        }        walk(try app.snapshot())        return out    }    /// Every element read has words; where `first` and `before` are given, each id in `first` is read before the    /// first element whose id begins with `before`.    @MainActor fileprivate func sweep(_ app: XCUIApplication, _ page: String, first: [String] = [], before: String? = nil) throws {        let read = try reading(app)        XCTAssertFalse(read.isEmpty, "\(page): something is read")        for element in read where element.type != .cell && element.label.trimmingCharacters(in: .whitespaces).isEmpty            && !element.id.hasPrefix("shell-") && !element.id.hasPrefix("card-") {            XCTFail("SWEEP \(page): \(element.type.rawValue) id=\(element.id) at \(element.frame) is read with no words")        }        guard let before, let rows = read.firstIndex(where: { $0.id.hasPrefix(before) }) else { return }        for id in first {            guard let at = read.firstIndex(where: { $0.id == id }) else { XCTFail("SWEEP \(page): \(id) is not read"); continue }            XCTAssertLessThan(at, rows, "SWEEP \(page): \(id) is read before the rows: " + read.map { $0.id.isEmpty ? $0.label : $0.id }.prefix(30).joined(separator: " | "))        }    }    // RULE: VoiceOver's walk, Chats, a row, its conversation, its header, the person's page and back: every element    // read has words, and the floating header is read before the conversation's rows, not after them.    @MainActor func testVoiceOverReadsChatInASensibleOrder() throws {        let app = launched([])        let row = app.cells.firstMatch        XCTAssertTrue(row.waitForExistence(timeout: 30))        try sweep(app, "chats", first: ["chat-filter-unread"], before: "chat-row-")        row.tap()        XCTAssertTrue(app.descendants(matching: .any)["chat-attach"].firstMatch.waitForExistence(timeout: 10), "the conversation opened")        Thread.sleep(forTimeInterval: 0.8)        // OPEN: the rows are a UIKit table under the SwiftUI header, and VoiceOver reads them first; neither the        // header declared first nor sort priorities on its layers moved them (the VoiceOver walk, 21 Nov 2026).        XCTExpectFailure("the floating header is read after the conversation's rows", strict: false) {            try? sweep(app, "conversation order", first: ["chat-back", "chat-person"], before: "chat-bubble-")        }        try sweep(app, "conversation")        app.descendants(matching: .any)["chat-person"].firstMatch.tap()        let back = app.descendants(matching: .any)["chat-person-back"].firstMatch        let groupBack = app.descendants(matching: .any)["chat-group-back"].firstMatch        XCTAssertTrue(back.waitForExistence(timeout: 10) || groupBack.exists, "the person's page opened: " + String(app.debugDescription.prefix(2000)))        Thread.sleep(forTimeInterval: 0.8)        try sweep(app, "person")        let firstRead = try reading(app).first        XCTAssertTrue(firstRead?.id == "chat-person-back" || firstRead?.id == "chat-group-back", "the page's Back is read first: \(String(describing: firstRead))")        (back.exists ? back : groupBack).tap()        XCTAssertTrue(app.descendants(matching: .any)["chat-attach"].firstMatch.waitForExistence(timeout: 10), "back to the conversation")        app.descendants(matching: .any)["chat-back"].firstMatch.tap()        XCTAssertTrue(row.waitForExistence(timeout: 10), "back to Chats")        try sweep(app, "chats again")    }}/// What the audit found, gathered from its handler.private final class Found: @unchecked Sendable {    var lines: [String] = []}