Skip to main content

blitz_control_protocol/
server.rs

1use std::fs::remove_file;
2use std::io;
3use std::os::unix::ffi::OsStrExt;
4use std::os::unix::fs::PermissionsExt;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use endpoint_libs::libs::ws::mcp_wire::{INVALID_REQUEST, JsonRpcError};
11use endpoint_libs::libs::ws::transport::TransportStream;
12
13use crate::latest::{Flag, Latest, Once};
14pub(crate) use endpoint_libs::libs::ws::MessageStream;
15use endpoint_libs::libs::ws::transport::framed::framed_json_neutral;
16use endpoint_libs::libs::ws::transport::nagoya::NagoyaStream;
17use endpoint_libs::libs::ws::{StreamError, WireMessage};
18use nagoya::reactor::socket::TcpListener as BoundListener;
19use nagoya::reactor::{Addr, Reactor, TcpListener, TcpStream};
20
21use crate::{
22    AgentControlRequest, DebugDescriptor, DebugEvent, DebugResponse, DebugStream,
23    DiagnosticsRequest, IncomingRequest, decode_incoming_value, decode_wire_value,
24    encode_diagnostics_event, encode_initialize_response, encode_response, encode_rpc_error,
25    encode_tools_list_response, guarded_writer, peek_value_request_id,
26};
27
28pub enum ControlBridgeRequest {
29    Agent(AgentControlRequest),
30    Diagnostics(DiagnosticsRequest),
31    Targeted(crate::TargetRequest),
32}
33
34#[derive(Clone)]
35enum EventSource {
36    Latest(Arc<Latest<DebugEvent>>),
37    Journal(Arc<crate::journal::DiagnosticJournal>),
38}
39
40impl EventSource {
41    fn sequence(&self) -> u64 {
42        match self {
43            Self::Latest(events) => events.revision(),
44            Self::Journal(events) => events.sequence(),
45        }
46    }
47}
48
49/// Who is answering, and what they can answer.
50///
51/// # Why the server has to be told
52///
53/// It used to read this off its own cargo features: the tool list advertised
54/// diagnostics when the crate had been built with them, and `serverInfo` said
55/// `tauri-runtime-blitz` (now izumo) because that is where the code lived. Both were
56/// guesses that happened to hold while there was one host.
57///
58/// There are three now, and none of them is this crate. The window runtime,
59/// the headless browser and an embedder driving a browser in-process each have
60/// their own name, their own version and their own answer to whether they can
61/// collect a snapshot, and a transport cannot infer any of it. A host that
62/// cannot collect diagnostics says so here, and its bridge answers the request
63/// with an error rather than the server failing to compile the arm.
64#[derive(Debug, Clone)]
65pub struct Host {
66    /// What the process serving this socket is called. Reported as MCP
67    /// `serverInfo.name`.
68    pub name: String,
69    /// That process's version. Reported as `serverInfo.version` and as the
70    /// descriptor's `rendererRevision`.
71    pub version: String,
72    /// Whether `blitz.diagnostics` is worth advertising in `tools/list`.
73    ///
74    /// Advertising a tool that answers every call with an error is worse than
75    /// omitting it: a client reports the application as broken instead of as a
76    /// plain build.
77    pub diagnostics: bool,
78}
79
80/// How the server reaches whatever is holding the document.
81///
82/// A plain closure, deliberately: the server binds a socket, frames requests
83/// and hands them over, and knows nothing about windows, event loops or Tauri.
84/// The crate's own tests have always constructed one from a bare closure with
85/// nothing running, which is the proof that a host does not need a window to
86/// serve inspection.
87///
88/// Public so a headless host can serve one. While this was `pub(crate)` the
89/// only way to inspect a Blitz document from outside was to open a window,
90/// which is what pushed a QA harness into screenshot and tree-file workarounds
91/// that could not answer any question involving a click.
92pub type ControlBridge =
93    Arc<dyn Fn(ControlBridgeRequest) -> Arc<Once<DebugResponse>> + Send + Sync + 'static>;
94
95#[cfg(test)]
96pub(crate) static CONTROL_TEST_LOCK: nagoya::sync::RwLock<()> = nagoya::sync::RwLock::new(());
97
98pub struct AgentControlServer {
99    descriptor_path: PathBuf,
100    socket_path: PathBuf,
101    shutdown: Option<Arc<Flag>>,
102    task: Option<nagoya::JoinHandle<Arc<ServerWork>>>,
103    /// Holds deep-profiling collection open while a tool can attach.
104    ///
105    /// The consumer is out of process, so it cannot hold a session itself and
106    /// the server holds one on its behalf. The server's lifetime is the right
107    /// one: it exists exactly while the socket is listening, and a per-request
108    /// session would be useless, because the frames a snapshot reports were
109    /// presented before the request arrived.
110    ///
111    /// `None` when the profile does not permit sampling, which is the ordinary
112    /// case: inspection without deep profiling stays free.
113    ///
114    /// Only a build that can collect diagnostics has anything to sample, which
115    /// is why this is the one place the transport touches blitz at all, and why
116    /// it is behind `capture` rather than `server`.
117    #[cfg(feature = "capture")]
118    _sampling: Option<blitz_shell::DeepProfilingSession>,
119}
120
121impl AgentControlServer {
122    /// Bind the inspection socket and announce the descriptor.
123    ///
124    /// Nothing here needs a window: it creates a Unix listener, writes a
125    /// descriptor file and serves frames through nagoya. A headless host that
126    /// owns a document can call this and be inspected exactly like the real
127    /// application, which is what lets a QA sweep run with no display server
128    /// and still answer questions that require clicking.
129    pub fn start(bridge: ControlBridge, host: Host) -> io::Result<Self> {
130        Self::start_inner(bridge, host, None)
131    }
132
133    /// Start with a bounded latest-value diagnostic event source.
134    ///
135    /// A watch receiver is deliberate: a slow inspector needs the newest
136    /// revision, not an ever-growing queue of every frame it failed to read.
137    pub fn start_with_events(
138        bridge: ControlBridge,
139        host: Host,
140        events: Arc<Latest<DebugEvent>>,
141    ) -> io::Result<Self> {
142        Self::start_inner(bridge, host, Some(EventSource::Latest(events)))
143    }
144
145    pub fn start_with_journal(
146        bridge: ControlBridge,
147        host: Host,
148        events: Arc<crate::journal::DiagnosticJournal>,
149    ) -> io::Result<Self> {
150        Self::start_inner(bridge, host, Some(EventSource::Journal(events)))
151    }
152
153    fn start_inner(
154        bridge: ControlBridge,
155        host: Host,
156        events: Option<EventSource>,
157    ) -> io::Result<Self> {
158        let instance_id = instance_id();
159        let directory = crate::control_directory::default_directory();
160
161        // The directory carries the access control, and it is set before
162        // anything inside it exists.
163        //
164        // A mode on the socket cannot be: a Unix socket is created by `bind`
165        // already listening, so any mode applied afterwards leaves a window in
166        // which the path is connectable. The old directory setup used
167        // `create_dir_all`, which is world readable under `/tmp`, and
168        // the socket's `0600` landed after `bind`.
169        //
170        // `0700` on the directory closes it without depending on ordering at
171        // all: a process that cannot traverse the directory cannot reach the
172        // socket whatever the socket's own mode says. The socket keeps `0600`
173        // as well, because defence that rests on one check is defence that
174        // rests on nobody ever relaxing the directory.
175        match guarded_writer::create_private_dir(&directory) {
176            Ok(()) => {}
177            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
178            Err(error) => return Err(error),
179        }
180        let directory = crate::control_directory::validate_directory(&directory)?;
181        let descriptor_path = directory.join(format!("{instance_id}.json"));
182        let socket_path = descriptor_path.with_extension("sock");
183        reap_dead_descriptors(&descriptor_path);
184
185        // Bound here, before `start` returns, so a caller that connects the
186        // moment it has the path finds a socket listening. Registering it on a
187        // reactor is done here as well; binding is not deferred, since doing it
188        // there was a race the tests caught immediately.
189        let addr = Addr::path(socket_path.as_os_str().as_bytes())
190            .map_err(|_| io::Error::other("socket path is not a valid unix address"))?;
191        let listener = BoundListener::bind(addr, 128)
192            .map_err(|error| io::Error::other(format!("bind: {error:?}")))?;
193        std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))?;
194        let listener = TcpListener::from_listener(listener, &server_reactor()?)
195            .map_err(|error| io::Error::other(format!("register listener: {error:?}")))?;
196
197        let descriptor = DebugDescriptor {
198            protocol_version: crate::DEBUG_PROTOCOL_VERSION,
199            pid: std::process::id(),
200            instance_id,
201            address: format!("unix://{}", socket_path.display()),
202            renderer: "blitz".into(),
203            renderer_revision: host.version.clone(),
204        };
205        crate::control_directory::validate_socket(&directory, &descriptor.address)?;
206        write_descriptor(&descriptor_path, &descriptor)?;
207
208        let shutdown_flag = Flag::new();
209        let task = enqueue(Arc::new(ServerWork {
210            listener,
211            bridge,
212            host,
213            events,
214            shutdown: Arc::clone(&shutdown_flag),
215        }));
216
217        Ok(Self {
218            descriptor_path,
219            socket_path,
220            shutdown: Some(shutdown_flag),
221            task: Some(task),
222            // Taken after the socket is listening, so a permitted profile
223            // begins collecting for the tool that is now able to attach, and
224            // stops again when this server is dropped.
225            #[cfg(feature = "capture")]
226            _sampling: blitz_shell::begin_deep_profiling(),
227        })
228    }
229
230    /// Where this server announced itself.
231    ///
232    /// A headless host prints this so a client can attach to that exact
233    /// instance. Searching the descriptor directory instead races every other
234    /// instance on the machine, and a component sweep runs one host after
235    /// another, so the newest descriptor is not reliably the right one.
236    ///
237    /// Was `#[cfg(test)]`, because inside this crate the runtime already knows
238    /// where it wrote the descriptor and only a test needed to ask.
239    pub fn descriptor_path(&self) -> &Path {
240        &self.descriptor_path
241    }
242
243    /// Reacquire the sampling session after an embedder changes permission.
244    ///
245    /// The server can start before application settings or CLI overrides are
246    /// loaded. In that order `_sampling` begins as `None`; merely granting
247    /// permission later does not mutate an already-running server, so every
248    /// diagnostic snapshot keeps reporting `script: null` until restart.
249    ///
250    /// Public because the embedder that owns the setting is no longer in this
251    /// crate. It was `pub(crate)`, called by the runtime that lived beside it.
252    #[cfg(feature = "capture")]
253    pub fn refresh_deep_profiling(&mut self) {
254        self._sampling = blitz_shell::begin_deep_profiling();
255    }
256
257    /// The socket this server is listening on.
258    ///
259    /// A caller that already knows the descriptor path can derive this, and
260    /// several do; saying it directly is cheaper than agreeing on the
261    /// extension by convention.
262    pub fn socket_path(&self) -> &Path {
263        &self.socket_path
264    }
265}
266
267impl Drop for AgentControlServer {
268    fn drop(&mut self) {
269        if let Some(shutdown) = self.shutdown.take() {
270            shutdown.raise();
271        }
272        if let Some(task) = self.task.take() {
273            drop(nagoya::block_on(task));
274        }
275        let _ = remove_file(&self.socket_path);
276        let _ = remove_file(&self.descriptor_path);
277    }
278}
279struct ServerWork {
280    listener: TcpListener,
281    bridge: ControlBridge,
282    host: Host,
283    events: Option<EventSource>,
284    shutdown: Arc<Flag>,
285}
286
287fn server_reactor() -> io::Result<nagoya::reactor::Handle> {
288    static REACTOR: std::sync::OnceLock<io::Result<Reactor>> = std::sync::OnceLock::new();
289    REACTOR
290        .get_or_init(|| {
291            Reactor::start()
292                .map_err(|error| io::Error::other(format!("control reactor: {error:?}")))
293        })
294        .as_ref()
295        .map(Reactor::handle)
296        .map_err(|error| io::Error::new(error.kind(), error.to_string()))
297}
298
299fn enqueue(work: Arc<ServerWork>) -> nagoya::JoinHandle<Arc<ServerWork>> {
300    nagoya::spawn(run(work))
301}
302
303async fn run(work: Arc<ServerWork>) -> Arc<ServerWork> {
304    use futures::StreamExt;
305    use futures::future::{Either, select};
306    use futures::stream::FuturesUnordered;
307
308    // Completed connections leave the set, so reconnecting does not retain
309    // one task slot for every connection the server has ever accepted.
310    {
311        let mut connections = FuturesUnordered::new();
312        loop {
313            let stopping = work.shutdown.raised();
314            let accepted = work.listener.accept();
315            futures::pin_mut!(stopping, accepted);
316
317            // The shutdown flag wins over readiness from any connection.
318            let accepted = if connections.is_empty() {
319                match select(stopping, accepted).await {
320                    Either::Left(_) => break,
321                    Either::Right((accepted, _)) => accepted,
322                }
323            } else {
324                let progress = select(accepted, connections.next());
325                futures::pin_mut!(progress);
326                match select(stopping, progress).await {
327                    Either::Left(_) => break,
328                    Either::Right((Either::Left((accepted, _)), _)) => accepted,
329                    Either::Right((Either::Right(_), _)) => continue,
330                }
331            };
332
333            let Ok((stream, _)) = accepted else {
334                break;
335            };
336            connections.push(handle_connection(
337                stream,
338                Arc::clone(&work.bridge),
339                work.host.clone(),
340                work.events.clone(),
341            ));
342        }
343    }
344    // Every connection is dropped before the finished work changes owner.
345    work
346}
347
348enum ConnectionInput {
349    Message(Option<Result<WireMessage, StreamError>>),
350    /// The newest event, carried directly. A `Latest` has no sender to drop,
351    /// so there is no receive error to represent.
352    Event(Box<DebugEvent>),
353    Journal(crate::journal::JournalItem),
354}
355
356fn stream_wants_event(streams: &[DebugStream], event: &DebugEvent) -> bool {
357    match event {
358        DebugEvent::DiagnosticLoss { stream, .. } => streams.contains(stream),
359        DebugEvent::Snapshot(_) => streams.contains(&DebugStream::Snapshots),
360        DebugEvent::Metrics(_) => streams.contains(&DebugStream::Metrics),
361        DebugEvent::Console(_) => streams.contains(&DebugStream::Console),
362        DebugEvent::RuntimeError(_) => streams.contains(&DebugStream::RuntimeErrors),
363        DebugEvent::PaintCommitted { .. } => streams.contains(&DebugStream::Paint),
364    }
365}
366
367async fn handle_connection(
368    stream: TcpStream,
369    bridge: ControlBridge,
370    host: Host,
371    events: Option<EventSource>,
372) {
373    let mut stream = crate::server_stream::ServerStream(TransportStream::new(framed_json_neutral(
374        NagoyaStream::new(stream),
375    )));
376    let mut observed = Vec::<DebugStream>::new();
377    // This reader's position in the event stream. Held here rather than in the
378    // slot, because two connections read the same `Latest` from different
379    // places and one catching up must not move the other.
380    let mut seen = events.as_ref().map_or(0, EventSource::sequence);
381    let mut target_options = crate::TargetOptions::default();
382    loop {
383        let input = if observed.is_empty() {
384            ConnectionInput::Message(stream.recv().await)
385        } else if let Some(EventSource::Journal(journal)) = events.as_ref() {
386            use futures::future::{Either, select};
387            let message = stream.recv();
388            let changed = journal.next_after(seen);
389            futures::pin_mut!(message, changed);
390            match select(message, changed).await {
391                Either::Left((message, _)) => ConnectionInput::Message(message),
392                Either::Right((item, _)) => {
393                    seen = item.sequence();
394                    ConnectionInput::Journal(item)
395                }
396            }
397        } else if let Some(EventSource::Latest(latest)) = events.as_ref() {
398            use futures::future::{Either, select};
399            let message = stream.recv();
400            let changed = latest.changed_since(seen);
401            futures::pin_mut!(message, changed);
402            match select(message, changed).await {
403                Either::Left((message, _)) => ConnectionInput::Message(message),
404                Either::Right(((event, revision), _)) => {
405                    seen = revision;
406                    match event {
407                        Some(event) => ConnectionInput::Event(Box::new(event)),
408                        None => continue,
409                    }
410                }
411            }
412        } else {
413            ConnectionInput::Message(stream.recv().await)
414        };
415
416        let message = match input {
417            ConnectionInput::Journal(item) => {
418                let frame = match item {
419                    crate::journal::JournalItem::Overflow { first, last } => {
420                        crate::encode_diagnostic_overflow(first, last)
421                    }
422                    crate::journal::JournalItem::Event(record) => {
423                        let selected = target_options.all_targets
424                            || record.context.target_id
425                                == target_options.target.as_ref().map_or_else(
426                                    crate::TargetId::chrome,
427                                    crate::TargetSelector::id,
428                                );
429                        if !selected || !stream_wants_event(&observed, &record.event) {
430                            continue;
431                        }
432                        crate::encode_target_event(&record)
433                    }
434                };
435                let frame = frame.unwrap_or_else(|_| {
436                    crate::encode_diagnostic_overflow(seen, seen)
437                        .expect("the bounded overflow notification is serializable")
438                });
439                if stream.send(frame).await.is_err() {
440                    break;
441                }
442                continue;
443            }
444            ConnectionInput::Event(event) => {
445                if !stream_wants_event(&observed, &event) {
446                    continue;
447                }
448                let Ok(frame) = encode_diagnostics_event(&event) else {
449                    continue;
450                };
451                if stream.send(frame).await.is_err() {
452                    break;
453                }
454                continue;
455            }
456            ConnectionInput::Message(Some(message)) => message,
457            ConnectionInput::Message(None) => break,
458        };
459        let response = match message {
460            Ok(message) => match decode_wire_value(message) {
461                Ok(value) => {
462                    // Recover the id before typed decoding consumes the parsed
463                    // value. The previous path parsed the complete request once
464                    // for this id and again for the request itself.
465                    let request_id = peek_value_request_id(&value);
466                    match decode_incoming_value(value) {
467                        Ok(IncomingRequest::Initialize { id }) => {
468                            encode_initialize_response(id, &host.name, &host.version)
469                        }
470                        Ok(IncomingRequest::Initialized) => continue,
471                        Ok(IncomingRequest::ToolsList { id }) => {
472                            encode_tools_list_response(id, host.diagnostics)
473                        }
474                        Ok(IncomingRequest::Targeted { id, request }) => {
475                            let streams = match &request.command {
476                                crate::TargetCommand::Diagnostics(
477                                    DiagnosticsRequest::Observe { streams },
478                                ) => Some(streams.clone()),
479                                _ => None,
480                            };
481                            let options = request.options.clone();
482                            let baseline = events.as_ref().map_or(0, EventSource::sequence);
483                            let validation = request.validate_options().and_then(|()| {
484                                if streams.is_some()
485                                    && options
486                                        .after_sequence
487                                        .is_some_and(|sequence| sequence > baseline)
488                                {
489                                    Err(crate::target::error(
490                                        "invalidSequence",
491                                        "afterSequence exceeds the current journal sequence",
492                                    ))
493                                } else {
494                                    Ok(())
495                                }
496                            });
497                            let response = match validation {
498                                Err(error) => DebugResponse::Error(error),
499                                Ok(()) => bridge(ControlBridgeRequest::Targeted(request))
500                                    .recv()
501                                    .await
502                                    .unwrap_or_else(|| {
503                                        DebugResponse::Error(crate::target::error(
504                                            "bridgeClosed",
505                                            "the UI-thread bridge closed",
506                                        ))
507                                    }),
508                            };
509                            if matches!(response.unscoped(), DebugResponse::Ack)
510                                && let Some(streams) = streams
511                            {
512                                observed = streams;
513                                seen = options.after_sequence.unwrap_or(baseline);
514                                target_options = options;
515                            }
516                            encode_response(id, &response)
517                        }
518                        Ok(IncomingRequest::Agent { id, request }) => {
519                            let response = bridge(ControlBridgeRequest::Agent(request))
520                                .recv()
521                                .await
522                                .unwrap_or_else(|| {
523                                    DebugResponse::Error(crate::DebugError {
524                                        code: "bridgeClosed".into(),
525                                        message: "the UI-thread control bridge closed".into(),
526                                    })
527                                });
528                            encode_response(id, &response)
529                        }
530                        // The protocol defines diagnostics unconditionally, and
531                        // so does this transport. Whether they can be collected
532                        // is the host's answer, given in `Host::diagnostics`
533                        // for the tool list and in its bridge for a call that
534                        // arrives anyway.
535                        Ok(IncomingRequest::Diagnostics {
536                            id,
537                            request: DiagnosticsRequest::Observe { streams },
538                        }) => {
539                            let baseline = events.as_ref().map_or(0, EventSource::sequence);
540                            let response =
541                                if matches!(events.as_ref(), Some(EventSource::Journal(_))) {
542                                    bridge(ControlBridgeRequest::Targeted(crate::TargetRequest {
543                                        options: crate::TargetOptions::default(),
544                                        command: crate::TargetCommand::Diagnostics(
545                                            DiagnosticsRequest::Observe {
546                                                streams: streams.clone(),
547                                            },
548                                        ),
549                                    }))
550                                    .recv()
551                                    .await
552                                    .unwrap_or_else(|| {
553                                        DebugResponse::Error(crate::target::error(
554                                            "bridgeClosed",
555                                            "the UI-thread bridge closed",
556                                        ))
557                                    })
558                                } else {
559                                    DebugResponse::Ack
560                                };
561                            if matches!(response.unscoped(), DebugResponse::Ack) {
562                                observed = streams;
563                                seen = baseline;
564                                target_options = crate::TargetOptions::default();
565                            }
566                            encode_response(id, &response)
567                        }
568                        Ok(IncomingRequest::Diagnostics { id, request }) => {
569                            let response = bridge(ControlBridgeRequest::Diagnostics(request))
570                                .recv()
571                                .await
572                                .unwrap_or_else(|| {
573                                    DebugResponse::Error(crate::DebugError {
574                                        code: "bridgeClosed".into(),
575                                        message: "the UI-thread diagnostics bridge closed".into(),
576                                    })
577                                });
578                            encode_response(id, &response)
579                        }
580                        Err(error) => encode_rpc_error(
581                            request_id,
582                            JsonRpcError::new(INVALID_REQUEST, error.to_string()),
583                        ),
584                    }
585                }
586                Err(error) => {
587                    encode_rpc_error(None, JsonRpcError::new(INVALID_REQUEST, error.to_string()))
588                }
589            },
590            // A transport error is not a bad request: the framing is broken or
591            // the peer is gone, and the next read returns the same error
592            // immediately. Answering and continuing spun this task at a full
593            // core for the life of the process, one per client that ever
594            // disconnected, which is most of them. Measured on an idle app:
595            // 0.0% CPU without the control server, 55-76% with it after a few
596            // tools had connected and gone.
597            //
598            // So answer once, best effort, then stop reading this connection.
599            Err(error) => {
600                let farewell =
601                    encode_rpc_error(None, JsonRpcError::new(INVALID_REQUEST, error.to_string()));
602                if let Ok(farewell) = farewell {
603                    let _ = stream.send(farewell).await;
604                }
605                break;
606            }
607        };
608        let response = response.unwrap_or_else(|error| {
609            encode_rpc_error(
610                None,
611                JsonRpcError::new(
612                    INVALID_REQUEST,
613                    format!("could not encode response: {error}"),
614                ),
615            )
616            .expect("the fallback JSON-RPC error is serializable")
617        });
618        if stream.send(response).await.is_err() {
619            break;
620        }
621    }
622}
623
624fn instance_id() -> String {
625    let nanos = SystemTime::now()
626        .duration_since(UNIX_EPOCH)
627        .unwrap_or_default()
628        .as_nanos();
629    format!("{}-{nanos:x}", std::process::id())
630}
631
632/// Treat every result except ESRCH as live or unknown.
633fn pid_is_live(pid: u32) -> bool {
634    let Ok(pid) = libc::pid_t::try_from(pid) else {
635        return true;
636    };
637    if pid <= 0 {
638        return true;
639    }
640    // SAFETY: A positive PID and signal zero probe without sending a signal.
641    let result = unsafe { libc::kill(pid, 0) };
642    !(result == -1 && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH))
643}
644
645/// Sweep dead instances before binding, including orphaned sockets.
646/// Each entry must independently pass ownership and file-type checks.
647fn reap_dead_descriptors(own: &Path) {
648    reap_dead_descriptors_with(own, pid_is_live);
649}
650
651fn reap_dead_descriptors_with(own: &Path, is_live: impl Fn(u32) -> bool) {
652    use std::os::unix::fs::MetadataExt;
653
654    use rustix::fs::{AtFlags, FileType, Mode, OFlags};
655
656    let Some(dir) = own.parent() else { return };
657    let Ok(dir) = crate::control_directory::validate_directory(dir) else {
658        return;
659    };
660    let Ok(before) = std::fs::symlink_metadata(&dir) else {
661        return;
662    };
663    let Ok(fd) = rustix::fs::open(
664        &dir,
665        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
666        Mode::empty(),
667    ) else {
668        return;
669    };
670    let directory = std::fs::File::from(fd);
671    let Ok(after) = directory.metadata() else {
672        return;
673    };
674    let uid = rustix::process::geteuid().as_raw();
675    if !after.is_dir()
676        || after.uid() != uid
677        || after.mode() & 0o077 != 0
678        || before.dev() != after.dev()
679        || before.ino() != after.ino()
680    {
681        return;
682    }
683    let Ok(entries) = rustix::fs::Dir::read_from(&directory) else {
684        return;
685    };
686    for entry in entries {
687        let Ok(entry) = entry else {
688            continue;
689        };
690        let name = entry.file_name();
691        let bytes = name.to_bytes();
692        if own.file_name().is_some_and(|own| own.as_bytes() == bytes) {
693            continue;
694        }
695        let (stem, expected_type) = if let Some(stem) = bytes.strip_suffix(b".json") {
696            (stem, FileType::RegularFile)
697        } else if let Some(stem) = bytes.strip_suffix(b".sock") {
698            (stem, FileType::Socket)
699        } else {
700            continue;
701        };
702        let Some(separator) = stem.iter().position(|byte| *byte == b'-') else {
703            continue;
704        };
705        let pid_bytes = &stem[..separator];
706        if pid_bytes.is_empty()
707            || !pid_bytes.iter().all(u8::is_ascii_digit)
708            || separator + 1 == stem.len()
709        {
710            continue;
711        }
712        let Some(pid) = std::str::from_utf8(pid_bytes)
713            .ok()
714            .and_then(|pid| pid.parse::<u32>().ok())
715            .filter(|pid| *pid > 0 && libc::pid_t::try_from(*pid).is_ok())
716        else {
717            continue;
718        };
719        let Ok(before) = rustix::fs::statat(&directory, name, AtFlags::SYMLINK_NOFOLLOW) else {
720            continue;
721        };
722        if before.st_uid != uid
723            || FileType::from_raw_mode(before.st_mode) != expected_type
724            || is_live(pid)
725        {
726            continue;
727        }
728        let Ok(after) = rustix::fs::statat(&directory, name, AtFlags::SYMLINK_NOFOLLOW) else {
729            continue;
730        };
731        if after.st_uid != uid
732            || FileType::from_raw_mode(after.st_mode) != expected_type
733            || before.st_dev != after.st_dev
734            || before.st_ino != after.st_ino
735        {
736            continue;
737        }
738        // The pinned directory confines deletion; unlinkat never follows the leaf.
739        let _ = rustix::fs::unlinkat(&directory, name, AtFlags::empty());
740    }
741}
742
743fn write_descriptor(path: &Path, descriptor: &DebugDescriptor) -> io::Result<()> {
744    let parent = path
745        .parent()
746        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "descriptor needs a parent"))?;
747    crate::control_directory::validate_directory(parent)?;
748    match std::fs::symlink_metadata(path) {
749        Ok(_) => {
750            return Err(io::Error::new(
751                io::ErrorKind::AlreadyExists,
752                "refusing to replace an existing control descriptor",
753            ));
754        }
755        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
756        Err(error) => return Err(error),
757    }
758    let mut content = serde_json::to_string_pretty(descriptor).map_err(io::Error::other)?;
759    content.push('\n');
760    guarded_writer::write_file(path, content.as_bytes())?;
761    crate::control_directory::open_descriptor(path)?;
762    Ok(())
763}
764
765#[cfg(test)]
766mod tests {
767    use endpoint_libs::libs::ws::mcp_wire::{JsonRpcId, JsonRpcMessage, JsonRpcRequest};
768
769    use super::*;
770    use crate::{
771        AgentAction, AgentControlRequest, DebugResponse, MCP_INITIALIZE, MCP_TOOLS_LIST,
772        decode_response, decode_rpc, encode_agent_request, encode_rpc,
773    };
774    use crate::{
775        DebugEvent, DebugSnapshot, DebugStream, DiagnosticsRequest, RendererMetrics, RevisionSet,
776        SnapshotRequest, decode_diagnostics_event, encode_diagnostics_request,
777    };
778
779    /// A host that can do everything, for the tests that are about the
780    /// transport rather than about what is on the other side of it.
781    /// Connect to a running server's socket, on a reactor of the caller's own.
782    ///
783    /// A test drives both ends: the server polls its socket on the thread it
784    /// spawned, and this is the client side, which needs a reactor of its own
785    /// because a nagoya socket only makes progress while the reactor it was
786    /// created on is polled. `Reactor::start` owns a thread, so the connection
787    /// keeps being driven while the test awaits a reply on it.
788    async fn connect(path: &Path) -> NagoyaStream {
789        static CLIENT_REACTOR: std::sync::OnceLock<(Reactor, nagoya::reactor::Handle)> =
790            std::sync::OnceLock::new();
791        let (_, handle) = CLIENT_REACTOR.get_or_init(|| {
792            let reactor = Reactor::start().expect("client reactor");
793            let handle = reactor.handle();
794            (reactor, handle)
795        });
796        let addr = Addr::path(path.as_os_str().as_bytes()).expect("socket path");
797        let stream = TcpStream::connect(addr, handle).await.expect("connect");
798        NagoyaStream::new(stream)
799    }
800
801    fn test_host() -> Host {
802        Host {
803            name: "test-host".into(),
804            version: "0.0.0".into(),
805            diagnostics: true,
806        }
807    }
808
809    #[test]
810    fn local_server_is_mcp_compatible_and_needs_no_session_or_token() {
811        nagoya::block_on(async {
812            let _guard = CONTROL_TEST_LOCK.write().await;
813            let bridge: ControlBridge = Arc::new(|request| {
814                let answer = Once::new();
815                assert!(matches!(
816                    request,
817                    ControlBridgeRequest::Agent(AgentControlRequest::Act(AgentAction::Click {
818                        node_id: 42
819                    }))
820                ));
821                answer.fill(DebugResponse::Ack);
822                answer
823            });
824            let server = AgentControlServer::start(bridge, test_host()).unwrap();
825            assert!(server.descriptor_path().is_file());
826            assert_eq!(
827                server
828                    .descriptor_path()
829                    .metadata()
830                    .unwrap()
831                    .permissions()
832                    .mode()
833                    & 0o777,
834                0o600
835            );
836
837            let stream = connect(server.socket_path()).await;
838            let mut stream = TransportStream::new(framed_json_neutral(stream));
839            stream
840                .send(
841                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
842                        JsonRpcId::Number(1),
843                        MCP_INITIALIZE,
844                        serde_json::json!({"protocolVersion": "2025-06-18"}),
845                    )))
846                    .unwrap(),
847                )
848                .await
849                .unwrap();
850            assert!(matches!(
851                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap(),
852                JsonRpcMessage::Response(_)
853            ));
854            stream
855                .send(
856                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
857                        JsonRpcId::Number(2),
858                        MCP_TOOLS_LIST,
859                        serde_json::json!({}),
860                    )))
861                    .unwrap(),
862                )
863                .await
864                .unwrap();
865            assert!(matches!(
866                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap(),
867                JsonRpcMessage::Response(_)
868            ));
869            let id = JsonRpcId::Number(42);
870            stream
871                .send(
872                    encode_agent_request(
873                        id.clone(),
874                        &AgentControlRequest::Act(AgentAction::Click { node_id: 42 }),
875                    )
876                    .unwrap(),
877                )
878                .await
879                .unwrap();
880            let response = stream.recv().await.unwrap().unwrap();
881            assert_eq!(decode_response(response).unwrap(), (id, DebugResponse::Ack));
882
883            let second = connect(server.socket_path()).await;
884            let mut second = TransportStream::new(framed_json_neutral(second));
885            let id = JsonRpcId::String("second-observer".into());
886            second
887                .send(
888                    encode_agent_request(
889                        id.clone(),
890                        &AgentControlRequest::Act(AgentAction::Click { node_id: 42 }),
891                    )
892                    .unwrap(),
893                )
894                .await
895                .unwrap();
896            assert_eq!(
897                decode_response(second.recv().await.unwrap().unwrap()).unwrap(),
898                (id, DebugResponse::Ack)
899            );
900
901            drop(server);
902        });
903    }
904
905    #[test]
906    fn diagnostics_metrics_reach_the_runtime_bridge_over_mcp() {
907        nagoya::block_on(async {
908            let _guard = CONTROL_TEST_LOCK.write().await;
909            let bridge: ControlBridge = Arc::new(|request| {
910                let answer = Once::new();
911                assert!(matches!(
912                    request,
913                    ControlBridgeRequest::Diagnostics(DiagnosticsRequest::Metrics)
914                ));
915                answer.fill(DebugResponse::Metrics(RendererMetrics {
916                    resident_bytes: Some(8192),
917                    ..Default::default()
918                }));
919                answer
920            });
921            let server = AgentControlServer::start(bridge, test_host()).unwrap();
922            let stream = connect(server.socket_path()).await;
923            let mut stream = TransportStream::new(framed_json_neutral(stream));
924            let id = JsonRpcId::Number(91);
925
926            stream
927                .send(encode_diagnostics_request(id.clone(), &DiagnosticsRequest::Metrics).unwrap())
928                .await
929                .unwrap();
930
931            assert_eq!(
932                decode_response(stream.recv().await.unwrap().unwrap()).unwrap(),
933                (
934                    id,
935                    DebugResponse::Metrics(RendererMetrics {
936                        resident_bytes: Some(8192),
937                        ..Default::default()
938                    })
939                )
940            );
941        });
942    }
943
944    #[test]
945    fn observe_pushes_only_requested_latest_value_events() {
946        nagoya::block_on(async {
947            let _guard = CONTROL_TEST_LOCK.write().await;
948            let bridge: ControlBridge = Arc::new(|_request| {
949                panic!("observe is connection-local and must not reach the UI bridge")
950            });
951            let events = Latest::new();
952            let server =
953                AgentControlServer::start_with_events(bridge, test_host(), Arc::clone(&events))
954                    .unwrap();
955            let stream = connect(server.socket_path()).await;
956            let mut stream = TransportStream::new(framed_json_neutral(stream));
957            let id = JsonRpcId::Number(92);
958
959            stream
960                .send(
961                    encode_diagnostics_request(
962                        id.clone(),
963                        &DiagnosticsRequest::Observe {
964                            streams: vec![DebugStream::Paint],
965                        },
966                    )
967                    .unwrap(),
968                )
969                .await
970                .unwrap();
971            assert_eq!(
972                decode_response(stream.recv().await.unwrap().unwrap()).unwrap(),
973                (id, DebugResponse::Ack)
974            );
975
976            let event = DebugEvent::PaintCommitted { revision: 7 };
977            events.set(event.clone()).await;
978            assert_eq!(
979                decode_diagnostics_event(stream.recv().await.unwrap().unwrap()).unwrap(),
980                event
981            );
982        });
983    }
984
985    #[test]
986    fn large_snapshot_keeps_the_socket_open_for_follow_up_requests() {
987        nagoya::block_on(async {
988            let _guard = CONTROL_TEST_LOCK.write().await;
989            const LARGE_DOM_BYTES: usize = 9 * 1024 * 1024;
990            let bridge: ControlBridge = Arc::new(|request| {
991                let answer = Once::new();
992                let response = match request {
993                    ControlBridgeRequest::Diagnostics(DiagnosticsRequest::Snapshot(_)) => {
994                        DebugResponse::Snapshot(DebugSnapshot {
995                            revisions: RevisionSet::default(),
996                            active_window: Some("main".into()),
997                            active_element: None,
998                            dom: Some(serde_json::Value::String("x".repeat(LARGE_DOM_BYTES))),
999                            layout: None,
1000                            computed_style: None,
1001                            metrics: RendererMetrics::default(),
1002                        })
1003                    }
1004                    ControlBridgeRequest::Diagnostics(DiagnosticsRequest::Metrics) => {
1005                        DebugResponse::Metrics(RendererMetrics {
1006                            resident_bytes: Some(4096),
1007                            ..Default::default()
1008                        })
1009                    }
1010                    _ => panic!("unexpected request"),
1011                };
1012                answer.fill(response);
1013                answer
1014            });
1015            let server = AgentControlServer::start(bridge, test_host()).unwrap();
1016            let stream = connect(server.socket_path()).await;
1017            let mut stream = TransportStream::new(framed_json_neutral(stream));
1018
1019            let snapshot_id = JsonRpcId::Number(92);
1020            stream
1021                .send(
1022                    encode_diagnostics_request(
1023                        snapshot_id.clone(),
1024                        &DiagnosticsRequest::Snapshot(SnapshotRequest {
1025                            include_dom: true,
1026                            include_layout: false,
1027                            include_computed_style: false,
1028                            node_ids: Vec::new(),
1029                        }),
1030                    )
1031                    .unwrap(),
1032                )
1033                .await
1034                .unwrap();
1035            let (response_id, response) =
1036                decode_response(stream.recv().await.unwrap().unwrap()).unwrap();
1037            assert_eq!(response_id, snapshot_id);
1038            let DebugResponse::Snapshot(snapshot) = response else {
1039                panic!("expected a diagnostic snapshot")
1040            };
1041            assert_eq!(
1042                snapshot.dom.unwrap().as_str().unwrap().len(),
1043                LARGE_DOM_BYTES
1044            );
1045
1046            let metrics_id = JsonRpcId::Number(93);
1047            stream
1048                .send(
1049                    encode_diagnostics_request(metrics_id.clone(), &DiagnosticsRequest::Metrics)
1050                        .unwrap(),
1051                )
1052                .await
1053                .unwrap();
1054            assert_eq!(
1055                decode_response(stream.recv().await.unwrap().unwrap()).unwrap(),
1056                (
1057                    metrics_id,
1058                    DebugResponse::Metrics(RendererMetrics {
1059                        resident_bytes: Some(4096),
1060                        ..Default::default()
1061                    })
1062                )
1063            );
1064        });
1065    }
1066
1067    #[test]
1068    fn initialize_payload_uses_json_rpc() {
1069        let message =
1070            encode_initialize_response(JsonRpcId::Number(1), "test-host", "0.1.0").unwrap();
1071        let WireMessage::Text(payload) = message else {
1072            panic!("initialize response must be text")
1073        };
1074        let decoded: JsonRpcMessage = serde_json::from_str(&payload).unwrap();
1075        assert!(matches!(decoded, JsonRpcMessage::Response(_)));
1076    }
1077
1078    /**
1079     * A dead instance's descriptor goes; a live one's stays.
1080     *
1081     * The filename carries a pid and a nanosecond stamp, so every launch leaves
1082     * a new pair behind and nothing removed them — one machine had 99. `Drop`
1083     * handles an orderly exit, but a crash, a `kill -9`, or a rebuild that
1084     * unlinks the socket under a running instance all skip it. A tool then has
1085     * to guess which is current, which is how attaching to a stale socket
1086     * became routine.
1087     *
1088     * The asymmetry is the whole point: reaping too eagerly would delete a
1089     * concurrent instance's descriptor, which is worse than leaving litter.
1090     */
1091    #[test]
1092    fn reaping_removes_dead_descriptors_and_spares_live_ones() {
1093        let dir = std::env::temp_dir().join(format!(
1094            "blitz-reap-{}-{:x}",
1095            std::process::id(),
1096            SystemTime::now()
1097                .duration_since(UNIX_EPOCH)
1098                .unwrap_or_default()
1099                .as_nanos()
1100        ));
1101        crate::guarded_writer::create_private_dir(&dir).expect("scratch directory is created");
1102
1103        let write = |name: &str, pid: u32| {
1104            let path = dir.join(format!("{name}.json"));
1105            write_descriptor(
1106                &path,
1107                &DebugDescriptor {
1108                    protocol_version: crate::DEBUG_PROTOCOL_VERSION,
1109                    pid,
1110                    instance_id: name.into(),
1111                    address: format!("unix://{}", dir.join(format!("{name}.sock")).display()),
1112                    renderer: "blitz".into(),
1113                    renderer_revision: "0.0.0".into(),
1114                },
1115            )
1116            .expect("descriptor is written");
1117            let _socket = std::os::unix::net::UnixListener::bind(dir.join(format!("{name}.sock")))
1118                .expect("socket is bound");
1119            path
1120        };
1121
1122        // Inject liveness so the test does not depend on process permissions.
1123        let own = write(&format!("{}-own", std::process::id()), std::process::id());
1124        let live = write("1-live", 1);
1125        let dead = write("2-dead", 2);
1126
1127        reap_dead_descriptors_with(&own, |pid| pid == std::process::id() || pid == 1);
1128
1129        assert!(own.exists(), "the caller's own descriptor is never reaped");
1130        assert!(live.exists(), "a live instance must keep its descriptor");
1131        assert!(!dead.exists(), "a dead instance's descriptor is removed");
1132        assert!(
1133            !dir.join("2-dead.sock").exists(),
1134            "the orphaned socket goes with it"
1135        );
1136
1137        let _ = std::fs::remove_dir_all(&dir);
1138    }
1139    /// A gone server advertises nothing.
1140    ///
1141    /// Carried over from the browser's own control server, which is being
1142    /// deleted in favour of this one: it asserted that dropping the server
1143    /// removes both files, and losing that assertion would lose the property.
1144    /// Leaving either behind advertises a host that is not there, and a client
1145    /// that finds a stale descriptor attaches to a socket nobody is serving.
1146    #[test]
1147    fn teardown_removes_the_socket_and_the_descriptor() {
1148        nagoya::block_on(async {
1149            let _guard = CONTROL_TEST_LOCK.write().await;
1150            let bridge: ControlBridge = Arc::new(|_request| {
1151                let answer = Once::new();
1152                answer.fill(DebugResponse::Ack);
1153                answer
1154            });
1155            let server = AgentControlServer::start(bridge, test_host()).unwrap();
1156            let descriptor = server.descriptor_path().to_path_buf();
1157            let socket = server.socket_path().to_path_buf();
1158            assert!(descriptor.is_file(), "the descriptor was not published");
1159            assert!(socket.exists(), "the socket was not bound");
1160
1161            drop(server);
1162
1163            assert!(!socket.exists(), "the socket outlived the server");
1164            assert!(
1165                !descriptor.exists(),
1166                "the descriptor outlived the server, so a client can still find it"
1167            );
1168        });
1169    }
1170
1171    /// What the tool list says is the host's answer, not this crate's.
1172    ///
1173    /// It used to be `cfg!(feature = "diagnostics")` read off the crate that
1174    /// happened to contain the server. There are three hosts now and the
1175    /// transport is in none of them.
1176    #[test]
1177    fn a_host_that_cannot_collect_diagnostics_does_not_advertise_them() {
1178        nagoya::block_on(async {
1179            let _guard = CONTROL_TEST_LOCK.write().await;
1180            let bridge: ControlBridge = Arc::new(|_request| {
1181                let answer = Once::new();
1182                answer.fill(DebugResponse::Ack);
1183                answer
1184            });
1185            let server = AgentControlServer::start(
1186                bridge,
1187                Host {
1188                    name: "plain-host".into(),
1189                    version: "9.9.9".into(),
1190                    diagnostics: false,
1191                },
1192            )
1193            .unwrap();
1194
1195            let stream = connect(server.socket_path()).await;
1196            let mut stream = TransportStream::new(framed_json_neutral(stream));
1197            stream
1198                .send(
1199                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
1200                        JsonRpcId::Number(1),
1201                        MCP_TOOLS_LIST,
1202                        serde_json::json!({}),
1203                    )))
1204                    .unwrap(),
1205                )
1206                .await
1207                .unwrap();
1208            let JsonRpcMessage::Response(response) =
1209                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap()
1210            else {
1211                panic!("tools/list should be a response")
1212            };
1213            let tools = response.result.unwrap()["tools"].as_array().unwrap().len();
1214            assert_eq!(
1215                tools, 1,
1216                "a host that cannot collect diagnostics must not offer the tool: \
1217             a client reports the application as broken rather than as a plain \
1218             build"
1219            );
1220        });
1221    }
1222
1223    /// The host names itself in the handshake.
1224    #[test]
1225    fn initialize_reports_the_host_rather_than_the_transport() {
1226        nagoya::block_on(async {
1227            let _guard = CONTROL_TEST_LOCK.write().await;
1228            let bridge: ControlBridge = Arc::new(|_request| {
1229                let answer = Once::new();
1230                answer.fill(DebugResponse::Ack);
1231                answer
1232            });
1233            let server = AgentControlServer::start(
1234                bridge,
1235                Host {
1236                    name: "chuzz-headless".into(),
1237                    version: "1.2.3".into(),
1238                    diagnostics: true,
1239                },
1240            )
1241            .unwrap();
1242
1243            let stream = connect(server.socket_path()).await;
1244            let mut stream = TransportStream::new(framed_json_neutral(stream));
1245            stream
1246                .send(
1247                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
1248                        JsonRpcId::Number(1),
1249                        MCP_INITIALIZE,
1250                        serde_json::json!({"protocolVersion": "2025-06-18"}),
1251                    )))
1252                    .unwrap(),
1253                )
1254                .await
1255                .unwrap();
1256            let JsonRpcMessage::Response(response) =
1257                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap()
1258            else {
1259                panic!("initialize should be a response")
1260            };
1261            let result = response.result.unwrap();
1262            assert_eq!(result["serverInfo"]["name"], "chuzz-headless");
1263            assert_eq!(result["serverInfo"]["version"], "1.2.3");
1264
1265            let descriptor: DebugDescriptor =
1266                serde_json::from_str(&std::fs::read_to_string(server.descriptor_path()).unwrap())
1267                    .unwrap();
1268            assert_eq!(
1269                descriptor.renderer_revision, "1.2.3",
1270                "the descriptor reports the host's version, not the protocol crate's"
1271            );
1272        });
1273    }
1274}