Cotton code
216 lines · 12.0 KB · SwiftRaw
// Storage by chat (the owner's iPhone, Comms build 23, 23 Nov 2026, item 4;// CONTRACT.md "Storage by chat"). Under Storage's totals, one list of chats,// largest first, each with what it keeps on this phone; a tap opens its// breakdown (only the kinds it holds), then Free this chat, which takes only// that chat's files safe in the account and keeps every preview.//// Chat Dev's invented chats (-chat-warm-seed YES) answer the core's own// `chat.storage` over invented files of known sizes (chat-warm.json's// `storage`, written by `write_chat_warm_fixture`): Asha's chat (photos and a// video), the Hill trip (photos and a file), Meera's chat (a photo, a file,// and a voice message not synced yet). At the default text size and the largest.import XCTestfinal class ChatStorageByChatTests: XCTestCase {    private let asha = "11111111-1111-4111-8111-0000000000a1"    private let hill = "11111111-1111-4111-8111-0000000000b1"    private let meera = "11111111-1111-4111-8111-0000000000e1"    private static let largest = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]    override func setUp() { continueAfterFailure = false }    @MainActor private func launched(_ extra: [String] = [], large: Bool) -> XCUIApplication {        let app = XCUIApplication()        app.launchArguments += ["-chat-warm-seed", "YES", "-chat-warm-place", "you", "-chat-warm-you", "storage"] + extra + (large ? Self.largest : [])        app.launch()        return app    }    @MainActor private func id(_ app: XCUIApplication, _ identifier: String) -> XCUIElement {        app.descendants(matching: .any).matching(identifier: identifier).firstMatch    }    @MainActor private func reach(_ element: XCUIElement, in app: XCUIApplication) {        for _ in 0..<14 where !element.isHittable { app.swipeUp(velocity: .slow) }    }    @MainActor private func keep(_ name: String) {        let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())        shot.name = name        shot.lifetime = .keepAlways        add(shot)    }    private func size(_ large: Bool) -> String { large ? "largest" : "default" }    /// "19 MB", "0.3 MB", "1.3 GB" as bytes, near enough to compare.    private func bytes(_ said: String) -> Double? {        let words = said.split(separator: " ")        guard let number = words.first.flatMap({ Double($0) }), words.count > 1 else { return nil }        return number * (words[1].hasPrefix("GB") ? 1e9 : 1e6)    }    // MARK: the list    @MainActor private func largestFirst(large: Bool) {        let app = launched(large: large)        XCTAssertTrue(id(app, "you-storage-total").waitForExistence(timeout: 60), "Storage's totals stand")        let first = id(app, "you-storage-chat-\(asha)")        XCTAssertTrue(first.waitForExistence(timeout: 30), "the chats stand under the totals")        XCTAssertGreaterThan(first.frame.minY, id(app, "settings-storage-files").frame.maxY, "under the totals")        let rows = [asha, hill, meera].map { id(app, "you-storage-chat-\($0)") }        var above = -Double.infinity, larger = Double.infinity        for row in rows {            XCTAssertTrue(row.exists, row.identifier)            XCTAssertGreaterThan(Double(row.frame.minY), above, "\(row.label) stands below the one before")            above = Double(row.frame.minY)            let said = String(row.label.split(separator: ",").last ?? "").trimmingCharacters(in: .whitespaces)            let measured = try! XCTUnwrap(bytes(said), row.label)            XCTAssertLessThanOrEqual(measured, larger, "largest first: \(row.label)")            larger = measured        }        XCTAssertTrue(rows[0].label.hasPrefix("Asha Verma, "), rows[0].label)        XCTAssertTrue(rows[1].label.hasPrefix("Hill trip, "), rows[1].label)        XCTAssertTrue(rows[2].label.hasPrefix("Meera Iyer, "), rows[2].label)        XCTAssertFalse(id(app, "you-storage-chat-11111111-1111-4111-8111-0000000000d1").exists, "Ravi's chat keeps nothing here: not listed")        reach(rows[0], in: app)        keep("storage-chat-list-\(size(large))")    }    @MainActor func testTheListIsLargestFirst() { largestFirst(large: false) }    @MainActor func testTheListIsLargestFirstAtTheLargestText() { largestFirst(large: true) }    // MARK: one chat    @MainActor private func onlyItsKinds(large: Bool) {        let app = launched(large: large)        let row = id(app, "you-storage-chat-\(asha)")        XCTAssertTrue(row.waitForExistence(timeout: 60))        reach(row, in: app)        row.tap()        XCTAssertTrue(id(app, "you-storage-chat-page").waitForExistence(timeout: 10), "Asha's breakdown opens")        XCTAssertTrue(id(app, "you-storage-chat-photos").exists, "photos")        XCTAssertTrue(id(app, "you-storage-chat-videos").exists, "a video")        XCTAssertFalse(id(app, "you-storage-chat-voice").exists, "no voice message in Asha's chat: not said")        XCTAssertFalse(id(app, "you-storage-chat-files").exists, "no file in Asha's chat: not said")        keep("storage-chat-asha-\(size(large))")        id(app, "you-storage-chat-page-back").tap()        let meeras = id(app, "you-storage-chat-\(meera)")        XCTAssertTrue(meeras.waitForExistence(timeout: 10), "Back returns to the list")        reach(meeras, in: app)        meeras.tap()        XCTAssertTrue(id(app, "you-storage-chat-page").waitForExistence(timeout: 10), "Meera's breakdown opens")        for kind in ["photos", "voice", "files"] {            XCTAssertTrue(id(app, "you-storage-chat-\(kind)").exists, "Meera's chat holds \(kind)")        }        XCTAssertFalse(id(app, "you-storage-chat-videos").exists, "no video in Meera's chat: not said")        let free = id(app, "you-storage-chat-free")        reach(free, in: app)        XCTAssertTrue(free.isHittable, "Free this chat")        XCTAssertEqual(free.label, "Free this chat")        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH 'Frees ' AND label CONTAINS 'Previews stay'")).firstMatch.exists, "the line says what stays")        keep("storage-chat-meera-\(size(large))")    }    @MainActor func testABreakdownShowsOnlyTheKindsItHolds() { onlyItsKinds(large: false) }    @MainActor func testABreakdownShowsOnlyTheKindsItHoldsAtTheLargestText() { onlyItsKinds(large: true) }    // MARK: Free this chat    /// Whether `ink` is the empty tile's own ground (#F0EBE3 by day): a blank box.    private func blank(_ ink: [Int]) -> Bool {        abs(ink[0] - 0xF0) < 8 && abs(ink[1] - 0xEB) < 8 && abs(ink[2] - 0xE3) < 8    }    private func ink(at point: CGPoint) -> [Int] {        let image = XCUIScreen.main.screenshot().image        let cg = image.cgImage!        let scale = CGFloat(cg.width) / image.size.width        var bytes = [UInt8](repeating: 0, count: cg.width * cg.height * 4)        let context = CGContext(data: &bytes, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: cg.width * 4,                                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!        context.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height))        let x = min(cg.width - 1, max(0, Int(point.x * scale))), y = min(cg.height - 1, max(0, Int(point.y * scale)))        let i = (y * cg.width + x) * 4        return [Int(bytes[i]), Int(bytes[i + 1]), Int(bytes[i + 2])]    }    @MainActor private func freeLowersAndKeepsPreviews(large: Bool) {        let app = launched(large: large)        let row = id(app, "you-storage-chat-\(meera)")        XCTAssertTrue(row.waitForExistence(timeout: 60))        reach(row, in: app)        let listed = try! XCTUnwrap(bytes(String(row.label.split(separator: ",").last ?? "").trimmingCharacters(in: .whitespaces)), row.label)        row.tap()        let total = id(app, "you-storage-chat-total")        XCTAssertTrue(total.waitForExistence(timeout: 10))        let before = try! XCTUnwrap(bytes(total.label), total.label)        XCTAssertEqual(before, listed, accuracy: 1, "the breakdown says what the list says")        let free = id(app, "you-storage-chat-free")        reach(free, in: app)        free.tap()        // It asks first, in the core's words.        let yes = app.buttons.matching(NSPredicate(format: "label == %@", "Free up")).firstMatch        XCTAssertTrue(yes.waitForExistence(timeout: 10), "it asks first")        keep("storage-chat-free-ask-\(size(large))")        yes.tap()        let toast = app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH 'Freed '")).firstMatch        XCTAssertTrue(toast.waitForExistence(timeout: 10), "the page's toast says what was freed")        // The chat is read again after it: its size falls.        let lowered = Date().addingTimeInterval(10)        while (bytes(total.label) ?? before) >= before, Date() < lowered { RunLoop.current.run(until: Date().addingTimeInterval(0.25)) }        XCTAssertEqual(bytes(total.label) ?? 0, 300_000, accuracy: 60_000, "the voice message not synced yet stays: \(total.label)")        XCTAssertFalse(id(app, "you-storage-chat-photos").exists, "the photo safe in the account went")        XCTAssertTrue(id(app, "you-storage-chat-voice").exists, "the voice message stays")        XCTAssertFalse(id(app, "you-storage-chat-free").isEnabled, "nothing more to free")        keep("storage-chat-freed-\(size(large))")        id(app, "you-storage-chat-page-back").tap()        let again = id(app, "you-storage-chat-\(meera)")        XCTAssertTrue(again.waitForExistence(timeout: 10))        XCTAssertLessThan(try! XCTUnwrap(bytes(String(again.label.split(separator: ",").last ?? "").trimmingCharacters(in: .whitespaces))), listed, "the list says the lower size: \(again.label)")        // Meera's chat, opened: its photo's file is gone from the phone, its preview stands at once.        for _ in 0..<14 where !id(app, "you-storage-page-back").isHittable { app.swipeDown(velocity: .fast) }        id(app, "you-storage-page-back").tap()        let chats = app.buttons["chat-place-chats"]        XCTAssertTrue(chats.waitForExistence(timeout: 10))        chats.tap()        let chatRow = id(app, "chat-row-\(meera)")        XCTAssertTrue(chatRow.waitForExistence(timeout: 10), "Meera's chat in the list")        reach(chatRow, in: app)        chatRow.tap()        let photo = app.descendants(matching: .any)["chat-bubble-m-media-1"].firstMatch        XCTAssertTrue(photo.waitForExistence(timeout: 10), "the photo stands")        let window = app.windows.firstMatch.frame        let inView = { photo.frame.minY > window.minY + 110 && photo.frame.minY + 160 < window.maxY - 130 }        for _ in 0..<8 where !inView() {            let dy = max(-300, min(300, window.minY + 200 - photo.frame.minY))            let start = app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))            start.press(forDuration: 0.05, thenDragTo: start.withOffset(CGVector(dx: 0, dy: dy)), withVelocity: .slow, thenHoldForDuration: 0.4)        }        XCTAssertTrue(inView(), "the photo is on screen: \(photo.frame)")        let f = photo.frame        let seen = ink(at: CGPoint(x: min(f.maxX - 20, f.minX + 168), y: f.minY + 70))        XCTAssertFalse(blank(seen), "after Free this chat the preview still stands: \(seen)")        XCTAssertFalse(photo.label.contains("Picture not available"), photo.label)        keep("storage-chat-preview-after-\(size(large))")    }    @MainActor func testFreeThisChatLowersItsSizeAndKeepsPreviews() { freeLowersAndKeepsPreviews(large: false) }    @MainActor func testFreeThisChatAtTheLargestText() { freeLowersAndKeepsPreviews(large: true) }    // At night: the list and a breakdown in the night look.    @MainActor func testAtNight() {        XCUIDevice.shared.appearance = .dark        defer { XCUIDevice.shared.appearance = .light }        let app = launched(large: false)        let row = id(app, "you-storage-chat-\(asha)")        XCTAssertTrue(row.waitForExistence(timeout: 60))        reach(row, in: app)        keep("storage-chat-list-night")        row.tap()        XCTAssertTrue(id(app, "you-storage-chat-free").waitForExistence(timeout: 10))        keep("storage-chat-asha-night")    }}