gitbayUITests/LiveSmokeUITests.swift

v1.6.0
gitbay-ios/gitbayUITests/LiveSmokeUITests.swift history · blame · raw

1976 lines · 98376 bytes

   1import XCTest
   2
   3/// Live smoke flows against gitbay.org, driven by accessibility — the
   4/// coordinate-free verification the simulator's input pipeline cannot be
   5/// trusted to do (krz/gitbay-ios#5).
   6///
   7/// These WRITE to the live instance (an MR is opened and closed, a
   8/// milestone assigned), so they only run when explicitly asked:
   9///
  10///     TEST_RUNNER_GITBAY_UITEST_LIVE=1 xcodebuild test \
  11///       -only-testing:gitbayUITests ...
  12///
  13/// They run as the `ios-smoke` account, a krz admin that owns the
  14/// scratch and fixture repositories (smoke-account.sh provisions it).
  15/// Everything they write goes to those, never to krz/gitbay-ios. A
  16/// signed-out device is signed in at setUp from
  17/// TEST_RUNNER_GITBAY_UITEST_TOKEN.
  18final class LiveSmokeUITests: XCTestCase {
  19
  20    private var app: XCUIApplication!
  21
  22    /// The scratch repo testRepoManagementFlows creates. A run that dies
  23    /// before deleting it leaves it behind, and then every later run
  24    /// fails at "create sheet did not dismiss" — the create is refused
  25    /// because the name is taken, which reads like a UI bug and is not.
  26    /// Removed before and after, so neither a crashed run nor this one
  27    /// can strand it.
  28    private static let scratchRepo = "\(smokeUser)/ui-smoke"
  29
  30    /// The account the suite runs as. smoke-account.sh creates it with
  31    /// the profile description, PGP key and fixture repository the
  32    /// assertions below read back.
  33    static let smokeUser = "ios-smoke"
  34    static let smokeProfileDescription = "Live UI smoke account for gitbay-ios"
  35    static let smokePGPEmail = "ios-smoke+pgp@gitbay.org"
  36
  37    /// The repository the write flows work in: the fixture issue and
  38    /// merge requests, and the file testBlameAndEditFlows edits.
  39    /// smoke-account.sh seeds it, with `main` and `ui-smoke` divergent.
  40    static let fixtureRepo = "\(smokeUser)/ui-smoke-edit"
  41
  42    override func setUpWithError() throws {
  43        try XCTSkipUnless(
  44            ProcessInfo.processInfo.environment["GITBAY_UITEST_LIVE"] == "1",
  45            "live UI smoke is opt-in; set TEST_RUNNER_GITBAY_UITEST_LIVE=1"
  46        )
  47        continueAfterFailure = false
  48        app = XCUIApplication()
  49        // xcodebuild runs tests on simulator clones, so the base
  50        // device's appearance never applies; force it per run.
  51        switch ProcessInfo.processInfo.environment["GITBAY_UITEST_DARK"] {
  52        case "1": app.launchArguments.append("-gb-dark")
  53        case "0": app.launchArguments.append("-gb-light")
  54        default: break // follow the device, as a real launch does
  55        }
  56        app.launch()
  57        // A fresh device — a clone on another runtime, say — starts on
  58        // the token screen; the flows assume a signed-in app.
  59        signInIfNeeded()
  60        if name.contains("testRepoManagementFlows") {
  61            deleteScratchRepo()
  62        }
  63        if name.contains("testCreationAndEditingFlows") {
  64            try requireFixtureRepo()
  65            ensureFixtureMilestone()
  66            ensureFixtureIssue()
  67            try requireFixtureBranch()
  68        }
  69        if name.contains("testBlameAndEditFlows") {
  70            try requireFixtureRepo()
  71        }
  72        if name.contains("testSnippetFlows") {
  73            deleteSmokeSnippets()
  74        }
  75        if name.contains("testOrgLabelAndMilestoneFlows") {
  76            ensureOrgFixtures()
  77        }
  78        if name.contains("testCloseInFavourFlow") {
  79            try requireFixtureRepo()
  80            try requireFixtureBranch()
  81            closeSmokeMergeRequests()
  82            try openSupersedeFixtures()
  83        }
  84        if name.contains("testMRLabelFlow") {
  85            try requireFixtureRepo()
  86            try requireFixtureBranch()
  87            closeSmokeMergeRequests()
  88            _ = runCommand(["mr", "create", Self.fixtureRepo, "--source", "ui-smoke", "--target", "main",
  89                            "--title", Self.labelledTitle])
  90            _ = runCommand(["mr", "create", Self.fixtureRepo, "--source", "main", "--target", "ui-smoke",
  91                            "--title", Self.unlabelledTitle])
  92            let open = openSmokeMergeRequests().map { $0.title }
  93            try XCTSkipUnless(open.contains(Self.labelledTitle) && open.contains(Self.unlabelledTitle),
  94                              "could not open both label fixture merge requests on \(Self.fixtureRepo)")
  95        }
  96        if name.contains("testMarkupPreviewFlow") {
  97            try requireFixtureRepo()
  98            ensureFixtureIssue()
  99        }
 100    }
 101
 102    override func tearDownWithError() throws {
 103        if name.contains("testRepoManagementFlows") {
 104            deleteScratchRepo()
 105        }
 106        if name.contains("testSnippetFlows") {
 107            deleteSmokeSnippets()
 108        }
 109        if name.contains("testCloseInFavourFlow") {
 110            closeSmokeMergeRequests()
 111        }
 112        if name.contains("testMRLabelFlow") {
 113            closeSmokeMergeRequests()
 114            _ = runCommand(["label", "remove", Self.fixtureRepo, Self.smokeMRLabel])
 115        }
 116    }
 117
 118    // MARK: - Fixtures for the v1.2.0 flows
 119
 120    static let smokeSnippetDescription = "UI smoke snippet"
 121
 122    /// Remove every snippet the flow made, before and after, so a run
 123    /// that died mid-way cannot strand one or hit the per-account cap.
 124    private func deleteSmokeSnippets() {
 125        guard let data = readCommand(["snippet", "list"]),
 126              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
 127              let rows = envelope["data"] as? [[String: Any]] else { return }
 128        for row in rows where row["description"] as? String == Self.smokeSnippetDescription {
 129            if let id = row["id"] as? String {
 130                _ = runCommand(["snippet", "delete", id])
 131            }
 132        }
 133    }
 134
 135    static let smokeOrg = "krz"
 136    static let smokeOrgLabel = "ui-smoke-label"
 137    static let smokeOrgMilestone = "ui-smoke milestone"
 138
 139    /// The org milestone is a fixture, reused and left closed: the
 140    /// server has no milestone delete, so creating one per run would
 141    /// pile them up. The label is removed by the flow itself; a stale
 142    /// one is removed here first.
 143    private func ensureOrgFixtures() {
 144        _ = runCommand(["org", "label", "remove", Self.smokeOrg, Self.smokeOrgLabel])
 145        guard let data = readCommand(["org", "milestone", "list", Self.smokeOrg, "--state", "all"]),
 146              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
 147        else { return }
 148        let rows = envelope["data"] as? [[String: Any]] ?? []
 149        if let row = rows.first(where: { $0["title"] as? String == Self.smokeOrgMilestone }) {
 150            if row["state"] as? String == "open" {
 151                _ = runCommand(["org", "milestone", "close", Self.smokeOrg, Self.smokeOrgMilestone])
 152            }
 153        } else {
 154            _ = runCommand(["org", "milestone", "create", Self.smokeOrg, Self.smokeOrgMilestone])
 155            _ = runCommand(["org", "milestone", "close", Self.smokeOrg, Self.smokeOrgMilestone])
 156        }
 157    }
 158
 159    static let supersededTitle = "UI smoke: superseded"
 160    static let successorTitle = "UI smoke: successor"
 161    static let labelledTitle = "UI smoke: labels"
 162    static let unlabelledTitle = "UI smoke: unlabelled"
 163    static let smokeMRLabel = "ui-smoke-mr-label"
 164
 165    /// Close in favour needs two open merge requests. The fixture branch
 166    /// gives one (ui-smoke -> main); main has commits ui-smoke lacks, so
 167    /// the reverse (main -> ui-smoke) is the other. Both are the API's
 168    /// to open; the flow closes the first from the app and tearDown
 169    /// closes whatever is left.
 170    private func openSupersedeFixtures() throws {
 171        _ = runCommand(["mr", "create", Self.fixtureRepo, "--source", "ui-smoke", "--target", "main",
 172                        "--title", Self.supersededTitle])
 173        _ = runCommand(["mr", "create", Self.fixtureRepo, "--source", "main", "--target", "ui-smoke",
 174                        "--title", Self.successorTitle])
 175        let open = openSmokeMergeRequests().map { $0.title }
 176        try XCTSkipUnless(open.contains(Self.supersededTitle) && open.contains(Self.successorTitle), """
 177            could not open both fixture merge requests on \(Self.fixtureRepo) \
 178            (have \(open)); the ui-smoke branch may be level with main.
 179            """)
 180    }
 181
 182    private func openSmokeMergeRequests() -> [(number: Int, title: String)] {
 183        guard let data = readCommand(["mr", "list", Self.fixtureRepo, "--state", "open"]),
 184              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
 185              let rows = envelope["data"] as? [[String: Any]] else { return [] }
 186        return rows.compactMap { row in
 187            guard let number = row["number"] as? Int, let title = row["title"] as? String,
 188                  title.hasPrefix("UI smoke:") else { return nil }
 189            return (number, title)
 190        }
 191    }
 192
 193    private func closeSmokeMergeRequests() {
 194        for mr in openSmokeMergeRequests() {
 195            _ = runCommand(["mr", "close", Self.fixtureRepo, String(mr.number)])
 196        }
 197    }
 198
 199    /// `repo delete` over the JSON API — the app has no delete screen
 200    /// (deletion is SSH-only by design), so cleanup cannot go through
 201    /// the UI. A repo that is not there answers exit 3, which is the
 202    /// outcome we want anyway.
 203    private func deleteScratchRepo() {
 204        _ = runCommand(["repo", "delete", Self.scratchRepo, "--yes"])
 205        // The rename round-trip's halfway name, in case a run died there.
 206        _ = runCommand(["repo", "delete", Self.scratchRepo + "-2", "--yes"])
 207    }
 208
 209    /// The milestone the editing flow assigns. Created rather than
 210    /// required: unlike a branch, the API can make one.
 211    static let fixtureMilestone = "v1.0.0"
 212
 213    private func ensureFixtureMilestone() {
 214        guard let data = readCommand(["milestone", "list", Self.fixtureRepo, "--state", "all"]),
 215              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
 216        else { return }
 217        let rows = envelope["data"] as? [[String: Any]] ?? []
 218        if rows.contains(where: { $0["title"] as? String == Self.fixtureMilestone }) { return }
 219        _ = runCommand(["milestone", "create", Self.fixtureRepo, Self.fixtureMilestone])
 220    }
 221
 222    /// The issue the editing flow works on. It is a fixture, not a real
 223    /// issue: pinning the test to whatever issue happened to be open put
 224    /// it at the mercy of the project moving on, and it duly broke when
 225    /// that issue was closed (krz/gitbay-ios#8).
 226    static let fixtureIssueTitle = "ui-smoke fixture: do not close"
 227
 228    /// Guarantee the fixture issue exists and is open. It is reused
 229    /// rather than recreated, so runs do not pile up closed issues.
 230    private func ensureFixtureIssue() {
 231        guard let data = readCommand(
 232            ["issue", "list", Self.fixtureRepo, "--state", "open"]),
 233            let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
 234        else { return }
 235
 236        let issues = envelope["data"] as? [[String: Any]] ?? []
 237        if issues.contains(where: { $0["title"] as? String == Self.fixtureIssueTitle }) {
 238            return
 239        }
 240        _ = runCommand(
 241            ["issue", "create", Self.fixtureRepo, "--title", Self.fixtureIssueTitle, "--file", "-"],
 242            stdin: "Created by the live smoke suite. It exercises the milestone "
 243                 + "picker and the edit sheet, and is reused every run."
 244        )
 245    }
 246
 247    /// The MR flow needs a source branch carrying a commit main does not
 248    /// have. Nothing in the app or the API can create a branch — that is
 249    /// a push — so this only checks, and says so plainly rather than
 250    /// letting the test fail later at "created MR not in the list".
 251    private func requireFixtureBranch() throws {
 252        guard let data = readCommand(["repo", "refs", Self.fixtureRepo]),
 253              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
 254              let refs = envelope["data"] as? [String: Any],
 255              let branches = refs["branches"] as? [[String: Any]]
 256        else { return } // no token, or the instance is unreachable
 257        let names = branches.compactMap { $0["name"] as? String }
 258        try XCTSkipUnless(names.contains("ui-smoke"), """
 259            \(Self.fixtureRepo) has no ui-smoke branch. The MR flows open \
 260            one merge request each way between it and main, so each side \
 261            needs a commit the other lacks; smoke-account.sh seeds both.
 262            """)
 263    }
 264
 265    /// POST /api/v1/cmd. Writes the suite needs but the app cannot make.
 266    @discardableResult
 267    private func runCommand(_ argv: [String], stdin: String? = nil) -> Data? {
 268        var body: [String: Any] = ["argv": argv]
 269        if let stdin { body["stdin"] = stdin }
 270        return call(method: "POST", path: "/api/v1/cmd", body: body)
 271    }
 272
 273    /// GET /api/v1/read, for the reads that decide what a test sets up.
 274    private func readCommand(_ argv: [String]) -> Data? {
 275        let query = argv
 276            .map { "argv=" + ($0.addingPercentEncoding(
 277                withAllowedCharacters: .alphanumerics) ?? $0) }
 278            .joined(separator: "&")
 279        return call(method: "GET", path: "/api/v1/read?" + query, body: nil)
 280    }
 281
 282    private func call(method: String, path: String, body: [String: Any]?) -> Data? {
 283        guard let token = ProcessInfo.processInfo
 284            .environment["GITBAY_UITEST_TOKEN"], !token.isEmpty,
 285            let url = URL(string: "https://gitbay.org" + path)
 286        else { return nil }
 287
 288        var request = URLRequest(url: url)
 289        request.httpMethod = method
 290        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
 291        if let body {
 292            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
 293            request.httpBody = try? JSONSerialization.data(withJSONObject: body)
 294        }
 295
 296        var result: Data?
 297        let done = DispatchSemaphore(value: 0)
 298        URLSession.shared.dataTask(with: request) { data, _, _ in
 299            result = data
 300            done.signal()
 301        }.resume()
 302        _ = done.wait(timeout: .now() + 15)
 303        return result
 304    }
 305
 306    /// Everything in one ordered pass: milestone assign, edit-save,
 307    /// MR create, MR close. One test so the flows share navigation and
 308    /// the writes happen exactly once.
 309    func testCreationAndEditingFlows() throws {
 310        openRepo(Self.fixtureRepo)
 311
 312        // --- the fixture issue: milestone picker assigns the fixture ---
 313        app.staticTexts["Issues"].firstMatch.tap()
 314        let issueRow = app.staticTexts
 315            .containing(NSPredicate(format: "label CONTAINS 'ui-smoke fixture'")).firstMatch
 316        XCTAssertTrue(issueRow.waitForExistence(timeout: 10),
 317                      "fixture issue not in the list; setUp should have created it")
 318        issueRow.tap()
 319
 320        let milestoneMenu = app.descendants(matching: .any)
 321            .matching(identifier: "milestone-menu").firstMatch
 322        XCTAssertTrue(milestoneMenu.waitForExistence(timeout: 10))
 323        milestoneMenu.tap()
 324        let milestoneChoice = app.buttons
 325            .containing(NSPredicate(format: "label BEGINSWITH %@", Self.fixtureMilestone)).firstMatch
 326        XCTAssertTrue(milestoneChoice.waitForExistence(timeout: 5), "milestone menu did not open")
 327        milestoneChoice.tap()
 328        // The reload renders the assigned milestone in the header row.
 329        XCTAssertTrue(app.staticTexts[Self.fixtureMilestone].firstMatch
 330            .waitForExistence(timeout: 10), "milestone not shown after assign")
 331
 332        // --- the fixture issue: edit sheet saves (content unchanged) ---
 333        app.descendants(matching: .any).matching(identifier: "issue-actions-menu")
 334            .firstMatch.tap()
 335        let edit = app.buttons["Edit"].firstMatch
 336        XCTAssertTrue(edit.waitForExistence(timeout: 5))
 337        edit.tap()
 338        let title = app.descendants(matching: .any)
 339            .matching(identifier: "compose-title").firstMatch
 340        XCTAssertTrue(title.waitForExistence(timeout: 5), "edit sheet did not open")
 341        XCTAssertTrue((title.value as? String)?.contains("ui-smoke fixture") == true,
 342                      "edit sheet did not prefill")
 343        // Save the body as org, reopen, and the picker must start on Org:
 344        // the sheet has to read the stored format, not its own default.
 345        let format = app.segmentedControls.matching(identifier: "compose-format").firstMatch
 346        XCTAssertTrue(format.waitForExistence(timeout: 5), "format picker missing")
 347        XCTAssertTrue(format.buttons["Markdown"].isSelected, "fixture did not open on Markdown")
 348        format.buttons["Org"].tap()
 349        app.descendants(matching: .any).matching(identifier: "compose-submit")
 350            .firstMatch.tap()
 351        // Sheet dismissal proves the save round-tripped without error.
 352        XCTAssertTrue(waitForDisappearance(title, timeout: 15), "edit save did not dismiss")
 353
 354        app.descendants(matching: .any).matching(identifier: "issue-actions-menu")
 355            .firstMatch.tap()
 356        XCTAssertTrue(edit.waitForExistence(timeout: 5))
 357        edit.tap()
 358        XCTAssertTrue(format.waitForExistence(timeout: 5), "edit sheet did not reopen")
 359        XCTAssertTrue(format.buttons["Org"].isSelected, "edit sheet did not open on the stored format")
 360        // Restore the fixture to markdown.
 361        format.buttons["Markdown"].tap()
 362        app.descendants(matching: .any).matching(identifier: "compose-submit")
 363            .firstMatch.tap()
 364        XCTAssertTrue(waitForDisappearance(title, timeout: 15), "edit save did not dismiss")
 365
 366        back() // to issues list
 367        back() // to repo screen
 368
 369        // --- MR: create from ui-smoke, then close it ---
 370        app.staticTexts["Merge Requests"].firstMatch.tap()
 371        app.descendants(matching: .any).matching(identifier: "mr-create-button")
 372            .firstMatch.tap()
 373
 374        let source = app.descendants(matching: .any)
 375            .matching(identifier: "mr-source").firstMatch
 376        XCTAssertTrue(source.waitForExistence(timeout: 5), "MR create sheet did not open")
 377        focusAndType(source, "ui-smoke")
 378
 379        let target = app.descendants(matching: .any)
 380            .matching(identifier: "mr-target").firstMatch
 381        // The default branch prefilled while the sheet loaded.
 382        XCTAssertEqual(target.value as? String, "main", "target did not prefill")
 383
 384        let mrTitle = app.descendants(matching: .any)
 385            .matching(identifier: "mr-title").firstMatch
 386        focusAndType(mrTitle, "UI smoke: mr create from the app")
 387
 388        app.descendants(matching: .any).matching(identifier: "mr-submit")
 389            .firstMatch.tap()
 390
 391        let createdRow = app.staticTexts
 392            .containing(NSPredicate(format: "label CONTAINS 'UI smoke'")).firstMatch
 393        XCTAssertTrue(createdRow.waitForExistence(timeout: 15), "created MR not in the list")
 394        createdRow.tap()
 395
 396        // The gates are shown before any merge is tried.
 397        let gates = header("Gates")
 398        XCTAssertTrue(scrollTo(gates, swipes: 8), "gates section missing")
 399
 400        // A fresh MR has one revision; the section lists it.
 401        let revisions = header("Revisions")
 402        XCTAssertTrue(scrollTo(revisions, swipes: 8), "revisions section missing")
 403        XCTAssertTrue(app.staticTexts["v1"].firstMatch.exists, "first revision not listed")
 404
 405        app.descendants(matching: .any).matching(identifier: "mr-actions-menu")
 406            .firstMatch.tap()
 407        let close = app.buttons["Close"].firstMatch
 408        XCTAssertTrue(close.waitForExistence(timeout: 5))
 409        close.tap()
 410        // The confirmation dialog's destructive Close.
 411        let confirm = app.buttons["Close"].firstMatch
 412        XCTAssertTrue(confirm.waitForExistence(timeout: 5), "close confirmation missing")
 413        confirm.tap()
 414
 415        XCTAssertTrue(app.staticTexts["closed"].firstMatch
 416            .waitForExistence(timeout: 15), "MR did not show closed after close")
 417    }
 418
 419    // MARK: - Helpers
 420
 421    private func openRepo(_ path: String) {
 422        selectTab("Repositories")
 423
 424        // `.searchable` keeps the field tucked above the list until it is
 425        // scrolled into view.
 426        let search = app.searchFields.firstMatch
 427        if !search.waitForExistence(timeout: 5) {
 428            app.swipeDown()
 429            XCTAssertTrue(search.waitForExistence(timeout: 10), "search field never appeared")
 430        }
 431        focusAndType(search, path)
 432
 433        let row = app.staticTexts[path].firstMatch
 434        XCTAssertTrue(row.waitForExistence(timeout: 15), "\(path) not in the repo list")
 435        row.tap()
 436        // Repo screen is loaded once its links render.
 437        XCTAssertTrue(app.staticTexts["Files"].firstMatch.waitForExistence(timeout: 10),
 438                      "repo screen did not open")
 439    }
 440
 441    private func back() {
 442        app.navigationBars.buttons.firstMatch.tap()
 443    }
 444
 445    /// Keys, PGP and email live behind the account menu, which is on the
 446    /// My Profile tab and nowhere else.
 447    func openAccountScreen(file: StaticString = #filePath, line: UInt = #line) {
 448        selectTab("My Profile")
 449        let menu = app.descendants(matching: .any)
 450            .matching(identifier: "account-menu").firstMatch
 451        XCTAssertTrue(menu.waitForExistence(timeout: 15),
 452                      "account menu missing", file: file, line: line)
 453        menu.tap()
 454        let keys = app.buttons["Keys & Email"].firstMatch
 455        XCTAssertTrue(keys.waitForExistence(timeout: 5),
 456                      "Keys & Email missing from the account menu", file: file, line: line)
 457        keys.tap()
 458    }
 459
 460    /// Seeding a repository's first commit is a push, which no test can
 461    /// make, so this only checks — and says why, rather than failing
 462    /// later at "ios-smoke/ui-smoke-edit not in the repo list".
 463    private func requireFixtureRepo() throws {
 464        guard let data = readCommand(["repo", "show", Self.fixtureRepo]),
 465              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
 466        else { return } // no token, or the instance is unreachable
 467        try XCTSkipUnless(envelope["data"] != nil, """
 468            \(Self.fixtureRepo) is missing. The write flows work in it; \
 469            gitbayUITests/smoke-account.sh seeds it (or push it by hand, \
 470            see that script) and run again.
 471            """)
 472    }
 473
 474    /// Scroll a list until an element is in the hierarchy. Offscreen
 475    /// rows do not exist to XCUITest, so waitForExistence alone fails on
 476    /// anything below the fold.
 477    @discardableResult
 478    /// A list section header. iOS 18 renders these uppercased and iOS 26
 479    /// as written, so the match ignores case.
 480    func header(_ text: String) -> XCUIElement {
 481        app.staticTexts.matching(NSPredicate(format: "label ==[c] %@", text)).firstMatch
 482    }
 483
 484    func scrollTo(_ element: XCUIElement, swipes: Int = 6) -> Bool {
 485        for _ in 0..<swipes {
 486            if element.exists { return true }
 487            app.swipeUp()
 488        }
 489        return element.exists
 490    }
 491
 492    /// Switch tabs and wait until that tab is actually front. A tap
 493    /// dispatched before the app is interactive — which happens right
 494    /// after launch when there is no sign-in to slow things down — is
 495    /// swallowed silently, so this taps until the tab reports selected.
 496    func selectTab(_ name: String,
 497                   file: StaticString = #filePath, line: UInt = #line) {
 498        // iPadOS renders a TabView as a sidebar or top bar rather than a
 499        // bottom tab bar, so the control is not under app.tabBars there.
 500        var tab = app.tabBars.buttons[name].firstMatch
 501        if !tab.waitForExistence(timeout: 5) {
 502            tab = app.buttons[name].firstMatch
 503        }
 504        XCTAssertTrue(tab.waitForExistence(timeout: 15),
 505                      "\(name) tab missing", file: file, line: line)
 506        // The app is interactive once its own chrome is hittable.
 507        XCTAssertTrue(tab.isHittable || tab.waitForExistence(timeout: 5),
 508                      "\(name) tab never became hittable", file: file, line: line)
 509
 510        for _ in 0..<4 {
 511            if tab.isSelected, app.navigationBars[name].firstMatch.exists { return }
 512            tab.tap()
 513            if app.navigationBars[name].firstMatch.waitForExistence(timeout: 5) { return }
 514        }
 515        XCTFail("\(name) tab did not come to front", file: file, line: line)
 516    }
 517
 518    /// Empty a text field before typing. Search fields keep their query
 519    /// across navigation, and the clear button is not reliably
 520    /// addressable, so this deletes character by character.
 521    func clearAndType(_ element: XCUIElement, _ text: String,
 522                      file: StaticString = #filePath, line: UInt = #line) {
 523        element.tap()
 524        if !app.keyboards.firstMatch.waitForExistence(timeout: 5) {
 525            element.tap()
 526            XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5),
 527                          "keyboard never appeared", file: file, line: line)
 528        }
 529        if let existing = element.value as? String,
 530           existing != element.placeholderValue, !existing.isEmpty {
 531            element.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue,
 532                                    count: existing.count))
 533        }
 534        element.typeText(text)
 535    }
 536
 537    /// Tap a field and type into it, surviving the focus race: a tap can
 538    /// land before the field is ready, and the keystrokes go nowhere.
 539    func focusAndType(_ element: XCUIElement, _ text: String,
 540                      file: StaticString = #filePath, line: UInt = #line) {
 541        element.tap()
 542        if !app.keyboards.firstMatch.waitForExistence(timeout: 5) {
 543            element.tap()
 544            XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5),
 545                          "keyboard never appeared for \(element)", file: file, line: line)
 546        }
 547        element.typeText(text)
 548    }
 549
 550    private func waitForDisappearance(_ element: XCUIElement, timeout: TimeInterval) -> Bool {
 551        let predicate = NSPredicate(format: "exists == false")
 552        let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
 553        return XCTWaiter().wait(for: [expectation], timeout: timeout) == .completed
 554    }
 555}
 556
 557extension LiveSmokeUITests {
 558
 559    /// Repo management, kept reversible: create a scratch repo (deleted
 560    /// by the runner afterwards, deletion is CLI-only by design), pin and
 561    /// unpin, a topic round-trip, a merge-rule toggle round-trip, and the
 562    /// build-trigger error path on a repo with no job config.
 563    func testRepoManagementFlows() throws {
 564        // --- repo create first: it ends in the list's search state,
 565        // which the next step reuses. (Scratch repo; the runner deletes
 566        // it over SSH afterwards — deletion is CLI-only by design.)
 567        selectTab("Repositories")
 568        app.descendants(matching: .any).matching(identifier: "repo-create-button")
 569            .firstMatch.tap()
 570        let newRepo = app.buttons["New Repository"].firstMatch
 571        XCTAssertTrue(newRepo.waitForExistence(timeout: 5), "create menu did not open")
 572        newRepo.tap()
 573        let pathField = app.descendants(matching: .any)
 574            .matching(identifier: "repo-create-path").firstMatch
 575        XCTAssertTrue(pathField.waitForExistence(timeout: 5))
 576        focusAndType(pathField, "ui-smoke")
 577        app.switches.firstMatch.tap() // Private on
 578        app.descendants(matching: .any).matching(identifier: "repo-create-submit")
 579            .firstMatch.tap()
 580        // The sheet dismissing proves the create round-tripped; rows are
 581        // lazy, so find the new repo through the filter.
 582        XCTAssertTrue(waitForDisappearance(pathField, timeout: 15),
 583                      "create sheet did not dismiss")
 584        let createSearch = app.searchFields.firstMatch
 585        XCTAssertTrue(createSearch.waitForExistence(timeout: 10))
 586        focusAndType(createSearch, "ui-smoke")
 587        XCTAssertTrue(app.staticTexts[Self.scratchRepo].firstMatch
 588            .waitForExistence(timeout: 15), "created repo not in the list")
 589
 590        // --- access: grant a user on the scratch repo, then revoke ---
 591        app.staticTexts[Self.scratchRepo].firstMatch.tap()
 592        XCTAssertTrue(app.staticTexts["Files"].firstMatch.waitForExistence(timeout: 10))
 593        app.staticTexts["Settings"].firstMatch.tap()
 594        let grantUser = app.descendants(matching: .any)
 595            .matching(identifier: "settings-grant-user").firstMatch
 596        XCTAssertTrue(scrollTo(grantUser, swipes: 8), "access section not reachable")
 597        focusAndType(grantUser, "apple-review")
 598        app.descendants(matching: .any).matching(identifier: "settings-grant-submit")
 599            .firstMatch.tap()
 600        let grantRow = app.staticTexts["apple-review"].firstMatch
 601        XCTAssertTrue(grantRow.waitForExistence(timeout: 15), "grant not listed")
 602        grantRow.swipeLeft()
 603        app.buttons["Revoke"].firstMatch.tap()
 604        let confirmGrantRevoke = app.buttons["Revoke"].firstMatch
 605        XCTAssertTrue(confirmGrantRevoke.waitForExistence(timeout: 5), "revoke confirmation missing")
 606        confirmGrantRevoke.tap()
 607        XCTAssertTrue(waitForDisappearance(grantRow, timeout: 15), "grant not revoked")
 608
 609        // --- webhooks: add one, see it listed, remove it ---
 610        let webhooksLink = app.descendants(matching: .any)
 611            .matching(identifier: "settings-webhooks-link").firstMatch
 612        XCTAssertTrue(scrollTo(webhooksLink, swipes: 8), "webhooks link not reachable")
 613        webhooksLink.tap()
 614        let addHook = app.descendants(matching: .any)
 615            .matching(identifier: "webhook-add-button").firstMatch
 616        XCTAssertTrue(addHook.waitForExistence(timeout: 10), "webhooks did not load")
 617        addHook.tap()
 618        let hookURL = app.descendants(matching: .any)
 619            .matching(identifier: "webhook-url").firstMatch
 620        XCTAssertTrue(hookURL.waitForExistence(timeout: 5), "webhook sheet did not open")
 621        focusAndType(hookURL, "https://example.com/ui-smoke")
 622        app.descendants(matching: .any).matching(identifier: "webhook-submit")
 623            .firstMatch.tap()
 624        let hookRow = app.staticTexts["https://example.com/ui-smoke"].firstMatch
 625        XCTAssertTrue(hookRow.waitForExistence(timeout: 15), "webhook not listed")
 626        hookRow.swipeLeft()
 627        app.buttons["Remove"].firstMatch.tap()
 628        let confirmHookRemove = app.buttons["Remove"].firstMatch
 629        XCTAssertTrue(confirmHookRemove.waitForExistence(timeout: 5), "webhook remove confirmation missing")
 630        confirmHookRemove.tap()
 631        XCTAssertTrue(waitForDisappearance(hookRow, timeout: 15), "webhook not removed")
 632        back() // webhooks -> settings
 633
 634        // --- rename the scratch repo there and back ---
 635        // Each rename pushes the renamed repository; the round-trip ends
 636        // on the scratch repo again, several screens deep.
 637        var firstRename = true
 638        let rename: (String, String) -> Void = { newName, expectedPath in
 639            if firstRename {
 640                firstRename = false // already on the settings screen
 641            } else {
 642                // Fresh repo screen: scroll to the top so no row hides
 643                // under the navigation bar, then reach Settings.
 644                self.app.swipeDown()
 645                let settingsLink = self.app.descendants(matching: .any).matching(identifier: "repo-settings-link").firstMatch
 646                XCTAssertTrue(self.scrollTo(settingsLink), "settings link not reachable")
 647                settingsLink.tap()
 648            }
 649            let renameButton = self.app.descendants(matching: .any)
 650                .matching(identifier: "settings-rename-button").firstMatch
 651            XCTAssertTrue(self.scrollTo(renameButton, swipes: 10), "rename button not reachable")
 652            renameButton.tap()
 653            let field = self.app.textFields["New name"].firstMatch
 654            XCTAssertTrue(field.waitForExistence(timeout: 5), "rename alert did not open")
 655            field.tap()
 656            // Prefilled with the current name; clear it before typing.
 657            field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 12) + newName)
 658            self.app.buttons["Rename"].firstMatch.tap()
 659            // The settings screen offers the renamed repository at the
 660            // top; the list is scrolled to its end, so go back up first.
 661            let renamedLink = self.app.descendants(matching: .any)
 662                .matching(identifier: "settings-renamed-link").firstMatch
 663            sleep(2)
 664            for _ in 0..<6 where !renamedLink.exists { self.app.swipeDown() }
 665            XCTAssertTrue(renamedLink.waitForExistence(timeout: 10), "rename did not land")
 666            renamedLink.tap()
 667            XCTAssertTrue(self.app.staticTexts[expectedPath].firstMatch.waitForExistence(timeout: 15),
 668                          "renamed repo did not open as \(expectedPath)")
 669        }
 670        rename("ui-smoke-2", Self.scratchRepo + "-2")
 671        rename("ui-smoke", Self.scratchRepo)
 672
 673        // --- pin / unpin round-trip on krz/gitbay-ios ---
 674        // Start the list fresh; the rename left the stack several deep.
 675        app.terminate()
 676        app.launch()
 677        selectTab("Repositories")
 678        let search = app.searchFields.firstMatch
 679        XCTAssertTrue(search.waitForExistence(timeout: 10))
 680        focusAndType(search, "krz/gitbay-ios")
 681        let repoRow = app.staticTexts["krz/gitbay-ios"].firstMatch
 682        XCTAssertTrue(repoRow.waitForExistence(timeout: 15))
 683        repoRow.tap()
 684        XCTAssertTrue(app.staticTexts["Files"].firstMatch.waitForExistence(timeout: 10))
 685        let menu = app.descendants(matching: .any)
 686            .matching(identifier: "repo-actions-menu").firstMatch
 687        XCTAssertTrue(menu.waitForExistence(timeout: 10))
 688        menu.tap()
 689        let pin = app.buttons["Pin"].firstMatch
 690        XCTAssertTrue(pin.waitForExistence(timeout: 5), "Pin action missing")
 691        pin.tap()
 692        // State refreshed from the dashboard: the menu now offers Unpin.
 693        menu.tap()
 694        let unpin = app.buttons["Unpin"].firstMatch
 695        XCTAssertTrue(unpin.waitForExistence(timeout: 10), "pin did not take")
 696        unpin.tap()
 697
 698        // Bookmark it, find it in the bookmarks list, then unbookmark.
 699        // A run that died between the two leaves it bookmarked; undo
 700        // that first so the step starts from the same state every time.
 701        menu.tap()
 702        let leftover = app.buttons["Unbookmark"].firstMatch
 703        if leftover.waitForExistence(timeout: 3) {
 704            leftover.tap()
 705            XCTAssertTrue(waitForDisappearance(leftover, timeout: 10))
 706            menu.tap()
 707        }
 708        let bookmark = app.buttons["Bookmark"].firstMatch
 709        XCTAssertTrue(bookmark.waitForExistence(timeout: 5), "Bookmark action missing")
 710        bookmark.tap()
 711        // An active search hides the list's toolbar, so start the list
 712        // fresh: relaunching lands on a list with the bookmarks button.
 713        app.terminate()
 714        app.launch()
 715        selectTab("Repositories")
 716        let bookmarksButton = app.descendants(matching: .any)
 717            .matching(identifier: "repo-bookmarks-button").firstMatch
 718        XCTAssertTrue(bookmarksButton.waitForExistence(timeout: 15), "bookmarks button missing")
 719        bookmarksButton.tap()
 720        let bookmarkedRow = app.staticTexts["krz/gitbay-ios"].firstMatch
 721        XCTAssertTrue(bookmarkedRow.waitForExistence(timeout: 15),
 722                      "bookmarked repo not in the bookmarks list")
 723        // Open it from the bookmarks list and undo the bookmark there.
 724        bookmarkedRow.tap()
 725        XCTAssertTrue(menu.waitForExistence(timeout: 10))
 726        menu.tap()
 727        let unbookmark = app.buttons["Unbookmark"].firstMatch
 728        XCTAssertTrue(unbookmark.waitForExistence(timeout: 10), "bookmark did not take")
 729        unbookmark.tap()
 730
 731        // --- settings: topic and merge-rule round-trips ---
 732        // The links section can sit below the README fold, and the row's
 733        // label is not always exposed as a static text.
 734        let settingsLink = app.descendants(matching: .any)
 735            .matching(identifier: "repo-settings-link").firstMatch
 736        XCTAssertTrue(scrollTo(settingsLink), "settings link not reachable")
 737        settingsLink.tap()
 738        let addTopic = app.descendants(matching: .any)
 739            .matching(identifier: "settings-add-topic").firstMatch
 740        XCTAssertTrue(addTopic.waitForExistence(timeout: 10), "settings did not load")
 741        focusAndType(addTopic, "ios")
 742        app.descendants(matching: .any).matching(identifier: "settings-add-topic-submit")
 743            .firstMatch.tap()
 744        let chip = app.staticTexts["ios"].firstMatch
 745        XCTAssertTrue(chip.waitForExistence(timeout: 10), "topic did not appear")
 746        // Remove it again through the chip's own x button — by name, since
 747        // the repository carries other topics — and it asks first.
 748        app.descendants(matching: .any).matching(identifier: "settings-remove-topic-ios")
 749            .firstMatch.tap()
 750        let confirmRemove = app.buttons["Remove"].firstMatch
 751        XCTAssertTrue(confirmRemove.waitForExistence(timeout: 5), "topic remove confirmation missing")
 752        confirmRemove.tap()
 753        XCTAssertTrue(waitForDisappearance(chip, timeout: 10), "topic did not remove")
 754
 755        // Merge-requests-only sits with the protected branches.
 756        let mergeOnly = app.switches["Merge requests only"].firstMatch
 757        XCTAssertTrue(scrollTo(mergeOnly), "merge-only toggle not reachable")
 758        let innerMergeOnly = mergeOnly.switches.firstMatch
 759        let flipMergeOnly: () -> Void = {
 760            if innerMergeOnly.exists && innerMergeOnly != mergeOnly {
 761                innerMergeOnly.tap()
 762            } else {
 763                mergeOnly.coordinate(withNormalizedOffset: CGVector(dx: 0.93, dy: 0.5)).tap()
 764            }
 765        }
 766        flipMergeOnly()
 767        XCTAssertTrue(waitForValue(mergeOnly, "1", timeout: 10), "merge-only toggle did not persist on")
 768        flipMergeOnly()
 769        XCTAssertTrue(waitForValue(mergeOnly, "0", timeout: 10), "merge-only toggle did not persist off")
 770
 771        // A tag glob is protected, listed, and unprotected.
 772        let tagGlob = app.descendants(matching: .any)
 773            .matching(identifier: "settings-protect-tag").firstMatch
 774        XCTAssertTrue(scrollTo(tagGlob), "protected tags section not reachable")
 775        focusAndType(tagGlob, "ui-smoke-*")
 776        app.descendants(matching: .any).matching(identifier: "settings-protect-tag-submit")
 777            .firstMatch.tap()
 778        let globRow = app.staticTexts["ui-smoke-*"].firstMatch
 779        XCTAssertTrue(globRow.waitForExistence(timeout: 10), "tag glob not listed")
 780        // By identifier: the protected branch above has an Unprotect too.
 781        app.descendants(matching: .any).matching(identifier: "settings-unprotect-tag-ui-smoke-*")
 782            .firstMatch.tap()
 783        XCTAssertTrue(waitForDisappearance(globRow, timeout: 10), "tag glob not unprotected")
 784
 785        // Merge rules sit below the protected branches and tags.
 786        let resolved = app.switches["Require threads resolved"].firstMatch
 787        // The merge-requirements section sits below the fold, and a List
 788        // does not build rows it has not shown, so it must be scrolled
 789        // into existence before it can be queried.
 790        XCTAssertTrue(scrollTo(resolved), "merge requirements section not reachable")
 791        // SwiftUI exposes the row as a switch that wraps the real
 792        // control; tap the innermost switch when there is one, else the
 793        // right edge of the row.
 794        let inner = resolved.switches.firstMatch
 795        let control: () -> Void = {
 796            if inner.exists && inner != resolved {
 797                inner.tap()
 798            } else {
 799                resolved.coordinate(withNormalizedOffset: CGVector(dx: 0.93, dy: 0.5)).tap()
 800            }
 801        }
 802        control()
 803        XCTAssertTrue(waitForValue(resolved, "1", timeout: 10), "toggle did not persist on")
 804        control()
 805        XCTAssertTrue(waitForValue(resolved, "0", timeout: 10), "toggle did not persist off")
 806
 807        // The code-owner rule is one more toggle in the same section.
 808        let codeowners = app.switches["Require code owner review"].firstMatch
 809        XCTAssertTrue(scrollTo(codeowners), "code owner toggle not reachable")
 810        let innerCodeowners = codeowners.switches.firstMatch
 811        let flipCodeowners: () -> Void = {
 812            if innerCodeowners.exists && innerCodeowners != codeowners {
 813                innerCodeowners.tap()
 814            } else {
 815                codeowners.coordinate(withNormalizedOffset: CGVector(dx: 0.93, dy: 0.5)).tap()
 816            }
 817        }
 818        flipCodeowners()
 819        XCTAssertTrue(waitForValue(codeowners, "1", timeout: 10), "code owner toggle did not persist on")
 820        flipCodeowners()
 821        XCTAssertTrue(waitForValue(codeowners, "0", timeout: 10), "code owner toggle did not persist off")
 822
 823
 824        back() // settings -> repo
 825        // The repo screen keeps the scroll that reached Settings, which
 826        // can leave Builds under the navigation bar.
 827        app.swipeDown()
 828
 829        // --- nothing to trigger without a job file ---
 830        // This repo has no .gitbay/ci.yml, so `build jobs` returns none
 831        // and the control is gated rather than failing after a guess.
 832        app.staticTexts["Builds"].firstMatch.tap()
 833        let trigger = app.descendants(matching: .any)
 834            .matching(identifier: "build-trigger-button").firstMatch
 835        XCTAssertTrue(trigger.waitForExistence(timeout: 15), "trigger control missing")
 836        // Assert on behaviour, not on isEnabled: a disabled SwiftUI Menu
 837        // still reports itself enabled to XCUITest.
 838        trigger.tap()
 839        let anyJob = app.buttons.containing(
 840            NSPredicate(format: "label CONTAINS 'on push' OR label CONTAINS 'schedule '"))
 841            .firstMatch
 842        XCTAssertFalse(anyJob.waitForExistence(timeout: 3),
 843                       "a repo with no job file offered a job to trigger")
 844
 845    }
 846
 847    private func waitForValue(_ element: XCUIElement, _ value: String,
 848                              timeout: TimeInterval) -> Bool {
 849        let predicate = NSPredicate(format: "value == %@", value)
 850        let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
 851        return XCTWaiter().wait(for: [expectation], timeout: timeout) == .completed
 852    }
 853}
 854
 855extension LiveSmokeUITests {
 856
 857    /// Discovery is read-only: feed, server-side repo search, grep, and
 858    /// profiles. No cleanup needed.
 859    func testDiscoveryFlows() throws {
 860        // --- feed renders events and navigates ---
 861        selectTab("Feed")
 862        let firstEvent = app.cells.firstMatch
 863        XCTAssertTrue(firstEvent.waitForExistence(timeout: 15), "feed rendered no events")
 864        firstEvent.tap()
 865        // Wherever the event led, it left the feed root behind.
 866        XCTAssertTrue(app.navigationBars.buttons.firstMatch
 867            .waitForExistence(timeout: 10), "feed row did not navigate")
 868        back()
 869
 870        // --- server-side search: "astronomy" is only a topic, invisible
 871        // to the client-side path/description filter ---
 872        selectTab("Repositories")
 873        let search = app.searchFields.firstMatch
 874        XCTAssertTrue(search.waitForExistence(timeout: 10))
 875        focusAndType(search, "astronomy")
 876        let hit = app.staticTexts["krz/space-wiki"].firstMatch
 877        XCTAssertTrue(hit.waitForExistence(timeout: 15),
 878                      "server-side topic search found nothing")
 879        hit.tap()
 880        XCTAssertTrue(app.staticTexts["Files"].firstMatch.waitForExistence(timeout: 10))
 881
 882        // --- owner profile from the repo screen ---
 883        // The row's label merges; match it at any element type. It is
 884        // the last row of the links section, below the fold.
 885        let ownerLink = app.descendants(matching: .any)["krz"].firstMatch
 886        XCTAssertTrue(scrollTo(ownerLink), "owner link not reachable")
 887        ownerLink.tap()
 888        XCTAssertTrue(app.staticTexts["warez for the public"].firstMatch
 889            .waitForExistence(timeout: 15), "profile did not load")
 890        XCTAssertTrue(app.staticTexts
 891            .containing(NSPredicate(format: "label BEGINSWITH[c] 'Repositories'")).firstMatch
 892            .waitForExistence(timeout: 10), "profile repos missing")
 893        back()
 894
 895        // --- grep inside the repo, last: its search UI owns the screen ---
 896        app.staticTexts["Search in Files"].firstMatch.tap()
 897        let grepField = app.searchFields.firstMatch
 898        XCTAssertTrue(grepField.waitForExistence(timeout: 10))
 899        focusAndType(grepField, "space")
 900        app.keyboards.buttons["search"].firstMatch.tap()
 901        let match = app.cells.firstMatch
 902        XCTAssertTrue(match.waitForExistence(timeout: 15), "grep returned no matches")
 903    }
 904}
 905
 906extension LiveSmokeUITests {
 907
 908    /// Releases: list and detail on a real release, an edit round-trip
 909    /// that saves the prefilled content (a no-op write), and the
 910    /// missing-tag refusal on create. Nothing changes state.
 911    func testReleaseFlows() throws {
 912        openRepo("krz/gitbay")
 913        app.staticTexts["Releases"].firstMatch.tap()
 914
 915        // Newest first, and the list has grown past the fold, so the
 916        // first row is whichever release is current.
 917        let row = app.cells.firstMatch
 918        XCTAssertTrue(row.waitForExistence(timeout: 15), "release list empty")
 919        row.tap()
 920
 921        // Notes render and assets carry sizes. The assets sit under the
 922        // notes, which can run past the fold.
 923        XCTAssertTrue(app.descendants(matching: .any)
 924            .matching(identifier: "release-edit-button").firstMatch
 925            .waitForExistence(timeout: 15), "release did not open")
 926        XCTAssertTrue(scrollTo(app.staticTexts
 927            .containing(NSPredicate(format: "label CONTAINS 'SHA256SUMS'")).firstMatch, swipes: 10),
 928            "assets missing")
 929
 930        // Edit sheet prefills; saving unchanged content round-trips.
 931        app.descendants(matching: .any).matching(identifier: "release-edit-button")
 932            .firstMatch.tap()
 933        let title = app.descendants(matching: .any)
 934            .matching(identifier: "compose-title").firstMatch
 935        XCTAssertTrue(title.waitForExistence(timeout: 5), "edit sheet did not open")
 936        XCTAssertFalse((title.value as? String ?? "").isEmpty,
 937                       "edit sheet did not prefill")
 938        app.descendants(matching: .any).matching(identifier: "compose-submit")
 939            .firstMatch.tap()
 940        XCTAssertTrue(waitForDisappearance(title, timeout: 15),
 941                      "release edit did not dismiss")
 942
 943        back()
 944
 945        // Create with a tag that does not exist: the server's refusal is
 946        // the UI contract.
 947        app.descendants(matching: .any).matching(identifier: "release-create-button")
 948            .firstMatch.tap()
 949        let tag = app.descendants(matching: .any)
 950            .matching(identifier: "release-tag").firstMatch
 951        XCTAssertTrue(tag.waitForExistence(timeout: 5))
 952        focusAndType(tag, "v9.9.9")
 953        app.descendants(matching: .any).matching(identifier: "release-submit")
 954            .firstMatch.tap()
 955        XCTAssertTrue(app.staticTexts
 956            .containing(NSPredicate(format: "label CONTAINS 'push the tag first'")).firstMatch
 957            .waitForExistence(timeout: 15), "missing-tag refusal not surfaced")
 958        app.buttons["Cancel"].firstMatch.tap()
 959    }
 960}
 961
 962extension LiveSmokeUITests {
 963
 964    /// Account keys and email. Read-only plus refusal paths — no key is
 965    /// added or removed, no mail is sent.
 966    func testAccountFlows() throws {
 967        // Dashboard toolbar -> account screen.
 968        openAccountScreen()
 969
 970        // Real keys render: SSH fingerprints first.
 971        XCTAssertTrue(app.staticTexts
 972            .containing(NSPredicate(format: "label BEGINSWITH 'SHA256:'")).firstMatch
 973            .waitForExistence(timeout: 15), "SSH keys missing")
 974
 975        // Pasting garbage as an SSH key surfaces the server's validation.
 976        // Done while the SSH section is still on screen: labelled keys
 977        // are two lines each, so what follows sits below the fold.
 978        app.descendants(matching: .any).matching(identifier: "add-ssh-key")
 979            .firstMatch.tap()
 980        let paste = app.descendants(matching: .any)
 981            .matching(identifier: "key-paste-text").firstMatch
 982        XCTAssertTrue(paste.waitForExistence(timeout: 5))
 983        focusAndType(paste, "not a key")
 984        app.descendants(matching: .any).matching(identifier: "key-paste-submit")
 985            .firstMatch.tap()
 986        XCTAssertTrue(app.staticTexts
 987            .containing(NSPredicate(format: "label CONTAINS 'not a valid public key'")).firstMatch
 988            .waitForExistence(timeout: 15), "invalid-key refusal not surfaced")
 989        app.buttons["Cancel"].firstMatch.tap()
 990
 991        // The PGP key's UID email, below the keys on a List that does not
 992        // build rows it has not shown.
 993        XCTAssertTrue(scrollTo(app.staticTexts[Self.smokePGPEmail].firstMatch),
 994                      "PGP key UID missing")
 995
 996        // Activity mail flips off and back on; the value comes back from
 997        // the server each time.
 998        let mail = app.switches["Activity by mail"].firstMatch
 999        XCTAssertTrue(scrollTo(mail), "mail toggle not reachable")
1000        let innerMail = mail.switches.firstMatch
1001        let flipMail: () -> Void = {
1002            if innerMail.exists && innerMail != mail {
1003                innerMail.tap()
1004            } else {
1005                mail.coordinate(withNormalizedOffset: CGVector(dx: 0.93, dy: 0.5)).tap()
1006            }
1007        }
1008        let mailWasOn = (mail.value as? String) == "1"
1009        flipMail()
1010        XCTAssertTrue(waitForValue(mail, mailWasOn ? "0" : "1", timeout: 10), "mail toggle did not persist")
1011        flipMail()
1012        XCTAssertTrue(waitForValue(mail, mailWasOn ? "1" : "0", timeout: 10), "mail toggle did not restore")
1013
1014        // The watch preference (v1.19.0) flips the same way.
1015        let watch = app.switches["Watch writable repositories"].firstMatch
1016        XCTAssertTrue(scrollTo(watch), "watch toggle not reachable")
1017        let innerWatch = watch.switches.firstMatch
1018        let flipWatch: () -> Void = {
1019            if innerWatch.exists && innerWatch != watch {
1020                innerWatch.tap()
1021            } else {
1022                watch.coordinate(withNormalizedOffset: CGVector(dx: 0.93, dy: 0.5)).tap()
1023            }
1024        }
1025        let watchWasOn = (watch.value as? String) == "1"
1026        flipWatch()
1027        XCTAssertTrue(waitForValue(watch, watchWasOn ? "0" : "1", timeout: 10), "watch toggle did not persist")
1028        flipWatch()
1029        XCTAssertTrue(waitForValue(watch, watchWasOn ? "1" : "0", timeout: 10), "watch toggle did not restore")
1030
1031        // A bogus verification code is refused, not swallowed.
1032        let code = app.descendants(matching: .any)
1033            .matching(identifier: "email-code").firstMatch
1034        // Email sits below the keys on a List, which does not build rows
1035        // it has not shown.
1036        XCTAssertTrue(scrollTo(code), "email section not reachable")
1037        // The addresses list above the fields, the primary one marked.
1038        XCTAssertTrue(app.staticTexts["primary"].firstMatch.exists, "primary address not marked")
1039        focusAndType(code, "000000")
1040        let verify = app.descendants(matching: .any)
1041            .matching(identifier: "email-verify").firstMatch
1042        XCTAssertTrue(verify.waitForExistence(timeout: 5))
1043        XCTAssertTrue(verify.isEnabled, "verify stayed disabled — code text never landed")
1044        verify.tap()
1045        XCTAssertTrue(app.staticTexts
1046            .containing(NSPredicate(format: "label CONTAINS 'invalid, expired'")).firstMatch
1047            .waitForExistence(timeout: 15), "bad-code refusal not surfaced")
1048    }
1049}
1050
1051extension LiveSmokeUITests {
1052
1053    /// Orgs: members render, and a team lives a full life — created,
1054    /// granted a repo, the grant revoked, the team deleted. Everything
1055    /// this test makes, it removes.
1056    func testOrgFlows() throws {
1057        openAccountScreen()
1058
1059        let orgRow = app.staticTexts["krz"].firstMatch
1060        XCTAssertTrue(orgRow.waitForExistence(timeout: 15), "org list missing")
1061        orgRow.tap()
1062
1063        // Members render with roles.
1064        XCTAssertTrue(app.staticTexts[Self.smokeUser].firstMatch
1065            .waitForExistence(timeout: 15), "org members missing")
1066
1067        // Create a team.
1068        let teamField = app.descendants(matching: .any)
1069            .matching(identifier: "org-new-team").firstMatch
1070        XCTAssertTrue(teamField.waitForExistence(timeout: 5))
1071        focusAndType(teamField, "ui-smoke")
1072        app.descendants(matching: .any).matching(identifier: "org-new-team-submit")
1073            .firstMatch.tap()
1074        let teamRow = app.staticTexts["ui-smoke"].firstMatch
1075        XCTAssertTrue(teamRow.waitForExistence(timeout: 15), "created team not listed")
1076
1077        // Grant it a repo, then revoke.
1078        teamRow.tap()
1079        let repoField = app.textFields["org/repo"].firstMatch
1080        XCTAssertTrue(repoField.waitForExistence(timeout: 10))
1081        focusAndType(repoField, "krz/gitbay-ios")
1082        app.buttons["Grant"].firstMatch.tap()
1083        let grantRow = app.staticTexts["krz/gitbay-ios"].firstMatch
1084        XCTAssertTrue(grantRow.waitForExistence(timeout: 15), "grant not listed")
1085        grantRow.swipeLeft()
1086        app.buttons["Revoke"].firstMatch.tap()
1087        // The confirmation dialog's destructive Revoke.
1088        let confirmRevoke = app.buttons["Revoke"].firstMatch
1089        XCTAssertTrue(confirmRevoke.waitForExistence(timeout: 5), "revoke confirmation missing")
1090        confirmRevoke.tap()
1091        XCTAssertTrue(waitForDisappearance(grantRow, timeout: 15), "grant not revoked")
1092
1093        back()
1094
1095        // Delete the team, through its confirmation.
1096        let row = app.staticTexts["ui-smoke"].firstMatch
1097        XCTAssertTrue(row.waitForExistence(timeout: 10))
1098        row.swipeLeft()
1099        app.buttons["Delete"].firstMatch.tap()
1100        // The confirmation dialog's destructive Delete.
1101        let confirm = app.buttons["Delete"].firstMatch
1102        XCTAssertTrue(confirm.waitForExistence(timeout: 5))
1103        confirm.tap()
1104        XCTAssertTrue(waitForDisappearance(row, timeout: 15), "team not deleted")
1105    }
1106}
1107
1108extension LiveSmokeUITests {
1109
1110    /// The pre-merge screenshot checkpoint: walks the dense screens and
1111    /// attaches captures. Run per device/appearance; export the
1112    /// attachments from the xcresult. Signs in first when the device has
1113    /// no session and TEST_RUNNER_GITBAY_UITEST_TOKEN is provided.
1114    func testScreenshotCheckpoint() throws {
1115        signInIfNeeded()
1116
1117        snap("dashboard")
1118
1119        openRepo("krz/gitbay")
1120        snap("repo")
1121
1122        app.staticTexts["Merge Requests"].firstMatch.tap()
1123        let all = app.segmentedControls.buttons["All"].firstMatch
1124        XCTAssertTrue(all.waitForExistence(timeout: 10), "state picker missing")
1125        all.tap()
1126        // A real MR row carries its !number; the picker row does not.
1127        let mrNumber = app.staticTexts
1128            .containing(NSPredicate(format: "label BEGINSWITH '!'")).firstMatch
1129        XCTAssertTrue(mrNumber.waitForExistence(timeout: 15), "no MR rows after All")
1130        snap("mr-list")
1131
1132        mrNumber.tap()
1133        // The detail opens at its header; the diff row sits below the
1134        // fold and a List does not build rows it has not shown.
1135        let diffRow = app.staticTexts["Diff"].firstMatch
1136        XCTAssertTrue(scrollTo(diffRow), "MR detail has no diff row")
1137        snap("mr-detail")
1138
1139        diffRow.tap()
1140        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 15))
1141        snap("diff")
1142    }
1143
1144    private func signInIfNeeded() {
1145        // Signed in already: the tab bar is up and there is no token field.
1146        if app.tabBars.firstMatch.waitForExistence(timeout: 10),
1147           !app.secureTextFields.firstMatch.exists {
1148            return
1149        }
1150        let tokenField = app.secureTextFields.firstMatch
1151        guard tokenField.waitForExistence(timeout: 5) else { return }
1152        guard let token = ProcessInfo.processInfo.environment["GITBAY_UITEST_TOKEN"] else {
1153            XCTFail("device is signed out and no GITBAY_UITEST_TOKEN was provided")
1154            return
1155        }
1156        focusAndType(tokenField, token + "\n")
1157        XCTAssertTrue(app.staticTexts["Dashboard"].firstMatch
1158            .waitForExistence(timeout: 20), "sign-in did not land")
1159        dismissSavePasswordPrompt()
1160    }
1161
1162    /// iOS offers to save whatever went into a SecureField, and the sheet
1163    /// sits over the app until answered — over the dashboard, in one set
1164    /// of store screenshots. It belongs to springboard, not to the app.
1165    private func dismissSavePasswordPrompt() {
1166        let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")
1167        let notNow = springboard.buttons["Not Now"].firstMatch
1168        if notNow.waitForExistence(timeout: 8) {
1169            notNow.tap()
1170            _ = waitForDisappearance(notNow, timeout: 10)
1171            return
1172        }
1173        let inApp = app.buttons["Not Now"].firstMatch
1174        if inApp.waitForExistence(timeout: 3) {
1175            inApp.tap()
1176            _ = waitForDisappearance(inApp, timeout: 10)
1177            return
1178        }
1179        // No prompt is fine: iOS only offers once per credential.
1180    }
1181
1182    /// Capture a screen, but not while it is still loading. These go to
1183    /// the App Store, and a spinner shipped as a screenshot once already.
1184    private func snap(_ name: String, file: StaticString = #filePath, line: UInt = #line) {
1185        let spinner = app.activityIndicators.firstMatch
1186        if spinner.exists {
1187            XCTAssertTrue(waitForDisappearance(spinner, timeout: 30),
1188                          "\(name) still loading after 30s", file: file, line: line)
1189        }
1190        // A list that has loaded has rows; an empty state has text. Either
1191        // way something must be on screen besides chrome.
1192        let content = app.cells.firstMatch
1193        _ = content.waitForExistence(timeout: 10)
1194
1195        let attachment = XCTAttachment(screenshot: app.screenshot())
1196        attachment.name = name
1197        attachment.lifetime = .keepAlways
1198        add(attachment)
1199    }
1200}
1201
1202extension LiveSmokeUITests {
1203
1204    /// Blame and file editing — the two capabilities that were web-only
1205    /// until krz/gitbay#42 and #43 made them commands. Blame is read-only
1206    /// on a real repo; the edit writes to a scratch repo the runner
1207    /// creates and deletes over SSH.
1208    func testBlameAndEditFlows() throws {
1209        // --- blame on a real file ---
1210        openRepo("krz/gitbay")
1211        app.staticTexts["Files"].firstMatch.tap()
1212        let goMod = app.staticTexts["go.mod"].firstMatch
1213        XCTAssertTrue(goMod.waitForExistence(timeout: 15), "go.mod not in the tree")
1214        goMod.tap()
1215        XCTAssertTrue(app.descendants(matching: .any).matching(identifier: "file-actions-menu")
1216            .firstMatch.waitForExistence(timeout: 15), "file screen did not open")
1217        app.descendants(matching: .any).matching(identifier: "file-actions-menu")
1218            .firstMatch.tap()
1219        app.buttons["Blame"].firstMatch.tap()
1220        // Attribution shows the commit subject beside the lines.
1221        XCTAssertTrue(app.staticTexts
1222            .containing(NSPredicate(format: "label CONTAINS 'gitbay'")).firstMatch
1223            .waitForExistence(timeout: 20), "blame rendered no attribution")
1224
1225        // --- edit on the scratch repo ---
1226        // Relaunch rather than reuse the list: `.searchable` keeps the
1227        // previous query, and clearing it from the harness is unreliable.
1228        app.terminate()
1229        app.launch()
1230        openRepo(Self.fixtureRepo)
1231        app.staticTexts["Files"].firstMatch.tap()
1232        let notes = app.staticTexts["notes.txt"].firstMatch
1233        XCTAssertTrue(notes.waitForExistence(timeout: 15), "notes.txt not in the tree")
1234        notes.tap()
1235
1236        let menu = app.descendants(matching: .any)
1237            .matching(identifier: "file-actions-menu").firstMatch
1238        XCTAssertTrue(menu.waitForExistence(timeout: 15))
1239        menu.tap()
1240        let edit = app.buttons
1241            .containing(NSPredicate(format: "label BEGINSWITH 'Edit on'")).firstMatch
1242        XCTAssertTrue(edit.waitForExistence(timeout: 5), "edit action missing")
1243        edit.tap()
1244
1245        let content = app.descendants(matching: .any)
1246            .matching(identifier: "file-edit-content").firstMatch
1247        XCTAssertTrue(content.waitForExistence(timeout: 10), "edit sheet did not open")
1248        focusAndType(content, " edited from the app")
1249
1250        let message = app.descendants(matching: .any)
1251            .matching(identifier: "file-edit-message").firstMatch
1252        focusAndType(message, "edit from ios")
1253
1254        app.descendants(matching: .any).matching(identifier: "file-edit-commit")
1255            .firstMatch.tap()
1256        XCTAssertTrue(waitForDisappearance(content, timeout: 20), "commit did not dismiss")
1257        // The reloaded file shows the committed text.
1258        XCTAssertTrue(app.staticTexts
1259            .containing(NSPredicate(format: "label CONTAINS 'edited from the app'")).firstMatch
1260            .waitForExistence(timeout: 20), "edit not reflected after commit")
1261    }
1262}
1263
1264
1265extension LiveSmokeUITests {
1266
1267    /// The navigation and profile changes: identity lives in one menu,
1268    /// the dashboard can create a repository, a profile is a real
1269    /// profile, and a log entry opens its commit.
1270    func testProfileAndNavigationFlows() throws {
1271        // --- the dashboard offers creation ---
1272        selectTab("Dashboard")
1273        let create = app.descendants(matching: .any)
1274            .matching(identifier: "dashboard-create-button").firstMatch
1275        XCTAssertTrue(create.waitForExistence(timeout: 15), "dashboard + missing")
1276        create.tap()
1277        let pathField = app.descendants(matching: .any)
1278            .matching(identifier: "repo-create-path").firstMatch
1279        XCTAssertTrue(pathField.waitForExistence(timeout: 10),
1280                      "dashboard + did not open the create sheet")
1281        app.buttons["Cancel"].firstMatch.tap()
1282
1283        // --- identity is its own tab; the account menu rides with it ---
1284        selectTab("My Profile")
1285        let menu = app.descendants(matching: .any)
1286            .matching(identifier: "account-menu").firstMatch
1287        XCTAssertTrue(menu.waitForExistence(timeout: 10),
1288                      "account menu missing from My Profile")
1289        menu.tap()
1290        XCTAssertTrue(app.buttons["Keys & Email"].firstMatch.waitForExistence(timeout: 5),
1291                      "keys not in the account menu")
1292        // ios-smoke is not an instance admin.
1293        XCTAssertFalse(app.descendants(matching: .any)
1294            .matching(identifier: "account-menu-admin").firstMatch.exists,
1295            "a non-admin is offered Admin")
1296        app.tap() // dismiss the menu; the profile is already on screen
1297
1298        // --- a profile is a profile: description, links, orgs, graph, repos ---
1299        XCTAssertTrue(app.staticTexts
1300            .containing(NSPredicate(format: "label CONTAINS %@", Self.smokeProfileDescription)).firstMatch
1301            .waitForExistence(timeout: 20), "profile description missing")
1302        XCTAssertTrue(header("Organizations").exists,
1303                      "org memberships missing")
1304        XCTAssertTrue(app.staticTexts["krz"].firstMatch.exists, "org row missing")
1305
1306        // --- an org admin can edit the org's profile ---
1307        app.staticTexts["krz"].firstMatch.tap()
1308        XCTAssertTrue(app.descendants(matching: .any)
1309            .matching(identifier: "profile-edit-button").firstMatch
1310            .waitForExistence(timeout: 15), "org profile offers no edit to its admin")
1311        back()
1312
1313        // --- saving the profile succeeds: profile set takes no about flags ---
1314        let edit = app.descendants(matching: .any)
1315            .matching(identifier: "profile-edit-button").firstMatch
1316        XCTAssertTrue(edit.waitForExistence(timeout: 10), "own profile offers no edit")
1317        edit.tap()
1318        let save = app.buttons["profile-edit-save"].firstMatch
1319        XCTAssertTrue(save.waitForExistence(timeout: 10), "edit sheet did not open")
1320        XCTAssertFalse(app.descendants(matching: .any)
1321            .matching(identifier: "profile-edit-about").firstMatch.exists,
1322            "the sheet still edits the about text")
1323        save.tap()
1324        XCTAssertTrue(app.navigationBars["Edit Profile"].waitForNonExistence(timeout: 15),
1325                      "profile save did not dismiss the sheet — the server refused it")
1326        XCTAssertFalse(save.exists, "the edit sheet is still on screen")
1327
1328        // --- the about text is a file: edit it, or offer to create it ---
1329        let aboutAction = app.descendants(matching: .any).matching(NSPredicate(
1330            format: "identifier IN %@", ["profile-about-edit", "profile-about-create"])).firstMatch
1331        XCTAssertTrue(scrollTo(aboutAction),
1332                      "own profile offers neither editing nor creating the about file")
1333
1334        // The graph and the repositories sit below the orgs and links,
1335        // and a List does not build rows it has not shown.
1336        XCTAssertTrue(scrollTo(app.staticTexts
1337            .containing(NSPredicate(format: "label CONTAINS 'contributions in the last year'")).firstMatch),
1338            "activity graph missing")
1339        XCTAssertTrue(scrollTo(app.staticTexts
1340            .containing(NSPredicate(format: "label BEGINSWITH[c] 'Repositories'")).firstMatch),
1341            "repositories missing")
1342
1343        // --- a log entry opens its commit ---
1344        app.terminate()
1345        app.launch()
1346        openRepo("krz/gitbay")
1347        app.staticTexts["History"].firstMatch.tap()
1348        let firstCommit = app.cells.firstMatch
1349        XCTAssertTrue(firstCommit.waitForExistence(timeout: 20), "history is empty")
1350        firstCommit.tap()
1351        // The commit screen IS the patch: no navigating away to find it.
1352        // A hunk header (@@) only appears in a rendered diff, and sits
1353        // below the message and the file list.
1354        let hunk = app.staticTexts
1355            .containing(NSPredicate(format: "label BEGINSWITH '@@'")).firstMatch
1356        _ = hunk.waitForExistence(timeout: 20)
1357        XCTAssertTrue(scrollTo(hunk, swipes: 10),
1358                      "commit screen did not render the patch inline")
1359    }
1360}
1361
1362extension LiveSmokeUITests {
1363
1364    /// The three gaps that needed no server work: branches and tags,
1365    /// milestones, and an MR's milestone. Read-only except the MR
1366    /// milestone, which is set and cleared back.
1367    func testRefsAndMilestoneFlows() throws {
1368        openRepo("krz/gitbay")
1369
1370        // --- branches and tags, and browsing at a ref ---
1371        app.staticTexts["Branches & Tags"].firstMatch.tap()
1372        let main = app.staticTexts["main"].firstMatch
1373        XCTAssertTrue(main.waitForExistence(timeout: 20), "refs did not load")
1374        XCTAssertTrue(app.staticTexts["default"].firstMatch.exists,
1375                      "the default branch is not marked")
1376        XCTAssertTrue(header("Tags").exists, "tags section missing")
1377        main.tap()
1378        // Tapping a ref browses the repository there.
1379        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 20),
1380                      "browsing at a ref showed nothing")
1381        back()
1382        back()
1383
1384        // --- milestones with progress ---
1385        app.staticTexts["Milestones"].firstMatch.tap()
1386        XCTAssertTrue(app.segmentedControls.firstMatch.waitForExistence(timeout: 15),
1387                      "milestones did not load")
1388        app.segmentedControls.buttons["All"].firstMatch.tap()
1389        XCTAssertTrue(app.staticTexts
1390            .containing(NSPredicate(format: "label CONTAINS 'closed'")).firstMatch
1391            .waitForExistence(timeout: 20), "milestone progress missing")
1392        back()
1393
1394        // --- an MR's milestone reads back, and can be cleared ---
1395        app.staticTexts["Merge Requests"].firstMatch.tap()
1396        app.segmentedControls.buttons["All"].firstMatch.tap()
1397        let mrNumber = app.staticTexts
1398            .containing(NSPredicate(format: "label BEGINSWITH '!'")).firstMatch
1399        XCTAssertTrue(mrNumber.waitForExistence(timeout: 20), "no MRs")
1400        mrNumber.tap()
1401        let milestone = app.descendants(matching: .any)
1402            .matching(identifier: "mr-milestone-menu").firstMatch
1403        // The nav bar is the "opened" signal; everything else on this
1404        // screen can be below the fold.
1405        XCTAssertTrue(app.navigationBars.element.waitForExistence(timeout: 20),
1406                      "MR detail did not open")
1407        XCTAssertTrue(scrollTo(milestone, swipes: 8), "MR milestone row missing")
1408        milestone.tap()
1409        // The picker offers None plus the open milestones.
1410        XCTAssertTrue(app.buttons["None"].firstMatch.waitForExistence(timeout: 10),
1411                      "milestone picker did not open")
1412        app.buttons["None"].firstMatch.tap()
1413    }
1414}
1415
1416extension LiveSmokeUITests {
1417
1418    /// Explore and history at a ref — the two capabilities krz/gitbay!101
1419    /// made reachable. Read-only.
1420    func testExploreAndRefLogFlows() throws {
1421        // --- explore lists what the instance hosts ---
1422        selectTab("Explore")
1423        let firstRepo = app.cells.firstMatch
1424        XCTAssertTrue(firstRepo.waitForExistence(timeout: 20), "explore listed nothing")
1425        // Public repos this account does not own are reachable here.
1426        XCTAssertTrue(app.staticTexts
1427            .containing(NSPredicate(format: "label CONTAINS 'audit-labs/'")).firstMatch
1428            .waitForExistence(timeout: 10), "explore is not the public listing")
1429        firstRepo.tap()
1430        XCTAssertTrue(app.staticTexts["Files"].firstMatch.waitForExistence(timeout: 20),
1431                      "explore row did not open its repo")
1432
1433        // --- history at a ref ---
1434        app.terminate()
1435        app.launch()
1436        openRepo("krz/gitbay")
1437        // Browse a ref, then ask for its history — the move the tree page
1438        // offers on the web.
1439        app.staticTexts["Branches & Tags"].firstMatch.tap()
1440        let main = app.staticTexts["main"].firstMatch
1441        XCTAssertTrue(main.waitForExistence(timeout: 20), "refs did not load")
1442        main.tap()
1443        let history = app.descendants(matching: .any)
1444            .matching(identifier: "tree-history-button").firstMatch
1445        XCTAssertTrue(history.waitForExistence(timeout: 20), "no History on the tree")
1446        history.tap()
1447        XCTAssertTrue(app.navigationBars
1448            .containing(NSPredicate(format: "identifier CONTAINS 'main'")).firstMatch
1449            .waitForExistence(timeout: 20), "ref history did not open")
1450        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 20),
1451                      "ref history rendered no commits")
1452    }
1453}
1454
1455extension LiveSmokeUITests {
1456
1457    /// The wiki — the last capability that was browser-only until
1458    /// krz/gitbay#48. Read-only; editing is a push, on every surface.
1459    func testWikiFlows() throws {
1460        openRepo("krz/gitbay")
1461        app.staticTexts["Wiki"].firstMatch.tap()
1462
1463        // The landing page leads and is marked.
1464        let home = app.staticTexts["Home"].firstMatch
1465        XCTAssertTrue(home.waitForExistence(timeout: 20), "wiki pages did not load")
1466        XCTAssertTrue(app.staticTexts["home"].firstMatch.exists,
1467                      "the landing page is not marked")
1468
1469        // Parity.org is an org page, so this also proves the org renderer
1470        // runs on wiki content and not just READMEs.
1471        let parity = app.staticTexts["Parity"].firstMatch
1472        XCTAssertTrue(parity.exists, "Parity page missing from the listing")
1473        parity.tap()
1474        XCTAssertTrue(app.staticTexts
1475            .containing(NSPredicate(format: "label CONTAINS 'surface'")).firstMatch
1476            .waitForExistence(timeout: 20), "wiki page rendered no prose")
1477        // Org headings render as headings, not as raw #+title:.
1478        XCTAssertFalse(app.staticTexts
1479            .containing(NSPredicate(format: "label CONTAINS '#+title'")).firstMatch.exists,
1480                       "org markup leaked into the rendered page")
1481    }
1482}
1483
1484
1485extension LiveSmokeUITests {
1486
1487    /// Builds on a repo that has a job file: the picker offers what the
1488    /// server names, and the detail screen says more than the log.
1489    func testBuildJobsAndDetail() throws {
1490        openRepo("krz/gitbay")
1491        app.staticTexts["Builds"].firstMatch.tap()
1492
1493        // The picker lists jobs from `build jobs` — no name to type.
1494        let trigger = app.descendants(matching: .any)
1495            .matching(identifier: "build-trigger-button").firstMatch
1496        XCTAssertTrue(trigger.waitForExistence(timeout: 20), "trigger control missing")
1497        XCTAssertTrue(trigger.isEnabled, "trigger is disabled where a job file exists")
1498        trigger.tap()
1499        let job = app.buttons
1500            .containing(NSPredicate(format: "label CONTAINS 'build' AND label CONTAINS 'on push'"))
1501            .firstMatch
1502        XCTAssertTrue(job.waitForExistence(timeout: 10),
1503                      "job menu did not list the job with why it runs")
1504        // Dismiss without queueing a real build.
1505        app.tap()
1506
1507        // The detail screen carries status, ref and timing, not just log.
1508        let firstBuild = app.cells.firstMatch
1509        XCTAssertTrue(firstBuild.waitForExistence(timeout: 20), "no builds listed")
1510        firstBuild.tap()
1511        for label in ["success", "queued"] where app.staticTexts[label].firstMatch.exists {
1512            XCTAssertTrue(true)
1513        }
1514        XCTAssertTrue(app.staticTexts
1515            .containing(NSPredicate(format: "label BEGINSWITH 'queued '")).firstMatch
1516            .waitForExistence(timeout: 20), "build detail shows no timing")
1517    }
1518}
1519
1520extension LiveSmokeUITests {
1521
1522    /// Store screenshots on iPad. It navigates by tab and through
1523    /// Explore rather than reusing the iPhone checkpoint: that one drives
1524    /// the repo list's `.searchable`, which iPadOS lays out differently,
1525    /// and chasing those differences is the iPad pass this release
1526    /// deferred. Tabs and a list row work on both.
1527    func testIPadScreenshotCheckpoint() throws {
1528        signInIfNeeded()
1529        snap("dashboard")
1530
1531        selectTab("Explore")
1532        snap("explore")
1533
1534        // First public repo in the list — no search field involved.
1535        let firstRepo = app.cells.firstMatch
1536        XCTAssertTrue(firstRepo.waitForExistence(timeout: 20), "explore listed nothing")
1537        firstRepo.tap()
1538        XCTAssertTrue(app.staticTexts["Files"].firstMatch.waitForExistence(timeout: 20),
1539                      "repo screen did not open")
1540        snap("repo")
1541
1542        selectTab("Feed")
1543        snap("feed")
1544
1545        selectTab("My Profile")
1546        // Any signed-in account can edit its own profile, so this holds
1547        // for store screenshots taken as a real user too.
1548        XCTAssertTrue(app.descendants(matching: .any)
1549            .matching(identifier: "profile-edit-button").firstMatch
1550            .waitForExistence(timeout: 20), "profile did not load")
1551        snap("profile")
1552    }
1553}
1554
1555extension LiveSmokeUITests {
1556
1557    /// Snippets, a full life on the caller's own account: create, add a
1558    /// file, replace it, remove it, change visibility, delete. setUp and
1559    /// tearDown remove anything left by this description.
1560    func testSnippetFlows() throws {
1561        selectTab("My Profile")
1562        app.descendants(matching: .any).matching(identifier: "account-menu").firstMatch.tap()
1563        let snippets = app.buttons["Snippets"].firstMatch
1564        XCTAssertTrue(snippets.waitForExistence(timeout: 5), "Snippets missing from the account menu")
1565        snippets.tap()
1566
1567        // --- create ---
1568        let create = app.descendants(matching: .any)
1569            .matching(identifier: "snippet-create-button").firstMatch
1570        XCTAssertTrue(create.waitForExistence(timeout: 15), "snippet list did not open")
1571        create.tap()
1572        let nameField = app.descendants(matching: .any)
1573            .matching(identifier: "snippet-file-name").firstMatch
1574        XCTAssertTrue(nameField.waitForExistence(timeout: 5), "create sheet did not open")
1575        focusAndType(nameField, "ui-smoke.txt")
1576        focusAndType(app.descendants(matching: .any)
1577            .matching(identifier: "snippet-description").firstMatch, Self.smokeSnippetDescription)
1578        let content = app.descendants(matching: .any)
1579            .matching(identifier: "snippet-content").firstMatch
1580        focusAndType(content, "hello from the live suite")
1581        app.descendants(matching: .any).matching(identifier: "snippet-submit").firstMatch.tap()
1582        XCTAssertTrue(waitForDisappearance(nameField, timeout: 20), "create did not dismiss")
1583
1584        let row = app.staticTexts[Self.smokeSnippetDescription].firstMatch
1585        XCTAssertTrue(row.waitForExistence(timeout: 15), "created snippet not listed")
1586        row.tap()
1587
1588        // --- detail: the file renders, unlisted by default ---
1589        XCTAssertTrue(app.staticTexts["ui-smoke.txt"].firstMatch.waitForExistence(timeout: 15),
1590                      "snippet file missing")
1591        XCTAssertTrue(app.staticTexts["unlisted"].firstMatch.exists, "default visibility not unlisted")
1592
1593        // --- add a second file ---
1594        let actions = app.descendants(matching: .any)
1595            .matching(identifier: "snippet-actions-menu").firstMatch
1596        XCTAssertTrue(actions.waitForExistence(timeout: 10), "owner actions missing")
1597        actions.tap()
1598        let addFile = app.buttons["Add file"].firstMatch
1599        XCTAssertTrue(addFile.waitForExistence(timeout: 5))
1600        addFile.tap()
1601        let secondName = app.descendants(matching: .any)
1602            .matching(identifier: "snippet-file-name").firstMatch
1603        XCTAssertTrue(secondName.waitForExistence(timeout: 5), "add-file sheet did not open")
1604        focusAndType(secondName, "second.txt")
1605        focusAndType(app.descendants(matching: .any)
1606            .matching(identifier: "snippet-content").firstMatch, "two")
1607        app.descendants(matching: .any).matching(identifier: "snippet-submit").firstMatch.tap()
1608        XCTAssertTrue(waitForDisappearance(secondName, timeout: 20), "add file did not dismiss")
1609        let second = app.staticTexts["second.txt"].firstMatch
1610        XCTAssertTrue(second.waitForExistence(timeout: 15), "added file missing")
1611
1612        // --- replace its content from the file menu ---
1613        let fileMenu = app.descendants(matching: .any)
1614            .matching(identifier: "snippet-file-menu-second.txt").firstMatch
1615        XCTAssertTrue(scrollTo(fileMenu), "file menu not reachable")
1616        fileMenu.tap()
1617        let edit = app.buttons["Edit"].firstMatch
1618        XCTAssertTrue(edit.waitForExistence(timeout: 5))
1619        edit.tap()
1620        let editor = app.descendants(matching: .any)
1621            .matching(identifier: "snippet-content").firstMatch
1622        XCTAssertTrue(editor.waitForExistence(timeout: 5), "edit sheet did not open")
1623        XCTAssertTrue((editor.value as? String)?.contains("two") == true, "edit sheet did not prefill")
1624        focusAndType(editor, " and three")
1625        app.descendants(matching: .any).matching(identifier: "snippet-submit").firstMatch.tap()
1626        XCTAssertTrue(waitForDisappearance(editor, timeout: 20), "file save did not dismiss")
1627        XCTAssertTrue(app.staticTexts
1628            .containing(NSPredicate(format: "label CONTAINS 'and three'")).firstMatch
1629            .waitForExistence(timeout: 15), "replaced content not rendered")
1630
1631        // --- remove it, through its confirmation ---
1632        XCTAssertTrue(scrollTo(fileMenu), "file menu not reachable after edit")
1633        fileMenu.tap()
1634        app.buttons["Remove"].firstMatch.tap()
1635        let confirmRemove = app.buttons["Remove"].firstMatch
1636        XCTAssertTrue(confirmRemove.waitForExistence(timeout: 5), "remove confirmation missing")
1637        confirmRemove.tap()
1638        XCTAssertTrue(waitForDisappearance(second, timeout: 15), "file not removed")
1639
1640        // --- visibility to public ---
1641        actions.tap()
1642        let settings = app.buttons["Description & visibility"].firstMatch
1643        XCTAssertTrue(settings.waitForExistence(timeout: 5))
1644        settings.tap()
1645        let visibility = app.segmentedControls.firstMatch
1646        XCTAssertTrue(visibility.waitForExistence(timeout: 5), "settings sheet did not open")
1647        visibility.buttons["public"].tap()
1648        app.buttons["Save"].firstMatch.tap()
1649        XCTAssertTrue(app.staticTexts["public"].firstMatch.waitForExistence(timeout: 15),
1650                      "visibility change not shown")
1651
1652        // --- delete, through its confirmation; the list no longer has it ---
1653        actions.tap()
1654        app.buttons["Delete snippet"].firstMatch.tap()
1655        let confirmDelete = app.buttons["Delete"].firstMatch
1656        XCTAssertTrue(confirmDelete.waitForExistence(timeout: 5), "delete confirmation missing")
1657        confirmDelete.tap()
1658        XCTAssertTrue(create.waitForExistence(timeout: 15), "did not return to the snippet list")
1659        XCTAssertTrue(waitForDisappearance(row, timeout: 15), "deleted snippet still listed")
1660    }
1661
1662    /// An SSH key's label round-trips: set from the row's swipe action,
1663    /// then restored to what it was (or cleared).
1664    func testSSHKeyLabelFlow() throws {
1665        openAccountScreen()
1666        let fingerprint = app.staticTexts
1667            .containing(NSPredicate(format: "label BEGINSWITH 'SHA256:'")).firstMatch
1668        XCTAssertTrue(fingerprint.waitForExistence(timeout: 15), "SSH keys missing")
1669        let fp = fingerprint.label
1670
1671        // What the key is called now, so it can be put back.
1672        var original = ""
1673        if let data = readCommand(["keys", "list"]),
1674           let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1675           let rows = envelope["data"] as? [[String: Any]],
1676           let row = rows.first(where: { $0["fingerprint"] as? String == fp }) {
1677            original = row["label"] as? String ?? ""
1678        }
1679
1680        let relabel: (String) -> Void = { text in
1681            fingerprint.swipeLeft()
1682            let label = self.app.buttons["Label"].firstMatch
1683            XCTAssertTrue(label.waitForExistence(timeout: 5), "Label swipe action missing")
1684            label.tap()
1685            let field = self.app.alerts.textFields.firstMatch
1686            XCTAssertTrue(field.waitForExistence(timeout: 5), "label alert missing")
1687            self.clearAndType(field, text)
1688            self.app.alerts.buttons["Save"].firstMatch.tap()
1689        }
1690
1691        relabel("ui-smoke")
1692        XCTAssertTrue(app.staticTexts["ui-smoke"].firstMatch.waitForExistence(timeout: 15),
1693                      "label not shown after save")
1694
1695        relabel(original)
1696        XCTAssertTrue(waitForDisappearance(app.staticTexts["ui-smoke"].firstMatch, timeout: 15),
1697                      "label not restored")
1698        if !original.isEmpty {
1699            XCTAssertTrue(app.staticTexts[original].firstMatch.waitForExistence(timeout: 10),
1700                          "original label not back")
1701        }
1702    }
1703
1704    /// Org labels and milestones from the org screen: a label is created
1705    /// and removed; the fixture milestone is reopened and closed again,
1706    /// and creating it a second time surfaces the server's refusal.
1707    func testOrgLabelAndMilestoneFlows() throws {
1708        openAccountScreen()
1709        let orgRow = app.staticTexts[Self.smokeOrg].firstMatch
1710        XCTAssertTrue(orgRow.waitForExistence(timeout: 15), "org list missing")
1711        orgRow.tap()
1712        XCTAssertTrue(app.staticTexts[Self.smokeUser].firstMatch.waitForExistence(timeout: 15),
1713                      "org members missing")
1714
1715        // --- labels ---
1716        let labels = app.staticTexts["Labels"].firstMatch
1717        XCTAssertTrue(scrollTo(labels), "Labels link not reachable")
1718        labels.tap()
1719        let newName = app.descendants(matching: .any)
1720            .matching(identifier: "label-new-name").firstMatch
1721        XCTAssertTrue(newName.waitForExistence(timeout: 15), "org labels did not open")
1722        focusAndType(newName, Self.smokeOrgLabel)
1723        app.descendants(matching: .any).matching(identifier: "label-create-submit").firstMatch.tap()
1724        let chip = app.staticTexts[Self.smokeOrgLabel].firstMatch
1725        XCTAssertTrue(chip.waitForExistence(timeout: 15), "org label not listed after create")
1726
1727        // The org's own screen manages its rows: the menu is there, not
1728        // the read-only mark.
1729        let cell = app.cells.containing(.staticText, identifier: Self.smokeOrgLabel).firstMatch
1730        let menu = cell.buttons.firstMatch
1731        XCTAssertTrue(menu.waitForExistence(timeout: 5), "org label has no menu on the org screen")
1732        menu.tap()
1733        let remove = app.buttons["Remove"].firstMatch
1734        XCTAssertTrue(remove.waitForExistence(timeout: 5))
1735        remove.tap()
1736        let confirmRemove = app.buttons["Remove"].firstMatch
1737        XCTAssertTrue(confirmRemove.waitForExistence(timeout: 5), "remove confirmation missing")
1738        confirmRemove.tap()
1739        XCTAssertTrue(waitForDisappearance(chip, timeout: 15), "org label not removed")
1740        back()
1741
1742        // --- milestones ---
1743        let milestones = app.staticTexts["Milestones"].firstMatch
1744        XCTAssertTrue(scrollTo(milestones), "Milestones link not reachable")
1745        milestones.tap()
1746        let picker = app.segmentedControls.firstMatch
1747        XCTAssertTrue(picker.waitForExistence(timeout: 15), "org milestones did not open")
1748        picker.buttons["Closed"].tap()
1749        let fixture = app.staticTexts[Self.smokeOrgMilestone].firstMatch
1750        XCTAssertTrue(fixture.waitForExistence(timeout: 15), "fixture milestone not among closed")
1751        fixture.swipeLeft()
1752        let reopen = app.buttons["Reopen"].firstMatch
1753        XCTAssertTrue(reopen.waitForExistence(timeout: 5), "reopen action missing on the org screen")
1754        reopen.tap()
1755        XCTAssertTrue(waitForDisappearance(fixture, timeout: 15), "reopened milestone still among closed")
1756        picker.buttons["Open"].tap()
1757        XCTAssertTrue(fixture.waitForExistence(timeout: 15), "reopened milestone not among open")
1758
1759        // Creating it again is refused with the server's sentence.
1760        app.descendants(matching: .any).matching(identifier: "milestone-create-button").firstMatch.tap()
1761        let title = app.descendants(matching: .any)
1762            .matching(identifier: "milestone-title").firstMatch
1763        XCTAssertTrue(title.waitForExistence(timeout: 5), "create sheet did not open")
1764        focusAndType(title, Self.smokeOrgMilestone)
1765        app.descendants(matching: .any).matching(identifier: "milestone-submit").firstMatch.tap()
1766        XCTAssertTrue(app.staticTexts
1767            .containing(NSPredicate(format: "label CONTAINS[c] 'already'")).firstMatch
1768            .waitForExistence(timeout: 15), "duplicate milestone refusal not surfaced")
1769        app.buttons["Cancel"].firstMatch.tap()
1770
1771        // Back to closed, where the fixture rests.
1772        XCTAssertTrue(fixture.waitForExistence(timeout: 10))
1773        fixture.swipeLeft()
1774        let close = app.buttons["Close"].firstMatch
1775        XCTAssertTrue(close.waitForExistence(timeout: 5), "close action missing on the org screen")
1776        close.tap()
1777        XCTAssertTrue(waitForDisappearance(fixture, timeout: 15), "closed milestone still among open")
1778    }
1779
1780    /// Build list filters on a repo with builds: a status narrows the
1781    /// list, a job narrows it further, and an impossible pair shows the
1782    /// filtered empty state. Clearing brings the list back.
1783    func testBuildFilterFlow() throws {
1784        openRepo("krz/gitbay")
1785        app.staticTexts["Builds"].firstMatch.tap()
1786        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 20), "no builds listed")
1787
1788        let filter = app.descendants(matching: .any)
1789            .matching(identifier: "build-filter-button").firstMatch
1790        XCTAssertTrue(filter.waitForExistence(timeout: 10), "filter button missing")
1791
1792        let choose: (String, String) -> Void = { menuId, option in
1793            let menu = self.app.descendants(matching: .any).matching(identifier: menuId).firstMatch
1794            XCTAssertTrue(menu.waitForExistence(timeout: 5), "\(menuId) missing")
1795            menu.tap()
1796            let choice = self.app.buttons[option].firstMatch
1797            XCTAssertTrue(choice.waitForExistence(timeout: 5), "\(option) not offered")
1798            choice.tap()
1799        }
1800
1801        // status = success: rows remain and every row says success.
1802        filter.tap()
1803        choose("build-filter-status-menu", "success")
1804        app.buttons["Done"].firstMatch.tap()
1805        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 20), "no successful builds")
1806        XCTAssertFalse(app.staticTexts["failure"].firstMatch.exists, "a failed build survived the filter")
1807
1808        // job = test as well: the rows name the job.
1809        filter.tap()
1810        choose("build-filter-job-menu", "test")
1811        app.buttons["Done"].firstMatch.tap()
1812        XCTAssertTrue(app.staticTexts["test"].firstMatch
1813            .waitForExistence(timeout: 20), "job filter did not narrow to test")
1814
1815        // status = pending on a quiet repo: the filtered empty state.
1816        filter.tap()
1817        choose("build-filter-status-menu", "pending")
1818        app.buttons["Done"].firstMatch.tap()
1819        XCTAssertTrue(app.staticTexts["No builds match these filters."].firstMatch
1820            .waitForExistence(timeout: 20), "filtered empty state missing")
1821
1822        // Clear: the list is back.
1823        filter.tap()
1824        app.buttons["Clear filters"].firstMatch.tap()
1825        app.buttons["Done"].firstMatch.tap()
1826        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 20), "list did not come back")
1827    }
1828
1829    /// krz/gitbay has well over thirty builds, so the thirty-first is on
1830    /// the second page. Reaching it means the footer asked for more.
1831    func testBuildPagingFlow() throws {
1832        guard let data = readCommand(["build", "list", "krz/gitbay", "--limit", "31"]),
1833              let envelope = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
1834              let page = envelope["data"] as? [String: Any],
1835              let items = page["items"] as? [[String: Any]], items.count == 31,
1836              let number = items[30]["number"] as? Int
1837        else { throw XCTSkip("could not read krz/gitbay's builds over the API") }
1838
1839        openRepo("krz/gitbay")
1840        app.staticTexts["Builds"].firstMatch.tap()
1841        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 20), "no builds listed")
1842        let thirtyFirst = app.staticTexts
1843            .containing(NSPredicate(format: "label BEGINSWITH %@", "#\(number) ")).firstMatch
1844        XCTAssertTrue(scrollTo(thirtyFirst, swipes: 20),
1845                      "build #\(number), the first row of page two, never appeared")
1846    }
1847
1848    /// Close in favour of another: the first fixture merge request is
1849    /// closed from the app naming the second; the page then says so and
1850    /// links to it.
1851    func testCloseInFavourFlow() throws {
1852        openRepo(Self.fixtureRepo)
1853        app.staticTexts["Merge Requests"].firstMatch.tap()
1854        let superseded = app.staticTexts[Self.supersededTitle].firstMatch
1855        XCTAssertTrue(superseded.waitForExistence(timeout: 15), "fixture MR not listed")
1856        superseded.tap()
1857
1858        app.descendants(matching: .any).matching(identifier: "mr-actions-menu").firstMatch.tap()
1859        let close = app.buttons["Close"].firstMatch
1860        XCTAssertTrue(close.waitForExistence(timeout: 5))
1861        close.tap()
1862        let inFavour = app.buttons["Close in favour of another…"].firstMatch
1863        XCTAssertTrue(inFavour.waitForExistence(timeout: 5), "close dialog has no in-favour choice")
1864        inFavour.tap()
1865
1866        let successor = app.staticTexts[Self.successorTitle].firstMatch
1867        XCTAssertTrue(successor.waitForExistence(timeout: 15), "successor not offered")
1868        successor.tap()
1869        let confirm = app.buttons["Close"].firstMatch
1870        XCTAssertTrue(confirm.waitForExistence(timeout: 5), "in-favour confirmation missing")
1871        confirm.tap()
1872
1873        XCTAssertTrue(app.staticTexts
1874            .containing(NSPredicate(format: "label BEGINSWITH 'closed in favour of !'")).firstMatch
1875            .waitForExistence(timeout: 20), "resolution does not name the successor")
1876        let link = app.staticTexts
1877            .containing(NSPredicate(format: "label BEGINSWITH 'Superseded by !'")).firstMatch
1878        XCTAssertTrue(scrollTo(link), "superseded-by link missing")
1879        link.tap()
1880        XCTAssertTrue(app.staticTexts[Self.successorTitle].firstMatch.waitForExistence(timeout: 20),
1881                      "link did not open the successor")
1882    }
1883
1884    /// A label added from the merge request screen shows as a chip, the
1885    /// list filters to it, and removing it clears the chip.
1886    func testMRLabelFlow() throws {
1887        openRepo(Self.fixtureRepo)
1888        app.staticTexts["Merge Requests"].firstMatch.tap()
1889        let row = app.staticTexts[Self.labelledTitle].firstMatch
1890        XCTAssertTrue(row.waitForExistence(timeout: 15), "fixture MR not listed")
1891        row.tap()
1892
1893        let field = app.textFields["mr-label-field"].firstMatch
1894        XCTAssertTrue(scrollTo(field), "no label field on the merge request")
1895        field.tap()
1896        field.typeText(Self.smokeMRLabel)
1897        app.buttons["mr-label-add"].firstMatch.tap()
1898        let remove = app.buttons["mr-label-remove-\(Self.smokeMRLabel)"].firstMatch
1899        XCTAssertTrue(remove.waitForExistence(timeout: 15), "added label has no chip")
1900
1901        back()
1902        XCTAssertTrue(app.staticTexts[Self.unlabelledTitle].firstMatch.waitForExistence(timeout: 15),
1903                      "unlabelled fixture MR not listed")
1904        app.descendants(matching: .any).matching(identifier: "mr-filter-button").firstMatch.tap()
1905        let menu = app.descendants(matching: .any).matching(identifier: "filter-label-menu").firstMatch
1906        XCTAssertTrue(menu.waitForExistence(timeout: 10), "MR filter sheet has no label picker")
1907        menu.tap()
1908        let choice = app.buttons[Self.smokeMRLabel].firstMatch
1909        XCTAssertTrue(choice.waitForExistence(timeout: 10), "label not offered in the picker")
1910        choice.tap()
1911        app.buttons["Done"].firstMatch.tap()
1912        XCTAssertTrue(row.waitForExistence(timeout: 15), "label filter dropped the labelled MR")
1913        XCTAssertTrue(app.staticTexts[Self.unlabelledTitle].firstMatch.waitForNonExistence(timeout: 15),
1914                      "label filter did not narrow the list")
1915
1916        row.tap()
1917        XCTAssertTrue(scrollTo(remove), "chip missing on reopen")
1918        remove.tap()
1919        XCTAssertTrue(remove.waitForNonExistence(timeout: 15), "removed label still shown")
1920    }
1921
1922    /// A comment's preview renders its markup before anything is sent:
1923    /// the bold markers are gone and the word remains. Nothing is posted.
1924    func testMarkupPreviewFlow() throws {
1925        openRepo(Self.fixtureRepo)
1926        app.staticTexts["Issues"].firstMatch.tap()
1927        let issue = app.staticTexts[Self.fixtureIssueTitle].firstMatch
1928        XCTAssertTrue(issue.waitForExistence(timeout: 15), "fixture issue not listed")
1929        issue.tap()
1930
1931        let field = app.descendants(matching: .any)
1932            .matching(identifier: "issue-comment-field").firstMatch
1933        XCTAssertTrue(scrollTo(field, swipes: 10), "no comment field on the issue")
1934        let draft = "**Bold preview**"
1935        focusAndType(field, draft)
1936
1937        let preview = app.descendants(matching: .any)
1938            .matching(identifier: "issue-comment-preview").firstMatch
1939        XCTAssertTrue(scrollTo(preview), "no preview row for a non-empty comment")
1940        // The keyboard can cover the row right after typing.
1941        for _ in 0..<3 where !preview.isHittable { app.swipeUp() }
1942        preview.tap()
1943        let rendered = app.staticTexts
1944            .containing(NSPredicate(format: "label CONTAINS 'Bold preview'")).firstMatch
1945        if !rendered.waitForExistence(timeout: 3) {
1946            // The row's identifier can land on the cell rather than the toggle.
1947            app.buttons["Preview"].firstMatch.tap()
1948        }
1949        XCTAssertTrue(rendered.waitForExistence(timeout: 5), "preview did not render the draft")
1950        XCTAssertFalse(app.staticTexts
1951            .containing(NSPredicate(format: "label CONTAINS '**Bold'")).firstMatch.exists,
1952            "preview shows the raw markup")
1953
1954        // Kept on success too: this is how the preview's look is checked
1955        // in light and dark without signing a simulator in by hand.
1956        // The rendered text sits under the keyboard, below the comment
1957        // field. A drag on the list moves the row above the keyboard for
1958        // the screenshot; the wait lets the scroll settle.
1959        if app.keyboards.firstMatch.exists {
1960            app.swipeDown()
1961            _ = app.keyboards.firstMatch.waitForNonExistence(timeout: 3)
1962        }
1963        XCTAssertTrue(scrollTo(rendered), "rendered preview scrolled away")
1964        let shot = XCTAttachment(screenshot: app.screenshot())
1965        shot.name = "markup preview"
1966        shot.lifetime = .keepAlways
1967        add(shot)
1968
1969        // Leave the fixture as found: clear the draft, send nothing.
1970        XCTAssertTrue(scrollTo(field), "comment field scrolled away")
1971        field.coordinate(withNormalizedOffset: CGVector(dx: 0.98, dy: 0.9)).tap()
1972        let typed = (field.value as? String)?.count ?? draft.count
1973        field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: typed))
1974        XCTAssertTrue(preview.waitForNonExistence(timeout: 5), "preview row outlived an empty comment")
1975    }
1976}