ps-qa 0.8.2

Drive a running Blitz app through its MCP control socket and assert what the renderer did
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Pointer, keyboard, and text input against a running application.

use std::collections::HashSet;
use std::time::{Duration, Instant};

use blitz_control_protocol::{
    AgentAction, AgentControlRequest, InputCommand, KeyPhase, Modifiers, PointerPhase,
    SemanticNode, WheelPhase, client::safe_response_code,
};
use eyre::{Result, bail, eyre};

use crate::diagnostics::metrics_if_supported;
use crate::inspector::{Client, inspect};
use crate::qa::KeyStep;
use crate::target::{locate_control, selector_matches_node};
use crate::timing::{check_timeout, pace, sleep_pace};
use crate::{cli, reach, report};

pub(crate) async fn hover_over(client: &mut Client, want: &str) -> Result<bool> {
    // "x,y" targets a point directly. A scroll container often has no
    // accessible name, so naming is not always enough to put the pointer inside
    // the thing you mean to scroll: a repeated label can find a button in the
    // sidebar and every wheel event went there.
    if let Some((x, y)) = want.split_once(',')
        && let (Ok(x), Ok(y)) = (x.trim().parse::<f64>(), y.trim().parse::<f64>())
    {
        {
            client
                .agent(&AgentControlRequest::Act(AgentAction::Input(
                    InputCommand::Pointer {
                        phase: PointerPhase::Move,
                        x,
                        y,
                        button: 0,
                        modifiers: Modifiers::default(),
                    },
                )))
                .await?;
            println!("pointer at {x:.0},{y:.0}");
            return Ok(true);
        }
    }
    let (snapshot, _) = inspect(client).await?;
    let Some(node) = snapshot
        .nodes
        .iter()
        .filter(|node| node.visible && selector_matches_node(node, want))
        .filter_map(|node| node.bounds.map(|bounds| (node, bounds)))
        .max_by(|a, b| {
            (a.1[2] * a.1[3])
                .partial_cmp(&(b.1[2] * b.1[3]))
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .map(|(node, bounds)| (node.name.clone(), bounds))
    else {
        println!("no visible node named {want:?} to hover; wheel goes wherever it goes");
        return Ok(false);
    };
    let (name, bounds) = node;
    let (x, y) = (bounds[0] + bounds[2] / 2.0, bounds[1] + bounds[3] / 2.0);
    client
        .agent(&AgentControlRequest::Act(AgentAction::Input(
            InputCommand::Pointer {
                phase: PointerPhase::Move,
                x,
                y,
                button: 0,
                modifiers: Modifiers::default(),
            },
        )))
        .await?;
    println!("pointer over {name:?} at {x:.0},{y:.0}");
    Ok(true)
}

/// Move a real pointer while held; coordinates stay in viewport pixels at any zoom.
pub(crate) async fn pointer_drag(
    client: &mut Client,
    want: &str,
    dx: f64,
    dy: f64,
    steps: u32,
    cancel: bool,
    to: Option<&str>,
) -> Result<()> {
    if !dx.is_finite() || !dy.is_finite() || steps == 0 || steps > 240 {
        bail!("pointer drag needs finite offsets and 1..=240 steps");
    }
    let destination = if let Some(to) = to {
        let (_, bounds) = locate_control(client, to, &[]).await?;
        Some((bounds[0] + bounds[2] / 2.0, bounds[1] + bounds[3] / 2.0))
    } else {
        None
    };
    let (_, bounds) = locate_control(client, want, &[]).await?;
    let start = (bounds[0] + bounds[2] / 2.0, bounds[1] + bounds[3] / 2.0);
    let (dx, dy) = destination.map_or((dx, dy), |end| (end.0 - start.0, end.1 - start.1));
    let request = |phase, x, y| {
        AgentControlRequest::Act(AgentAction::Input(InputCommand::Pointer {
            phase,
            x,
            y,
            button: 0,
            modifiers: Modifiers::default(),
        }))
    };
    for phase in [PointerPhase::Move, PointerPhase::Down] {
        client.agent(&request(phase, start.0, start.1)).await?;
    }
    let mut position = start;
    for step in 1..=steps {
        let fraction = f64::from(step) / f64::from(steps);
        position = (start.0 + dx * fraction, start.1 + dy * fraction);
        if let Err(error) = client
            .agent(&request(PointerPhase::Move, position.0, position.1))
            .await
        {
            // A failed move must not leave the shared host's pointer held down.
            let _ = client
                .agent(&request(PointerPhase::Cancel, position.0, position.1))
                .await;
            return Err(error);
        }
        sleep_pace().await;
    }
    client
        .agent(&request(
            if cancel {
                PointerPhase::Cancel
            } else {
                PointerPhase::Up
            },
            position.0,
            position.1,
        ))
        .await?;
    println!(
        "pointer drag {want:?}: {:.1},{:.1} -> {:.1},{:.1} ({})",
        start.0,
        start.1,
        position.0,
        position.1,
        if cancel { "cancelled" } else { "released" }
    );
    Ok(())
}

pub(crate) async fn scroll(client: &mut Client, ticks: usize, delta: f64) -> Result<()> {
    // Say what the pace is, every time, before any number is printed.
    //
    // The default sends a wheel event every 1/60s, so the app is asked for
    // roughly 60 frames a second and answers about 53 once the sleep overhead
    // is counted. Read without this line, that 53 looks like the application
    // failing to keep up on a 120Hz display, and the `missed_refreshes` figure
    // beside it appears to confirm it. Both are describing this loop.
    //
    // `--pace 0` sends as fast as the app accepts, which is what measures
    // the application: it reaches 120fps with no missed refreshes.
    let pace = pace();
    if pace.is_zero() {
        println!("pace: unpaced (--pace 0) - measures app throughput");
    } else {
        println!(
            "pace: {:.2}ms between events ({:.0} Hz requested); fps and missed_refreshes \
             below describe this pace, not the app's limit. Pass --pace 0 to remove it",
            pace.as_secs_f64() * 1000.0,
            1.0 / pace.as_secs_f64(),
        );
    }

    let mut latencies = scroll_events(client, ticks, delta).await?;
    report::show_latencies("wheel events", ticks, &mut latencies);
    Ok(())
}

/** Send wheel input without the benchmark report, for declarative QA actions. */
pub(crate) async fn scroll_events(
    client: &mut Client,
    ticks: usize,
    delta: f64,
) -> Result<Vec<f64>> {
    let mut latencies = Vec::with_capacity(ticks);
    for _ in 0..ticks {
        let started = Instant::now();
        client
            .agent(&AgentControlRequest::Act(AgentAction::Input(
                InputCommand::Wheel {
                    delta_x: 0.0,
                    delta_y: delta,
                    phase: WheelPhase::Moved,
                    modifiers: Modifiers::default(),
                },
            )))
            .await?;
        latencies.push(started.elapsed().as_secs_f64() * 1000.0);
        sleep_pace().await;
    }
    Ok(latencies)
}

/// Whether a semantic role accepts literal text entry.
///
/// An editable combobox is still a text field. Restricting this to `textbox`
/// made `type_into` unable to exercise exactly the input side of ComboBox,
/// even though the protocol's SetValue action already supports its underlying
/// input element.
fn is_text_field_role(role: &str) -> bool {
    matches!(
        role,
        "textbox" | "textarea" | "input" | "combobox" | "searchbox" | "spinbutton"
    )
}

/// The unique enabled, visible text field matching `want` on the active layer.
/// Ambiguous matches fail closed instead of selecting the first matching node.
fn unique_text_field<'a>(
    fields: impl IntoIterator<Item = &'a SemanticNode>,
) -> std::result::Result<Option<&'a SemanticNode>, &'static str> {
    let mut found = None;
    for field in fields {
        if found.is_some() {
            return Err("ambiguous_text_field_match");
        }
        found = Some(field);
    }
    Ok(found)
}

fn find_text_field<'a>(
    nodes: &'a [SemanticNode],
    want: &str,
) -> std::result::Result<Option<&'a SemanticNode>, &'static str> {
    let modal_scope: HashSet<u64> = reach::dismissers(nodes)
        .first()
        .map(|(id, _)| reach::enclosing_dialog(nodes, *id))
        .unwrap_or_default()
        .into_iter()
        .collect();
    let surface_scope: HashSet<u64> = reach::surfaces()
        .iter()
        .find(|surface| reach::on_surface(nodes, surface))
        .map(|surface| reach::on_surface_subtree(nodes, surface))
        .unwrap_or_default()
        .into_iter()
        .collect();
    let fields: Vec<&SemanticNode> = nodes
        .iter()
        .filter(|node| {
            is_text_field_role(node.role.as_str())
                && node.enabled
                && node.visible
                && node
                    .bounds
                    .is_some_and(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
        })
        .collect();

    let matches_name = |node: &&SemanticNode| want.is_empty() || selector_matches_node(node, want);
    for scope in [&modal_scope, &surface_scope] {
        let scoped = unique_text_field(
            fields
                .iter()
                .copied()
                .filter(|node| matches_name(node) && scope.contains(&node.id)),
        )?;
        if scoped.is_some() {
            return Ok(scoped);
        }
    }
    unique_text_field(fields.into_iter().filter(matches_name))
}

/// Drive real key events into a focused text field and price them.
///
/// Typing is the interaction the composer autosizes on: it writes
/// `style.height`, reads `scrollHeight`, and writes it again, so every
/// keystroke forces a synchronous layout resolve. Scrolling never exercises
/// that path, which is why a scroll benchmark cannot stand in for this one.
/// Send a named key, optionally repeated, after focusing something inside a
/// named container.
///
/// Wheel events could not scroll the transcript: they carry no coordinates, and
/// pointing them at the pane still moved nothing. Page Up does, because it goes
/// to the focused scroller, and without it every attempt to reach the rows the
/// owner was looking at meant asking a person to scroll. A bug that only
/// reproduces by hand is a bug that gets one measurement per message.
pub(crate) async fn press_key(
    client: &mut Client,
    name: &str,
    count: usize,
    over: &str,
    require_target: bool,
) -> Result<()> {
    // A key goes to the focused node, so focus the target first without
    // activating it. This cannot be a click: a button's click is its action,
    // and setup would submit, delete or fork before the key under test arrived.
    let (snapshot, _) = inspect(client).await?;
    // A control whose only label is `sr-only` reaches the semantic tree with an
    // empty name, so no substring can address it. The slider is one, which is
    // why targeting by node id has to be possible at all.
    let by_id = over.parse::<u64>().ok().filter(|id| {
        snapshot.nodes.iter().any(|node| {
            node.id == *id
                && node
                    .bounds
                    .is_some_and(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
        })
    });
    let target = if by_id.is_some() || over.is_empty() {
        by_id
    } else {
        match locate_control(client, over, &[]).await {
            Ok((node_id, _)) => Some(node_id),
            Err(error) if require_target => {
                bail!("no enabled, painted key target matching {over:?}: {error}")
            }
            Err(_) => None,
        }
    };
    if let Some(target) = target {
        client
            .agent(&AgentControlRequest::Act(AgentAction::Focus {
                node_id: target,
            }))
            .await?;
        println!("focused node {target} for {name} x{count}");
    } else if require_target {
        bail!("no enabled, painted key target matching {over:?}");
    } else {
        println!("no visible node named {over:?}; sending {name} to whatever has focus");
    }

    let (key, code, modifiers) = parse_key_chord(name)?;

    for _ in 0..count {
        dispatch_key(client, &key, &code, modifiers, KeyPhase::Down).await?;
        dispatch_key(client, &key, &code, modifiers, KeyPhase::Up).await?;
        sleep_pace().await;
    }
    Ok(())
}

/// Parse the same compact chord a person would write in a QA manifest.
///
/// `key` and `code` are both what the DOM calls them. They are not
/// interchangeable and sending the wrong one is a silent no-op. Modifiers
/// belong on both phases of the key event, so the application sees the actual
/// shortcut rather than a plain character that merely resembles it.
pub(crate) fn parse_key_chord(name: &str) -> Result<(String, String, Modifiers)> {
    // A manifest writes the space key as `" "`. Trimming that would drop the
    // only part and report an empty chord.
    if !name.is_empty() && name.chars().all(char::is_whitespace) {
        return Ok((" ".to_owned(), "Space".to_owned(), Modifiers::default()));
    }
    let mut parts = name
        .split('+')
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .peekable();
    let mut modifiers = Modifiers::default();
    let mut key_name = None;

    while let Some(part) = parts.next() {
        let lower = part.to_ascii_lowercase();
        let is_last = parts.peek().is_none();
        if is_last {
            key_name = Some(lower);
            break;
        }
        match lower.as_str() {
            "meta" | "cmd" | "command" => modifiers.meta = true,
            "ctrl" | "control" => modifiers.control = true,
            "alt" | "option" => modifiers.alt = true,
            "shift" => modifiers.shift = true,
            other => bail!("unknown key modifier {other:?}: meta, cmd, ctrl, alt, shift"),
        }
    }

    let key_name = key_name.ok_or_else(|| eyre!("key chord is empty"))?;
    if key_name.len() == 1 {
        let character = key_name.as_bytes()[0];
        if character.is_ascii_alphabetic() {
            return Ok((
                if modifiers.shift {
                    key_name.to_ascii_uppercase()
                } else {
                    key_name.clone()
                },
                format!("Key{}", (character as char).to_ascii_uppercase()),
                modifiers,
            ));
        }
        if character.is_ascii_digit() {
            return Ok((key_name.clone(), format!("Digit{key_name}"), modifiers));
        }
    }
    let (key, code) = match key_name.as_str() {
        "pageup" | "pgup" => ("PageUp", "PageUp"),
        "pagedown" | "pgdn" => ("PageDown", "PageDown"),
        "home" => ("Home", "Home"),
        "end" => ("End", "End"),
        "up" | "arrowup" => ("ArrowUp", "ArrowUp"),
        "down" | "arrowdown" => ("ArrowDown", "ArrowDown"),
        "left" | "arrowleft" => ("ArrowLeft", "ArrowLeft"),
        "right" | "arrowright" => ("ArrowRight", "ArrowRight"),
        "tab" => ("Tab", "Tab"),
        "enter" => ("Enter", "Enter"),
        "escape" | "esc" => ("Escape", "Escape"),
        "delete" | "del" => ("Delete", "Delete"),
        "backspace" => ("Backspace", "Backspace"),
        "shift" => {
            modifiers.shift = true;
            ("Shift", "ShiftLeft")
        }
        "ctrl" | "control" => {
            modifiers.control = true;
            ("Control", "ControlLeft")
        }
        "alt" | "option" => {
            modifiers.alt = true;
            ("Alt", "AltLeft")
        }
        "meta" | "cmd" | "command" => {
            modifiers.meta = true;
            ("Meta", "MetaLeft")
        }
        "space" | "spacebar" => (" ", "Space"),
        other => {
            bail!(
                "unknown key {other:?}: letters, digits, pageup, pagedown, home, end, arrows, tab, enter, escape, delete, backspace, space, shift, ctrl, alt, meta"
            )
        }
    };
    Ok((key.to_owned(), code.to_owned(), modifiers))
}

/// One `InputCommand::Key` frame. [`press_key`] and [`key_steps`] both send
/// through here, so a sequence uses the same wire shape as a chord.
async fn dispatch_key(
    client: &mut Client,
    key: &str,
    code: &str,
    modifiers: Modifiers,
    phase: KeyPhase,
) -> Result<()> {
    client
        .agent(&AgentControlRequest::Act(AgentAction::Input(
            InputCommand::Key {
                phase,
                key: key.to_owned(),
                code: code.to_owned(),
                modifiers,
            },
        )))
        .await?;
    Ok(())
}

/// Send a timed key sequence to the focused element, or the document.
///
/// Press is down then up. Hold waits the given milliseconds between those
/// phases. Down and Up send one phase. Wait only sleeps. Names go through
/// [`parse_key_chord`]. Nothing here focuses a control: the events land on
/// whatever already has focus, and the document root when nothing does.
pub(crate) async fn key_steps(client: &mut Client, steps: &[KeyStep]) -> Result<()> {
    for step in steps {
        match step {
            KeyStep::Press(name) => {
                let (key, code, modifiers) = parse_key_chord(name)?;
                dispatch_key(client, &key, &code, modifiers, KeyPhase::Down).await?;
                dispatch_key(client, &key, &code, modifiers, KeyPhase::Up).await?;
            }
            KeyStep::Hold(name, milliseconds) => {
                let (key, code, modifiers) = parse_key_chord(name)?;
                dispatch_key(client, &key, &code, modifiers, KeyPhase::Down).await?;
                nagoya::sleep(Duration::from_millis(*milliseconds)).await;
                dispatch_key(client, &key, &code, modifiers, KeyPhase::Up).await?;
            }
            KeyStep::Down(name) => {
                let (key, code, modifiers) = parse_key_chord(name)?;
                dispatch_key(client, &key, &code, modifiers, KeyPhase::Down).await?;
            }
            KeyStep::Up(name) => {
                let (key, code, modifiers) = parse_key_chord(name)?;
                dispatch_key(client, &key, &code, modifiers, KeyPhase::Up).await?;
            }
            KeyStep::Wait(milliseconds) => {
                nagoya::sleep(Duration::from_millis(*milliseconds)).await;
            }
        }
    }
    Ok(())
}

pub(crate) async fn type_keys(client: &mut Client, count: usize, want: &str) -> Result<()> {
    let (snapshot, _) = inspect(client).await?;
    let field = find_text_field(&snapshot.nodes, want)
        .map_err(|_| eyre!("multiple enabled, visible text fields match the selector"))?
        .ok_or_else(|| eyre!("no enabled, visible text field found; open a tab with a composer"))?;
    println!(
        "typing into node {} role={} name={}",
        field.id,
        field.role,
        report::py_repr(&field.name.chars().take(40).collect::<String>())
    );
    client
        .agent(&AgentControlRequest::Act(AgentAction::Click {
            node_id: field.id,
        }))
        .await?;

    let before = metrics_if_supported(client).await?;
    let mut latencies = Vec::with_capacity(count);
    for index in 0..count {
        let letter = (b'a' + (index % 26) as u8) as char;
        let started = Instant::now();
        for phase in [KeyPhase::Down, KeyPhase::Up] {
            client
                .agent(&AgentControlRequest::Act(AgentAction::Input(
                    InputCommand::Key {
                        phase,
                        key: letter.to_string(),
                        code: format!("Key{}", letter.to_ascii_uppercase()),
                        modifiers: Modifiers::default(),
                    },
                )))
                .await?;
        }
        latencies.push(started.elapsed().as_secs_f64() * 1000.0);
        sleep_pace().await;
    }
    let after = metrics_if_supported(client).await?;

    report::show_latencies("keystrokes", count, &mut latencies);
    report_frames(before.as_ref(), after.as_ref(), count);
    Ok(())
}

/// A value-free stage label for runtime credential setup diagnostics.
#[derive(Debug)]
pub(crate) struct TextEntryFailure(&'static str);

impl TextEntryFailure {
    pub(crate) fn category(&self) -> &'static str {
        self.0
    }
}

impl std::fmt::Display for TextEntryFailure {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "text entry failed at {}", self.0)
    }
}

impl std::error::Error for TextEntryFailure {}

fn inspect_failure_category(error: &eyre::Report) -> &'static str {
    match safe_response_code(error) {
        Some("documentUnavailable") => "inspect_document_unavailable",
        Some(_) => "inspect_rejected",
        None => "inspect_transport_or_protocol_failure",
    }
}

fn set_value_failure_category(error: &eyre::Report) -> &'static str {
    match safe_response_code(error) {
        Some("notEditable") => "set_value_not_editable",
        Some("unknownNode") => "set_value_unknown_node",
        Some("documentUnavailable") => "set_value_document_unavailable",
        Some(_) => "set_value_rejected",
        None => "set_value_transport_or_protocol_failure",
    }
}

async fn wait_for_text_field_id(
    client: &mut Client,
    want: &str,
    within: Duration,
) -> Result<Option<u64>> {
    // `within` bounds the wait for the field, not one inspect: a busy page can
    // take longer than that to answer a single request, which surfaced as a
    // transport failure rather than as a slow page.
    let previous_timeout = client.request_timeout();
    client.set_request_timeout(within.max(previous_timeout));
    let result: Result<Option<u64>> = async {
        let deadline = Instant::now() + within;
        let event_driven = client.arm_paint_events().await.unwrap_or(false);
        loop {
            let snapshot = match inspect(client).await {
                Ok((snapshot, _)) => snapshot,
                Err(error) => {
                    let category = inspect_failure_category(&error);
                    if category == "inspect_transport_or_protocol_failure"
                        && Instant::now() < deadline
                    {
                        nagoya::sleep(Duration::from_millis(100)).await;
                        continue;
                    }
                    return Err(eyre::Report::new(TextEntryFailure(category)));
                }
            };
            let field_id = find_text_field(&snapshot.nodes, want)
                .map_err(|category| eyre::Report::new(TextEntryFailure(category)))?
                .map(|field| field.id);
            if field_id.is_some() {
                return Ok(field_id);
            }
            if Instant::now() >= deadline {
                return Ok(None);
            }
            if event_driven {
                let remaining = deadline.saturating_duration_since(Instant::now());
                if !remaining.is_zero() {
                    let _ = client.wait_for_paint(remaining).await?;
                }
            } else {
                nagoya::sleep(Duration::from_millis(25)).await;
            }
        }
    }
    .await;
    client.set_request_timeout(previous_timeout);
    result
}

/// Set literal text on one exact, enabled, visible semantic text-field node.
pub(crate) async fn type_text(client: &mut Client, want: &str, text: &str) -> Result<u64> {
    let node_id = wait_for_text_field_id(client, want, check_timeout(900))
        .await?
        .ok_or_else(|| eyre::Report::new(TextEntryFailure("matching_text_field_not_found")))?;
    if cli::trace() {
        println!("        setting {want:?} (id {node_id})");
    }
    // Reveal the field first, as a click does: an outcome that requires the
    // field to be painted (a select whose new label must show) cannot pass for
    // a field the page has scrolled out of the viewport. Best effort: a host
    // that cannot scroll still gets the value.
    let _ = client
        .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
            node_id,
        }))
        .await;
    client
        .agent(&AgentControlRequest::Act(AgentAction::SetValue {
            node_id,
            value: text.to_owned(),
        }))
        .await
        .map_err(|error| eyre::Report::new(TextEntryFailure(set_value_failure_category(&error))))?;
    Ok(node_id)
}

/// Price a single click, such as switching to a tab.
///
/// A tab switch flips `display: none` to `flex` over that tab's whole subtree,
/// so taffy lays out in one pass everything the tab retained while hidden. That
/// is a different cost from typing and needs its own measurement.
pub(crate) async fn click_named(client: &mut Client, want: &str) -> Result<()> {
    let (target_id, _) = locate_control(client, want, &[]).await?;
    let (snapshot, _) = inspect(client).await?;
    let target = snapshot
        .nodes
        .iter()
        .find(|node| node.id == target_id)
        .ok_or_else(|| eyre!("node {target_id} disappeared after it was located"))?;
    println!(
        "clicking node {} role={} name={}",
        target.id,
        target.role,
        report::py_repr(&target.name.chars().take(50).collect::<String>())
    );

    // A click is dispatched at the node's coordinates, so a node scrolled out
    // of the viewport gets a `pointerdown` at a point nothing is at and no
    // click at all. "Show 12 earlier messages" sat at y=-2246 and every attempt
    // to press it read as the button doing nothing.
    let before = metrics_if_supported(client).await?;
    let started = Instant::now();
    client
        .agent(&AgentControlRequest::Act(AgentAction::Click {
            node_id: target_id,
        }))
        .await?;
    let ack = started.elapsed().as_secs_f64() * 1000.0;
    let after = metrics_if_supported(client).await?;

    println!("click acked in {ack:.1}ms");
    report_frames(before.as_ref(), after.as_ref(), 1);
    Ok(())
}

/// The frame numbers either side of an action, when there are any.
///
/// A headless host has no compositor and says so. The click still happened and
/// its acknowledgement is still timed; what is missing is the frame context,
/// and saying that out loud is better than printing zeroes that read as a
/// renderer doing nothing.
fn report_frames(
    before: Option<&blitz_control_protocol::RendererMetrics>,
    after: Option<&blitz_control_protocol::RendererMetrics>,
    actions: usize,
) {
    let (Some(before), Some(after)) = (before, after) else {
        println!("frames: the host reports no renderer metrics; it has no compositor");
        return;
    };
    report::show("before", before);
    report::show("after", after);
    report::show_delta(before, after, actions);
}

#[cfg(test)]
mod tests {
    use super::is_text_field_role;

    #[test]
    fn editable_aria_roles_are_literal_text_targets() {
        for role in [
            "textbox",
            "textarea",
            "input",
            "combobox",
            "searchbox",
            "spinbutton",
        ] {
            assert!(is_text_field_role(role), "{role}");
        }
        for role in ["button", "listbox", "option", "slider"] {
            assert!(!is_text_field_role(role), "{role}");
        }
    }
}