ps-qa 0.7.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
//! Pointer, keyboard, and text input against a running application.

use std::collections::HashSet;
use std::time::Instant;

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

use crate::diagnostics::metrics_if_supported;
use crate::inspector::{Client, inspect};
use crate::target::{locate_control, selector_matches_node};
use crate::timing::{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,
) -> Result<()> {
    if !dx.is_finite() || !dy.is_finite() || steps == 0 || steps > 240 {
        bail!("pointer drag needs finite offsets and 1..=240 steps");
    }
    let (_, bounds) = locate_control(client, want, &[]).await?;
    let start = (bounds[0] + bounds[2] / 2.0, bounds[1] + bounds[3] / 2.0);
    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 painted text-entry control whose semantic name mentions `want` on the active layer.
fn find_text_field<'a>(nodes: &'a [SemanticNode], want: &str) -> Option<&'a SemanticNode> {
    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
                    .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] {
        if let Some(field) = fields
            .iter()
            .find(|node| matches_name(node) && scope.contains(&node.id))
        {
            return Some(field);
        }
    }
    fields.into_iter().find(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 {
        for phase in [KeyPhase::Down, KeyPhase::Up] {
            client
                .agent(&AgentControlRequest::Act(AgentAction::Input(
                    InputCommand::Key {
                        phase,
                        key: key.clone(),
                        code: code.clone(),
                        modifiers,
                    },
                )))
                .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)> {
    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"),
        "space" | "spacebar" => (" ", "Space"),
        other => {
            bail!(
                "unknown key {other:?}: letters, digits, pageup, pagedown, home, end, arrows, tab, enter, escape, delete, backspace, space"
            )
        }
    };
    Ok((key.to_owned(), code.to_owned(), modifiers))
}

pub(crate) async fn type_keys(client: &mut Client, count: usize, want: &str) -> Result<()> {
    let (snapshot, _) = inspect(client).await?;
    let Some(field) = find_text_field(&snapshot.nodes, want) else {
        bail!("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(())
}

/// Set literal text on an exact semantic text-field node.
pub(crate) async fn type_text(client: &mut Client, want: &str, text: &str) -> Result<u64> {
    let (snapshot, _) = inspect(client).await?;
    let field = find_text_field(&snapshot.nodes, want)
        .ok_or_else(|| eyre!("no enabled, visible text field matching {want:?}"))?;
    if cli::trace() {
        println!("        setting {want:?} (id {})", field.id);
    }
    client
        .agent(&AgentControlRequest::Act(AgentAction::SetValue {
            node_id: field.id,
            value: text.to_owned(),
        }))
        .await?;
    Ok(field.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}");
        }
    }
}