Skip to main content

blitz_control_protocol/
client.rs

1//! The socket transport, connecting half: finding a running host, and talking
2//! to it.
3//!
4//! # Why this is a sibling of the server and not a layer above it
5//!
6//! A peer can be both. AgencyZero is driven by agents over this protocol while
7//! it drives a browser it embeds, and a QA harness that launches a headless
8//! host is a client of one socket in a process that could serve another. The
9//! two halves share the vocabulary, the framing and the error taxonomy, and
10//! neither is built on the other, so a build takes whichever halves it needs.
11//!
12//! Neither half needs blitz. The framing is the protocol; the document is not.
13//! `ps-qa` takes this feature and nothing else, and `cargo tree -p ps-qa`
14//! showing no renderer, window runtime or GPU stack is the check that keeps it
15//! that way.
16//!
17//! The transport is deliberately not hand-rolled. Frames are length-prefixed
18//! rather than newline-delimited, which is why a naive socket read hangs, and
19//! `endpoint_libs`' `framed_json_neutral` is the same codec the server writes with.
20//!
21//! This was `ps-qa`'s `inspector` module. It moved here so there is one client
22//! rather than one per consumer: the browser's own `chuzz-inspect` had grown a
23//! second one that built its requests as untyped JSON by hand, with a comment
24//! explaining which fields the runtime would and would not accept.
25
26use std::collections::VecDeque;
27use std::io::Read;
28use std::path::{Path, PathBuf};
29use std::time::Duration;
30use std::time::Instant;
31
32use crate::{
33    AgentControlRequest, AgentSnapshot, DEBUG_PROTOCOL_VERSION, DebugDescriptor, DebugEvent,
34    DebugProtocolError, DebugResponse, DebugStream, DiagnosticsRequest, JsonRpcId, JsonRpcMessage,
35    JsonRpcRequest, MCP_PROTOCOL_VERSION, MessageStream, TransportStream, WireMessage,
36    decode_diagnostics_event_value, decode_response_value, decode_wire_value, encode_agent_request,
37    encode_diagnostics_request, encode_rpc, peek_value_request_id,
38};
39use eyre::{Context, Result, bail, eyre};
40use std::os::unix::ffi::OsStrExt;
41
42use endpoint_libs::libs::ws::transport::framed::framed_json_neutral;
43use endpoint_libs::libs::ws::transport::nagoya::NagoyaStream;
44use nagoya::reactor::{Addr, Reactor, TcpStream};
45use nagoya::timeout;
46
47/// Matches the Python client's bench timeout. Long because a driven
48/// interaction can leave the app resolving for a while before it answers.
49const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
50const MAX_QUEUED_EVENTS: usize = 256;
51
52/// Where an inspector announced itself, and what it said.
53#[derive(Debug)]
54pub struct Descriptor {
55    pub path: PathBuf,
56    validated_socket_path: PathBuf,
57    pub descriptor: DebugDescriptor,
58    /// The descriptor verbatim, for the dump modes. Reprinting a re-serialized
59    /// struct would hide any field this build of the tool does not know about.
60    pub raw: serde_json::Value,
61    verified_reachable: bool,
62}
63
64/// The reactor every inspector connection lives on.
65///
66/// A nagoya socket makes progress only while the reactor it was created on is
67/// polled, and this client is a library: it does not own the caller's thread and
68/// cannot assume one is polling anything. `Reactor::start` owns a thread, so a
69/// connection keeps being driven between the caller's awaits.
70///
71/// One for the process rather than one per connection: a thread per inspector
72/// connection would be a thread per command in a QA sweep.
73fn client_reactor() -> &'static nagoya::reactor::Handle {
74    static REACTOR: std::sync::OnceLock<(Reactor, nagoya::reactor::Handle)> =
75        std::sync::OnceLock::new();
76    let (_, handle) = REACTOR.get_or_init(|| {
77        let reactor = Reactor::start().expect("inspector reactor could not start");
78        let handle = reactor.handle();
79        (reactor, handle)
80    });
81    handle
82}
83
84impl Descriptor {
85    pub fn socket_path(&self) -> PathBuf {
86        self.validated_socket_path.clone()
87    }
88
89    /// Trap 8 in docs/performance.md: an unpinned descriptor directory keeps
90    /// dead instances around. Pid existence is not enough: macOS reuses pids,
91    /// so an unrelated process can make a stale descriptor look current. The
92    /// control socket is the service, and a successful connection is the only
93    /// liveness check that proves the descriptor can actually be used.
94    fn is_reachable(&self) -> bool {
95        let Some(directory) = self.validated_socket_path.parent() else {
96            return false;
97        };
98        let address = format!("unix://{}", self.validated_socket_path.display());
99        let Ok(socket) = crate::control_directory::validate_socket(directory, &address) else {
100            return false;
101        };
102        std::os::unix::net::UnixStream::connect(socket).is_ok()
103    }
104
105    pub fn warn_if_stale(&self) {
106        if !self.verified_reachable && !self.is_reachable() {
107            eprintln!(
108                "warning: descriptor {} names pid {}, but its control socket is unreachable",
109                self.path.display(),
110                self.descriptor.pid
111            );
112        }
113    }
114}
115
116/// Locate a running inspector, preferring an explicitly pinned descriptor.
117///
118/// `--descriptor <path>` wins. Otherwise the build's own pinned path is
119/// authoritative when it exists: an invalid or stale pin is an error rather
120/// than a reason to attach to another host. The temporary directory is scanned
121/// only when no implicit pin exists.
122///
123/// A named descriptor that is not there is an error, not an invitation to
124/// scan. Falling through to discovery attached to the newest *other* host on
125/// the machine, which on a machine running several suites at once is another
126/// site's document: the tree came back, it was plausible, and it described a
127/// page nobody had asked about. A typo in a path is not consent to inspect
128/// somebody else's application.
129pub fn discover(explicit: Option<&str>) -> Result<Descriptor> {
130    discover_with_paths(
131        explicit,
132        Path::new("target/blitz-control.json"),
133        &crate::control_directory::default_directory(),
134    )
135}
136
137fn discover_with_paths(
138    explicit: Option<&str>,
139    pinned: &Path,
140    root: &Path,
141) -> Result<Descriptor> {
142    if let Some(path) = explicit {
143        let path = PathBuf::from(path);
144        if !path.exists() {
145            bail!(
146                "descriptor {} does not exist. ps-qa attaches to the descriptor you \
147                 name and to no other; omit --descriptor to discover a running host.",
148                path.display()
149            );
150        }
151        return read_descriptor(&path);
152    }
153
154    // The delivery script pins this path into the bundle's `Info.plist`, so a
155    // locally built app announces itself here and nowhere else. Scanning only
156    // $TMPDIR meant the one instance that was definitely running was the one
157    // instance discovery could not see, and it picked a dead descriptor from a
158    // previous run instead, which is how preferring a live pid still failed.
159    match std::fs::symlink_metadata(pinned) {
160        Ok(_) => {
161            let result = read_descriptor(pinned).and_then(|mut descriptor| {
162                if !descriptor.is_reachable() {
163                    bail!("control socket is unreachable");
164                }
165                descriptor.verified_reachable = true;
166                Ok(descriptor)
167            });
168            return result.wrap_err_with(|| {
169                format!(
170                    "implicit pinned descriptor {} exists but is invalid or unreachable; fix or remove this pin before discovery",
171                    pinned.display()
172                )
173            });
174        }
175        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
176        Err(error) => {
177            return Err(error).wrap_err_with(|| {
178                format!("checking implicit pinned descriptor {}", pinned.display())
179            });
180        }
181    }
182
183    let mut found: Vec<(std::time::SystemTime, PathBuf)> =
184        if crate::control_directory::validate_directory(root).is_ok() {
185            std::fs::read_dir(root)
186                .into_iter()
187                .flatten()
188                .flatten()
189                .map(|entry| entry.path())
190                .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
191                .filter_map(|path| {
192                    let file = crate::control_directory::open_descriptor(&path).ok()?;
193                    let modified = file.metadata().ok()?.modified().ok()?;
194                    Some((modified, path))
195                })
196                .collect()
197        } else {
198            Vec::new()
199        };
200    found.sort();
201
202    // Newest *reachable* instance, not simply newest.
203    //
204    // Descriptors outlive the process that wrote them, and a machine that has
205    // run the app more than once has a directory full of them. Taking the most
206    // recent file connected to whichever instance happened to exit last: at
207    // best a refused connection, at worst a successful attach to a stale socket
208    // and a set of numbers describing a process nobody is looking at. The
209    // warning for that case already existed and was printed immediately before
210    // connecting anyway.
211    for (_, path) in found.iter().rev() {
212        let Ok(mut descriptor) = read_descriptor(path) else {
213            continue;
214        };
215        if descriptor.is_reachable() {
216            descriptor.verified_reachable = true;
217            return Ok(descriptor);
218        }
219    }
220
221    bail!(
222        "no reachable inspector descriptor found; is a diagnostics build running?\n\
223         looked at target/blitz-control.json and {}. Pass --descriptor \
224         <path> to inspect a specific descriptor.",
225        root.display()
226    )
227}
228
229fn read_descriptor(path: &Path) -> Result<Descriptor> {
230    let mut file = crate::control_directory::open_descriptor(path)
231        .with_context(|| format!("opening private descriptor {}", path.display()))?;
232    let mut text = String::new();
233    file.read_to_string(&mut text)
234        .with_context(|| format!("reading descriptor {}", path.display()))?;
235    let raw: serde_json::Value = serde_json::from_str(&text)
236        .with_context(|| format!("parsing descriptor {}", path.display()))?;
237    let descriptor: DebugDescriptor = serde_json::from_value(raw.clone())
238        .with_context(|| format!("descriptor {} is not a DebugDescriptor", path.display()))?;
239    if descriptor.protocol_version != DEBUG_PROTOCOL_VERSION {
240        bail!(
241            "descriptor {} uses debug protocol {}, but this client speaks {}; \
242             use a client built for protocol {} (for ps-qa, build it from the \
243             blitz-control-protocol release or checkout that the host was built against)",
244            path.display(),
245            descriptor.protocol_version,
246            DEBUG_PROTOCOL_VERSION,
247            descriptor.protocol_version
248        );
249    }
250    let parent = path
251        .parent()
252        .filter(|parent| !parent.as_os_str().is_empty())
253        .unwrap_or_else(|| Path::new("."));
254    let directory = crate::control_directory::validate_directory(parent)
255        .with_context(|| format!("validating descriptor directory {}", parent.display()))?;
256    let validated_socket_path =
257        crate::control_directory::validate_socket(&directory, &descriptor.address)
258            .with_context(|| format!("validating descriptor socket {}", path.display()))?;
259    Ok(Descriptor {
260        path: path.to_path_buf(),
261        validated_socket_path,
262        descriptor,
263        raw,
264        verified_reachable: false,
265    })
266}
267
268/// A connected inspector client.
269///
270/// `MessageStream` is the object-safe half of the endpoint-libs transport seam,
271/// so the concrete framing type, which is opaque, never has to be named.
272pub struct Client {
273    stream: Box<dyn MessageStream>,
274    next_id: i64,
275    request_timeout: Duration,
276    terminal: Option<TerminalFailure>,
277    events: VecDeque<DebugEvent>,
278    notifications: VecDeque<serde_json::Value>,
279    lost_notifications: u64,
280    target_options: crate::TargetOptions,
281    target_context: Option<crate::TargetContext>,
282}
283
284#[derive(Clone, Debug)]
285enum TerminalFailure {
286    RequestTimeout {
287        request_id: String,
288        phase: &'static str,
289        timeout: Duration,
290    },
291    Disconnected {
292        request_id: String,
293        phase: &'static str,
294        cause: String,
295    },
296}
297
298impl TerminalFailure {
299    fn report(&self) -> eyre::Report {
300        match self {
301            Self::RequestTimeout {
302                request_id,
303                phase,
304                timeout,
305            } => eyre::Report::new(InspectorRequestTimeout {
306                request_id: request_id.clone(),
307                phase,
308                timeout: *timeout,
309            }),
310            Self::Disconnected {
311                request_id,
312                phase,
313                cause,
314            } => eyre::Report::new(InspectorDisconnected {
315                request_id: request_id.clone(),
316                phase,
317                cause: cause.clone(),
318            }),
319        }
320    }
321
322    fn message(&self) -> String {
323        self.report().to_string()
324    }
325
326    fn is_timeout(&self) -> bool {
327        matches!(self, Self::RequestTimeout { .. })
328    }
329}
330
331/// A request exceeded its single transport deadline.
332#[derive(Clone, Debug)]
333pub struct InspectorRequestTimeout {
334    pub request_id: String,
335    pub phase: &'static str,
336    pub timeout: Duration,
337}
338
339impl std::fmt::Display for InspectorRequestTimeout {
340    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        write!(
342            formatter,
343            "InspectorRequestTimeout: request {} timed out during {} after {:?}",
344            self.request_id, self.phase, self.timeout
345        )
346    }
347}
348
349impl std::error::Error for InspectorRequestTimeout {}
350
351/// The inspector connection ended or failed during a request.
352#[derive(Clone, Debug)]
353pub struct InspectorDisconnected {
354    pub request_id: String,
355    pub phase: &'static str,
356    pub cause: String,
357}
358
359impl std::fmt::Display for InspectorDisconnected {
360    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361        write!(
362            formatter,
363            "InspectorDisconnected: request {} failed during {}: {}",
364            self.request_id, self.phase, self.cause
365        )
366    }
367}
368
369impl std::error::Error for InspectorDisconnected {}
370
371fn transport_disconnect_cause(error: &endpoint_libs::libs::ws::StreamError) -> String {
372    if matches!(error, endpoint_libs::libs::ws::StreamError::Closed) {
373        return "clean connection close".to_owned();
374    }
375
376    let mut source = Some(error as &dyn std::error::Error);
377    while let Some(cause) = source {
378        if let Some(io_error) = cause.downcast_ref::<std::io::Error>()
379            && matches!(
380                io_error.kind(),
381                std::io::ErrorKind::UnexpectedEof
382                    | std::io::ErrorKind::ConnectionReset
383                    | std::io::ErrorKind::BrokenPipe
384            )
385        {
386            return format!("{:?}: {}", io_error.kind(), io_error);
387        }
388        source = cause.source();
389    }
390
391    error.to_string()
392}
393
394#[derive(Debug)]
395struct InspectorResponseError {
396    code: String,
397    message: String,
398}
399
400impl std::fmt::Display for InspectorResponseError {
401    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
402        write!(
403            formatter,
404            "inspector returned {}: {}",
405            self.code, self.message
406        )
407    }
408}
409
410impl std::error::Error for InspectorResponseError {}
411
412/// Whether a host refused a request because it does not have the thing asked
413/// for, rather than because something went wrong.
414///
415/// The distinction matters for a headless host. It owns a document and no
416/// compositor, so there are no frame metrics to report and saying "unsupported"
417/// is the true answer. A caller that only wanted the numbers as context can
418/// carry on without them; one that exists to judge frame timing cannot, and
419/// should still fail.
420pub fn is_unsupported(error: &eyre::Report) -> bool {
421    error
422        .downcast_ref::<InspectorResponseError>()
423        .is_some_and(|refusal| refusal.code == "unsupported")
424}
425
426/// Whether a host has no completed GPUBuffer write available yet.
427///
428/// This is an incomplete diagnostic sample, so a caller can retry within its
429/// outcome deadline. Other host refusals and transport errors stay failures.
430pub fn is_pending(error: &eyre::Report) -> bool {
431    error
432        .downcast_ref::<InspectorResponseError>()
433        .is_some_and(|refusal| refusal.code == "pending")
434}
435
436/// Return a bounded response category without exposing the inspector message.
437pub fn safe_response_code(error: &eyre::Report) -> Option<&'static str> {
438    let code = error
439        .downcast_ref::<InspectorResponseError>()?
440        .code
441        .as_str();
442    Some(match code {
443        "notEditable" => "notEditable",
444        "unknownNode" => "unknownNode",
445        "documentUnavailable" => "documentUnavailable",
446        "unsupportedRequest" => "unsupportedRequest",
447        _ => "other",
448    })
449}
450
451impl Client {
452    pub fn select_target(&mut self, target: Option<crate::TargetSelector>) {
453        self.target_options = crate::TargetOptions {
454            target,
455            ..Default::default()
456        };
457        self.target_context = None;
458    }
459
460    pub fn target_context(&self) -> Option<&crate::TargetContext> {
461        self.target_context.as_ref()
462    }
463
464    fn target_frame(&self, frame: WireMessage) -> Result<WireMessage> {
465        let mut value = decode_wire_value(frame).map_err(protocol_error)?;
466        if value["method"] != "tools/call" {
467            return Ok(WireMessage::Text(serde_json::to_string(&value)?.into()));
468        }
469        let tool = value["params"]["name"]
470            .as_str()
471            .unwrap_or_default()
472            .to_owned();
473        let arguments = &mut value["params"]["arguments"];
474        let object = arguments
475            .as_object_mut()
476            .ok_or_else(|| eyre!("tool arguments must be an object"))?;
477        if !object.contains_key("target")
478            && object.get("allTargets") != Some(&serde_json::Value::Bool(true))
479            && let Some(target) = &self.target_options.target
480        {
481            object.insert("target".into(), serde_json::to_value(target)?);
482        }
483        let options: crate::TargetOptions = serde_json::from_value(arguments.clone())?;
484        let command = if tool == crate::AGENT_CONTROL_TOOL {
485            serde_json::from_value(arguments.clone())
486                .ok()
487                .map(crate::TargetCommand::Agent)
488        } else if tool == crate::DIAGNOSTICS_TOOL {
489            serde_json::from_value(arguments.clone())
490                .ok()
491                .map(crate::TargetCommand::Diagnostics)
492        } else {
493            None
494        };
495        if options.target == self.target_options.target
496            && !options.all_targets
497            && let (Some(context), Some(command)) = (&self.target_context, command)
498        {
499            let request = crate::TargetRequest { options, command };
500            if (request.uses_nodes()
501                || matches!(
502                    request.command,
503                    crate::TargetCommand::Agent(crate::AgentControlRequest::Act(_))
504                ))
505                && matches!(context.target_id, crate::TargetId::Tab(_))
506            {
507                let object = arguments.as_object_mut().expect("arguments object");
508                object
509                    .entry("expectedGeneration")
510                    .or_insert_with(|| context.generation.into());
511                object
512                    .entry("expectedDocumentId")
513                    .or_insert_with(|| context.document_id.into());
514            }
515        }
516        Ok(WireMessage::Text(serde_json::to_string(&value)?.into()))
517    }
518
519    fn queue_notification(&mut self, value: serde_json::Value) {
520        if value.get("method").is_none() || value.get("id").is_some() {
521            return;
522        }
523        if self.notifications.len() == MAX_QUEUED_EVENTS {
524            self.notifications.pop_front();
525            self.lost_notifications += 1;
526        }
527        self.notifications.push_back(value);
528    }
529
530    fn capture_target_context(&mut self, value: &serde_json::Value) {
531        let Some(context) = value.pointer("/result/structuredContent/context") else {
532            return;
533        };
534        let Ok(context) = serde_json::from_value::<crate::TargetContext>(context.clone()) else {
535            return;
536        };
537        let selected = self
538            .target_options
539            .target
540            .as_ref()
541            .map_or_else(crate::TargetId::chrome, crate::TargetSelector::id);
542        if context.target_id == selected {
543            self.target_context = Some(context);
544        }
545    }
546
547    fn queue_event(&mut self, event: DebugEvent) {
548        if self.events.len() == MAX_QUEUED_EVENTS {
549            self.events.pop_front();
550        }
551        self.events.push_back(event);
552    }
553
554    pub async fn connect(socket: &Path) -> Result<Self> {
555        const CONNECT_DEADLINE: Duration = Duration::from_millis(500);
556        const RETRY_DELAY: Duration = Duration::from_millis(20);
557
558        let started = Instant::now();
559        let stream = loop {
560            let addr = Addr::path(socket.as_os_str().as_bytes())
561                .map_err(|_| std::io::Error::other("socket path is not a valid unix address"))?;
562            match TcpStream::connect(addr, client_reactor()).await {
563                Ok(stream) => break stream,
564                Err(_) if started.elapsed() < CONNECT_DEADLINE => {
565                    nagoya::sleep(RETRY_DELAY).await;
566                }
567                Err(error) => {
568                    return Err(error)
569                        .with_context(|| format!("connecting to {}", socket.display()));
570                }
571            }
572        };
573        Ok(Self {
574            stream: Box::new(TransportStream::new(framed_json_neutral(
575                NagoyaStream::new(stream),
576            ))),
577            next_id: 0,
578            request_timeout: REQUEST_TIMEOUT,
579            terminal: None,
580            events: VecDeque::new(),
581            notifications: VecDeque::new(),
582            lost_notifications: 0,
583            target_options: crate::TargetOptions::default(),
584            target_context: None,
585        })
586    }
587
588    /// Bound every inspector exchange for a latency-sensitive command.
589    ///
590    /// Interactive dump/diagnostic modes retain the generous default. QA and
591    /// coverage explicitly lower it so a dead action cannot multiply a
592    /// minute-long transport wait across a suite.
593    pub fn set_request_timeout(&mut self, request_timeout: Duration) {
594        self.request_timeout = request_timeout;
595    }
596
597    pub fn request_timeout(&self) -> Duration {
598        self.request_timeout
599    }
600
601    pub fn is_terminal(&self) -> bool {
602        self.terminal.is_some()
603    }
604
605    pub fn terminal_is_timeout(&self) -> bool {
606        self.terminal
607            .as_ref()
608            .is_some_and(TerminalFailure::is_timeout)
609    }
610
611    pub fn terminal_failure_message(&self) -> Option<String> {
612        self.terminal.as_ref().map(TerminalFailure::message)
613    }
614
615    fn ensure_available(&self) -> Result<()> {
616        match &self.terminal {
617            Some(failure) => Err(failure.report()),
618            None => Ok(()),
619        }
620    }
621
622    fn mark_timeout(&mut self, id: &JsonRpcId, phase: &'static str) -> eyre::Report {
623        let failure = TerminalFailure::RequestTimeout {
624            request_id: format!("{id:?}"),
625            phase,
626            timeout: self.request_timeout,
627        };
628        self.terminal = Some(failure.clone());
629        failure.report()
630    }
631
632    fn mark_disconnected(
633        &mut self,
634        id: &JsonRpcId,
635        phase: &'static str,
636        cause: String,
637    ) -> eyre::Report {
638        let failure = TerminalFailure::Disconnected {
639            request_id: format!("{id:?}"),
640            phase,
641            cause,
642        };
643        self.terminal = Some(failure.clone());
644        failure.report()
645    }
646
647    fn next_id(&mut self) -> JsonRpcId {
648        self.next_id += 1;
649        JsonRpcId::Number(self.next_id)
650    }
651
652    /// Send one request and return the frame that answers *it*.
653    ///
654    /// Matching on the id is not pedantry. The server pushes notifications on
655    /// the same socket, so a client that returns the next frame it sees will
656    /// eventually hand a console message back as though it were metrics.
657    async fn exchange(
658        &mut self,
659        request: WireMessage,
660        id: &JsonRpcId,
661    ) -> Result<serde_json::Value> {
662        self.ensure_available()?;
663        let request = self.target_frame(request)?;
664        let deadline = Instant::now() + self.request_timeout;
665        let send_remaining = deadline.saturating_duration_since(Instant::now());
666        match timeout(send_remaining, self.stream.send(request)).await {
667            Err(_) => return Err(self.mark_timeout(id, "send")),
668            Ok(Err(error)) => {
669                let cause = transport_disconnect_cause(&error);
670                return Err(self.mark_disconnected(id, "send", cause));
671            }
672            Ok(Ok(())) => {}
673        }
674
675        loop {
676            let remaining = deadline.saturating_duration_since(Instant::now());
677            if remaining.is_zero() {
678                return Err(self.mark_timeout(id, "receive"));
679            }
680
681            let message = match timeout(remaining, self.stream.recv()).await {
682                Err(_) => return Err(self.mark_timeout(id, "receive")),
683                Ok(None) => {
684                    return Err(self.mark_disconnected(id, "receive", "clean EOF".to_owned()));
685                }
686                Ok(Some(Err(error))) => {
687                    let cause = transport_disconnect_cause(&error);
688                    return Err(self.mark_disconnected(id, "receive", cause));
689                }
690                Ok(Some(Ok(message))) => message,
691            };
692
693            let value = decode_wire_value(message).map_err(protocol_error)?;
694            if peek_value_request_id(&value).as_ref() == Some(id) {
695                self.capture_target_context(&value);
696                return Ok(value);
697            }
698            self.queue_notification(value.clone());
699            if let Ok(event) = decode_diagnostics_event_value(value) {
700                self.queue_event(event);
701            }
702        }
703    }
704
705    /// A raw JSON-RPC call, for `initialize` and `tools/list`, which are not
706    /// tool calls and so have no typed request in the protocol crate.
707    pub async fn raw_request(
708        &mut self,
709        method: &str,
710        params: serde_json::Value,
711    ) -> Result<serde_json::Value> {
712        let id = self.next_id();
713        let request = encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
714            id.clone(),
715            method,
716            params,
717        )))
718        .map_err(protocol_error)?;
719        self.exchange(request, &id).await
720    }
721
722    pub async fn initialize(&mut self) -> Result<serde_json::Value> {
723        self.raw_request(
724            "initialize",
725            serde_json::json!({"protocolVersion": MCP_PROTOCOL_VERSION}),
726        )
727        .await
728    }
729
730    pub async fn tools_list(&mut self) -> Result<serde_json::Value> {
731        self.raw_request("tools/list", serde_json::json!({})).await
732    }
733
734    /// An agent-control call, encoded from the server's own type.
735    ///
736    /// This is the whole reason the protocol crate exists. `AgentAction` is
737    /// adjacently tagged, so the `{"action":"click","nodeId":9}` that reads
738    /// correctly is not what the server accepts, and getting it wrong used to
739    /// present as a hung application rather than as an encoding mistake.
740    pub async fn agent(&mut self, request: &AgentControlRequest) -> Result<Answer> {
741        let id = self.next_id();
742        let frame = encode_agent_request(id.clone(), request).map_err(protocol_error)?;
743        let value = self.exchange(frame, &id).await?;
744        Answer::new(value)
745    }
746
747    pub async fn diagnostics(&mut self, request: &DiagnosticsRequest) -> Result<Answer> {
748        let id = self.next_id();
749        let frame = encode_diagnostics_request(id.clone(), request).map_err(protocol_error)?;
750        let value = self.exchange(frame, &id).await?;
751        Answer::new(value)
752    }
753
754    /// Establish a paint-event baseline immediately before driving input.
755    ///
756    /// New runtimes answer with `Ack` and suppress any revision that predates
757    /// this call. Older runtimes answer `streamingUnavailable`; callers retain
758    /// their bounded compatibility fallback in that case.
759    pub async fn arm_paint_events(&mut self) -> Result<bool> {
760        self.events
761            .retain(|event| !matches!(event, DebugEvent::PaintCommitted { .. }));
762        match self
763            .diagnostics(&DiagnosticsRequest::Observe {
764                streams: vec![DebugStream::Paint],
765            })
766            .await
767        {
768            Ok(_) => Ok(true),
769            Err(error)
770                if error
771                    .downcast_ref::<InspectorResponseError>()
772                    .is_some_and(|error| error.code == "streamingUnavailable") =>
773            {
774                Ok(false)
775            }
776            Err(error) => Err(error),
777        }
778    }
779
780    /// Wait for the first real frame committed after an armed interaction.
781    pub async fn wait_for_paint(&mut self, within: Duration) -> Result<bool> {
782        self.ensure_available()?;
783        if let Some(index) = self
784            .events
785            .iter()
786            .position(|event| matches!(event, DebugEvent::PaintCommitted { .. }))
787        {
788            self.events.remove(index);
789            return Ok(true);
790        }
791
792        let deadline = Instant::now() + within;
793        loop {
794            let remaining = deadline.saturating_duration_since(Instant::now());
795            if remaining.is_zero() {
796                return Ok(false);
797            }
798            let id = JsonRpcId::Number(self.next_id);
799            let message = match timeout(remaining, self.stream.recv()).await {
800                Err(_) => return Ok(false),
801                Ok(None) => {
802                    return Err(self.mark_disconnected(&id, "paint", "clean EOF".to_owned()));
803                }
804                Ok(Some(Err(error))) => {
805                    let cause = transport_disconnect_cause(&error);
806                    return Err(self.mark_disconnected(&id, "paint", cause));
807                }
808                Ok(Some(Ok(message))) => message,
809            };
810            let value = decode_wire_value(message).map_err(protocol_error)?;
811            self.queue_notification(value.clone());
812            match decode_diagnostics_event_value(value) {
813                Ok(DebugEvent::PaintCommitted { .. }) => return Ok(true),
814                Ok(event) => self.queue_event(event),
815                Err(_) => {}
816            }
817        }
818    }
819
820    /// The same call, but returning a protocol-level error rather than failing
821    /// on it.
822    ///
823    /// `watch` needs this because `observe` is not implemented server-side: it
824    /// answers `streamingUnavailable`. Printing that answer and then draining
825    /// is what the previous client did, and it is the more useful behaviour:
826    /// the mode reports what the server said instead of dying on it.
827    pub async fn diagnostics_envelope(
828        &mut self,
829        request: &DiagnosticsRequest,
830    ) -> Result<serde_json::Value> {
831        let id = self.next_id();
832        let frame = encode_diagnostics_request(id.clone(), request).map_err(protocol_error)?;
833        self.exchange(frame, &id).await
834    }
835
836    pub async fn agent_envelope(
837        &mut self,
838        request: &AgentControlRequest,
839    ) -> Result<serde_json::Value> {
840        let id = self.next_id();
841        let frame = encode_agent_request(id.clone(), request).map_err(protocol_error)?;
842        self.exchange(frame, &id).await
843    }
844
845    /// Collect pushed notifications for a while, as `watch` does.
846    pub async fn drain(&mut self, seconds: f64) -> Result<Vec<serde_json::Value>> {
847        self.ensure_available()?;
848        let deadline = Instant::now() + Duration::from_secs_f64(seconds);
849        let mut out: Vec<_> = self.notifications.drain(..).collect();
850        if self.lost_notifications > 0 {
851            out.insert(0, serde_json::json!({"method": crate::DIAGNOSTICS_EVENT_NOTIFICATION, "params": {
852                "event": "clientNotificationOverflow", "value": {"dropped": std::mem::take(&mut self.lost_notifications)}
853            }}));
854        }
855        loop {
856            let remaining = deadline.saturating_duration_since(Instant::now());
857            if remaining.is_zero() {
858                return Ok(out);
859            }
860            match timeout(remaining, self.stream.recv()).await {
861                Err(_) => return Ok(out),
862                Ok(None) => {
863                    let id = JsonRpcId::Number(self.next_id);
864                    return Err(self.mark_disconnected(&id, "drain", "clean EOF".to_owned()));
865                }
866                Ok(Some(Ok(message))) => {
867                    out.push(decode_wire_value(message).map_err(protocol_error)?)
868                }
869                Ok(Some(Err(error))) => {
870                    let id = JsonRpcId::Number(self.next_id);
871                    let cause = transport_disconnect_cause(&error);
872                    return Err(self.mark_disconnected(&id, "drain", cause));
873                }
874            }
875        }
876    }
877}
878
879/// Read the application's semantic tree and report the inspector round-trip.
880///
881/// Most commands need this exact request. Keeping it beside the transport
882/// prevents every command module from rebuilding the protocol exchange.
883pub async fn inspect(client: &mut Client) -> Result<(AgentSnapshot, f64)> {
884    inspect_from(client, None).await
885}
886
887/// Read only one semantic subtree.
888///
889/// Polling a known destination from the document root makes interaction
890/// latency proportional to every unrelated node in the application. The
891/// protocol already accepts a semantic root, so stabilization can acquire the
892/// target once and observe only the component that must remain mounted.
893pub async fn inspect_subtree(client: &mut Client, root: u64) -> Result<(AgentSnapshot, f64)> {
894    inspect_from(client, Some(root)).await
895}
896
897async fn inspect_from(client: &mut Client, root: Option<u64>) -> Result<(AgentSnapshot, f64)> {
898    let started = Instant::now();
899    let answer = client
900        .agent(&AgentControlRequest::Inspect {
901            root,
902            max_depth: 40,
903        })
904        .await?;
905    let elapsed = started.elapsed().as_secs_f64() * 1000.0;
906    match answer.response {
907        DebugResponse::AgentSnapshot(snapshot) => Ok((snapshot, elapsed)),
908        other => bail!("asked for a semantic snapshot, got {other:?}"),
909    }
910}
911
912pub struct Answer {
913    pub response: DebugResponse,
914}
915
916impl Answer {
917    fn new(value: serde_json::Value) -> Result<Self> {
918        let (_, response) = decode_response_value(value).map_err(protocol_error)?;
919        let response = match response {
920            DebugResponse::Targeted(reply) => *reply.response,
921            response => response,
922        };
923        if let DebugResponse::Error(error) = &response {
924            return Err(eyre::Report::new(InspectorResponseError {
925                code: error.code.clone(),
926                message: error.message.clone(),
927            }));
928        }
929        Ok(Self { response })
930    }
931}
932
933fn protocol_error(error: DebugProtocolError) -> eyre::Report {
934    eyre!("{error}")
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940    use crate::{JsonRpcResponse, encode_diagnostics_event};
941    use nagoya::reactor::TcpListener;
942    use std::os::unix::ffi::OsStrExt;
943    use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};
944    use std::os::unix::net::UnixListener as StdUnixListener;
945    use std::sync::atomic::{AtomicUsize, Ordering};
946
947    static PIN_FIXTURE_ID: AtomicUsize = AtomicUsize::new(0);
948    const PIN_FIXTURE_ROOT_ENV: &str = "PS_OBSERVABILITY_PIN_FIXTURE_ROOT";
949    const MACOS_SUN_PATH_CAPACITY: usize = 104;
950
951    fn default_fixture_root() -> PathBuf {
952        let base = if cfg!(target_os = "macos") {
953            PathBuf::from("/tmp")
954        } else {
955            std::env::temp_dir()
956        };
957        let directory = base.join(format!("pso-{}", rustix::process::geteuid().as_raw()));
958        match crate::guarded_writer::create_private_dir(&directory) {
959            Ok(()) => {}
960            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
961            Err(error) => panic!("create default fixture root {}: {error}", directory.display()),
962        }
963        directory
964    }
965
966    fn fixture_root() -> PathBuf {
967        let configured = std::env::var_os(PIN_FIXTURE_ROOT_ENV)
968            .map(PathBuf::from)
969            .unwrap_or_else(default_fixture_root);
970        assert!(configured.is_absolute(), "{PIN_FIXTURE_ROOT_ENV} must be an absolute path: {}", configured.display());
971        let before = std::fs::symlink_metadata(&configured).unwrap_or_else(|error| {
972            panic!("{PIN_FIXTURE_ROOT_ENV} must name an existing directory ({}): {error}", configured.display())
973        });
974        validate_fixture_root_metadata(&configured, &before);
975        let canonical = configured.canonicalize().unwrap_or_else(|error| {
976            panic!("cannot resolve {PIN_FIXTURE_ROOT_ENV} directory {}: {error}", configured.display())
977        });
978        let after = std::fs::symlink_metadata(&canonical).unwrap_or_else(|error| {
979            panic!("cannot recheck {PIN_FIXTURE_ROOT_ENV} directory {}: {error}", canonical.display())
980        });
981        validate_fixture_root_metadata(&canonical, &after);
982        assert!(before.dev() == after.dev() && before.ino() == after.ino(), "{PIN_FIXTURE_ROOT_ENV} changed while being validated: {}", configured.display());
983        canonical
984    }
985
986    fn validate_fixture_root_metadata(path: &Path, metadata: &std::fs::Metadata) {
987        assert!(!metadata.file_type().is_symlink() && metadata.is_dir(), "{PIN_FIXTURE_ROOT_ENV} must be a real directory, not a symlink: {}", path.display());
988        assert_eq!(metadata.uid(), rustix::process::geteuid().as_raw(), "{PIN_FIXTURE_ROOT_ENV} must be owned by the current user: {}", path.display());
989        assert!(metadata.mode() & 0o300 == 0o300, "{PIN_FIXTURE_ROOT_ENV} must be writable and searchable by its owner: {}", path.display());
990    }
991
992    struct PinDiscoveryFixture {
993        root: PathBuf,
994        pinned: PathBuf,
995        pin_directory: PathBuf,
996        runtime: PathBuf,
997        listeners: Vec<StdUnixListener>,
998    }
999
1000    impl PinDiscoveryFixture {
1001        fn new() -> Self {
1002            let base = fixture_root();
1003            let root = loop {
1004                let sequence = PIN_FIXTURE_ID.fetch_add(1, Ordering::Relaxed);
1005                let nonce = std::time::SystemTime::now()
1006                    .duration_since(std::time::UNIX_EPOCH)
1007                    .expect("system clock is after the epoch")
1008                    .as_nanos();
1009                let candidate = base.join(format!("pin-{:x}-{nonce:x}-{sequence:x}", std::process::id()));
1010                match crate::guarded_writer::create_private_dir(&candidate) {
1011                    Ok(()) => break candidate,
1012                    Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
1013                    Err(error) => panic!("create unique private fixture child {} under {}: {error}", candidate.display(), base.display()),
1014                }
1015            };
1016            let pin_directory = root.join("pin");
1017            let runtime = root.join("run");
1018            let setup = (|| -> Result<()> {
1019                crate::guarded_writer::create_private_dir(&pin_directory)?;
1020                crate::guarded_writer::create_private_dir(&runtime)?;
1021                Ok(())
1022            })();
1023            if let Err(error) = setup {
1024                let _ = std::fs::remove_dir_all(&root);
1025                panic!("create fixture directories under {}: {error}", root.display());
1026            }
1027            let pinned = pin_directory.join("blitz-control.json");
1028            Self {
1029                root,
1030                pinned,
1031                pin_directory,
1032                runtime,
1033                listeners: Vec::new(),
1034            }
1035        }
1036
1037        fn descriptor(&mut self, directory: &Path, file: &str, socket_name: &str) -> PathBuf {
1038            let socket = directory.join(socket_name);
1039            assert_socket_path_length(&socket);
1040            let listener = StdUnixListener::bind(&socket).expect("bind private fixture socket");
1041            std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))
1042                .expect("restrict fixture socket mode");
1043            self.listeners.push(listener);
1044            let descriptor = directory.join(file);
1045            crate::guarded_writer::write_file(
1046                &descriptor,
1047                serde_json::json!({
1048                    "protocolVersion": DEBUG_PROTOCOL_VERSION,
1049                    "pid": 1,
1050                    "instanceId": file,
1051                    "address": format!("unix://{}", socket.display()),
1052                    "renderer": "fixture",
1053                    "rendererRevision": "test"
1054                })
1055                .to_string()
1056                .as_bytes(),
1057            )
1058            .expect("write valid fixture descriptor");
1059            descriptor
1060        }
1061
1062        fn fallback(&mut self) -> PathBuf {
1063            self.descriptor(&self.runtime.clone(), "fallback.json", "f.sock")
1064        }
1065
1066        fn prove_fallback_is_discoverable(&self, fallback: &Path) {
1067            let selected = discover_fixture(self).expect("fallback is discoverable before pin");
1068            assert_eq!(selected.path, fallback);
1069            self.drain_listener("f.sock");
1070        }
1071
1072        fn set_modified(path: &Path, seconds: u64) -> std::time::SystemTime {
1073            let modified = std::time::UNIX_EPOCH + Duration::from_secs(seconds);
1074            let file = std::fs::File::open(path).expect("open fixture descriptor for timestamps");
1075            file.set_times(
1076                std::fs::FileTimes::new().set_modified(modified),
1077            )
1078            .expect("set fixture descriptor timestamp");
1079            std::fs::metadata(path)
1080                .expect("stat timestamped fixture descriptor")
1081                .modified()
1082                .expect("read fixture descriptor timestamp")
1083        }
1084
1085        fn drain_listener(&self, socket_name: &str) {
1086            let path = self.runtime.join(socket_name);
1087            if let Some(listener) = self
1088                .listeners
1089                .iter()
1090                .find(|listener| {
1091                    listener
1092                        .local_addr()
1093                        .ok()
1094                        .and_then(|addr| addr.as_pathname().map(Path::to_path_buf))
1095                        .as_deref()
1096                        == Some(path.as_path())
1097                })
1098            {
1099                listener.set_nonblocking(true).expect("nonblocking fixture listener");
1100                loop {
1101                    match listener.accept() {
1102                        Ok((stream, _)) => drop(stream),
1103                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
1104                        Err(error) => panic!("drain fallback listener: {error}"),
1105                    }
1106                }
1107            }
1108        }
1109
1110        fn assert_no_fallback_connection(&self) {
1111            let path = self.runtime.join("f.sock");
1112            let listener = self
1113                .listeners
1114                .iter()
1115                .find(|listener| {
1116                    listener
1117                        .local_addr()
1118                        .ok()
1119                        .and_then(|addr| addr.as_pathname().map(Path::to_path_buf))
1120                        .as_deref()
1121                        == Some(path.as_path())
1122                })
1123                .expect("fallback listener");
1124            listener.set_nonblocking(true).expect("nonblocking fallback listener");
1125            match listener.accept() {
1126                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
1127                Ok((stream, _)) => {
1128                    drop(stream);
1129                    panic!("rejected pin connected to fallback host");
1130                }
1131                Err(error) => panic!("check fallback listener: {error}"),
1132            }
1133        }
1134    }
1135
1136    impl Drop for PinDiscoveryFixture {
1137        fn drop(&mut self) {
1138            self.listeners.clear();
1139            let _ = std::fs::remove_dir_all(&self.root);
1140        }
1141    }
1142
1143    fn discover_fixture(fixture: &PinDiscoveryFixture) -> Result<Descriptor> {
1144        discover_with_paths(None, &fixture.pinned, &fixture.runtime)
1145    }
1146
1147    #[test]
1148    fn pinned_discovery_absent_pin_uses_reachable_fallback() {
1149        let mut fixture = PinDiscoveryFixture::new();
1150        let fallback = fixture.fallback();
1151        let selected = discover_fixture(&fixture).expect("fallback is discoverable");
1152        assert_eq!(selected.path, fallback);
1153        fixture.drain_listener("f.sock");
1154    }
1155
1156    #[test]
1157    fn pinned_discovery_absent_pin_keeps_newest_reachable_selection() {
1158        let mut fixture = PinDiscoveryFixture::new();
1159        let oldest = fixture.descriptor(&fixture.runtime.clone(), "older.json", "o.sock");
1160        let newest = fixture.descriptor(&fixture.runtime.clone(), "newest.json", "n.sock");
1161        let unreachable = fixture.descriptor(&fixture.runtime.clone(), "latest.json", "x.sock");
1162        let latest_socket = fixture.runtime.join("x.sock");
1163        drop(fixture.listeners.pop().expect("latest listener"));
1164        assert!(latest_socket.exists(), "closed socket path remains for validation");
1165        let oldest_time = PinDiscoveryFixture::set_modified(&oldest, 1_700_000_000);
1166        let newest_time = PinDiscoveryFixture::set_modified(&newest, 1_700_000_010);
1167        let unreachable_time = PinDiscoveryFixture::set_modified(&unreachable, 1_700_000_020);
1168        assert!(oldest_time < newest_time);
1169        assert!(newest_time < unreachable_time);
1170        let selected = discover_fixture(&fixture).expect("newest reachable descriptor selected");
1171        assert_eq!(selected.path, newest);
1172        fixture.drain_listener("n.sock");
1173    }
1174
1175    #[test]
1176    fn pinned_discovery_rejects_malformed_pin_without_connecting_fallback() {
1177        let mut fixture = PinDiscoveryFixture::new();
1178        let fallback = fixture.fallback();
1179        fixture.prove_fallback_is_discoverable(&fallback);
1180        crate::guarded_writer::write_file(&fixture.pinned, b"{").expect("write malformed pin");
1181        let error = discover_fixture(&fixture).expect_err("invalid existing pin must fail");
1182        assert!(error.to_string().contains(fixture.pinned.to_str().unwrap()));
1183        fixture.assert_no_fallback_connection();
1184    }
1185
1186    #[test]
1187    fn pinned_discovery_rejects_insecure_parent_without_connecting_fallback() {
1188        let mut fixture = PinDiscoveryFixture::new();
1189        let fallback = fixture.fallback();
1190        fixture.prove_fallback_is_discoverable(&fallback);
1191        fixture.descriptor(
1192            &fixture.pin_directory.clone(),
1193            "blitz-control.json",
1194            "p.sock",
1195        );
1196        std::fs::set_permissions(&fixture.pin_directory, std::fs::Permissions::from_mode(0o755))
1197            .expect("make pin parent insecure");
1198        let error = discover_fixture(&fixture).expect_err("insecure pin parent must fail");
1199        let cause = format!("{error:#}");
1200        assert!(cause.contains(fixture.pinned.to_str().unwrap()));
1201        assert!(
1202            cause.contains("validating descriptor directory"),
1203            "insecure-parent case failed for an unexpected reason: {cause}"
1204        );
1205        fixture.assert_no_fallback_connection();
1206    }
1207
1208    #[test]
1209    fn pinned_discovery_rejects_socket_outside_pin_parent_without_fallback() {
1210        let mut fixture = PinDiscoveryFixture::new();
1211        let fallback = fixture.fallback();
1212        fixture.prove_fallback_is_discoverable(&fallback);
1213        let outside = fixture.runtime.join("f.sock");
1214        crate::guarded_writer::write_file(
1215            &fixture.pinned,
1216            serde_json::json!({
1217                "protocolVersion": DEBUG_PROTOCOL_VERSION,
1218                "pid": 1,
1219                "instanceId": "outside",
1220                "address": format!("unix://{}", outside.display()),
1221                "renderer": "fixture",
1222                "rendererRevision": "test"
1223            })
1224            .to_string()
1225            .as_bytes(),
1226        )
1227        .expect("write outside-socket pin");
1228        let error = discover_fixture(&fixture).expect_err("socket outside pin parent must fail");
1229        assert!(error.to_string().contains(fixture.pinned.to_str().unwrap()));
1230        fixture.assert_no_fallback_connection();
1231    }
1232
1233    #[test]
1234    fn pinned_discovery_rejects_unreachable_and_dangling_pins_without_fallback() {
1235        let mut fixture = PinDiscoveryFixture::new();
1236        let fallback = fixture.fallback();
1237        fixture.prove_fallback_is_discoverable(&fallback);
1238        let stale_socket = fixture.pin_directory.join("s.sock");
1239        assert_socket_path_length(&stale_socket);
1240        let stale_listener = StdUnixListener::bind(&stale_socket).expect("bind stale pin socket");
1241        std::fs::set_permissions(&stale_socket, std::fs::Permissions::from_mode(0o600))
1242            .expect("restrict stale socket mode");
1243        drop(stale_listener);
1244        crate::guarded_writer::write_file(
1245            &fixture.pinned,
1246            serde_json::json!({
1247                "protocolVersion": DEBUG_PROTOCOL_VERSION,
1248                "pid": 1,
1249                "instanceId": "stale",
1250                "address": format!("unix://{}", stale_socket.display()),
1251                "renderer": "fixture",
1252                "rendererRevision": "test"
1253            })
1254            .to_string()
1255            .as_bytes(),
1256        )
1257        .expect("write stale pin");
1258        let error = discover_fixture(&fixture).expect_err("unreachable pin must fail");
1259        assert!(error.to_string().contains(fixture.pinned.to_str().unwrap()));
1260        fixture.assert_no_fallback_connection();
1261
1262        std::fs::remove_file(&fixture.pinned).expect("remove stale pin");
1263        symlink(fixture.pin_directory.join("missing.json"), &fixture.pinned)
1264            .expect("create dangling pin symlink");
1265        let error = discover_fixture(&fixture).expect_err("dangling pin must fail");
1266        assert!(error.to_string().contains(fixture.pinned.to_str().unwrap()));
1267        fixture.assert_no_fallback_connection();
1268    }
1269
1270    #[test]
1271    fn pinned_discovery_valid_pin_wins_and_explicit_path_precedes_invalid_pin() {
1272        let mut fixture = PinDiscoveryFixture::new();
1273        let fallback = fixture.fallback();
1274        let pinned = fixture.descriptor(&fixture.pin_directory.clone(), "blitz-control.json", "p.sock");
1275        let selected = discover_fixture(&fixture).expect("reachable pin is authoritative");
1276        assert_eq!(selected.path, pinned);
1277        assert!(selected.verified_reachable);
1278        fixture.assert_no_fallback_connection();
1279
1280        std::fs::remove_file(&fixture.pinned).expect("remove pin file");
1281        crate::guarded_writer::write_file(&fixture.pinned, b"invalid").expect("write bad pin");
1282        let explicit = discover_with_paths(
1283            Some(fallback.to_str().unwrap()),
1284            &fixture.pinned,
1285            &fixture.runtime,
1286        )
1287        .expect("explicit descriptor retains precedence");
1288        assert_eq!(explicit.path, fallback);
1289        assert!(!explicit.verified_reachable);
1290        fixture.assert_no_fallback_connection();
1291    }
1292
1293    #[test]
1294    fn pinned_discovery_explicit_closed_socket_remains_uncached() {
1295        let mut fixture = PinDiscoveryFixture::new();
1296        let explicit = fixture.descriptor(&fixture.pin_directory.clone(), "explicit.json", "e.sock");
1297        drop(fixture.listeners.pop().expect("explicit listener"));
1298        assert!(fixture.pin_directory.join("e.sock").exists());
1299        let selected = discover_with_paths(
1300            Some(explicit.to_str().unwrap()),
1301            &fixture.pinned,
1302            &fixture.runtime,
1303        )
1304        .expect("explicit descriptor read does not add a reachability probe");
1305        assert_eq!(selected.path, explicit);
1306        assert!(!selected.verified_reachable);
1307        assert!(!selected.is_reachable());
1308    }
1309
1310    fn assert_socket_path_length(path: &Path) {
1311        let length = path.as_os_str().as_bytes().len();
1312        assert!(
1313            length < MACOS_SUN_PATH_CAPACITY,
1314            "Unix socket path is {length} bytes; expected fewer than {MACOS_SUN_PATH_CAPACITY}: {}",
1315            path.display()
1316        );
1317    }
1318
1319    #[test]
1320    fn pinned_discovery_empty_runtime_reports_no_host() {
1321        let fixture = PinDiscoveryFixture::new();
1322        let error = discover_fixture(&fixture).expect_err("empty runtime has no host");
1323        assert!(error.to_string().contains("no reachable inspector descriptor found"));
1324    }
1325
1326    #[test]
1327    fn connect_retries_startup_and_exchange_preserves_events() {
1328        nagoya::block_on(async {
1329            let socket = std::env::temp_dir().join(format!(
1330                "ps-qa-transport-{}-{}.sock",
1331                std::process::id(),
1332                std::time::SystemTime::now()
1333                    .duration_since(std::time::UNIX_EPOCH)
1334                    .expect("system clock is after the epoch")
1335                    .as_nanos()
1336            ));
1337            let server_socket = socket.clone();
1338            let server = async move {
1339                // The descriptor can be visible before its socket is bound. Make
1340                // that production race deterministic and require the client retry.
1341                nagoya::sleep(Duration::from_millis(40)).await;
1342                let addr = Addr::path(server_socket.as_os_str().as_bytes()).expect("socket path");
1343                let listener = TcpListener::bind(addr, client_reactor()).expect("bind test socket");
1344                let (stream, _) = listener.accept().await.expect("accept test client");
1345                let mut stream =
1346                    TransportStream::new(framed_json_neutral(NagoyaStream::new(stream)));
1347                let _request = stream
1348                    .recv()
1349                    .await
1350                    .expect("client keeps connection open")
1351                    .expect("read initialize request");
1352                stream
1353                    .send(
1354                        encode_diagnostics_event(&DebugEvent::PaintCommitted { revision: 7 })
1355                            .expect("encode paint event"),
1356                    )
1357                    .await
1358                    .expect("send paint event");
1359                stream
1360                    .send(
1361                        encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
1362                            Some(JsonRpcId::Number(1)),
1363                            serde_json::json!({"protocolVersion": MCP_PROTOCOL_VERSION}),
1364                        )))
1365                        .expect("encode initialize response"),
1366                    )
1367                    .await
1368                    .expect("send initialize response");
1369            };
1370
1371            let client_socket = socket.clone();
1372            let client = async move {
1373                let mut client = Client::connect(&client_socket)
1374                    .await
1375                    .expect("client retries until socket is bound");
1376                client.initialize().await.expect("initialize completes");
1377                assert!(
1378                    client
1379                        .wait_for_paint(Duration::ZERO)
1380                        .await
1381                        .expect("queued paint remains readable"),
1382                    "an event arriving before the response must not steal the response or be discarded"
1383                );
1384            };
1385
1386            nagoya::timeout(
1387                Duration::from_secs(2),
1388                futures::future::join(server, client),
1389            )
1390            .await
1391            .expect("transport fixture watchdog");
1392            let _ = std::fs::remove_file(socket);
1393        });
1394    }
1395
1396    #[test]
1397    fn notifications_do_not_renew_the_request_deadline() {
1398        nagoya::block_on(async {
1399            let socket = std::env::temp_dir().join(format!(
1400                "ps-qa-notification-timeout-{}-{}.sock",
1401                std::process::id(),
1402                Instant::now().elapsed().as_nanos()
1403            ));
1404            let server_socket = socket.clone();
1405            let server = async move {
1406                let addr = Addr::path(server_socket.as_os_str().as_bytes()).expect("socket path");
1407                let listener = TcpListener::bind(addr, client_reactor()).expect("bind fixture");
1408                let (stream, _) = listener.accept().await.expect("accept client");
1409                let mut stream =
1410                    TransportStream::new(framed_json_neutral(NagoyaStream::new(stream)));
1411                let _request = stream
1412                    .recv()
1413                    .await
1414                    .expect("client stays connected")
1415                    .expect("request is readable");
1416                for _ in 0..40 {
1417                    let event =
1418                        encode_diagnostics_event(&DebugEvent::PaintCommitted { revision: 1 })
1419                            .expect("encode notification");
1420                    if stream.send(event).await.is_err() {
1421                        break;
1422                    }
1423                    nagoya::sleep(Duration::from_millis(5)).await;
1424                }
1425            };
1426
1427            let client_socket = socket.clone();
1428            let client = async move {
1429                let mut client = Client::connect(&client_socket)
1430                    .await
1431                    .expect("connect fixture");
1432                client.set_request_timeout(Duration::from_millis(100));
1433
1434                let started = Instant::now();
1435                let error = client
1436                    .initialize()
1437                    .await
1438                    .expect_err("notifications do not answer initialize");
1439                assert!(
1440                    error.downcast_ref::<InspectorRequestTimeout>().is_some(),
1441                    "expected typed request timeout, got {error}"
1442                );
1443                assert!(started.elapsed() < Duration::from_millis(250));
1444
1445                let started = Instant::now();
1446                let error = client
1447                    .tools_list()
1448                    .await
1449                    .expect_err("a timed out stream is terminal");
1450                assert!(
1451                    error.downcast_ref::<InspectorRequestTimeout>().is_some(),
1452                    "expected the stored terminal timeout, got {error}"
1453                );
1454                assert!(started.elapsed() < Duration::from_millis(25));
1455            };
1456
1457            nagoya::timeout(
1458                Duration::from_secs(2),
1459                futures::future::join(server, client),
1460            )
1461            .await
1462            .expect("notification fixture watchdog");
1463            let _ = std::fs::remove_file(socket);
1464        });
1465    }
1466
1467    #[test]
1468    fn transport_disconnect_classifies_typed_io_sources() {
1469        for (kind, label) in [
1470            (std::io::ErrorKind::UnexpectedEof, "UnexpectedEof"),
1471            (std::io::ErrorKind::ConnectionReset, "ConnectionReset"),
1472            (std::io::ErrorKind::BrokenPipe, "BrokenPipe"),
1473        ] {
1474            let error = endpoint_libs::libs::ws::StreamError::Other(eyre::Report::new(
1475                std::io::Error::from(kind),
1476            ));
1477            assert!(
1478                transport_disconnect_cause(&error).contains(label),
1479                "typed I/O source {kind:?} was not preserved"
1480            );
1481        }
1482    }
1483
1484    #[test]
1485    fn descriptor_protocol_mismatch_is_rejected_before_connecting() {
1486        let directory = std::env::temp_dir().join(format!(
1487            "ps-qa-descriptor-version-{}-{}",
1488            std::process::id(),
1489            std::time::SystemTime::now()
1490                .duration_since(std::time::UNIX_EPOCH)
1491                .expect("system clock is after the epoch")
1492                .as_nanos()
1493        ));
1494        crate::guarded_writer::create_private_dir(&directory)
1495            .expect("scratch directory is created");
1496        let path = directory.join("fixture.json");
1497        crate::guarded_writer::write_file(
1498            &path,
1499            serde_json::json!({
1500                "protocolVersion": DEBUG_PROTOCOL_VERSION + 1,
1501                "pid": 1,
1502                "instanceId": "fixture",
1503                "address": "unix:///tmp/fixture.sock",
1504                "renderer": "fixture",
1505                "rendererRevision": "test"
1506            })
1507            .to_string()
1508            .as_bytes(),
1509        )
1510        .expect("write descriptor fixture");
1511        let error = read_descriptor(&path).expect_err("newer protocol must not be guessed");
1512        assert!(
1513            error.to_string().contains("this client speaks"),
1514            "unexpected error: {error}"
1515        );
1516        let _ = std::fs::remove_file(path);
1517        let _ = std::fs::remove_dir(directory);
1518    }
1519}