Cotton code
212 lines · 11.8 KB · SwiftRaw
// Deleted for everyone in WhatsApp means deleted in Cotton (the owner,// FEEDBACK-3, 23 Nov 2026; CONTRACT.md "Deleted for everyone in WhatsApp",// core b9f13b322f). Over Chat Dev's invented chats (-chat-warm-seed YES, the// core's own answers from write_chat_warm_fixture): in the Book club, a// WhatsApp group, Esha's picture with its words (which Farid's reply quoted),// the person's own message he deleted from WhatsApp and Divya's newest were// each deleted for everyone, and the core's sweep erased them. Each stands// where it was, on its sender's side, as "This message was deleted" in// Comms' deleted look, with no picture; none of their words is drawn// anywhere: not in the chat, not in the reply that quoted one, not in the// list's last line, and search finds nothing by them. Shots wa-deleted-*.import XCTestfinal class ChatWhatsAppDeletedTests: XCTestCase {    private let book = "11111111-1111-4111-8111-0000000000g1"    private static let largestText = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]    /// The deleted messages' words, as the invented chat held them before.    private let gone = ["coffee ring", "walnut cake", "plumber"]    private let deleted = "This message was deleted"    /// The chat's word for the person in a message's spoken line.    private enum ShellWords { static let you = "You" }    /// The Warm ground, by day and by night.    private static let grounds = [[0xFA, 0xF7, 0xF2], [0x17, 0x14, 0x11]]    private static func near(_ a: [Int], _ b: [Int]) -> Bool { zip(a, b).allSatisfy { abs($0 - $1) <= 4 } }    /// The screen's colour at a point.    private static func pixel(_ screenshot: XCUIScreenshot, x: CGFloat, y: CGFloat) -> [Int] {        let image = screenshot.image        guard let cg = image.cgImage else { return [] }        let scale = CGFloat(cg.width) / image.size.width        var bytes = [UInt8](repeating: 0, count: 4)        let context = CGContext(data: &bytes, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4,                                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!        context.draw(cg, in: CGRect(x: -(x * scale).rounded(), y: -(CGFloat(cg.height) - (y * scale).rounded() - 1), width: CGFloat(cg.width), height: CGFloat(cg.height)))        return [Int(bytes[0]), Int(bytes[1]), Int(bytes[2])]    }    override func setUp() {        continueAfterFailure = false        XCUIDevice.shared.orientation = .portrait    }    override func tearDown() {        XCUIDevice.shared.appearance = .light    }    private func keep(_ name: String) {        let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())        shot.name = name        shot.lifetime = .keepAlways        add(shot)    }    @MainActor private func launched(_ extra: [String]) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-chat-warm-seed", "YES"] + extra        app.launch()        return app    }    @MainActor private func bubble(_ id: String, in app: XCUIApplication) -> XCUIElement {        app.descendants(matching: .any)["chat-bubble-\(id)"].firstMatch    }    /// Everything drawn whose words hold `words`.    @MainActor private func holding(_ words: String, in app: XCUIApplication) -> [String] {        let any = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS[c] %@ OR value CONTAINS[c] %@", words, words))        return any.allElementsBoundByIndex.map { "\($0.identifier): \($0.label)" }    }    @MainActor private func bubbles(saying words: String, in app: XCUIApplication) -> [XCUIElement] {        app.descendants(matching: .any)            .matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS %@", "chat-bubble-", words))            .allElementsBoundByIndex    }    @MainActor private func walk(_ extra: [String], _ shots: String) {        // The chat: three deleted, each where it was, in the deleted look; the rest whole.        let app = launched(["-chat-warm-open", book] + extra)        let table = app.tables["chat-thread"]        XCTAssertTrue(table.waitForExistence(timeout: 30), "the Book club opened")        XCTAssertTrue(bubble("m-g4", in: app).waitForExistence(timeout: 10), "his own message that stays")        for _ in 0..<4 { table.swipeDown() }        let first = bubble("m-g1", in: app)        XCTAssertTrue(first.waitForExistence(timeout: 5), "Divya's first stands")        XCTAssertTrue(first.label.contains("Next month: the lighthouse book?"), first.label)        keep("wa-deleted-\(shots)-top")        for _ in 0..<4 { table.swipeUp() }        keep("wa-deleted-\(shots)-foot")        // On its sender's side: his own (said as "You") in his warm block at the right, theirs on the ground at the left.        let width = app.windows.firstMatch.frame.width        let shot = XCUIScreen.main.screenshot()        // At the foot, nothing over them: those whose middle stands between the header and the foot line.        let window = app.windows.firstMatch.frame        let markers = bubbles(saying: deleted, in: app).filter { $0.frame.midY > window.minY + 140 && $0.frame.midY < window.maxY - 120 }        XCTAssertFalse(markers.isEmpty, "the deleted at the foot in view")        // Across the right half at each one's middle: his block covers every point, in its own colour; theirs stand in        // no block, so none of their points is his block's colour (at the largest text their words reach the right too).        let inks = { (marker: XCUIElement) in stride(from: 0.55, through: 0.9, by: 0.05).map { Self.pixel(shot, x: width * $0, y: marker.frame.midY) } }        let his = markers.filter { $0.label.hasPrefix(ShellWords.you) }        var block: [[Int]] = []        for marker in his {            let seen = inks(marker)            XCTAssertFalse(seen.contains { ink in Self.grounds.contains { Self.near($0, ink) } }, "his own stands in his block at the right: \(seen)")            // The block's fill: the colour most of its points show (a point on his words' strokes is not the fill).            if let fill = Dictionary(grouping: seen, by: { $0 }).max(by: { $0.value.count < $1.value.count })?.key { block.append(fill) }        }        for marker in markers where !marker.label.hasPrefix(ShellWords.you) {            let seen = inks(marker)            if block.isEmpty {                XCTAssertTrue(seen.contains { ink in Self.grounds.contains { Self.near($0, ink) } }, "theirs stand on the ground: \(seen)")            } else {                XCTAssertFalse(seen.contains { ink in block.contains { Self.near($0, ink) } }, "theirs stand in no block: \(seen)")            }        }        var marked: [XCUIElement] = []        for _ in 0..<6 {            marked = bubbles(saying: deleted, in: app)            if marked.count >= 3 { break }            table.swipeDown()        }        let all = bubbles(saying: deleted, in: app)        XCTAssertEqual(Set(all.map(\.identifier)).count, 3, "Esha's, his own and Divya's stand deleted")        XCTAssertEqual(all.filter { $0.label.hasPrefix(ShellWords.you) }.count, 1, "one is his own: \(all.map(\.label))")        for words in gone {            XCTAssertEqual(holding(words, in: app), [], "no word of a deleted message is drawn in the chat")        }        // No picture stands in Esha's place: each says only that it was deleted, and holds no picture of its own.        for marker in bubbles(saying: deleted, in: app) {            XCTAssertFalse(marker.label.localizedCaseInsensitiveContains("photo") || marker.label.localizedCaseInsensitiveContains("picture"), "the picture went with it: \(marker.label)")        }        // Farid's reply stands, its quote holding none of Esha's words.        let reply = bubble("m-g3", in: app)        XCTAssertTrue(reply.exists, "Farid's reply stands")        XCTAssertTrue(reply.label.contains("Ha, mine has sand in it"), reply.label)        XCTAssertFalse(reply.label.localizedCaseInsensitiveContains("coffee"), "the quote keeps none of her words: \(reply.label)")        keep("wa-deleted-\(shots)-chat")        // The list: the Book club's last line is the deletion, never Divya's words.        app.buttons["chat-back"].tap()        let row = app.descendants(matching: .any)["chat-row-\(book)"].firstMatch        XCTAssertTrue(row.waitForExistence(timeout: 10), "the Book club in the list")        XCTAssertFalse(row.label.localizedCaseInsensitiveContains("plumber"), "the last line keeps none of her words: \(row.label)")        keep("wa-deleted-\(shots)-list")        // Search: a deleted message's words find nothing; a kept one's still finds the chat.        let search = app.textFields["chat-search"]        XCTAssertTrue(search.waitForExistence(timeout: 5))        for words in gone {            search.tap()            search.typeText(words)            Thread.sleep(forTimeInterval: 1)            XCTAssertFalse(row.exists, "\"\(words)\" finds the Book club nowhere")            XCTAssertEqual(holding(words, in: app).filter { !$0.hasPrefix("chat-search") }, [], "nothing found by \"\(words)\"")            if words == gone.first { keep("wa-deleted-\(shots)-search") }            search.clearAndEnter("")        }        search.tap()        search.typeText("lighthouse")        XCTAssertTrue(row.waitForExistence(timeout: 5), "a kept message's words still find the chat")    }    // RULE (owner, FEEDBACK-3): a WhatsApp message deleted for everyone stands as "This message was deleted" where it    // was, with no picture, and none of its words is drawn in the chat, a quote, the list or search.    @MainActor func testADeletedWhatsAppMessageLeavesNoWords() { walk([], "default") }    // RULE: the same at the largest text.    @MainActor func testADeletedWhatsAppMessageLeavesNoWordsAtTheLargestText() { walk(Self.largestText, "largest") }    // RULE (owner, FEEDBACK-3): deleted while he looks, a message leaves the open chat at once: its words go and the    // marker stands where it stood, below what came before it, with nothing else moving.    @MainActor func testDeletedWhileHeLooksItLeavesInItsPlace() {        let app = launched(["-chat-warm-open", book, "-chat-warm-revoke", "15"])        let table = app.tables["chat-thread"]        XCTAssertTrue(table.waitForExistence(timeout: 30), "the Book club opened")        let before = bubble("m-g4", in: app)        XCTAssertTrue(before.waitForExistence(timeout: 10), "his own message that stays")        let cake = bubble("m-g5", in: app)        XCTAssertTrue(cake.waitForExistence(timeout: 5), "his message stands before the delete")        XCTAssertTrue(cake.label.contains("walnut cake"), cake.label)        keep("wa-deleted-live-before")        // The deletes land while the chat stays open: nothing is tapped, nothing reopened.        let left = expectation(for: NSPredicate(format: "exists == false"), evaluatedWith: cake)        wait(for: [left], timeout: 40)        XCTAssertEqual(holding("walnut cake", in: app), [], "none of its words stays drawn")        let markers = bubbles(saying: deleted, in: app)        XCTAssertFalse(markers.isEmpty, "the marker stands in its place")        XCTAssertTrue(markers.contains { $0.frame.minY >= before.frame.maxY - 1 }, "below what came before it: \(markers.map(\.frame))")        XCTAssertTrue(bubble("m-g4", in: app).exists, "what stayed stays")        keep("wa-deleted-live-after")    }    // RULE: the same at night.    @MainActor func testADeletedWhatsAppMessageLeavesNoWordsAtNight() {        XCUIDevice.shared.appearance = .dark        walk([], "dark")    }}private extension XCUIElement {    /// Empties a field and types `text` into it.    func clearAndEnter(_ text: String) {        tap()        if let held = value as? String, !held.isEmpty {            typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: held.count))        }        if !text.isEmpty { typeText(text) }    }}