blitz-control-protocol 0.7.3

The Blitz agent-control and diagnostics surface: one vocabulary, one core, two transports
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
use std::fs::{OpenOptions, remove_file};
use std::io::{self, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::{SystemTime, UNIX_EPOCH};

use endpoint_libs::libs::ws::mcp_wire::{INVALID_REQUEST, JsonRpcError};
use endpoint_libs::libs::ws::transport::TransportStream;

use crate::latest::{Flag, Latest, Once};
use endpoint_libs::libs::ws::transport::framed::framed_json_neutral;
use endpoint_libs::libs::ws::transport::nagoya::NagoyaStream;
use endpoint_libs::libs::ws::{MessageStream, StreamError, WireMessage};
use nagoya::reactor::socket::TcpListener as BoundListener;
use nagoya::reactor::{Addr, Reactor, TcpListener, TcpStream, block_on_with};

use crate::{
    AgentControlRequest, DebugDescriptor, DebugEvent, DebugResponse, DebugStream,
    DiagnosticsRequest, IncomingRequest, decode_incoming_value, decode_wire_value,
    encode_diagnostics_event, encode_initialize_response, encode_response, encode_rpc_error,
    encode_tools_list_response, peek_value_request_id,
};

pub enum ControlBridgeRequest {
    Agent(AgentControlRequest),
    Diagnostics(DiagnosticsRequest),
    Targeted(crate::TargetRequest),
}

#[derive(Clone)]
enum EventSource {
    Latest(Arc<Latest<DebugEvent>>),
    Journal(Arc<crate::journal::DiagnosticJournal>),
}

impl EventSource {
    fn sequence(&self) -> u64 {
        match self {
            Self::Latest(events) => events.revision(),
            Self::Journal(events) => events.sequence(),
        }
    }
}

/// Who is answering, and what they can answer.
///
/// # Why the server has to be told
///
/// It used to read this off its own cargo features: the tool list advertised
/// diagnostics when the crate had been built with them, and `serverInfo` said
/// `tauri-runtime-blitz` (now izumo) because that is where the code lived. Both were
/// guesses that happened to hold while there was one host.
///
/// There are three now, and none of them is this crate. The window runtime,
/// the headless browser and an embedder driving a browser in-process each have
/// their own name, their own version and their own answer to whether they can
/// collect a snapshot, and a transport cannot infer any of it. A host that
/// cannot collect diagnostics says so here, and its bridge answers the request
/// with an error rather than the server failing to compile the arm.
#[derive(Debug, Clone)]
pub struct Host {
    /// What the process serving this socket is called. Reported as MCP
    /// `serverInfo.name`.
    pub name: String,
    /// That process's version. Reported as `serverInfo.version` and as the
    /// descriptor's `rendererRevision`.
    pub version: String,
    /// Whether `blitz.diagnostics` is worth advertising in `tools/list`.
    ///
    /// Advertising a tool that answers every call with an error is worse than
    /// omitting it: a client reports the application as broken instead of as a
    /// plain build.
    pub diagnostics: bool,
}

/// How the server reaches whatever is holding the document.
///
/// A plain closure, deliberately: the server binds a socket, frames requests
/// and hands them over, and knows nothing about windows, event loops or Tauri.
/// The crate's own tests have always constructed one from a bare closure with
/// nothing running, which is the proof that a host does not need a window to
/// serve inspection.
///
/// Public so a headless host can serve one. While this was `pub(crate)` the
/// only way to inspect a Blitz document from outside was to open a window,
/// which is what pushed a QA harness into screenshot and tree-file workarounds
/// that could not answer any question involving a click.
pub type ControlBridge =
    Arc<dyn Fn(ControlBridgeRequest) -> Arc<Once<DebugResponse>> + Send + Sync + 'static>;

#[cfg(test)]
pub(crate) static CONTROL_TEST_LOCK: nagoya::sync::RwLock<()> = nagoya::sync::RwLock::new(());

pub struct AgentControlServer {
    descriptor_path: PathBuf,
    socket_path: PathBuf,
    shutdown: Option<Arc<Flag>>,
    thread: Option<JoinHandle<()>>,
    /// Holds deep-profiling collection open while a tool can attach.
    ///
    /// The consumer is out of process, so it cannot hold a session itself and
    /// the server holds one on its behalf. The server's lifetime is the right
    /// one: it exists exactly while the socket is listening, and a per-request
    /// session would be useless, because the frames a snapshot reports were
    /// presented before the request arrived.
    ///
    /// `None` when the profile does not permit sampling, which is the ordinary
    /// case: inspection without deep profiling stays free.
    ///
    /// Only a build that can collect diagnostics has anything to sample, which
    /// is why this is the one place the transport touches blitz at all, and why
    /// it is behind `capture` rather than `server`.
    #[cfg(feature = "capture")]
    _sampling: Option<blitz_shell::DeepProfilingSession>,
}

impl AgentControlServer {
    /// Bind the inspection socket and announce the descriptor.
    ///
    /// Nothing here needs a window: it creates a Unix listener, writes a
    /// descriptor file and serves frames from a thread. A headless host that
    /// owns a document can call this and be inspected exactly like the real
    /// application, which is what lets a QA sweep run with no display server
    /// and still answer questions that require clicking.
    pub fn start(bridge: ControlBridge, host: Host) -> io::Result<Self> {
        Self::start_inner(bridge, host, None)
    }

    /// Start with a bounded latest-value diagnostic event source.
    ///
    /// A watch receiver is deliberate: a slow inspector needs the newest
    /// revision, not an ever-growing queue of every frame it failed to read.
    pub fn start_with_events(
        bridge: ControlBridge,
        host: Host,
        events: Arc<Latest<DebugEvent>>,
    ) -> io::Result<Self> {
        Self::start_inner(bridge, host, Some(EventSource::Latest(events)))
    }

    pub fn start_with_journal(
        bridge: ControlBridge,
        host: Host,
        events: Arc<crate::journal::DiagnosticJournal>,
    ) -> io::Result<Self> {
        Self::start_inner(bridge, host, Some(EventSource::Journal(events)))
    }

    fn start_inner(
        bridge: ControlBridge,
        host: Host,
        events: Option<EventSource>,
    ) -> io::Result<Self> {
        let instance_id = instance_id();
        let descriptor_path = descriptor_path(&instance_id);
        let socket_path = descriptor_path.with_extension("sock");

        // The directory carries the access control, and it is set before
        // anything inside it exists.
        //
        // A mode on the socket cannot be: a Unix socket is created by `bind`
        // already listening, so any mode applied afterwards leaves a window in
        // which the path is connectable. That window was real here. The
        // directory had whatever `create_dir_all` gives, which is world
        // readable under `/tmp`, and the socket's `0600` landed after `bind`.
        //
        // `0700` on the directory closes it without depending on ordering at
        // all: a process that cannot traverse the directory cannot reach the
        // socket whatever the socket's own mode says. The socket keeps `0600`
        // as well, because defence that rests on one check is defence that
        // rests on nobody ever relaxing the directory.
        if let Some(parent) = socket_path.parent() {
            std::fs::create_dir_all(parent)?;
            std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
        }
        let _ = remove_file(&socket_path);

        // Bound here, before `start` returns, so a caller that connects the
        // moment it has the path finds a socket listening. Registering it on a
        // reactor is the server thread's job; binding is not, and doing it
        // there was a race the tests caught immediately.
        let addr = Addr::path(socket_path.as_os_str().as_bytes())
            .map_err(|_| io::Error::other("socket path is not a valid unix address"))?;
        let listener = BoundListener::bind(addr, 128)
            .map_err(|error| io::Error::other(format!("bind: {error:?}")))?;
        std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))?;

        let descriptor = DebugDescriptor {
            protocol_version: crate::DEBUG_PROTOCOL_VERSION,
            pid: std::process::id(),
            instance_id,
            address: format!("unix://{}", socket_path.display()),
            renderer: "blitz".into(),
            renderer_revision: host.version.clone(),
        };
        write_descriptor(&descriptor_path, &descriptor)?;
        reap_dead_descriptors(&descriptor_path);

        let shutdown_flag = Flag::new();
        let shutdown_for_thread = Arc::clone(&shutdown_flag);
        let thread = thread::Builder::new()
            .name("blitz-agent-control".into())
            .spawn(move || run(listener, bridge, host, events, shutdown_for_thread))?;

        Ok(Self {
            descriptor_path,
            socket_path,
            shutdown: Some(shutdown_flag),
            thread: Some(thread),
            // Taken after the socket is listening, so a permitted profile
            // begins collecting for the tool that is now able to attach, and
            // stops again when this server is dropped.
            #[cfg(feature = "capture")]
            _sampling: blitz_shell::begin_deep_profiling(),
        })
    }

    /// Where this server announced itself.
    ///
    /// A headless host prints this so a client can attach to that exact
    /// instance. Searching the descriptor directory instead races every other
    /// instance on the machine, and a component sweep runs one host after
    /// another, so the newest descriptor is not reliably the right one.
    ///
    /// Was `#[cfg(test)]`, because inside this crate the runtime already knows
    /// where it wrote the descriptor and only a test needed to ask.
    pub fn descriptor_path(&self) -> &Path {
        &self.descriptor_path
    }

    /// Reacquire the sampling session after an embedder changes permission.
    ///
    /// The server can start before application settings or CLI overrides are
    /// loaded. In that order `_sampling` begins as `None`; merely granting
    /// permission later does not mutate an already-running server, so every
    /// diagnostic snapshot keeps reporting `script: null` until restart.
    ///
    /// Public because the embedder that owns the setting is no longer in this
    /// crate. It was `pub(crate)`, called by the runtime that lived beside it.
    #[cfg(feature = "capture")]
    pub fn refresh_deep_profiling(&mut self) {
        self._sampling = blitz_shell::begin_deep_profiling();
    }

    /// The socket this server is listening on.
    ///
    /// A caller that already knows the descriptor path can derive this, and
    /// several do; saying it directly is cheaper than agreeing on the
    /// extension by convention.
    pub fn socket_path(&self) -> &Path {
        &self.socket_path
    }
}

impl Drop for AgentControlServer {
    fn drop(&mut self) {
        if let Some(shutdown) = self.shutdown.take() {
            shutdown.raise();
        }
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
        let _ = remove_file(&self.socket_path);
        let _ = remove_file(&self.descriptor_path);
    }
}
fn run(
    listener: BoundListener,
    bridge: ControlBridge,
    host: Host,
    events: Option<EventSource>,
    shutdown: Arc<Flag>,
) {
    // One reactor, owned by this thread, driving the listener and every
    // connection on it. A nagoya socket makes progress only while its own
    // reactor is polled, so the listener and the connections accepted from it
    // have to share one.
    let reactor = match Reactor::local() {
        Ok(reactor) => reactor,
        Err(error) => {
            eprintln!("control socket reactor could not start: {error:?}");
            return;
        }
    };
    let handle = reactor.handle();
    // Registered, not bound: the socket was bound in `start_inner` so that it
    // is listening before `start` returns. Registration is what has to happen
    // here, because it ties the listener to the reactor this thread polls.
    let listener = match TcpListener::from_listener(listener, &handle) {
        Ok(listener) => listener,
        Err(error) => {
            eprintln!("control socket could not register on the reactor: {error:?}");
            return;
        }
    };

    block_on_with(&reactor, async move {
        use futures::StreamExt;
        use futures::future::{Either, select};
        use futures::stream::FuturesUnordered;

        // Connections are held here and polled in place rather than spawned.
        // nagoya's `TaskSet` is the purpose-built runner for non-Send tasks on
        // one thread, but it never removes a finished task's entry: the slot
        // stays so a late wake still has a link to follow. A set fed by
        // unbounded connection churn therefore grows one entry per connection
        // ever accepted. A debug socket that a QA harness reconnects to in a
        // loop is exactly that churn. `FuturesUnordered` drops what finishes.
        let mut connections = FuturesUnordered::new();

        loop {
            let stopping = shutdown.raised();
            let accepted = listener.accept();
            futures::pin_mut!(stopping, accepted);

            // Shutdown is the outer left arm so a raised flag is not stuck
            // behind an accept, or behind a live connection that is also ready.
            let accepted = if connections.is_empty() {
                match select(stopping, accepted).await {
                    Either::Left(_) => break,
                    Either::Right((accepted, _)) => accepted,
                }
            } else {
                let progress = select(accepted, connections.next());
                futures::pin_mut!(progress);
                match select(stopping, progress).await {
                    Either::Left(_) => break,
                    Either::Right((Either::Left((accepted, _)), _)) => accepted,
                    // A connection finished and the set has already dropped it.
                    Either::Right((Either::Right(_), _)) => continue,
                }
            };

            let Ok((stream, _)) = accepted else {
                break;
            };
            connections.push(handle_connection(
                stream,
                Arc::clone(&bridge),
                host.clone(),
                events.clone(),
            ));
        }
    });
}

enum ConnectionInput {
    Message(Option<Result<WireMessage, StreamError>>),
    /// The newest event, carried directly. A `Latest` has no sender to drop,
    /// so there is no receive error to represent.
    Event(Box<DebugEvent>),
    Journal(crate::journal::JournalItem),
}

fn stream_wants_event(streams: &[DebugStream], event: &DebugEvent) -> bool {
    match event {
        DebugEvent::DiagnosticLoss { stream, .. } => streams.contains(stream),
        DebugEvent::Snapshot(_) => streams.contains(&DebugStream::Snapshots),
        DebugEvent::Metrics(_) => streams.contains(&DebugStream::Metrics),
        DebugEvent::Console(_) => streams.contains(&DebugStream::Console),
        DebugEvent::RuntimeError(_) => streams.contains(&DebugStream::RuntimeErrors),
        DebugEvent::PaintCommitted { .. } => streams.contains(&DebugStream::Paint),
    }
}

async fn handle_connection(
    stream: TcpStream,
    bridge: ControlBridge,
    host: Host,
    events: Option<EventSource>,
) {
    let mut stream = TransportStream::new(framed_json_neutral(NagoyaStream::new(stream)));
    let mut observed = Vec::<DebugStream>::new();
    // This reader's position in the event stream. Held here rather than in the
    // slot, because two connections read the same `Latest` from different
    // places and one catching up must not move the other.
    let mut seen = events.as_ref().map_or(0, EventSource::sequence);
    let mut target_options = crate::TargetOptions::default();
    loop {
        let input = if observed.is_empty() {
            ConnectionInput::Message(stream.recv().await)
        } else if let Some(EventSource::Journal(journal)) = events.as_ref() {
            use futures::future::{Either, select};
            let message = stream.recv();
            let changed = journal.next_after(seen);
            futures::pin_mut!(message, changed);
            match select(message, changed).await {
                Either::Left((message, _)) => ConnectionInput::Message(message),
                Either::Right((item, _)) => {
                    seen = item.sequence();
                    ConnectionInput::Journal(item)
                }
            }
        } else if let Some(EventSource::Latest(latest)) = events.as_ref() {
            use futures::future::{Either, select};
            let message = stream.recv();
            let changed = latest.changed_since(seen);
            futures::pin_mut!(message, changed);
            match select(message, changed).await {
                Either::Left((message, _)) => ConnectionInput::Message(message),
                Either::Right(((event, revision), _)) => {
                    seen = revision;
                    match event {
                        Some(event) => ConnectionInput::Event(Box::new(event)),
                        None => continue,
                    }
                }
            }
        } else {
            ConnectionInput::Message(stream.recv().await)
        };

        let message = match input {
            ConnectionInput::Journal(item) => {
                let frame = match item {
                    crate::journal::JournalItem::Overflow { first, last } => {
                        crate::encode_diagnostic_overflow(first, last)
                    }
                    crate::journal::JournalItem::Event(record) => {
                        let selected = target_options.all_targets
                            || record.context.target_id
                                == target_options.target.as_ref().map_or_else(
                                    crate::TargetId::chrome,
                                    crate::TargetSelector::id,
                                );
                        if !selected || !stream_wants_event(&observed, &record.event) {
                            continue;
                        }
                        crate::encode_target_event(&record)
                    }
                };
                let frame = frame.unwrap_or_else(|_| {
                    crate::encode_diagnostic_overflow(seen, seen)
                        .expect("the bounded overflow notification is serializable")
                });
                if stream.send(frame).await.is_err() {
                    break;
                }
                continue;
            }
            ConnectionInput::Event(event) => {
                if !stream_wants_event(&observed, &event) {
                    continue;
                }
                let Ok(frame) = encode_diagnostics_event(&event) else {
                    continue;
                };
                if stream.send(frame).await.is_err() {
                    break;
                }
                continue;
            }
            ConnectionInput::Message(Some(message)) => message,
            ConnectionInput::Message(None) => break,
        };
        let response = match message {
            Ok(message) => match decode_wire_value(message) {
                Ok(value) => {
                    // Recover the id before typed decoding consumes the parsed
                    // value. The previous path parsed the complete request once
                    // for this id and again for the request itself.
                    let request_id = peek_value_request_id(&value);
                    match decode_incoming_value(value) {
                        Ok(IncomingRequest::Initialize { id }) => {
                            encode_initialize_response(id, &host.name, &host.version)
                        }
                        Ok(IncomingRequest::Initialized) => continue,
                        Ok(IncomingRequest::ToolsList { id }) => {
                            encode_tools_list_response(id, host.diagnostics)
                        }
                        Ok(IncomingRequest::Targeted { id, request }) => {
                            let streams = match &request.command {
                                crate::TargetCommand::Diagnostics(
                                    DiagnosticsRequest::Observe { streams },
                                ) => Some(streams.clone()),
                                _ => None,
                            };
                            let options = request.options.clone();
                            let baseline = events.as_ref().map_or(0, EventSource::sequence);
                            let validation = request.validate_options().and_then(|()| {
                                if streams.is_some()
                                    && options
                                        .after_sequence
                                        .is_some_and(|sequence| sequence > baseline)
                                {
                                    Err(crate::target::error(
                                        "invalidSequence",
                                        "afterSequence exceeds the current journal sequence",
                                    ))
                                } else {
                                    Ok(())
                                }
                            });
                            let response = match validation {
                                Err(error) => DebugResponse::Error(error),
                                Ok(()) => bridge(ControlBridgeRequest::Targeted(request))
                                    .recv()
                                    .await
                                    .unwrap_or_else(|| {
                                        DebugResponse::Error(crate::target::error(
                                            "bridgeClosed",
                                            "the UI-thread bridge closed",
                                        ))
                                    }),
                            };
                            if matches!(response.unscoped(), DebugResponse::Ack)
                                && let Some(streams) = streams
                            {
                                observed = streams;
                                seen = options.after_sequence.unwrap_or(baseline);
                                target_options = options;
                            }
                            encode_response(id, &response)
                        }
                        Ok(IncomingRequest::Agent { id, request }) => {
                            let response = bridge(ControlBridgeRequest::Agent(request))
                                .recv()
                                .await
                                .unwrap_or_else(|| {
                                    DebugResponse::Error(crate::DebugError {
                                        code: "bridgeClosed".into(),
                                        message: "the UI-thread control bridge closed".into(),
                                    })
                                });
                            encode_response(id, &response)
                        }
                        // The protocol defines diagnostics unconditionally, and
                        // so does this transport. Whether they can be collected
                        // is the host's answer, given in `Host::diagnostics`
                        // for the tool list and in its bridge for a call that
                        // arrives anyway.
                        Ok(IncomingRequest::Diagnostics {
                            id,
                            request: DiagnosticsRequest::Observe { streams },
                        }) => {
                            let baseline = events.as_ref().map_or(0, EventSource::sequence);
                            let response =
                                if matches!(events.as_ref(), Some(EventSource::Journal(_))) {
                                    bridge(ControlBridgeRequest::Targeted(crate::TargetRequest {
                                        options: crate::TargetOptions::default(),
                                        command: crate::TargetCommand::Diagnostics(
                                            DiagnosticsRequest::Observe {
                                                streams: streams.clone(),
                                            },
                                        ),
                                    }))
                                    .recv()
                                    .await
                                    .unwrap_or_else(|| {
                                        DebugResponse::Error(crate::target::error(
                                            "bridgeClosed",
                                            "the UI-thread bridge closed",
                                        ))
                                    })
                                } else {
                                    DebugResponse::Ack
                                };
                            if matches!(response.unscoped(), DebugResponse::Ack) {
                                observed = streams;
                                seen = baseline;
                                target_options = crate::TargetOptions::default();
                            }
                            encode_response(id, &response)
                        }
                        Ok(IncomingRequest::Diagnostics { id, request }) => {
                            let response = bridge(ControlBridgeRequest::Diagnostics(request))
                                .recv()
                                .await
                                .unwrap_or_else(|| {
                                    DebugResponse::Error(crate::DebugError {
                                        code: "bridgeClosed".into(),
                                        message: "the UI-thread diagnostics bridge closed".into(),
                                    })
                                });
                            encode_response(id, &response)
                        }
                        Err(error) => encode_rpc_error(
                            request_id,
                            JsonRpcError::new(INVALID_REQUEST, error.to_string()),
                        ),
                    }
                }
                Err(error) => {
                    encode_rpc_error(None, JsonRpcError::new(INVALID_REQUEST, error.to_string()))
                }
            },
            // A transport error is not a bad request: the framing is broken or
            // the peer is gone, and the next read returns the same error
            // immediately. Answering and continuing spun this task at a full
            // core for the life of the process, one per client that ever
            // disconnected, which is most of them. Measured on an idle app:
            // 0.0% CPU without the control server, 55-76% with it after a few
            // tools had connected and gone.
            //
            // So answer once, best effort, then stop reading this connection.
            Err(error) => {
                let farewell =
                    encode_rpc_error(None, JsonRpcError::new(INVALID_REQUEST, error.to_string()));
                if let Ok(farewell) = farewell {
                    let _ = stream.send(farewell).await;
                }
                break;
            }
        };
        let response = response.unwrap_or_else(|error| {
            encode_rpc_error(
                None,
                JsonRpcError::new(
                    INVALID_REQUEST,
                    format!("could not encode response: {error}"),
                ),
            )
            .expect("the fallback JSON-RPC error is serializable")
        });
        if stream.send(response).await.is_err() {
            break;
        }
    }
}

fn instance_id() -> String {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("{}-{nanos:x}", std::process::id())
}

/// Whether a pid still names a live process.
///
/// `kill(pid, 0)` without a libc dependency, and `/proc` does not exist on
/// macOS. A `ps` that cannot be run at all reports "live", because deleting
/// another instance's descriptor on a bad guess is far worse than keeping a
/// stale file.
fn pid_is_live(pid: u32) -> bool {
    std::process::Command::new("ps")
        .args(["-p", &pid.to_string()])
        .output()
        .map(|out| out.status.success())
        .unwrap_or(true)
}

/// Delete descriptors whose process is gone.
///
/// The name carries a pid and a nanosecond stamp, so every launch leaves a new
/// pair behind and nothing ever removed them: a developer machine accumulates
/// them indefinitely, and one here had **99**. `Drop` cleans up an orderly
/// exit, but a crash, a `kill -9`, or a rebuild that unlinks the socket under a
/// running instance all skip it.
///
/// That is not merely untidy. A tool discovering the current descriptor has to
/// distinguish them, and a directory full of dead entries
/// is what makes "attached to a stale socket and reported numbers for a process
/// nobody is looking at" a routine failure rather than a rare one.
///
/// Only entries whose pid is dead are removed, so concurrent instances are left
/// strictly alone — and this one's own descriptor is skipped by path, since it
/// has just been written and its pid is obviously live.
fn reap_dead_descriptors(own: &Path) {
    reap_dead_descriptors_with(own, pid_is_live);
}

fn reap_dead_descriptors_with(own: &Path, is_live: impl Fn(u32) -> bool) {
    let Some(dir) = own.parent() else { return };
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path == own || path.extension().is_none_or(|ext| ext != "json") {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        let Ok(descriptor) = serde_json::from_str::<DebugDescriptor>(&text) else {
            continue;
        };
        if is_live(descriptor.pid) {
            continue;
        }
        let _ = remove_file(path.with_extension("sock"));
        let _ = remove_file(&path);
    }
}

fn descriptor_path(instance_id: &str) -> PathBuf {
    std::env::temp_dir()
        .join("tauri-blitz-agent")
        .join(format!("{instance_id}.json"))
}

fn write_descriptor(path: &Path, descriptor: &DebugDescriptor) -> io::Result<()> {
    let content = serde_json::to_string_pretty(descriptor).map_err(io::Error::other)?;
    if contains_secret_environment_value(&content) {
        return Err(io::Error::other(
            "refusing to write a descriptor that contains an environment secret",
        ));
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .mode(0o600)
        .open(path)?;
    file.write_all(content.as_bytes())?;
    file.write_all(b"\n")?;
    file.sync_all()
}

fn contains_secret_environment_value(content: &str) -> bool {
    let variables: Vec<(String, String)> = std::env::vars_os()
        .filter_map(|(name, value)| {
            Some((
                name.to_string_lossy().to_ascii_uppercase(),
                value.into_string().ok()?,
            ))
        })
        .collect();
    let has_password = variables.iter().any(|(name, _)| {
        name.contains("PASSWORD") || name.contains("PASSPHRASE") || name.ends_with("_PASS")
    });

    variables.iter().any(|(name, value)| {
        if value.is_empty() {
            return false;
        }
        let named_secret = name.contains("PASSWORD")
            || name.contains("PASSPHRASE")
            || name.ends_with("_PASS")
            || name.contains("SEED")
            || name.contains("PRIVATE_KEY")
            || name.ends_with("_KEY")
            || name == "KEY"
            || name.contains("TOKEN")
            || name.contains("SECRET")
            || name.contains("COOKIE")
            || name.contains("JWT")
            || name.contains("SESSION")
            || name.starts_with("AWS_")
            || name.contains("DOPPLER")
            || name.contains("HONEY")
            || name.contains("HOOK");
        let paired_username = has_password
            && (name.contains("USERNAME") || name == "USER" || name.ends_with("_USER"));
        if !named_secret && !paired_username {
            return false;
        }

        if content.contains(value) {
            return true;
        }
        serde_json::to_string(value)
            .is_ok_and(|quoted| quoted.len() > 2 && content.contains(&quoted[1..quoted.len() - 1]))
    })
}

#[cfg(test)]
mod tests {
    use endpoint_libs::libs::ws::mcp_wire::{JsonRpcId, JsonRpcMessage, JsonRpcRequest};

    use super::*;
    use crate::{
        AgentAction, AgentControlRequest, DebugResponse, MCP_INITIALIZE, MCP_TOOLS_LIST,
        decode_response, decode_rpc, encode_agent_request, encode_rpc,
    };
    use crate::{
        DebugEvent, DebugSnapshot, DebugStream, DiagnosticsRequest, RendererMetrics, RevisionSet,
        SnapshotRequest, decode_diagnostics_event, encode_diagnostics_request,
    };

    /// A host that can do everything, for the tests that are about the
    /// transport rather than about what is on the other side of it.
    /// Connect to a running server's socket, on a reactor of the caller's own.
    ///
    /// A test drives both ends: the server polls its socket on the thread it
    /// spawned, and this is the client side, which needs a reactor of its own
    /// because a nagoya socket only makes progress while the reactor it was
    /// created on is polled. `Reactor::start` owns a thread, so the connection
    /// keeps being driven while the test awaits a reply on it.
    async fn connect(path: &Path) -> NagoyaStream {
        static CLIENT_REACTOR: std::sync::OnceLock<(Reactor, nagoya::reactor::Handle)> =
            std::sync::OnceLock::new();
        let (_, handle) = CLIENT_REACTOR.get_or_init(|| {
            let reactor = Reactor::start().expect("client reactor");
            let handle = reactor.handle();
            (reactor, handle)
        });
        let addr = Addr::path(path.as_os_str().as_bytes()).expect("socket path");
        let stream = TcpStream::connect(addr, handle).await.expect("connect");
        NagoyaStream::new(stream)
    }

    fn test_host() -> Host {
        Host {
            name: "test-host".into(),
            version: "0.0.0".into(),
            diagnostics: true,
        }
    }

    #[test]
    fn local_server_is_mcp_compatible_and_needs_no_session_or_token() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            let bridge: ControlBridge = Arc::new(|request| {
                let answer = Once::new();
                assert!(matches!(
                    request,
                    ControlBridgeRequest::Agent(AgentControlRequest::Act(AgentAction::Click {
                        node_id: 42
                    }))
                ));
                answer.fill(DebugResponse::Ack);
                answer
            });
            let server = AgentControlServer::start(bridge, test_host()).unwrap();
            assert!(server.descriptor_path().is_file());
            assert_eq!(
                server
                    .descriptor_path()
                    .metadata()
                    .unwrap()
                    .permissions()
                    .mode()
                    & 0o777,
                0o600
            );

            let stream = connect(server.socket_path()).await;
            let mut stream = TransportStream::new(framed_json_neutral(stream));
            stream
                .send(
                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
                        JsonRpcId::Number(1),
                        MCP_INITIALIZE,
                        serde_json::json!({"protocolVersion": "2025-06-18"}),
                    )))
                    .unwrap(),
                )
                .await
                .unwrap();
            assert!(matches!(
                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap(),
                JsonRpcMessage::Response(_)
            ));
            stream
                .send(
                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
                        JsonRpcId::Number(2),
                        MCP_TOOLS_LIST,
                        serde_json::json!({}),
                    )))
                    .unwrap(),
                )
                .await
                .unwrap();
            assert!(matches!(
                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap(),
                JsonRpcMessage::Response(_)
            ));
            let id = JsonRpcId::Number(42);
            stream
                .send(
                    encode_agent_request(
                        id.clone(),
                        &AgentControlRequest::Act(AgentAction::Click { node_id: 42 }),
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
            let response = stream.recv().await.unwrap().unwrap();
            assert_eq!(decode_response(response).unwrap(), (id, DebugResponse::Ack));

            let second = connect(server.socket_path()).await;
            let mut second = TransportStream::new(framed_json_neutral(second));
            let id = JsonRpcId::String("second-observer".into());
            second
                .send(
                    encode_agent_request(
                        id.clone(),
                        &AgentControlRequest::Act(AgentAction::Click { node_id: 42 }),
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(
                decode_response(second.recv().await.unwrap().unwrap()).unwrap(),
                (id, DebugResponse::Ack)
            );

            drop(server);
        });
    }

    #[test]
    fn diagnostics_metrics_reach_the_runtime_bridge_over_mcp() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            let bridge: ControlBridge = Arc::new(|request| {
                let answer = Once::new();
                assert!(matches!(
                    request,
                    ControlBridgeRequest::Diagnostics(DiagnosticsRequest::Metrics)
                ));
                answer.fill(DebugResponse::Metrics(RendererMetrics {
                    resident_bytes: Some(8192),
                    ..Default::default()
                }));
                answer
            });
            let server = AgentControlServer::start(bridge, test_host()).unwrap();
            let stream = connect(server.socket_path()).await;
            let mut stream = TransportStream::new(framed_json_neutral(stream));
            let id = JsonRpcId::Number(91);

            stream
                .send(encode_diagnostics_request(id.clone(), &DiagnosticsRequest::Metrics).unwrap())
                .await
                .unwrap();

            assert_eq!(
                decode_response(stream.recv().await.unwrap().unwrap()).unwrap(),
                (
                    id,
                    DebugResponse::Metrics(RendererMetrics {
                        resident_bytes: Some(8192),
                        ..Default::default()
                    })
                )
            );
        });
    }

    #[test]
    fn observe_pushes_only_requested_latest_value_events() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            let bridge: ControlBridge = Arc::new(|_request| {
                panic!("observe is connection-local and must not reach the UI bridge")
            });
            let events = Latest::new();
            let server =
                AgentControlServer::start_with_events(bridge, test_host(), Arc::clone(&events))
                    .unwrap();
            let stream = connect(server.socket_path()).await;
            let mut stream = TransportStream::new(framed_json_neutral(stream));
            let id = JsonRpcId::Number(92);

            stream
                .send(
                    encode_diagnostics_request(
                        id.clone(),
                        &DiagnosticsRequest::Observe {
                            streams: vec![DebugStream::Paint],
                        },
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(
                decode_response(stream.recv().await.unwrap().unwrap()).unwrap(),
                (id, DebugResponse::Ack)
            );

            let event = DebugEvent::PaintCommitted { revision: 7 };
            events.set(event.clone()).await;
            assert_eq!(
                decode_diagnostics_event(stream.recv().await.unwrap().unwrap()).unwrap(),
                event
            );
        });
    }

    #[test]
    fn large_snapshot_keeps_the_socket_open_for_follow_up_requests() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            const LARGE_DOM_BYTES: usize = 9 * 1024 * 1024;
            let bridge: ControlBridge = Arc::new(|request| {
                let answer = Once::new();
                let response = match request {
                    ControlBridgeRequest::Diagnostics(DiagnosticsRequest::Snapshot(_)) => {
                        DebugResponse::Snapshot(DebugSnapshot {
                            revisions: RevisionSet::default(),
                            active_window: Some("main".into()),
                            active_element: None,
                            dom: Some(serde_json::Value::String("x".repeat(LARGE_DOM_BYTES))),
                            layout: None,
                            computed_style: None,
                            metrics: RendererMetrics::default(),
                        })
                    }
                    ControlBridgeRequest::Diagnostics(DiagnosticsRequest::Metrics) => {
                        DebugResponse::Metrics(RendererMetrics {
                            resident_bytes: Some(4096),
                            ..Default::default()
                        })
                    }
                    _ => panic!("unexpected request"),
                };
                answer.fill(response);
                answer
            });
            let server = AgentControlServer::start(bridge, test_host()).unwrap();
            let stream = connect(server.socket_path()).await;
            let mut stream = TransportStream::new(framed_json_neutral(stream));

            let snapshot_id = JsonRpcId::Number(92);
            stream
                .send(
                    encode_diagnostics_request(
                        snapshot_id.clone(),
                        &DiagnosticsRequest::Snapshot(SnapshotRequest {
                            include_dom: true,
                            include_layout: false,
                            include_computed_style: false,
                            node_ids: Vec::new(),
                        }),
                    )
                    .unwrap(),
                )
                .await
                .unwrap();
            let (response_id, response) =
                decode_response(stream.recv().await.unwrap().unwrap()).unwrap();
            assert_eq!(response_id, snapshot_id);
            let DebugResponse::Snapshot(snapshot) = response else {
                panic!("expected a diagnostic snapshot")
            };
            assert_eq!(
                snapshot.dom.unwrap().as_str().unwrap().len(),
                LARGE_DOM_BYTES
            );

            let metrics_id = JsonRpcId::Number(93);
            stream
                .send(
                    encode_diagnostics_request(metrics_id.clone(), &DiagnosticsRequest::Metrics)
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(
                decode_response(stream.recv().await.unwrap().unwrap()).unwrap(),
                (
                    metrics_id,
                    DebugResponse::Metrics(RendererMetrics {
                        resident_bytes: Some(4096),
                        ..Default::default()
                    })
                )
            );
        });
    }

    #[test]
    fn initialize_payload_uses_json_rpc() {
        let message =
            encode_initialize_response(JsonRpcId::Number(1), "test-host", "0.1.0").unwrap();
        let WireMessage::Text(payload) = message else {
            panic!("initialize response must be text")
        };
        let decoded: JsonRpcMessage = serde_json::from_str(&payload).unwrap();
        assert!(matches!(decoded, JsonRpcMessage::Response(_)));
    }

    /**
     * A dead instance's descriptor goes; a live one's stays.
     *
     * The filename carries a pid and a nanosecond stamp, so every launch leaves
     * a new pair behind and nothing removed them — one machine had 99. `Drop`
     * handles an orderly exit, but a crash, a `kill -9`, or a rebuild that
     * unlinks the socket under a running instance all skip it. A tool then has
     * to guess which is current, which is how attaching to a stale socket
     * became routine.
     *
     * The asymmetry is the whole point: reaping too eagerly would delete a
     * concurrent instance's descriptor, which is worse than leaving litter.
     */
    #[test]
    fn reaping_removes_dead_descriptors_and_spares_live_ones() {
        let dir = std::env::temp_dir().join(format!(
            "blitz-reap-{}-{:x}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).expect("scratch directory is created");

        let write = |name: &str, pid: u32| {
            let path = dir.join(format!("{name}.json"));
            write_descriptor(
                &path,
                &DebugDescriptor {
                    protocol_version: crate::DEBUG_PROTOCOL_VERSION,
                    pid,
                    instance_id: name.into(),
                    address: format!("unix://{}", dir.join(format!("{name}.sock")).display()),
                    renderer: "blitz".into(),
                    renderer_revision: "0.0.0".into(),
                },
            )
            .expect("descriptor is written");
            std::fs::write(dir.join(format!("{name}.sock")), b"").expect("socket stub is written");
            path
        };

        // Liveness is injected here because process inspection may be denied by
        // the test sandbox. This test owns descriptor cleanup, not `ps` itself.
        let own = write("own", std::process::id());
        let live = write("live", 1);
        let dead = write("dead", 2);

        reap_dead_descriptors_with(&own, |pid| pid == std::process::id() || pid == 1);

        assert!(own.exists(), "the caller's own descriptor is never reaped");
        assert!(live.exists(), "a live instance must keep its descriptor");
        assert!(!dead.exists(), "a dead instance's descriptor is removed");
        assert!(
            !dir.join("dead.sock").exists(),
            "the orphaned socket goes with it"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }
    /// A gone server advertises nothing.
    ///
    /// Carried over from the browser's own control server, which is being
    /// deleted in favour of this one: it asserted that dropping the server
    /// removes both files, and losing that assertion would lose the property.
    /// Leaving either behind advertises a host that is not there, and a client
    /// that finds a stale descriptor attaches to a socket nobody is serving.
    #[test]
    fn teardown_removes_the_socket_and_the_descriptor() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            let bridge: ControlBridge = Arc::new(|_request| {
                let answer = Once::new();
                answer.fill(DebugResponse::Ack);
                answer
            });
            let server = AgentControlServer::start(bridge, test_host()).unwrap();
            let descriptor = server.descriptor_path().to_path_buf();
            let socket = server.socket_path().to_path_buf();
            assert!(descriptor.is_file(), "the descriptor was not published");
            assert!(socket.exists(), "the socket was not bound");

            drop(server);

            assert!(!socket.exists(), "the socket outlived the server");
            assert!(
                !descriptor.exists(),
                "the descriptor outlived the server, so a client can still find it"
            );
        });
    }

    /// What the tool list says is the host's answer, not this crate's.
    ///
    /// It used to be `cfg!(feature = "diagnostics")` read off the crate that
    /// happened to contain the server. There are three hosts now and the
    /// transport is in none of them.
    #[test]
    fn a_host_that_cannot_collect_diagnostics_does_not_advertise_them() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            let bridge: ControlBridge = Arc::new(|_request| {
                let answer = Once::new();
                answer.fill(DebugResponse::Ack);
                answer
            });
            let server = AgentControlServer::start(
                bridge,
                Host {
                    name: "plain-host".into(),
                    version: "9.9.9".into(),
                    diagnostics: false,
                },
            )
            .unwrap();

            let stream = connect(server.socket_path()).await;
            let mut stream = TransportStream::new(framed_json_neutral(stream));
            stream
                .send(
                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
                        JsonRpcId::Number(1),
                        MCP_TOOLS_LIST,
                        serde_json::json!({}),
                    )))
                    .unwrap(),
                )
                .await
                .unwrap();
            let JsonRpcMessage::Response(response) =
                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap()
            else {
                panic!("tools/list should be a response")
            };
            let tools = response.result.unwrap()["tools"].as_array().unwrap().len();
            assert_eq!(
                tools, 1,
                "a host that cannot collect diagnostics must not offer the tool: \
             a client reports the application as broken rather than as a plain \
             build"
            );
        });
    }

    /// The host names itself in the handshake.
    #[test]
    fn initialize_reports_the_host_rather_than_the_transport() {
        nagoya::block_on(async {
            let _guard = CONTROL_TEST_LOCK.write().await;
            let bridge: ControlBridge = Arc::new(|_request| {
                let answer = Once::new();
                answer.fill(DebugResponse::Ack);
                answer
            });
            let server = AgentControlServer::start(
                bridge,
                Host {
                    name: "chuzz-headless".into(),
                    version: "1.2.3".into(),
                    diagnostics: true,
                },
            )
            .unwrap();

            let stream = connect(server.socket_path()).await;
            let mut stream = TransportStream::new(framed_json_neutral(stream));
            stream
                .send(
                    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
                        JsonRpcId::Number(1),
                        MCP_INITIALIZE,
                        serde_json::json!({"protocolVersion": "2025-06-18"}),
                    )))
                    .unwrap(),
                )
                .await
                .unwrap();
            let JsonRpcMessage::Response(response) =
                decode_rpc(stream.recv().await.unwrap().unwrap()).unwrap()
            else {
                panic!("initialize should be a response")
            };
            let result = response.result.unwrap();
            assert_eq!(result["serverInfo"]["name"], "chuzz-headless");
            assert_eq!(result["serverInfo"]["version"], "1.2.3");

            let descriptor: DebugDescriptor =
                serde_json::from_str(&std::fs::read_to_string(server.descriptor_path()).unwrap())
                    .unwrap();
            assert_eq!(
                descriptor.renderer_revision, "1.2.3",
                "the descriptor reports the host's version, not the protocol crate's"
            );
        });
    }
}