blitz-control-protocol 0.7.3

The Blitz agent-control and diagnostics surface: one vocabulary, one core, two transports
Documentation
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
//! The socket transport, connecting half: finding a running host, and talking
//! to it.
//!
//! # Why this is a sibling of the server and not a layer above it
//!
//! A peer can be both. AgencyZero is driven by agents over this protocol while
//! it drives a browser it embeds, and a QA harness that launches a headless
//! host is a client of one socket in a process that could serve another. The
//! two halves share the vocabulary, the framing and the error taxonomy, and
//! neither is built on the other, so a build takes whichever halves it needs.
//!
//! Neither half needs blitz. The framing is the protocol; the document is not.
//! `ps-qa` takes this feature and nothing else, and `cargo tree -p ps-qa`
//! showing no renderer, window runtime or GPU stack is the check that keeps it
//! that way.
//!
//! The transport is deliberately not hand-rolled. Frames are length-prefixed
//! rather than newline-delimited, which is why a naive socket read hangs, and
//! `endpoint_libs`' `framed_json_neutral` is the same codec the server writes with.
//!
//! This was `ps-qa`'s `inspector` module. It moved here so there is one client
//! rather than one per consumer: the browser's own `chuzz-inspect` had grown a
//! second one that built its requests as untyped JSON by hand, with a comment
//! explaining which fields the runtime would and would not accept.

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::time::Instant;

use crate::{
    AgentControlRequest, AgentSnapshot, DEBUG_PROTOCOL_VERSION, DebugDescriptor, DebugEvent,
    DebugProtocolError, DebugResponse, DebugStream, DiagnosticsRequest, JsonRpcId, JsonRpcMessage,
    JsonRpcRequest, MCP_PROTOCOL_VERSION, MessageStream, TransportStream, WireMessage,
    decode_diagnostics_event_value, decode_response_value, decode_wire_value, encode_agent_request,
    encode_diagnostics_request, encode_rpc, peek_value_request_id,
};
use eyre::{Context, Result, bail, eyre};
use std::os::unix::ffi::OsStrExt;

use endpoint_libs::libs::ws::transport::framed::framed_json_neutral;
use endpoint_libs::libs::ws::transport::nagoya::NagoyaStream;
use nagoya::reactor::{Addr, Reactor, TcpStream};
use nagoya::timeout;

/// Matches the Python client's bench timeout. Long because a driven
/// interaction can leave the app resolving for a while before it answers.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
const MAX_QUEUED_EVENTS: usize = 256;

/// Where an inspector announced itself, and what it said.
#[derive(Debug)]
pub struct Descriptor {
    pub path: PathBuf,
    pub descriptor: DebugDescriptor,
    /// The descriptor verbatim, for the dump modes. Reprinting a re-serialized
    /// struct would hide any field this build of the tool does not know about.
    pub raw: serde_json::Value,
    verified_reachable: bool,
}

/// The reactor every inspector connection lives on.
///
/// A nagoya socket makes progress only while the reactor it was created on is
/// polled, and this client is a library: it does not own the caller's thread and
/// cannot assume one is polling anything. `Reactor::start` owns a thread, so a
/// connection keeps being driven between the caller's awaits.
///
/// One for the process rather than one per connection: a thread per inspector
/// connection would be a thread per command in a QA sweep.
fn client_reactor() -> &'static nagoya::reactor::Handle {
    static REACTOR: std::sync::OnceLock<(Reactor, nagoya::reactor::Handle)> =
        std::sync::OnceLock::new();
    let (_, handle) = REACTOR.get_or_init(|| {
        let reactor = Reactor::start().expect("inspector reactor could not start");
        let handle = reactor.handle();
        (reactor, handle)
    });
    handle
}

impl Descriptor {
    pub fn socket_path(&self) -> PathBuf {
        match self.descriptor.address.strip_prefix("unix://") {
            Some(path) => PathBuf::from(path),
            // The Python fell back to the descriptor path with the extension
            // swapped, and the server does name the socket that way.
            None => self.path.with_extension("sock"),
        }
    }

    /// Trap 8 in docs/performance.md: an unpinned descriptor directory keeps
    /// dead instances around. Pid existence is not enough: macOS reuses pids,
    /// so an unrelated process can make a stale descriptor look current. The
    /// control socket is the service, and a successful connection is the only
    /// liveness check that proves the descriptor can actually be used.
    fn is_reachable(&self) -> bool {
        std::os::unix::net::UnixStream::connect(self.socket_path()).is_ok()
    }

    pub fn warn_if_stale(&self) {
        if !self.verified_reachable && !self.is_reachable() {
            eprintln!(
                "warning: descriptor {} names pid {}, but its control socket is unreachable",
                self.path.display(),
                self.descriptor.pid
            );
        }
    }
}

/// Locate a running inspector, preferring an explicitly pinned descriptor.
///
/// `--descriptor <path>` wins. Otherwise the build's own pinned path is tried,
/// then the temporary directory is scanned, which is the fallback for a
/// hand-launched build and the one that can find a stale instance.
///
/// A named descriptor that is not there is an error, not an invitation to
/// scan. Falling through to discovery attached to the newest *other* host on
/// the machine, which on a machine running several suites at once is another
/// site's document: the tree came back, it was plausible, and it described a
/// page nobody had asked about. A typo in a path is not consent to inspect
/// somebody else's application.
pub fn discover(explicit: Option<&str>) -> Result<Descriptor> {
    if let Some(path) = explicit {
        let path = PathBuf::from(path);
        if !path.exists() {
            bail!(
                "descriptor {} does not exist. ps-qa attaches to the descriptor you \
                 name and to no other; omit --descriptor to discover a running host.",
                path.display()
            );
        }
        return read_descriptor(&path);
    }

    // The delivery script pins this path into the bundle's `Info.plist`, so a
    // locally built app announces itself here and nowhere else. Scanning only
    // $TMPDIR meant the one instance that was definitely running was the one
    // instance discovery could not see, and it picked a dead descriptor from a
    // previous run instead, which is how preferring a live pid still failed.
    let pinned = PathBuf::from("target/blitz-control.json");
    if pinned.exists()
        && let Ok(mut descriptor) = read_descriptor(&pinned)
        && descriptor.is_reachable()
    {
        descriptor.verified_reachable = true;
        return Ok(descriptor);
    }

    let root = PathBuf::from(std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".into()))
        .join("tauri-blitz-agent");
    let mut found: Vec<(std::time::SystemTime, PathBuf)> = std::fs::read_dir(&root)
        .into_iter()
        .flatten()
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
        .filter_map(|path| Some((path.metadata().ok()?.modified().ok()?, path)))
        .collect();
    found.sort();

    // Newest *reachable* instance, not simply newest.
    //
    // Descriptors outlive the process that wrote them, and a machine that has
    // run the app more than once has a directory full of them. Taking the most
    // recent file connected to whichever instance happened to exit last: at
    // best a refused connection, at worst a successful attach to a stale socket
    // and a set of numbers describing a process nobody is looking at. The
    // warning for that case already existed and was printed immediately before
    // connecting anyway.
    for (_, path) in found.iter().rev() {
        let Ok(mut descriptor) = read_descriptor(path) else {
            continue;
        };
        if descriptor.is_reachable() {
            descriptor.verified_reachable = true;
            return Ok(descriptor);
        }
    }

    bail!(
        "no reachable inspector descriptor found; is a diagnostics build running?\n\
         looked at target/blitz-control.json and {}. Pass --descriptor \
         <path> to inspect a specific descriptor.",
        root.display()
    )
}

fn read_descriptor(path: &Path) -> Result<Descriptor> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("reading descriptor {}", path.display()))?;
    let raw: serde_json::Value = serde_json::from_str(&text)
        .with_context(|| format!("parsing descriptor {}", path.display()))?;
    let descriptor: DebugDescriptor = serde_json::from_value(raw.clone())
        .with_context(|| format!("descriptor {} is not a DebugDescriptor", path.display()))?;
    if descriptor.protocol_version != DEBUG_PROTOCOL_VERSION {
        bail!(
            "descriptor {} uses debug protocol {}, but this client speaks {}; \
             use a client built for protocol {} (for ps-qa, build it from the \
             blitz-control-protocol release or checkout that the host was built against)",
            path.display(),
            descriptor.protocol_version,
            DEBUG_PROTOCOL_VERSION,
            descriptor.protocol_version
        );
    }
    Ok(Descriptor {
        path: path.to_path_buf(),
        descriptor,
        raw,
        verified_reachable: false,
    })
}

/// A connected inspector client.
///
/// `MessageStream` is the object-safe half of the endpoint-libs transport seam,
/// so the concrete framing type, which is opaque, never has to be named.
pub struct Client {
    stream: Box<dyn MessageStream>,
    next_id: i64,
    request_timeout: Duration,
    terminal: Option<TerminalFailure>,
    events: VecDeque<DebugEvent>,
    notifications: VecDeque<serde_json::Value>,
    lost_notifications: u64,
    target_options: crate::TargetOptions,
    target_context: Option<crate::TargetContext>,
}

#[derive(Clone, Debug)]
enum TerminalFailure {
    RequestTimeout {
        request_id: String,
        phase: &'static str,
        timeout: Duration,
    },
    Disconnected {
        request_id: String,
        phase: &'static str,
        cause: String,
    },
}

impl TerminalFailure {
    fn report(&self) -> eyre::Report {
        match self {
            Self::RequestTimeout {
                request_id,
                phase,
                timeout,
            } => eyre::Report::new(InspectorRequestTimeout {
                request_id: request_id.clone(),
                phase,
                timeout: *timeout,
            }),
            Self::Disconnected {
                request_id,
                phase,
                cause,
            } => eyre::Report::new(InspectorDisconnected {
                request_id: request_id.clone(),
                phase,
                cause: cause.clone(),
            }),
        }
    }

    fn message(&self) -> String {
        self.report().to_string()
    }

    fn is_timeout(&self) -> bool {
        matches!(self, Self::RequestTimeout { .. })
    }
}

/// A request exceeded its single transport deadline.
#[derive(Clone, Debug)]
pub struct InspectorRequestTimeout {
    pub request_id: String,
    pub phase: &'static str,
    pub timeout: Duration,
}

impl std::fmt::Display for InspectorRequestTimeout {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "InspectorRequestTimeout: request {} timed out during {} after {:?}",
            self.request_id, self.phase, self.timeout
        )
    }
}

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

/// The inspector connection ended or failed during a request.
#[derive(Clone, Debug)]
pub struct InspectorDisconnected {
    pub request_id: String,
    pub phase: &'static str,
    pub cause: String,
}

impl std::fmt::Display for InspectorDisconnected {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "InspectorDisconnected: request {} failed during {}: {}",
            self.request_id, self.phase, self.cause
        )
    }
}

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

fn transport_disconnect_cause(error: &endpoint_libs::libs::ws::StreamError) -> String {
    if matches!(error, endpoint_libs::libs::ws::StreamError::Closed) {
        return "clean connection close".to_owned();
    }

    let mut source = Some(error as &dyn std::error::Error);
    while let Some(cause) = source {
        if let Some(io_error) = cause.downcast_ref::<std::io::Error>()
            && matches!(
                io_error.kind(),
                std::io::ErrorKind::UnexpectedEof
                    | std::io::ErrorKind::ConnectionReset
                    | std::io::ErrorKind::BrokenPipe
            )
        {
            return format!("{:?}: {}", io_error.kind(), io_error);
        }
        source = cause.source();
    }

    error.to_string()
}

#[derive(Debug)]
struct InspectorResponseError {
    code: String,
    message: String,
}

impl std::fmt::Display for InspectorResponseError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "inspector returned {}: {}",
            self.code, self.message
        )
    }
}

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

/// Whether a host refused a request because it does not have the thing asked
/// for, rather than because something went wrong.
///
/// The distinction matters for a headless host. It owns a document and no
/// compositor, so there are no frame metrics to report and saying "unsupported"
/// is the true answer. A caller that only wanted the numbers as context can
/// carry on without them; one that exists to judge frame timing cannot, and
/// should still fail.
pub fn is_unsupported(error: &eyre::Report) -> bool {
    error
        .downcast_ref::<InspectorResponseError>()
        .is_some_and(|refusal| refusal.code == "unsupported")
}

/// Whether a host has no completed GPUBuffer write available yet.
///
/// This is an incomplete diagnostic sample, so a caller can retry within its
/// outcome deadline. Other host refusals and transport errors stay failures.
pub fn is_pending(error: &eyre::Report) -> bool {
    error
        .downcast_ref::<InspectorResponseError>()
        .is_some_and(|refusal| refusal.code == "pending")
}

/// Return a bounded response category without exposing the inspector message.
pub fn safe_response_code(error: &eyre::Report) -> Option<&'static str> {
    let code = error
        .downcast_ref::<InspectorResponseError>()?
        .code
        .as_str();
    Some(match code {
        "notEditable" => "notEditable",
        "unknownNode" => "unknownNode",
        "documentUnavailable" => "documentUnavailable",
        "unsupportedRequest" => "unsupportedRequest",
        _ => "other",
    })
}

impl Client {
    pub fn select_target(&mut self, target: Option<crate::TargetSelector>) {
        self.target_options = crate::TargetOptions {
            target,
            ..Default::default()
        };
        self.target_context = None;
    }

    pub fn target_context(&self) -> Option<&crate::TargetContext> {
        self.target_context.as_ref()
    }

    fn target_frame(&self, frame: WireMessage) -> Result<WireMessage> {
        let mut value = decode_wire_value(frame).map_err(protocol_error)?;
        if value["method"] != "tools/call" {
            return Ok(WireMessage::Text(serde_json::to_string(&value)?.into()));
        }
        let tool = value["params"]["name"]
            .as_str()
            .unwrap_or_default()
            .to_owned();
        let arguments = &mut value["params"]["arguments"];
        let object = arguments
            .as_object_mut()
            .ok_or_else(|| eyre!("tool arguments must be an object"))?;
        if !object.contains_key("target")
            && object.get("allTargets") != Some(&serde_json::Value::Bool(true))
            && let Some(target) = &self.target_options.target
        {
            object.insert("target".into(), serde_json::to_value(target)?);
        }
        let options: crate::TargetOptions = serde_json::from_value(arguments.clone())?;
        let command = if tool == crate::AGENT_CONTROL_TOOL {
            serde_json::from_value(arguments.clone())
                .ok()
                .map(crate::TargetCommand::Agent)
        } else if tool == crate::DIAGNOSTICS_TOOL {
            serde_json::from_value(arguments.clone())
                .ok()
                .map(crate::TargetCommand::Diagnostics)
        } else {
            None
        };
        if options.target == self.target_options.target
            && !options.all_targets
            && let (Some(context), Some(command)) = (&self.target_context, command)
        {
            let request = crate::TargetRequest { options, command };
            if (request.uses_nodes()
                || matches!(
                    request.command,
                    crate::TargetCommand::Agent(crate::AgentControlRequest::Act(_))
                ))
                && matches!(context.target_id, crate::TargetId::Tab(_))
            {
                let object = arguments.as_object_mut().expect("arguments object");
                object
                    .entry("expectedGeneration")
                    .or_insert_with(|| context.generation.into());
                object
                    .entry("expectedDocumentId")
                    .or_insert_with(|| context.document_id.into());
            }
        }
        Ok(WireMessage::Text(serde_json::to_string(&value)?.into()))
    }

    fn queue_notification(&mut self, value: serde_json::Value) {
        if value.get("method").is_none() || value.get("id").is_some() {
            return;
        }
        if self.notifications.len() == MAX_QUEUED_EVENTS {
            self.notifications.pop_front();
            self.lost_notifications += 1;
        }
        self.notifications.push_back(value);
    }

    fn capture_target_context(&mut self, value: &serde_json::Value) {
        let Some(context) = value.pointer("/result/structuredContent/context") else {
            return;
        };
        let Ok(context) = serde_json::from_value::<crate::TargetContext>(context.clone()) else {
            return;
        };
        let selected = self
            .target_options
            .target
            .as_ref()
            .map_or_else(crate::TargetId::chrome, crate::TargetSelector::id);
        if context.target_id == selected {
            self.target_context = Some(context);
        }
    }

    fn queue_event(&mut self, event: DebugEvent) {
        if self.events.len() == MAX_QUEUED_EVENTS {
            self.events.pop_front();
        }
        self.events.push_back(event);
    }

    pub async fn connect(socket: &Path) -> Result<Self> {
        const CONNECT_DEADLINE: Duration = Duration::from_millis(500);
        const RETRY_DELAY: Duration = Duration::from_millis(20);

        let started = Instant::now();
        let stream = loop {
            let addr = Addr::path(socket.as_os_str().as_bytes())
                .map_err(|_| std::io::Error::other("socket path is not a valid unix address"))?;
            match TcpStream::connect(addr, client_reactor()).await {
                Ok(stream) => break stream,
                Err(_) if started.elapsed() < CONNECT_DEADLINE => {
                    nagoya::sleep(RETRY_DELAY).await;
                }
                Err(error) => {
                    return Err(error)
                        .with_context(|| format!("connecting to {}", socket.display()));
                }
            }
        };
        Ok(Self {
            stream: Box::new(TransportStream::new(framed_json_neutral(
                NagoyaStream::new(stream),
            ))),
            next_id: 0,
            request_timeout: REQUEST_TIMEOUT,
            terminal: None,
            events: VecDeque::new(),
            notifications: VecDeque::new(),
            lost_notifications: 0,
            target_options: crate::TargetOptions::default(),
            target_context: None,
        })
    }

    /// Bound every inspector exchange for a latency-sensitive command.
    ///
    /// Interactive dump/diagnostic modes retain the generous default. QA and
    /// coverage explicitly lower it so a dead action cannot multiply a
    /// minute-long transport wait across a suite.
    pub fn set_request_timeout(&mut self, request_timeout: Duration) {
        self.request_timeout = request_timeout;
    }

    pub fn request_timeout(&self) -> Duration {
        self.request_timeout
    }

    pub fn is_terminal(&self) -> bool {
        self.terminal.is_some()
    }

    pub fn terminal_is_timeout(&self) -> bool {
        self.terminal
            .as_ref()
            .is_some_and(TerminalFailure::is_timeout)
    }

    pub fn terminal_failure_message(&self) -> Option<String> {
        self.terminal.as_ref().map(TerminalFailure::message)
    }

    fn ensure_available(&self) -> Result<()> {
        match &self.terminal {
            Some(failure) => Err(failure.report()),
            None => Ok(()),
        }
    }

    fn mark_timeout(&mut self, id: &JsonRpcId, phase: &'static str) -> eyre::Report {
        let failure = TerminalFailure::RequestTimeout {
            request_id: format!("{id:?}"),
            phase,
            timeout: self.request_timeout,
        };
        self.terminal = Some(failure.clone());
        failure.report()
    }

    fn mark_disconnected(
        &mut self,
        id: &JsonRpcId,
        phase: &'static str,
        cause: String,
    ) -> eyre::Report {
        let failure = TerminalFailure::Disconnected {
            request_id: format!("{id:?}"),
            phase,
            cause,
        };
        self.terminal = Some(failure.clone());
        failure.report()
    }

    fn next_id(&mut self) -> JsonRpcId {
        self.next_id += 1;
        JsonRpcId::Number(self.next_id)
    }

    /// Send one request and return the frame that answers *it*.
    ///
    /// Matching on the id is not pedantry. The server pushes notifications on
    /// the same socket, so a client that returns the next frame it sees will
    /// eventually hand a console message back as though it were metrics.
    async fn exchange(
        &mut self,
        request: WireMessage,
        id: &JsonRpcId,
    ) -> Result<serde_json::Value> {
        self.ensure_available()?;
        let request = self.target_frame(request)?;
        let deadline = Instant::now() + self.request_timeout;
        let send_remaining = deadline.saturating_duration_since(Instant::now());
        match timeout(send_remaining, self.stream.send(request)).await {
            Err(_) => return Err(self.mark_timeout(id, "send")),
            Ok(Err(error)) => {
                let cause = transport_disconnect_cause(&error);
                return Err(self.mark_disconnected(id, "send", cause));
            }
            Ok(Ok(())) => {}
        }

        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(self.mark_timeout(id, "receive"));
            }

            let message = match timeout(remaining, self.stream.recv()).await {
                Err(_) => return Err(self.mark_timeout(id, "receive")),
                Ok(None) => {
                    return Err(self.mark_disconnected(id, "receive", "clean EOF".to_owned()));
                }
                Ok(Some(Err(error))) => {
                    let cause = transport_disconnect_cause(&error);
                    return Err(self.mark_disconnected(id, "receive", cause));
                }
                Ok(Some(Ok(message))) => message,
            };

            let value = decode_wire_value(message).map_err(protocol_error)?;
            if peek_value_request_id(&value).as_ref() == Some(id) {
                self.capture_target_context(&value);
                return Ok(value);
            }
            self.queue_notification(value.clone());
            if let Ok(event) = decode_diagnostics_event_value(value) {
                self.queue_event(event);
            }
        }
    }

    /// A raw JSON-RPC call, for `initialize` and `tools/list`, which are not
    /// tool calls and so have no typed request in the protocol crate.
    pub async fn raw_request(
        &mut self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let id = self.next_id();
        let request = encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
            id.clone(),
            method,
            params,
        )))
        .map_err(protocol_error)?;
        self.exchange(request, &id).await
    }

    pub async fn initialize(&mut self) -> Result<serde_json::Value> {
        self.raw_request(
            "initialize",
            serde_json::json!({"protocolVersion": MCP_PROTOCOL_VERSION}),
        )
        .await
    }

    pub async fn tools_list(&mut self) -> Result<serde_json::Value> {
        self.raw_request("tools/list", serde_json::json!({})).await
    }

    /// An agent-control call, encoded from the server's own type.
    ///
    /// This is the whole reason the protocol crate exists. `AgentAction` is
    /// adjacently tagged, so the `{"action":"click","nodeId":9}` that reads
    /// correctly is not what the server accepts, and getting it wrong used to
    /// present as a hung application rather than as an encoding mistake.
    pub async fn agent(&mut self, request: &AgentControlRequest) -> Result<Answer> {
        let id = self.next_id();
        let frame = encode_agent_request(id.clone(), request).map_err(protocol_error)?;
        let value = self.exchange(frame, &id).await?;
        Answer::new(value)
    }

    pub async fn diagnostics(&mut self, request: &DiagnosticsRequest) -> Result<Answer> {
        let id = self.next_id();
        let frame = encode_diagnostics_request(id.clone(), request).map_err(protocol_error)?;
        let value = self.exchange(frame, &id).await?;
        Answer::new(value)
    }

    /// Establish a paint-event baseline immediately before driving input.
    ///
    /// New runtimes answer with `Ack` and suppress any revision that predates
    /// this call. Older runtimes answer `streamingUnavailable`; callers retain
    /// their bounded compatibility fallback in that case.
    pub async fn arm_paint_events(&mut self) -> Result<bool> {
        self.events
            .retain(|event| !matches!(event, DebugEvent::PaintCommitted { .. }));
        match self
            .diagnostics(&DiagnosticsRequest::Observe {
                streams: vec![DebugStream::Paint],
            })
            .await
        {
            Ok(_) => Ok(true),
            Err(error)
                if error
                    .downcast_ref::<InspectorResponseError>()
                    .is_some_and(|error| error.code == "streamingUnavailable") =>
            {
                Ok(false)
            }
            Err(error) => Err(error),
        }
    }

    /// Wait for the first real frame committed after an armed interaction.
    pub async fn wait_for_paint(&mut self, within: Duration) -> Result<bool> {
        self.ensure_available()?;
        if let Some(index) = self
            .events
            .iter()
            .position(|event| matches!(event, DebugEvent::PaintCommitted { .. }))
        {
            self.events.remove(index);
            return Ok(true);
        }

        let deadline = Instant::now() + within;
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Ok(false);
            }
            let id = JsonRpcId::Number(self.next_id);
            let message = match timeout(remaining, self.stream.recv()).await {
                Err(_) => return Ok(false),
                Ok(None) => {
                    return Err(self.mark_disconnected(&id, "paint", "clean EOF".to_owned()));
                }
                Ok(Some(Err(error))) => {
                    let cause = transport_disconnect_cause(&error);
                    return Err(self.mark_disconnected(&id, "paint", cause));
                }
                Ok(Some(Ok(message))) => message,
            };
            let value = decode_wire_value(message).map_err(protocol_error)?;
            self.queue_notification(value.clone());
            match decode_diagnostics_event_value(value) {
                Ok(DebugEvent::PaintCommitted { .. }) => return Ok(true),
                Ok(event) => self.queue_event(event),
                Err(_) => {}
            }
        }
    }

    /// The same call, but returning a protocol-level error rather than failing
    /// on it.
    ///
    /// `watch` needs this because `observe` is not implemented server-side: it
    /// answers `streamingUnavailable`. Printing that answer and then draining
    /// is what the previous client did, and it is the more useful behaviour:
    /// the mode reports what the server said instead of dying on it.
    pub async fn diagnostics_envelope(
        &mut self,
        request: &DiagnosticsRequest,
    ) -> Result<serde_json::Value> {
        let id = self.next_id();
        let frame = encode_diagnostics_request(id.clone(), request).map_err(protocol_error)?;
        self.exchange(frame, &id).await
    }

    pub async fn agent_envelope(
        &mut self,
        request: &AgentControlRequest,
    ) -> Result<serde_json::Value> {
        let id = self.next_id();
        let frame = encode_agent_request(id.clone(), request).map_err(protocol_error)?;
        self.exchange(frame, &id).await
    }

    /// Collect pushed notifications for a while, as `watch` does.
    pub async fn drain(&mut self, seconds: f64) -> Result<Vec<serde_json::Value>> {
        self.ensure_available()?;
        let deadline = Instant::now() + Duration::from_secs_f64(seconds);
        let mut out: Vec<_> = self.notifications.drain(..).collect();
        if self.lost_notifications > 0 {
            out.insert(0, serde_json::json!({"method": crate::DIAGNOSTICS_EVENT_NOTIFICATION, "params": {
                "event": "clientNotificationOverflow", "value": {"dropped": std::mem::take(&mut self.lost_notifications)}
            }}));
        }
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Ok(out);
            }
            match timeout(remaining, self.stream.recv()).await {
                Err(_) => return Ok(out),
                Ok(None) => {
                    let id = JsonRpcId::Number(self.next_id);
                    return Err(self.mark_disconnected(&id, "drain", "clean EOF".to_owned()));
                }
                Ok(Some(Ok(message))) => {
                    out.push(decode_wire_value(message).map_err(protocol_error)?)
                }
                Ok(Some(Err(error))) => {
                    let id = JsonRpcId::Number(self.next_id);
                    let cause = transport_disconnect_cause(&error);
                    return Err(self.mark_disconnected(&id, "drain", cause));
                }
            }
        }
    }
}

/// Read the application's semantic tree and report the inspector round-trip.
///
/// Most commands need this exact request. Keeping it beside the transport
/// prevents every command module from rebuilding the protocol exchange.
pub async fn inspect(client: &mut Client) -> Result<(AgentSnapshot, f64)> {
    inspect_from(client, None).await
}

/// Read only one semantic subtree.
///
/// Polling a known destination from the document root makes interaction
/// latency proportional to every unrelated node in the application. The
/// protocol already accepts a semantic root, so stabilization can acquire the
/// target once and observe only the component that must remain mounted.
pub async fn inspect_subtree(client: &mut Client, root: u64) -> Result<(AgentSnapshot, f64)> {
    inspect_from(client, Some(root)).await
}

async fn inspect_from(client: &mut Client, root: Option<u64>) -> Result<(AgentSnapshot, f64)> {
    let started = Instant::now();
    let answer = client
        .agent(&AgentControlRequest::Inspect {
            root,
            max_depth: 40,
        })
        .await?;
    let elapsed = started.elapsed().as_secs_f64() * 1000.0;
    match answer.response {
        DebugResponse::AgentSnapshot(snapshot) => Ok((snapshot, elapsed)),
        other => bail!("asked for a semantic snapshot, got {other:?}"),
    }
}

pub struct Answer {
    pub response: DebugResponse,
}

impl Answer {
    fn new(value: serde_json::Value) -> Result<Self> {
        let (_, response) = decode_response_value(value).map_err(protocol_error)?;
        let response = match response {
            DebugResponse::Targeted(reply) => *reply.response,
            response => response,
        };
        if let DebugResponse::Error(error) = &response {
            return Err(eyre::Report::new(InspectorResponseError {
                code: error.code.clone(),
                message: error.message.clone(),
            }));
        }
        Ok(Self { response })
    }
}

fn protocol_error(error: DebugProtocolError) -> eyre::Report {
    eyre!("{error}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{JsonRpcResponse, encode_diagnostics_event};
    use nagoya::reactor::TcpListener;

    #[test]
    fn connect_retries_startup_and_exchange_preserves_events() {
        nagoya::block_on(async {
            let socket = std::env::temp_dir().join(format!(
                "ps-qa-transport-{}-{}.sock",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .expect("system clock is after the epoch")
                    .as_nanos()
            ));
            let server_socket = socket.clone();
            let server = async move {
                // The descriptor can be visible before its socket is bound. Make
                // that production race deterministic and require the client retry.
                nagoya::sleep(Duration::from_millis(40)).await;
                let addr = Addr::path(server_socket.as_os_str().as_bytes()).expect("socket path");
                let listener = TcpListener::bind(addr, client_reactor()).expect("bind test socket");
                let (stream, _) = listener.accept().await.expect("accept test client");
                let mut stream =
                    TransportStream::new(framed_json_neutral(NagoyaStream::new(stream)));
                let _request = stream
                    .recv()
                    .await
                    .expect("client keeps connection open")
                    .expect("read initialize request");
                stream
                    .send(
                        encode_diagnostics_event(&DebugEvent::PaintCommitted { revision: 7 })
                            .expect("encode paint event"),
                    )
                    .await
                    .expect("send paint event");
                stream
                    .send(
                        encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
                            Some(JsonRpcId::Number(1)),
                            serde_json::json!({"protocolVersion": MCP_PROTOCOL_VERSION}),
                        )))
                        .expect("encode initialize response"),
                    )
                    .await
                    .expect("send initialize response");
            };

            let client_socket = socket.clone();
            let client = async move {
                let mut client = Client::connect(&client_socket)
                    .await
                    .expect("client retries until socket is bound");
                client.initialize().await.expect("initialize completes");
                assert!(
                    client
                        .wait_for_paint(Duration::ZERO)
                        .await
                        .expect("queued paint remains readable"),
                    "an event arriving before the response must not steal the response or be discarded"
                );
            };

            nagoya::timeout(
                Duration::from_secs(2),
                futures::future::join(server, client),
            )
            .await
            .expect("transport fixture watchdog");
            let _ = std::fs::remove_file(socket);
        });
    }

    #[test]
    fn notifications_do_not_renew_the_request_deadline() {
        nagoya::block_on(async {
            let socket = std::env::temp_dir().join(format!(
                "ps-qa-notification-timeout-{}-{}.sock",
                std::process::id(),
                Instant::now().elapsed().as_nanos()
            ));
            let server_socket = socket.clone();
            let server = async move {
                let addr = Addr::path(server_socket.as_os_str().as_bytes()).expect("socket path");
                let listener = TcpListener::bind(addr, client_reactor()).expect("bind fixture");
                let (stream, _) = listener.accept().await.expect("accept client");
                let mut stream =
                    TransportStream::new(framed_json_neutral(NagoyaStream::new(stream)));
                let _request = stream
                    .recv()
                    .await
                    .expect("client stays connected")
                    .expect("request is readable");
                for _ in 0..40 {
                    let event =
                        encode_diagnostics_event(&DebugEvent::PaintCommitted { revision: 1 })
                            .expect("encode notification");
                    if stream.send(event).await.is_err() {
                        break;
                    }
                    nagoya::sleep(Duration::from_millis(5)).await;
                }
            };

            let client_socket = socket.clone();
            let client = async move {
                let mut client = Client::connect(&client_socket)
                    .await
                    .expect("connect fixture");
                client.set_request_timeout(Duration::from_millis(100));

                let started = Instant::now();
                let error = client
                    .initialize()
                    .await
                    .expect_err("notifications do not answer initialize");
                assert!(
                    error.downcast_ref::<InspectorRequestTimeout>().is_some(),
                    "expected typed request timeout, got {error}"
                );
                assert!(started.elapsed() < Duration::from_millis(250));

                let started = Instant::now();
                let error = client
                    .tools_list()
                    .await
                    .expect_err("a timed out stream is terminal");
                assert!(
                    error.downcast_ref::<InspectorRequestTimeout>().is_some(),
                    "expected the stored terminal timeout, got {error}"
                );
                assert!(started.elapsed() < Duration::from_millis(25));
            };

            nagoya::timeout(
                Duration::from_secs(2),
                futures::future::join(server, client),
            )
            .await
            .expect("notification fixture watchdog");
            let _ = std::fs::remove_file(socket);
        });
    }

    #[test]
    fn transport_disconnect_classifies_typed_io_sources() {
        for (kind, label) in [
            (std::io::ErrorKind::UnexpectedEof, "UnexpectedEof"),
            (std::io::ErrorKind::ConnectionReset, "ConnectionReset"),
            (std::io::ErrorKind::BrokenPipe, "BrokenPipe"),
        ] {
            let error = endpoint_libs::libs::ws::StreamError::Other(eyre::Report::new(
                std::io::Error::from(kind),
            ));
            assert!(
                transport_disconnect_cause(&error).contains(label),
                "typed I/O source {kind:?} was not preserved"
            );
        }
    }

    #[test]
    fn descriptor_protocol_mismatch_is_rejected_before_connecting() {
        let path = std::env::temp_dir().join(format!(
            "ps-qa-descriptor-version-{}-{}.json",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system clock is after the epoch")
                .as_nanos()
        ));
        std::fs::write(
            &path,
            serde_json::json!({
                "protocolVersion": DEBUG_PROTOCOL_VERSION + 1,
                "pid": 1,
                "instanceId": "fixture",
                "address": "unix:///tmp/fixture.sock",
                "renderer": "fixture",
                "rendererRevision": "test"
            })
            .to_string(),
        )
        .expect("write descriptor fixture");
        let error = read_descriptor(&path).expect_err("newer protocol must not be guessed");
        assert!(
            error.to_string().contains("this client speaks"),
            "unexpected error: {error}"
        );
        let _ = std::fs::remove_file(path);
    }
}