tauri-runtime-blitz 0.3.4

Tauri runtime backed by Blitz and Boa
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
//! Inspecting, capturing and driving a document, with no window involved.
//!
//! Split out of the runtime because none of it needs one. A headless
//! inspection host wants exactly these functions: it serves a socket, answers
//! `Inspect`, and activates nodes. It opens nothing.
//!
//! While they lived beside the Tauri runtime, depending on them meant
//! compiling Tauri, and on Linux that means GTK -- system libraries pulled in
//! to build a binary that never creates a window, and a crate that would not
//! compile there at all. The dependency edge was wrong, not the platform.

use std::collections::HashMap;

#[cfg(all(feature = "agent-control", unix))]
use blitz_control_protocol::{
    AgentSnapshot, DebugError, DebugResponse, KeyPhase, Modifiers as ControlModifiers, SemanticNode,
};
#[cfg(all(feature = "diagnostics", unix))]
use blitz_control_protocol::{
    DebugSnapshot, FrameMetrics, FrameWindowMetrics, LayoutBounds, LayoutDiagnosticRow,
    LayoutEdges, LayoutOffset, LayoutSize, RendererMetrics, RevisionSet, ScriptMetrics,
    ScriptSource, SnapshotCost, SnapshotRequest, TimingStats,
};
#[cfg(all(feature = "agent-control", unix))]
use blitz_dom::Document;
use blitz_script::ScriptDocument;
#[cfg(all(feature = "agent-control", unix))]
use blitz_traits::events::{
    BlitzKeyEvent, BlitzPointerEvent, BlitzPointerId, DomEvent, DomEventData, KeyState,
    MouseEventButton, MouseEventButtons, Point, PointerCoords, PointerDetails, UiEvent,
};
#[cfg(all(feature = "diagnostics", unix))]
use blitz_traits::node_id::NodeId;
#[cfg(all(feature = "agent-control", unix))]
use keyboard_types::{Code, Key, Location, Modifiers as KeyboardModifiers};

/// The live inspector's reusable offscreen surface.
///
/// A capture used to construct this whole renderer for every frame. Besides
/// reallocating the viewport-sized RGBA buffer, that threw away the CPU text
/// renderer's glyph resources, so a stability assertion shaped and rasterised
/// every label four times. The surface belongs to one runtime and is resized
/// only when the window or requested scale changes.
#[cfg(all(feature = "diagnostics", unix))]
pub(crate) struct CaptureSurface {
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) renderer: anyrender_vello_cpu::VelloCpuImageRenderer,
    pub(crate) rgba: Vec<u8>,
}

/// Reusable offscreen renderer for captures of one document.
///
/// A headless inspection host asks for several adjacent frames when it checks
/// visual stability. Reusing this object preserves the CPU renderer's glyph
/// resources and pixel allocation between those requests instead of rebuilding
/// an entire renderer for every sample.
#[cfg(all(feature = "diagnostics", unix))]
pub struct DocumentCapture {
    surface: Option<CaptureSurface>,
}

#[cfg(all(feature = "diagnostics", unix))]
impl DocumentCapture {
    pub fn new() -> Self {
        Self { surface: None }
    }

    pub fn capture(
        &mut self,
        document: &mut ScriptDocument,
        request: blitz_control_protocol::CaptureRequest,
    ) -> Result<blitz_control_protocol::CapturedImage, DebugError> {
        capture_document_with_surface(document, request, &mut self.surface)
    }
}

#[cfg(all(feature = "diagnostics", unix))]
impl Default for DocumentCapture {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(feature = "diagnostics", unix))]
impl CaptureSurface {
    pub(crate) fn new(width: u32, height: u32) -> Self {
        use anyrender::ImageRenderer as _;

        Self {
            width,
            height,
            renderer: anyrender_vello_cpu::VelloCpuImageRenderer::new(width, height),
            rgba: Vec::with_capacity((width as usize) * (height as usize) * 4),
        }
    }

    pub(crate) fn size_to(&mut self, width: u32, height: u32) {
        use anyrender::ImageRenderer as _;

        if self.width == width && self.height == height {
            return;
        }
        self.renderer.resize(width, height);
        self.width = width;
        self.height = height;
    }
}

/// Draw a standalone script document through the same CPU paint path used by
/// runtime diagnostics.
///
/// Headless QA hosts intentionally have no `RuntimeApplication`, but they must
/// not substitute a second renderer for native visual checks. Keeping the
/// capture implementation here makes a host capture and a live-app capture
/// byte-for-byte comparable.
#[cfg(all(feature = "diagnostics", unix))]
pub fn capture_document(
    script_document: &mut ScriptDocument,
    request: blitz_control_protocol::CaptureRequest,
) -> Result<blitz_control_protocol::CapturedImage, DebugError> {
    DocumentCapture::new().capture(script_document, request)
}

#[cfg(all(feature = "diagnostics", unix))]
pub(crate) fn capture_document_with_surface(
    script_document: &mut ScriptDocument,
    request: blitz_control_protocol::CaptureRequest,
    surface: &mut Option<CaptureSurface>,
) -> Result<blitz_control_protocol::CapturedImage, DebugError> {
    use anyrender::ImageRenderer;
    use base64::Engine as _;

    // Clamped rather than trusted. A scale of zero produces a zero-sized
    // buffer and a negative one panics inside the rasteriser, and neither
    // should be reachable from a debug socket.
    let scale = if request.scale.is_finite() && request.scale > 0.0 {
        request.scale.clamp(0.1, 8.0)
    } else {
        1.0
    };

    let node_id = request.node_id;

    // Style and layout first, so the capture reflects pending mutations
    // rather than the frame before them. Same call `collect_diagnostics`
    // makes, for the same reason.
    script_document.inner_mut().resolve(0.0);

    // Copied out rather than held: the guard is a `Ref` and the borrow has
    // to end before the mutable one the paint below needs.
    let (full_width, full_height) = {
        let inner = script_document.inner();
        let viewport = inner.viewport();
        (viewport.window_size.0, viewport.window_size.1)
    };
    if full_width == 0 || full_height == 0 {
        return Err(debug_error(
            "captureUnavailable",
            "the document has no viewport to draw",
        ));
    }

    // The region to keep, in unscaled document pixels.
    let (crop_x, crop_y, crop_width, crop_height) = match node_id {
        None => (
            0.0_f64,
            0.0_f64,
            f64::from(full_width),
            f64::from(full_height),
        ),
        Some(id) => {
            let inner = script_document.inner();
            let node = inner
                .get_node(NodeId::from_u64(id))
                .ok_or_else(|| debug_error("unknownNode", &format!("no node {id}")))?;
            let layout = node.final_layout();
            let position = node.absolute_position(0.0, 0.0);
            if layout.size.width <= 0.0 || layout.size.height <= 0.0 {
                return Err(debug_error(
                    "captureEmpty",
                    &format!("node {id} has a zero-sized box, so there is nothing to capture"),
                ));
            }
            let box_ = (
                f64::from(position.x),
                f64::from(position.y),
                f64::from(layout.size.width),
                f64::from(layout.size.height),
            );
            drop(inner);
            box_
        }
    };

    let full_pixel_width = ((f64::from(full_width) * f64::from(scale)).round() as u32).max(1);
    let full_pixel_height = ((f64::from(full_height) * f64::from(scale)).round() as u32).max(1);
    // Clamp before painting: a node partly offscreen yields the visible part,
    // and the regional renderer never allocates pixels that will be discarded.
    let left = ((crop_x * f64::from(scale)).round().max(0.0) as u32).min(full_pixel_width);
    let top = ((crop_y * f64::from(scale)).round().max(0.0) as u32).min(full_pixel_height);
    let width = ((crop_width * f64::from(scale)).round() as u32)
        .min(full_pixel_width.saturating_sub(left))
        .max(1);
    let height = ((crop_height * f64::from(scale)).round() as u32)
        .min(full_pixel_height.saturating_sub(top))
        .max(1);
    // Leave room for the JSON-RPC and MCP envelopes inside the transport's
    // fixed frame ceiling. The old 64-million-pixel limit allowed a 256 MiB
    // raster and a 341 MiB base64 string, only for protocol encoding to reject
    // the result against its 16 MiB frame limit after all that work was done.
    const FRAME_ENVELOPE_RESERVE: usize = 64 * 1024;
    const MAX_BASE64_BYTES: usize =
        blitz_control_protocol::MAX_DEBUG_FRAME_BYTES - FRAME_ENVELOPE_RESERVE;
    const MAX_RAW_BYTES: usize = (MAX_BASE64_BYTES / 4) * 3;
    const MAX_PIXELS: u64 = (MAX_RAW_BYTES / 4) as u64;
    if u64::from(width) * u64::from(height) > MAX_PIXELS {
        return Err(debug_error(
            "captureTooLarge",
            &format!(
                "{width}x{height} cannot fit in one diagnostic frame; capture a node or lower the scale"
            ),
        ));
    }

    let surface = surface.get_or_insert_with(|| CaptureSurface::new(width, height));
    surface.size_to(width, height);
    // `ImageRenderer` retains its scene between calls. A capture is a complete
    // frame, not an incremental paint, so carrying the previous command list
    // forward duplicates every shape and makes each sample slower than the
    // last. Keep reusable renderer resources, but always begin with an empty
    // scene.
    surface.renderer.reset();
    let mut document = script_document.inner_mut();
    surface.renderer.render_to_vec(
        |scene| {
            if node_id.is_some() {
                blitz_paint::paint_scene_region(
                    scene,
                    &mut document,
                    blitz_paint::PaintRegion::crop(
                        f64::from(scale),
                        f64::from(left) / f64::from(scale),
                        f64::from(top) / f64::from(scale),
                        width,
                        height,
                    ),
                );
            } else {
                blitz_paint::paint_scene(
                    scene,
                    &mut document,
                    f64::from(scale),
                    width,
                    height,
                    0,
                    0,
                );
            }
        },
        &mut surface.rgba,
    );

    Ok(blitz_control_protocol::CapturedImage {
        width,
        height,
        rgba_base64: base64::engine::general_purpose::STANDARD.encode(&surface.rgba),
        node_id,
    })
}

/// Collect the same typed diagnostic snapshot from a standalone Blitz document
/// that the windowed runtime exposes over its control socket.
///
/// Headless component hosts own a `ScriptDocument` without a Tauri event loop.
/// Keeping snapshot collection here gives those hosts the renderer's real DOM,
/// layout and computed paint data instead of a partial or reimplemented view.
#[cfg(all(feature = "diagnostics", unix))]
pub fn snapshot_document(
    document: &mut ScriptDocument,
    request: SnapshotRequest,
    revision: u64,
) -> Result<DebugSnapshot, DebugError> {
    let started = std::time::Instant::now();
    let poll_started = std::time::Instant::now();
    let mut polls = 0u64;
    for _ in 0..100 {
        polls += 1;
        if !document.poll(None) {
            break;
        }
    }
    let poll_ms = poll_started.elapsed().as_secs_f64() * 1_000.0;
    // This forces a style and layout pass so the snapshot reports current
    // geometry. It is work the observer caused, so it is reported as snapshot
    // cost, never as the cost of a frame the application drew.
    let resolve_started = std::time::Instant::now();
    document.inner_mut().resolve(0.0);
    let snapshot_resolve_ms = resolve_started.elapsed().as_secs_f64() * 1_000.0;
    let inner = document.inner();
    let layout_node_limit = inner.tree().iter().count();
    let active_element = inner.get_focussed_node_id().map(|id| id.as_u64());
    let nodes: Vec<SemanticNode> = inner
        .tree()
        .iter()
        .filter_map(|(id, node)| {
            if !request.node_ids.is_empty() && !request.node_ids.contains(&id.as_u64()) {
                return None;
            }
            let element = node.element_data()?;
            if !dom_chain_is_attached(&inner, id, layout_node_limit)
                || !layout_chain_is_valid(&inner, id, layout_node_limit)
            {
                return None;
            }
            let rect = inner.get_client_bounding_rect(id);
            let visible = node_is_visible(&inner, id)
                && rect
                    .as_ref()
                    .is_some_and(|rect| rect.width > 0.0 && rect.height > 0.0);
            let role = semantic_role(element);
            let value = if role == "generic" {
                Some(
                    element
                        .attrs()
                        .iter()
                        .map(|attribute| format!("{}={}", attribute.name.local, attribute.value))
                        .collect::<Vec<_>>()
                        .join(" "),
                )
            } else {
                semantic_value(element)
            };
            Some(SemanticNode {
                dom_id: element_attr(element, "id").map(str::to_owned),
                id: id.as_u64(),
                parent: semantic_parent(&inner, id, None).map(|id| id.as_u64()),
                name: semantic_name(element, node, &role),
                role,
                value,
                enabled: element_attr(element, "disabled").is_none()
                    && element_attr(element, "aria-disabled") != Some("true"),
                visible,
                selected: semantic_selected(element),
                bounds: rect.and_then(|rect| {
                    let bounds = [rect.x, rect.y, rect.width, rect.height];
                    bounds
                        .iter()
                        .all(|value| value.is_finite())
                        .then_some(bounds)
                }),
                slot: element_attr(element, "data-slot").map(str::to_owned),
            })
        })
        .collect();
    let total_ms = started.elapsed().as_secs_f64() * 1_000.0;
    // The runtime keeps one counter and stamps it onto all four revision
    // fields. Style, layout and paint are not versioned independently
    // anywhere in blitz, so four copies of one number would claim a
    // resolution that does not exist. Report the counter once, as the
    // document revision, and leave the rest at zero.
    let revisions = RevisionSet {
        document: revision,
        style: 0,
        layout: 0,
        paint: 0,
    };
    // Real per-frame timings, published by blitz-shell from `View::redraw`.
    // These describe frames the application actually presented. Everything
    // measured inside this function describes the snapshot collection instead,
    // and is reported under `snapshot` so the two never get mixed up again.
    let frame_stats = blitz_shell::latest_frame_stats();
    let metrics = RendererMetrics {
        revisions: revisions.clone(),
        queue_depth: None,
        invalidations_coalesced: polls.saturating_sub(1),
        frame: frame_stats.as_ref().map(|stats| FrameMetrics {
            input_to_present_ms: None,
            style_ms: None,
            layout_ms: None,
            resolve_ms: stats.latest.resolve_ms,
            scene_ms: stats.latest.paint_ms,
            submit_ms: None,
            present_ms: None,
            renderer_ms: stats.latest.renderer_ms,
            total_ms: stats.latest.total_ms,
            age_ms: stats.latest.age_ms,
        }),
        frame_window: frame_stats.as_ref().map(|stats| FrameWindowMetrics {
            frames_total: stats.frames_total,
            window_frames: stats.window_frames,
            resolve: timing_stats(stats.resolve),
            scene: timing_stats(stats.paint),
            renderer: timing_stats(stats.renderer),
            total: timing_stats(stats.frame_total),
            interval: timing_stats(stats.interval),
            active_fps: stats.active_fps,
            missed_refreshes: stats.missed_refreshes,
            display_refresh_hz: stats.display_refresh_hz,
        }),
        snapshot: Some(SnapshotCost {
            poll_ms,
            resolve_ms: snapshot_resolve_ms,
            total_ms,
        }),
        // The other half of a frame. Everything above this line is the
        // engine; this is the language runtime the application actually
        // spends its time in.
        script: blitz_script::script_stats::latest_script_stats().map(|stats| ScriptMetrics {
            mean_ms: stats.mean_ms,
            p95_ms: stats.p95_ms,
            max_ms: stats.max_ms,
            window_polls: stats.window_polls,
            total_polls: stats.total_polls,
            productive_polls: stats.productive_polls,
            spent_ms: stats.spent_ms,
            breakdown: blitz_script::script_stats::work_breakdown()
                .into_iter()
                .take(12)
                .map(|(label, calls, total_ms, worst_ms)| ScriptSource {
                    label,
                    calls,
                    total_ms,
                    worst_ms,
                })
                .collect(),
        }),
        resident_bytes: resident_bytes(),
    };
    let dom = request
        .include_dom
        .then(|| serde_json::to_value(&nodes).unwrap_or(serde_json::Value::Null));
    let layout = request.include_layout.then(|| {
        nodes
            .iter()
            .filter_map(|node| diagnostic_layout_row(&inner, node))
            .collect()
    });
    /*
     * Resolved colours, folded into the layout rows.
     *
     * This used to answer `computedStyleUnavailable`, which left one class
     * of bug unanswerable from outside: an element whose *declared* colour
     * is correct and whose *painted* colour is not. Reading the stylesheet
     * cannot settle that - the cascade, the custom-property chain and the
     * `@supports` gating all sit between the two - and neither can a DOM
     * test environment, which has no cascade at all.
     *
     * Only the four that decide legibility, rather than a full style dump:
     * a snapshot of every longhand for 4,500 nodes is megabytes of JSON
     * nobody reads, and these are what a "why is this text invisible"
     * question actually needs.
     */
    let computed_style = request.include_computed_style.then(|| {
        serde_json::Value::Array(
            nodes
                .iter()
                .filter_map(|node| diagnostic_style_row(&inner, node))
                .collect(),
        )
    });
    Ok(DebugSnapshot {
        revisions,
        active_window: Some("blitz-main".into()),
        active_element,
        dom,
        layout,
        computed_style,
        metrics,
    })
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn element_attr<'a>(element: &'a blitz_dom::ElementData, name: &str) -> Option<&'a str> {
    element
        .attrs()
        .iter()
        .find(|attribute| attribute.name.local.as_ref() == name)
        // `as_ref`, not `as_str`. Attribute values are an interned atom as of
        // ps-blitz-dom 0.3.0-beta.11, and `str::as_str` is still unstable, so
        // `as_str` here resolved to the nightly-only inherent method and
        // failed to build on stable. `as_ref` borrows the atom as a `&str`,
        // which is what this signature returns.
        .map(|attribute| attribute.value.as_ref())
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn semantic_role(element: &blitz_dom::ElementData) -> String {
    if let Some(role) = element_attr(element, "role") {
        return role.into();
    }
    let tag = element.name.local.as_ref();
    match tag {
        "a" if element_attr(element, "href").is_some() => "link",
        "button" => "button",
        "textarea" => "textbox",
        "select" => "combobox",
        "option" => "option",
        "img" => "img",
        "nav" => "navigation",
        "main" => "main",
        "form" => "form",
        "ul" | "ol" => "list",
        "li" => "listitem",
        "table" => "table",
        "tr" => "row",
        "td" | "th" => "cell",
        "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => "heading",
        "input" => match element_attr(element, "type").unwrap_or("text") {
            "checkbox" => "checkbox",
            "radio" => "radio",
            "button" | "submit" | "reset" => "button",
            "range" => "slider",
            _ => "textbox",
        },
        _ => "generic",
    }
    .into()
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn semantic_name(
    element: &blitz_dom::ElementData,
    node: &blitz_dom::Node,
    role: &str,
) -> String {
    let name = element_attr(element, "aria-label")
        .or_else(|| element_attr(element, "alt"))
        .or_else(|| element_attr(element, "title"))
        .map(std::borrow::Cow::Borrowed)
        .or_else(|| {
            matches!(role, "button" | "link" | "heading" | "option")
                .then(|| std::borrow::Cow::Owned(node.text_content()))
        })
        .unwrap_or_default();
    let mut normalized = String::with_capacity(name.len().min(512));
    let mut characters = 0;
    for word in name.split_whitespace() {
        if !normalized.is_empty() && characters < 512 {
            normalized.push(' ');
            characters += 1;
        }
        for character in word.chars() {
            if characters == 512 {
                return normalized;
            }
            normalized.push(character);
            characters += 1;
        }
    }
    normalized
}

#[cfg(all(feature = "agent-control", unix))]
fn semantic_value(element: &blitz_dom::ElementData) -> Option<String> {
    element
        .text_input_data()
        .map(|input| input.editor.text().to_string())
        .or_else(|| {
            element
                .checkbox_input_checked()
                .map(|checked| checked.to_string())
        })
        .or_else(|| element_attr(element, "aria-valuenow").map(str::to_string))
        .or_else(|| element_attr(element, "value").map(str::to_string))
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn semantic_selected(element: &blitz_dom::ElementData) -> bool {
    /*
     * A real checkbox answers from its live state, not from its markup.
     *
     * `checkbox_input_checked` is the value the DOM updates when the control is
     * toggled; the attributes below are the document as it was parsed and never
     * move again. Asking the attributes about an input that has one is how a
     * toggle reports the same state for ever.
     */
    if let Some(checked) = element.checkbox_input_checked() {
        return checked;
    }

    /*
     * Presence is not truth for these two.
     *
     * `checked` and `selected` are HTML boolean attributes, so bare `checked`
     * means on. But a framework that renders a controlled value writes the
     * value out: Solid emits `checked="false"`, and `.is_some()` called that
     * selected. Every Switch, Radio and Checkbox in the QA harness reported
     * `selected: true` before anything was pressed and could never change,
     * which read as three components that ignore a click.
     *
     * Explicitly `"false"` is off; anything else present is on.
     */
    let attribute_on = |name| match element_attr(element, name) {
        Some("false") => false,
        Some(_) => true,
        None => false,
    };

    element_attr(element, "aria-selected") == Some("true")
        || element_attr(element, "aria-pressed") == Some("true")
        || element_attr(element, "aria-checked") == Some("true")
        || element_attr(element, "aria-current").is_some_and(|value| value != "false")
        || attribute_on("checked")
        || attribute_on("selected")
}

#[cfg(all(feature = "agent-control", unix))]
fn semantic_parent(
    document: &blitz_dom::BaseDocument,
    node_id: blitz_dom::NodeId,
    root: Option<blitz_dom::NodeId>,
) -> Option<blitz_dom::NodeId> {
    if Some(node_id) == root {
        return None;
    }
    let mut current = document.get_node(node_id)?.parent;
    while let Some(id) = current {
        let node = document.get_node(id)?;
        if node.element_data().is_some() {
            return Some(id);
        }
        current = node.parent;
    }
    None
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn node_is_visible(
    document: &blitz_dom::BaseDocument,
    node_id: blitz_dom::NodeId,
) -> bool {
    let mut current = Some(node_id);
    while let Some(id) = current {
        let Some(node) = document.get_node(id) else {
            return false;
        };
        if !node_is_individually_visible(node) {
            return false;
        }
        current = node.parent;
    }
    true
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn dom_chain_is_attached(
    document: &blitz_dom::BaseDocument,
    node_id: blitz_dom::NodeId,
    node_limit: usize,
) -> bool {
    let root = document.root_node().id;
    let mut current = Some(node_id);
    // Removed DOM nodes intentionally remain allocated while JavaScript may
    // still hold wrappers for them. They are not part of the document unless
    // their parent chain reaches the one document root.
    for _ in 0..=node_limit {
        let Some(id) = current else {
            return false;
        };
        if id == root {
            return true;
        }
        let Some(node) = document.get_node(id) else {
            return false;
        };
        current = node.parent;
    }
    false
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn layout_chain_is_valid(
    document: &blitz_dom::BaseDocument,
    node_id: blitz_dom::NodeId,
    node_limit: usize,
) -> bool {
    let mut current = Some(node_id);
    // A valid layout chain reaches its root in no more steps than there are
    // nodes. The bound also rejects corrupt cycles instead of hanging control.
    for _ in 0..=node_limit {
        let Some(id) = current else {
            return true;
        };
        let Some(node) = document.get_node(id) else {
            return false;
        };
        current = node.layout_parent.get();
    }
    false
}

/// Activate the node the caller selected, without asking hit-testing to select
/// it a second time from a screen coordinate.
///
/// The coordinates carried by DOM events are still the node's own geometry,
/// because handlers use offsets and text fields use them for caret placement.
/// They never choose the target. An overflowed or clipped node therefore gets
/// the same pointer, mouse and click sequence as an on-screen one.
#[cfg(all(feature = "agent-control", unix))]
/// Click a semantic node, by id, the way the runtime does.
///
/// Dispatches pointer, mouse and click events in browser order against the
/// document directly, so a headless host can drive a control without a window,
/// a pointer or a compositor. This is what makes the interaction checks
/// runnable at all: a still picture of the tree cannot answer what a control
/// does when it is pressed.
#[cfg(all(feature = "agent-control", unix))]
/// Send one key to a document, down then up.
///
/// Only keys, deliberately. The pointer and wheel arms of the runtime's input
/// handler carry pointer position and button state on the runtime itself, and a
/// headless host has no window for those to mean anything against. A key needs
/// nothing but the document.
///
/// Escape closing a menu is a real assertion in a check suite, and it is the one
/// that says a control does not trap the person using it. Without this a host
/// answers those checks with `unsupported`, which is honest but leaves the
/// suite unable to run them at all.
#[cfg(all(feature = "agent-control", unix))]
/// Move the pointer onto a semantic node, by id.
///
/// The position comes from the node's own box, so this needs no pointer
/// bookkeeping and works in a host that has no window to own a cursor. A
/// control revealed on hover cannot be reached any other way, and a defect that
/// only appears on the second entry cannot be reached at all without it.
#[cfg(all(feature = "agent-control", unix))]
pub fn hover_agent_node(
    document: &mut ScriptDocument,
    node_id: u64,
) -> Result<(f32, f32), DebugError> {
    let position = resolve_agent_node(document, node_id)?.1;
    document.handle_ui_event(UiEvent::PointerMove(pointer_event(
        position,
        MouseEventButton::Main,
        MouseEventButtons::default(),
        KeyboardModifiers::empty(),
    )));
    Ok(position)
}

pub fn press_agent_key(
    document: &mut ScriptDocument,
    key: &str,
    code: &str,
) -> Result<(), DebugError> {
    let parsed_key = key
        .parse::<Key>()
        .unwrap_or_else(|_| Key::Character(key.to_owned()));
    let parsed_code = code.parse::<Code>().unwrap_or(Code::Unidentified);
    for phase in [KeyPhase::Down, KeyPhase::Up] {
        let event = key_event(
            phase,
            parsed_key.clone(),
            parsed_code,
            keyboard_modifiers(Default::default()),
        );
        document.handle_ui_event(match phase {
            KeyPhase::Down => UiEvent::KeyDown(event),
            KeyPhase::Up => UiEvent::KeyUp(event),
        });
    }
    Ok(())
}

pub fn click_agent_node(
    document: &mut ScriptDocument,
    node_id: u64,
    count: u8,
) -> Result<(f32, f32), DebugError> {
    activate_agent_node(document, node_id, count)
}

#[cfg(all(feature = "agent-control", unix))]
pub fn focus_agent_node(
    document: &mut ScriptDocument,
    node_id: blitz_dom::NodeId,
) -> Result<(), DebugError> {
    let focusable = document
        .inner()
        .get_node(node_id)
        .and_then(|node| node.element_data())
        .is_some_and(focuses_on_click);
    if !focusable {
        return Err(debug_error(
            "notFocusable",
            "node does not accept keyboard focus",
        ));
    }
    document.inner_mut().set_focus_to(node_id);
    Ok(())
}

/// Read a document's semantic tree.
///
/// Split out of the runtime's `Inspect` handler so a host that is not this
/// runtime can answer the same request from the same code. Nothing in it is
/// window-dependent: it polls the document, resolves layout and reads the tree.
///
/// Sharing the implementation is the point. A second copy of "what is a node's
/// name" drifts from this one immediately. A QA harness that reimplemented
/// naming against `build_accessibility_tree` got a different answer than the
/// inspector for every element on the page, because that builder names only
/// text nodes and carries no geometry at all.
#[cfg(all(feature = "agent-control", unix))]
pub fn inspect_document(
    document: &mut ScriptDocument,
    root: Option<u64>,
    max_depth: u32,
    revision: u64,
) -> DebugResponse {
    /*
     * Drain immediately runnable script work, but do not force a full style and
     * layout pass for an already committed document. Agent actions resolve
     * before their Ack and the window loop resolves asynchronous frames; an
     * idle inspection is an observer, not another frame driver. Re-resolving
     * every 25ms made scoped outcome latency proportional to the entire retained
     * application even though the response contained one pane.
     */
    let mut ran_script = false;
    for _ in 0..100 {
        if !document.poll(None) {
            break;
        }
        ran_script = true;
    }
    if ran_script {
        document.inner_mut().resolve(0.0);
    }
    let inner = document.inner();
    let root = root.map(blitz_dom::NodeId::from_u64);
    if root.is_some_and(|id| inner.get_node(id).is_none()) {
        return control_error("unknownNode", "the requested root node does not exist");
    }
    let focused_node = inner.get_focussed_node_id().map(|id| id.as_u64());
    let node_limit = inner.tree().iter().count();
    let candidates = if let Some(root) = root {
        semantic_subtree_ids(&inner, root, max_depth)
            .into_iter()
            .filter_map(|id| {
                inner.get_node(id)?;
                dom_chain_is_attached(&inner, id, node_limit).then(|| SemanticCandidate {
                    id,
                    parent: semantic_parent(&inner, id, Some(root)),
                    visible: node_is_visible(&inner, id),
                })
            })
            .collect()
    } else {
        attached_semantic_candidates(&inner, max_depth)
    };
    let layout_validity = layout_chain_validities(&inner, &candidates, node_limit);
    let nodes = candidates
        .into_iter()
        .filter_map(|candidate| {
            let id = candidate.id;
            let node = inner.get_node(id)?;
            let element = node.element_data()?;
            if layout_validity.get(&id) != Some(&true) {
                return None;
            }
            let rect = inner.get_client_bounding_rect(id);
            let visible = candidate.visible
                && rect
                    .as_ref()
                    .is_some_and(|rect| rect.width > 0.0 && rect.height > 0.0);
            let role = semantic_role(element);
            let name = semantic_name(element, node, &role);
            let value = semantic_value(element);
            Some(SemanticNode {
                dom_id: element_attr(element, "id").map(str::to_owned),
                id: id.as_u64(),
                parent: candidate.parent.map(|id| id.as_u64()),
                role,
                name,
                value,
                enabled: element_attr(element, "disabled").is_none()
                    && element_attr(element, "aria-disabled") != Some("true"),
                visible,
                selected: semantic_selected(element),
                bounds: rect.and_then(|rect| {
                    let bounds = [rect.x, rect.y, rect.width, rect.height];
                    bounds
                        .iter()
                        .all(|value| value.is_finite())
                        .then_some(bounds)
                }),
                slot: element_attr(element, "data-slot").map(str::to_owned),
            })
        })
        .collect();
    DebugResponse::AgentSnapshot(AgentSnapshot {
        revision,
        active_window: Some("blitz-main".into()),
        focused_node,
        nodes,
    })
}

/// Carry blitz-shell's timing summary onto the wire type.
///
/// The two structs are deliberately separate: the protocol is versioned by this
/// crate, while the shell type is free to grow fields that have no wire meaning.
#[cfg(all(feature = "diagnostics", unix))]
pub(crate) fn timing_stats(stats: blitz_shell::TimingStats) -> TimingStats {
    TimingStats {
        mean_ms: stats.mean_ms,
        p95_ms: stats.p95_ms,
        max_ms: stats.max_ms,
    }
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn debug_error(code: &str, message: &str) -> DebugError {
    DebugError {
        code: code.into(),
        message: message.into(),
    }
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn focuses_on_click(element: &blitz_dom::ElementData) -> bool {
    let tag = element.name.local.as_ref();
    matches!(tag, "button" | "input" | "select" | "textarea")
        || tag == "a" && element_attr(element, "href").is_some()
        || element_attr(element, "tabindex")
            .and_then(|value| value.parse::<i32>().ok())
            .is_some_and(|value| value >= 0)
        || element_attr(element, "contenteditable").is_some_and(|value| value != "false")
}

#[cfg(all(feature = "diagnostics", unix))]
pub(crate) fn resident_bytes() -> Option<u64> {
    let output = std::process::Command::new("ps")
        .args(["-o", "rss=", "-p", &std::process::id().to_string()])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    std::str::from_utf8(&output.stdout)
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .and_then(|kilobytes| kilobytes.checked_mul(1_024))
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn node_is_individually_visible(node: &blitz_dom::Node) -> bool {
    if !node.flags.is_in_document() || node.is_display_none() {
        return false;
    }
    /*
     * `visibility: hidden` counts too, not just `display: none`.
     *
     * The two are different in layout and identical to a viewer: a hidden
     * node keeps its box and paints nothing. Reporting it as visible made
     * an audit of the running application call it a fault, because the box
     * was there and the pixels were not. Tailwind's `invisible` is exactly
     * this, and it is how a control that is deliberately dormant - a Stop
     * button with no run to stop - is expressed.
     *
     * `Collapse` is included: on anything that is not a table row it means
     * the same as `Hidden`, and on a row it removes the row entirely, so
     * treating it as not-visible is right in both cases.
     */
    if node.primary_styles().is_some_and(|style| {
        use style::computed_values::visibility::T as Visibility;
        matches!(
            style.clone_visibility(),
            Visibility::Hidden | Visibility::Collapse
        )
    }) {
        return false;
    }
    !node.element_data().is_some_and(|element| {
        element_attr(element, "hidden").is_some()
            || element_attr(element, "aria-hidden") == Some("true")
    })
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn resolve_agent_node(
    document: &mut ScriptDocument,
    raw_node_id: u64,
) -> Result<(blitz_dom::NodeId, (f32, f32)), DebugError> {
    let node_id = blitz_dom::NodeId::from_u64(raw_node_id);
    document.inner_mut().resolve(0.0);
    let inner = document.inner();
    let node = inner
        .get_node(node_id)
        .ok_or_else(|| debug_error("unknownNode", "node does not exist"))?;
    if !node_is_visible(&inner, node_id) {
        return Err(debug_error("notInteractable", "node is not visible"));
    }
    let node_limit = inner.tree().iter().count();
    if !dom_chain_is_attached(&inner, node_id, node_limit)
        || !layout_chain_is_valid(&inner, node_id, node_limit)
    {
        return Err(debug_error(
            "notInteractable",
            "node has a detached layout ancestor",
        ));
    }
    if node
        .element_data()
        .is_some_and(|element| element_attr(element, "disabled").is_some())
    {
        return Err(debug_error("notInteractable", "node is disabled"));
    }
    let rect = inner
        .get_client_bounding_rect(node_id)
        .filter(|rect| rect.width > 0.0 && rect.height > 0.0)
        .ok_or_else(|| debug_error("notInteractable", "node has no layout box"))?;
    Ok((
        node_id,
        (
            (rect.x + rect.width / 2.0) as f32,
            (rect.y + rect.height / 2.0) as f32,
        ),
    ))
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn pointer_event(
    position: (f32, f32),
    button: MouseEventButton,
    buttons: MouseEventButtons,
    modifiers: KeyboardModifiers,
) -> BlitzPointerEvent {
    BlitzPointerEvent {
        id: BlitzPointerId::Mouse,
        is_primary: true,
        coords: pointer_coords(position),
        button,
        buttons,
        mods: modifiers,
        details: PointerDetails::default(),
        element: Point::default(),
        active_pointers: Default::default(),
    }
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) struct SemanticCandidate {
    pub(crate) id: blitz_dom::NodeId,
    pub(crate) parent: Option<blitz_dom::NodeId>,
    pub(crate) visible: bool,
}

#[cfg(all(feature = "agent-control", unix))]
#[derive(Clone, Copy)]
enum LayoutChainState {
    Visiting,
    Valid,
    Invalid,
}

/// Resolve layout ancestry once for every inspected node.
///
/// DOM ancestry and layout ancestry are not interchangeable, but they share
/// the same performance trap: walking every node back to a root makes a full
/// inspection proportional to `nodes * depth`. Memoize each layout ancestor so
/// later candidates stop at the first result the traversal already proved.
#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn layout_chain_validities(
    document: &blitz_dom::BaseDocument,
    candidates: &[SemanticCandidate],
    node_limit: usize,
) -> HashMap<blitz_dom::NodeId, bool> {
    let mut states = HashMap::with_capacity(candidates.len());

    for candidate in candidates {
        if matches!(
            states.get(&candidate.id),
            Some(LayoutChainState::Valid | LayoutChainState::Invalid)
        ) {
            continue;
        }

        let mut chain = Vec::new();
        let mut current = Some(candidate.id);
        let valid = loop {
            let Some(id) = current else {
                break true;
            };
            match states.get(&id) {
                Some(LayoutChainState::Valid) => break true,
                Some(LayoutChainState::Invalid | LayoutChainState::Visiting) => break false,
                None => {}
            }
            if chain.len() > node_limit {
                break false;
            }
            let Some(node) = document.get_node(id) else {
                break false;
            };
            states.insert(id, LayoutChainState::Visiting);
            chain.push(id);
            current = node.layout_parent.get();
        };

        let resolved = if valid {
            LayoutChainState::Valid
        } else {
            LayoutChainState::Invalid
        };
        for id in chain {
            states.insert(id, resolved);
        }
    }

    states
        .into_iter()
        .filter_map(|(id, state)| match state {
            LayoutChainState::Valid => Some((id, true)),
            LayoutChainState::Invalid => Some((id, false)),
            LayoutChainState::Visiting => None,
        })
        .collect()
}

/// Collect one rooted DOM subtree in document order without visiting retained
/// panes outside it.
#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn semantic_subtree_ids(
    document: &blitz_dom::BaseDocument,
    root: blitz_dom::NodeId,
    max_depth: u32,
) -> Vec<blitz_dom::NodeId> {
    let mut out = Vec::new();
    let mut stack = vec![(root, 0_u32)];
    while let Some((node_id, depth)) = stack.pop() {
        let Some(node) = document.get_node(node_id) else {
            continue;
        };
        if node.element_data().is_some() {
            out.push(node_id);
        }
        for &child_id in node.children.iter().rev() {
            let child_depth = depth.saturating_add(
                document
                    .get_node(child_id)
                    .is_some_and(|child| child.element_data().is_some()) as u32,
            );
            if max_depth == 0 || child_depth <= max_depth {
                stack.push((child_id, child_depth));
            }
        }
    }
    out
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn pointer_coords((x, y): (f32, f32)) -> PointerCoords {
    PointerCoords {
        page_x: x,
        page_y: y,
        screen_x: x,
        screen_y: y,
        client_x: x,
        client_y: y,
    }
}

/// The colours a node actually resolved to, as `#rrggbbaa`.
///
/// The point of reporting these rather than the stylesheet is that they are the
/// end of the chain: the cascade, every custom-property indirection and the
/// `@supports` gating have already been applied, so a disagreement between what
/// a rule declares and what an element paints shows up here and nowhere else.
/// That disagreement is exactly the shape of "this text is invisible and the CSS
/// says it should not be", which cannot be settled by reading files.
///
/// Four properties rather than a full longhand dump: a complete style for every
/// node in a real application is megabytes of JSON that nobody reads, and these
/// are the ones legibility depends on.
#[cfg(all(feature = "diagnostics", unix))]
pub(crate) fn diagnostic_style_row(
    document: &blitz_dom::BaseDocument,
    node: &SemanticNode,
) -> Option<serde_json::Value> {
    let dom_node = document.get_node(NodeId::from_u64(node.id))?;
    let styles = dom_node.primary_styles()?;

    let current = styles.clone_color();
    // The same conversion `blitz-paint` does before handing a colour to the
    // rasteriser, inlined so this crate does not need that extension trait.
    let hex = |absolute: style::color::AbsoluteColor| {
        let [r, g, b, a] = *absolute
            .to_color_space(style::color::ColorSpace::Srgb)
            .raw_components();
        let channel = |value: f32| (value.clamp(0.0, 1.0) * 255.0).round() as u8;
        format!(
            "#{:02x}{:02x}{:02x}{:02x}",
            channel(r),
            channel(g),
            channel(b),
            channel(a),
        )
    };

    /*
     * Reported as a plain number of pixels rather than stylo's debug shape,
     * which nothing reading this over the wire can parse - and being able to
     * read it is the entire reason the field exists.
     */
    let radius = format!("{:?}", styles.get_border().border_top_left_radius.0.width);
    let border = styles.get_border();
    let border_width = border.border_top_width.0.to_f64_px();
    let font_size = styles.clone_font_size().computed_size().px();
    let has_text_content = !dom_node.text_content().trim().is_empty();

    Some(serde_json::json!({
        "nodeId": node.id,
        "color": hex(current),
        "backgroundColor": hex(
            styles.clone_background_color().resolve_to_absolute(&current),
        ),
        "borderColor": hex(border.border_top_color.resolve_to_absolute(&current)),
        "borderWidth": format!("{border_width}px"),
        "fontSize": format!("{font_size}px"),
        "hasTextContent": has_text_content,
        "opacity": styles.clone_opacity(),
        /*
         * The corner, as the renderer resolved it.
         *
         * Radius is set from three unrelated places in a themed application -
         * the library's own component CSS, the theme's tokens, and utility
         * classes at the call site - and which one wins is a cascade question
         * that reading any single file cannot answer. Reported repeatedly as
         * "radius is wrong" with no way to tell *which* of the three was
         * responsible; this is what settles it per element.
         */
        "borderTopLeftRadius": radius,
        "visibility": format!("{:?}", styles.clone_visibility()),
    }))
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn keyboard_modifiers(modifiers: ControlModifiers) -> KeyboardModifiers {
    let mut output = KeyboardModifiers::empty();
    output.set(KeyboardModifiers::SHIFT, modifiers.shift);
    output.set(KeyboardModifiers::CONTROL, modifiers.control);
    output.set(KeyboardModifiers::ALT, modifiers.alt);
    output.set(KeyboardModifiers::META, modifiers.meta);
    output
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn key_event(
    phase: KeyPhase,
    key: Key,
    code: Code,
    modifiers: KeyboardModifiers,
) -> BlitzKeyEvent {
    let text = match (&key, phase) {
        (Key::Character(value), KeyPhase::Down)
            if !modifiers.intersects(
                KeyboardModifiers::CONTROL | KeyboardModifiers::ALT | KeyboardModifiers::META,
            ) =>
        {
            Some(value.clone().into())
        }
        _ => None,
    };
    BlitzKeyEvent {
        key,
        code,
        modifiers,
        location: Location::Standard,
        is_auto_repeating: false,
        is_composing: false,
        state: match phase {
            KeyPhase::Down => KeyState::Pressed,
            KeyPhase::Up => KeyState::Released,
        },
        text,
    }
}

/// Collect the attached document in one traversal.
///
/// The previous full inspection asked every node to rediscover its depth,
/// semantic parent, attachment and inherited visibility by walking back to the
/// root independently. A retained application therefore paid roughly
/// `nodes * depth` before it serialized one byte. Carry those inherited facts
/// down the tree once instead.
#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn attached_semantic_candidates(
    document: &blitz_dom::BaseDocument,
    max_depth: u32,
) -> Vec<SemanticCandidate> {
    let root = document.root_node().id;
    let mut candidates = Vec::new();
    let mut stack = vec![(root, 0_u32, None, true)];

    while let Some((id, depth, semantic_parent, ancestors_visible)) = stack.pop() {
        let Some(node) = document.get_node(id) else {
            continue;
        };
        let visible = ancestors_visible && node_is_individually_visible(node);
        let is_element = node.element_data().is_some();
        if is_element && max_depth != 0 && depth > max_depth {
            continue;
        }
        if is_element {
            candidates.push(SemanticCandidate {
                id,
                parent: semantic_parent,
                visible,
            });
        }

        let child_depth = depth.saturating_add(is_element as u32);
        let child_parent = if is_element {
            Some(id)
        } else {
            semantic_parent
        };
        for &child in node.children.iter().rev() {
            stack.push((child, child_depth, child_parent, visible));
        }
    }

    candidates
}

#[cfg(all(feature = "agent-control", unix))]
pub(crate) fn control_error(code: &str, message: &str) -> DebugResponse {
    DebugResponse::Error(debug_error(code, message))
}

#[cfg(all(feature = "diagnostics", unix))]
pub(crate) fn diagnostic_layout_row(
    document: &blitz_dom::BaseDocument,
    node: &SemanticNode,
) -> Option<LayoutDiagnosticRow> {
    let bounds = node.bounds?;
    let dom_node = document.get_node(NodeId::from_u64(node.id))?;
    let layout = dom_node.final_layout();
    let unzoom = |value: f32| match dom_node.primary_styles() {
        Some(styles) => styles.effective_zoom.unzoom(value),
        None => value,
    };
    // Every field here is unzoomed, including the two that used to be raw.
    //
    // `scrollOffset` and `scrollRange` came straight off the layout while
    // `clientSize` and `scrollSize` went through `unzoom`, so a single row
    // carried two unit systems and any arithmetic across them was wrong by the
    // zoom factor. Under zoom that makes every scroller read as overscrolled,
    // and it is not only a reading error: a consumer testing
    // `scrollOffset < scrollSize - clientSize` for "is there more to scroll"
    // gets a false negative at the true end, leaving an overflow control
    // disabled while content remains off screen.
    //
    // Unzoomed is the right side to land on because it is what the DOM already
    // reports: `blitz-script`'s `scrollLeft`/`scrollTop` unzoom before
    // answering, so a raw diagnostic also disagreed with the same measurement
    // taken from script.
    //
    // Not covered by a unit test, deliberately rather than by omission. The
    // existing row test runs at zoom 1, where `unzoom` is the identity and a
    // mixed row is indistinguishable from a consistent one. Reproducing it
    // needs a scroller that is itself zoomed, and in this engine `zoom` on an
    // `overflow-y:auto` element leaves `scroll_height()` at 0 while `zoom` on
    // its child does not reach the scroller's own styles — so a test asserting
    // the relation either holds vacuously (0 == 0) or fails its own setup.
    // Verified against a zoomed live scroller where the raw offset exceeded
    // the unzoomed range by exactly the zoom factor.
    let scroll_offset = dom_node.scroll_offset();
    Some(LayoutDiagnosticRow {
        node_id: node.id,
        bounds: LayoutBounds::from(bounds),
        scroll_offset: LayoutOffset {
            x: f64::from(unzoom(scroll_offset.x as f32)),
            y: f64::from(unzoom(scroll_offset.y as f32)),
        },
        client_size: LayoutSize {
            width: f64::from(unzoom(layout.size.width)),
            height: f64::from(unzoom(layout.size.height)),
        },
        scroll_size: LayoutSize {
            width: f64::from(unzoom(layout.size.width + layout.scroll_width())),
            height: f64::from(unzoom(layout.size.height + layout.scroll_height())),
        },
        scroll_range: LayoutSize {
            width: f64::from(unzoom(layout.scroll_width())),
            height: f64::from(unzoom(layout.scroll_height())),
        },
        // Border and padding, so a box that renders taller than it was asked
        // for can be attributed instead of guessed at.
        //
        // Without these the only readable numbers are the outer bounds and
        // `clientSize`, and both are the border box: a pill declared `24px`
        // that measures 27.8 offers no way to tell a 1px border from padding
        // from a wrong height, and the difference decides which file to edit.
        // Four consecutive wrong diagnoses of one composer pill came from
        // inferring these from CSS files rather than reading what the engine
        // computed, which is exactly the guessing this replaces.
        //
        // Edge order matches CSS shorthand: top, right, bottom, left.
        border: LayoutEdges {
            top: f64::from(unzoom(layout.border.top)),
            right: f64::from(unzoom(layout.border.right)),
            bottom: f64::from(unzoom(layout.border.bottom)),
            left: f64::from(unzoom(layout.border.left)),
        },
        padding: LayoutEdges {
            top: f64::from(unzoom(layout.padding.top)),
            right: f64::from(unzoom(layout.padding.right)),
            bottom: f64::from(unzoom(layout.padding.bottom)),
            left: f64::from(unzoom(layout.padding.left)),
        },
        // The content box, which is what an author's `height` sets under the
        // default `content-box` sizing. `clientSize` above is the border box.
        content_size: LayoutSize {
            width: f64::from(unzoom(
                layout.size.width
                    - layout.border.left
                    - layout.border.right
                    - layout.padding.left
                    - layout.padding.right,
            )),
            height: f64::from(unzoom(
                layout.size.height
                    - layout.border.top
                    - layout.border.bottom
                    - layout.padding.top
                    - layout.padding.bottom,
            )),
        },
    })
}

pub(crate) fn activate_agent_node(
    document: &mut ScriptDocument,
    raw_node_id: u64,
    count: u8,
) -> Result<(f32, f32), DebugError> {
    let (node_id, position) = resolve_agent_node(document, raw_node_id)?;
    let focusable = document
        .inner()
        .get_node(node_id)
        .and_then(|node| node.element_data())
        .is_some_and(focuses_on_click);

    for _ in 0..count {
        let down = pointer_event(
            position,
            MouseEventButton::Main,
            MouseEventButtons::Primary,
            KeyboardModifiers::empty(),
        );
        let up = pointer_event(
            position,
            MouseEventButton::Main,
            MouseEventButtons::default(),
            KeyboardModifiers::empty(),
        );
        for data in [
            DomEventData::PointerDown(down.clone()),
            DomEventData::MouseDown(down),
            DomEventData::PointerUp(up.clone()),
            DomEventData::MouseUp(up.clone()),
            DomEventData::Click(up),
        ] {
            // A mousedown handler can deliberately replace its own control.
            // The action already happened; later phases have no surviving
            // target and must not be retargeted to whatever took its place.
            if document.inner().get_node(node_id).is_none() {
                break;
            }
            document.dispatch_dom_event(DomEvent::new(node_id, data));
        }
        if focusable && document.inner().get_node(node_id).is_some() {
            document.inner_mut().set_focus_to(node_id);
        }
    }
    Ok(position)
}