neovide 0.17.3

Neovide: No Nonsense Neovim Gui
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
//! Establishes RPC sessions with embedded or already running Neovim servers. The
//! transport comes from `NeovimInstance`. `NeovimSession::new` performs the
//! handshake and owns the RPC loop. After UI attachment, `bridge::run` watches
//! that loop and any child. A UI detach notification also ends the RPC loop,
//! without waiting for the transport to close. For an embedded server, the
//! child and stderr reader move to a supervisor that can outlive UI detachment
//! after `:connect`. The RPC setup adapts the Tokio creation code from nvim-rs.
//! https://github.com/KillTheMule/nvim-rs/blob/master/src/create/tokio.rs

#[cfg(debug_assertions)]
use core::fmt;
use std::collections::VecDeque;
use std::io::Error;
use std::io::Result;
#[cfg(target_os = "windows")]
use std::process::Child;
use std::process::ExitStatus;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;

use anyhow::Context;
use nvim_rs::Handler;
use nvim_rs::Value;
use nvim_rs::call_args;
use nvim_rs::error::CallError;
use nvim_rs::error::LoopError;
use nvim_rs::neovim::Neovim;
use nvim_rs::rpc::IntoVal;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::io::BufReader;
use tokio::io::split;
use tokio::net::TcpStream;
#[cfg(not(target_os = "windows"))]
use tokio::process::Child;
use tokio::process::Command;
use tokio::spawn;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tokio_util::compat::TokioAsyncWriteCompatExt;

pub type NeovimWriter = Box<dyn futures::AsyncWrite + Send + Unpin + 'static>;

/// Stderr lines retained for reporting a failed handshake. The reader logs
/// every line and keeps draining after an ordinary `:connect` leaves the
/// embedded child running.
const MAX_STDERR_LINES: usize = 128;

type BoxedReader = Box<dyn AsyncRead + Send + Unpin + 'static>;
type BoxedWriter = Box<dyn AsyncWrite + Send + Unpin + 'static>;

#[derive(Clone)]
struct SessionHandler<H> {
    handler: H,
    detach: Arc<Notify>,
    connect: Arc<AtomicBool>,
}

impl<H> SessionHandler<H> {
    fn observer(&self, events: &[Value]) -> bool {
        for event in events {
            if is_connect_event(event) {
                self.connect.store(true, Ordering::Relaxed);
            }

            let seen = self.connect.load(Ordering::Relaxed);
            if is_detach_event(event, seen) {
                return true;
            }
        }

        false
    }
}

impl<H: Handler<Writer = NeovimWriter>> Handler for SessionHandler<H> {
    type Writer = NeovimWriter;

    async fn handle_request(
        &self,
        name: String,
        args: Vec<Value>,
        neovim: Neovim<Self::Writer>,
    ) -> std::result::Result<Value, Value> {
        self.handler.handle_request(name, args, neovim).await
    }

    async fn handle_notify(&self, name: String, args: Vec<Value>, neovim: Neovim<Self::Writer>) {
        let should_detach = name == "redraw" && self.observer(&args);

        // Forward the whole batch before signaling detach so any connect event
        // reaches the handler before the RPC loop can close the current session.
        self.handler.handle_notify(name, args, neovim).await;

        if should_detach {
            self.detach.notify_one();
        }
    }
}

/// Detects a `connect` call in a redraw entry by its string address argument.
/// Empty addresses count and extra arguments are ignored. The caller keeps
/// this evidence across redraw batches to distinguish legacy detachment from
/// `:cquit 0`, since both can send an `error_exit` call with a zero status.
fn is_connect_event(event: &Value) -> bool {
    let Value::Array(event) = event else { return false };
    let [name, calls @ ..] = event.as_slice() else { return false };
    if name.as_str() != Some("connect") {
        return false;
    }

    calls.iter().any(|call| {
        let Value::Array(arguments) = call else { return false };
        let [address, ..] = arguments.as_slice() else { return false };
        address.as_str().is_some()
    })
}

/// Reads redraw entries shaped as [name, [arguments...], ...]. Note that a zero
/// status can also mean `:cquit 0` so detachment needs a preceding connect event
/// or a nonempty server address. Ambiguous exits keep RPC alive for the pending
/// `VimLeavePre` quit request and finish when the transport finally closes.
fn is_detach_event(event: &Value, connect: bool) -> bool {
    let Value::Array(event) = event else { return false };
    let [name, calls @ ..] = event.as_slice() else { return false };
    if name.as_str() != Some("error_exit") {
        return false;
    }

    calls.iter().any(|call| {
        let Value::Array(args) = call else { return false };
        let [status, ..] = args.as_slice() else { return false };
        if status.as_i64() != Some(0) {
            return false;
        }
        connect || args.get(1).and_then(Value::as_str).is_some_and(|addr| !addr.is_empty())
    })
}

fn is_windows_drive_path(address: &str) -> bool {
    let bytes = address.as_bytes();
    bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/'
}

/// Classify an address as TCP using `socket_address_tcp_host_end` from Neovim.
/// A colon after the first character marks TCP. A drive path such as
/// `C:/nvim/socket` is local. An address beginning with `:` is local too.
fn is_tcp_address(address: &str) -> bool {
    if is_windows_drive_path(address) {
        return false;
    }
    address.rfind(':').is_some_and(|index| index > 0)
}

/// Turn a bare pipe name or one using forward slashes into a Windows pipe path.
/// Canonical `\\.\pipe\nvim.123` names and drive paths such as `C:/nvim/socket`
/// pass through unchanged.
#[cfg(any(target_os = "windows", test))]
fn normalize_windows_pipe_address(address: String) -> String {
    const PIPE_PREFIX: &str = r"\\.\pipe\";
    const FORWARD_SLASH_PIPE_PREFIX: &str = "//./pipe/";

    if address.starts_with(PIPE_PREFIX) || is_windows_drive_path(&address) {
        address
    } else if let Some(name) = address.strip_prefix(FORWARD_SLASH_PIPE_PREFIX) {
        format!("{PIPE_PREFIX}{name}")
    } else {
        format!("{PIPE_PREFIX}{address}")
    }
}

/// A handshaken RPC connection, before or after `nvim_ui_attach`. `NeovimSession::new`
/// creates it. `bridge::run` consumes it after attachment. A server connection
/// has no child or stderr reader. An embedded connection holds both until
/// `supervise_process` transfers them to a separate task.
pub struct NeovimSession {
    pub neovim: Neovim<NeovimWriter>,
    pub io_handle: JoinHandle<std::result::Result<(), Box<LoopError>>>,
    pub neovim_process: Option<Child>,
    pub stderr_task: Option<JoinHandle<Vec<String>>>,
    #[cfg(not(target_os = "windows"))]
    pub stdin_fd: Option<rustix::fd::OwnedFd>,
}

#[cfg(debug_assertions)]
impl fmt::Debug for NeovimSession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NeovimSession").field("io_handle", &self.io_handle).finish()
    }
}

/// Keep an embedded child and its stderr reader alive beyond the UI channel.
/// `bridge::run` can drop the returned join handle when RPC closes. While the
/// runtime lives, the task continues waiting to reap the child. Once the child
/// exits, the task gives the stderr reader 500 ms to finish, then aborts it if
/// it is still running.
fn spawn_process_supervisor(
    mut child: Child,
    stderr_task: Option<JoinHandle<Vec<String>>>,
) -> JoinHandle<Result<ExitStatus>> {
    tokio::spawn(async move {
        // On Windows, this is std::process::Child. Polling avoids tying up a
        // blocking thread while an embedded server continues after :connect.
        // The supervisor remains alive to reap it when it eventually exits.
        #[cfg(target_os = "windows")]
        let status = loop {
            if let Some(status) = child.try_wait()? {
                break Ok(status);
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        };

        #[cfg(not(target_os = "windows"))]
        let status = child.wait().await;

        if let Some(mut stderr_task) = stderr_task
            && tokio::time::timeout(Duration::from_millis(500), &mut stderr_task).await.is_err()
        {
            stderr_task.abort();
        }

        status
    })
}

impl NeovimSession {
    /// Transfer an embedded child and stderr reader to their supervisor.
    /// Returns `None` for a connection to an existing server, which Neovide
    /// does not own. Dropping the join handle detaches the task, not the child.
    pub fn supervise_process(&mut self) -> Option<JoinHandle<Result<ExitStatus>>> {
        let child = self.neovim_process.take()?;
        let stderr_task = self.stderr_task.take();
        Some(spawn_process_supervisor(child, stderr_task))
    }

    pub async fn new(
        instance: NeovimInstance,
        handler: impl Handler<Writer = NeovimWriter>,
        channel_config: Option<&[(Value, Value)]>,
    ) -> anyhow::Result<Self> {
        // This needs to be done before the process is spawned, since the file descriptors are
        // inherited on unix-like systems
        #[cfg(not(target_os = "windows"))]
        let stdin_fd = instance.forward_stdin();
        let (reader, writer, stderr_reader, neovim_process) = instance.connect().await?;
        // Drain stderr from the embedded child until the pipe closes. Only the
        // last few lines are retained for a failed handshake. The supervisor
        // owns the task later.
        let stderr_task = stderr_reader.map(|reader| {
            tokio::spawn(async move {
                let mut lines = VecDeque::with_capacity(MAX_STDERR_LINES);
                let mut reader = BufReader::new(reader).lines();
                while let Some(line) = reader.next_line().await.unwrap_or_default() {
                    log::error!("{line}");
                    if lines.len() == MAX_STDERR_LINES {
                        lines.pop_front();
                    }
                    lines.push_back(line);
                }
                lines.into_iter().collect::<Vec<_>>()
            })
        });

        let handshake_message = "HandshakeMessage";
        let detach = Arc::new(Notify::new());
        let handler = SessionHandler {
            handler,
            detach: detach.clone(),
            connect: Arc::new(AtomicBool::new(false)),
        };

        let handshake_res = Neovim::<NeovimWriter>::handshake(
            reader.compat(),
            Box::new(writer.compat_write()),
            handler,
            handshake_message,
        )
        .await;
        match handshake_res {
            Err(err) => {
                if let Some(mut child) = neovim_process {
                    #[cfg(target_os = "windows")]
                    {
                        let _ = child.kill();
                        let _ = child.wait();
                    }
                    #[cfg(not(target_os = "windows"))]
                    {
                        let _ = child.start_kill();
                        let _ = child.wait().await;
                    }
                }
                if let Some(stderr_task) = stderr_task {
                    let stderr = "stderr output:\n".to_owned() + &stderr_task.await?.join("\n");
                    Err(err).context(stderr)
                } else {
                    Err(err.into())
                }
            }
            Ok((neovim, io)) => {
                let io_handle = spawn(async move {
                    // the /usr/bin/login wrapper can keep the pipe open after neovim detaches
                    // a detach notification ends this UI session while the server stays alive
                    tokio::select! {
                        result = io => result,
                        _ = detach.notified() => Ok(()),
                    }
                });

                if let Some(channel_config) = channel_config {
                    let restored = neovim
                        .call("nvim_chan_set", call_args![0, Value::Map(channel_config.to_vec())])
                        .await
                        .and_then(|response| response.map_err(Box::<CallError>::from));

                    if let Err(error) = restored {
                        io_handle.abort();
                        return Err(error).context("Could not restore Neovim channel properties");
                    }
                }

                Ok(Self {
                    neovim,
                    io_handle,
                    neovim_process,
                    stderr_task,
                    #[cfg(not(target_os = "windows"))]
                    stdin_fd,
                })
            }
        }
    }
}

/// The transport requested for a new Neovim RPC session. Startup may spawn an
/// embedded child. `--server` and session transitions use `Server` to attach to
/// an already listening instance.
#[derive(Debug)]
pub enum NeovimInstance {
    /// A new embedded instance to be spawned by the given command.
    Embedded(Command),

    /// An address expected to name a listening instance. This variant never
    /// spawns a child. `is_tcp_address` selects TCP or a local endpoint. Local
    /// endpoints are Unix sockets on Unix and named pipes on Windows.
    Server { address: String },
}

impl NeovimInstance {
    async fn connect(
        self,
    ) -> Result<(BoxedReader, BoxedWriter, Option<BoxedReader>, Option<Child>)> {
        match self {
            NeovimInstance::Embedded(cmd) => Self::spawn_process(cmd).await,
            NeovimInstance::Server { address } => Self::connect_to_server(address)
                .await
                .map(|(reader, writer)| (reader, writer, None, None)),
        }
    }

    async fn spawn_process(
        #[cfg(not(target_os = "windows"))] mut cmd: Command,
        #[cfg(target_os = "windows")] cmd: Command,
    ) -> Result<(BoxedReader, BoxedWriter, Option<BoxedReader>, Option<Child>)> {
        log::debug!("Starting neovim with: {cmd:?}");

        // On Windows, the stdio pipes we get for a spawned child are overlapped
        // handles. if we pass those handles through tokio's process wrapper, it
        // turns them into Blocking<ArcFile>, which can eventually call
        // std::sys::pal::windows::handle::Handle::synchronous_read.
        //
        // Rust intentionally aborts on that path when an overlapped operation is
        // still pending instead of completing synchronously.
        //
        // See https://github.com/rust-lang/rust/issues/81357
        //
        // We avoid that path by using std::process::Command directly on
        // Windows, taking the raw pipe handles, and wrapping them in
        // NamedPipeServer, which supports overlapped pipe I/O.
        #[cfg(target_os = "windows")]
        let mut cmd = cmd.into_std();

        let mut child =
            cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
        let reader_inner = child.stdout.take().ok_or_else(|| Error::other("Can't open stdout"))?;
        let writer_inner = child.stdin.take().ok_or_else(|| Error::other("Can't open stdin"))?;
        let stderr_reader_inner =
            child.stderr.take().ok_or_else(|| Error::other("Can't open stderr"))?;

        let reader: BoxedReader;
        let writer: BoxedWriter;
        let stderr_reader: BoxedReader;

        #[cfg(not(target_os = "windows"))]
        {
            reader = Box::new(reader_inner);
            writer = Box::new(writer_inner);
            stderr_reader = Box::new(stderr_reader_inner);
        }

        #[cfg(target_os = "windows")]
        {
            use std::os::windows::io::IntoRawHandle;

            use tokio::net::windows::named_pipe::NamedPipeServer;
            reader = Box::new(unsafe {
                NamedPipeServer::from_raw_handle(reader_inner.into_raw_handle())
            }?);
            writer = Box::new(unsafe {
                NamedPipeServer::from_raw_handle(writer_inner.into_raw_handle())
            }?);
            stderr_reader = Box::new(unsafe {
                NamedPipeServer::from_raw_handle(stderr_reader_inner.into_raw_handle())
            }?);
        }

        Ok((reader, writer, Some(stderr_reader), Some(child)))
    }

    async fn connect_to_server(address: String) -> Result<(BoxedReader, BoxedWriter)> {
        if is_tcp_address(&address) {
            Ok(Self::split(TcpStream::connect(address).await?))
        } else {
            #[cfg(unix)]
            return Ok(Self::split(tokio::net::UnixStream::connect(address).await?));

            #[cfg(windows)]
            {
                let address = normalize_windows_pipe_address(address);
                Ok(Self::split(
                    tokio::net::windows::named_pipe::ClientOptions::new().open(address)?,
                ))
            }

            #[cfg(not(any(unix, windows)))]
            Err(Error::new(
                std::io::ErrorKind::Unsupported,
                "Unix Domain Sockets and Named Pipes are not supported on this platform",
            ))
        }
    }

    #[cfg(not(target_os = "windows"))]
    fn forward_stdin(&self) -> Option<rustix::fd::OwnedFd> {
        use std::os::fd::AsFd;

        use rustix::fs::FileType;
        use rustix::fs::fstat;

        // stdin should be forwarded only in embedded mode when stdio is piped or redirected
        match self {
            Self::Embedded(..) => {
                let stdin = std::io::stdin();
                let should_forward = fstat(stdin.as_fd())
                    .map(|stat| match FileType::from_raw_mode(stat.st_mode) {
                        FileType::RegularFile => true,
                        #[cfg(not(target_os = "wasi"))]
                        FileType::Fifo | FileType::Socket => true,
                        _ => false,
                    })
                    .unwrap_or(false);

                // We have to use rustix here, since the Rust standard library currently sets O_CLOEXEC
                // on all file handles. And there's no way to pass file handles to subprocesses.
                // See [Tracking Issue for std::os::fd::CommandExt::fd](https://github.com/rust-lang/rust/issues/144989)
                should_forward.then(|| rustix::io::dup(stdin).ok()).flatten()
            }
            Self::Server { .. } => None,
        }
    }

    fn split(
        stream: impl AsyncRead + AsyncWrite + Send + Unpin + 'static,
    ) -> (BoxedReader, BoxedWriter) {
        let (reader, writer) = split(stream);
        (Box::new(reader), Box::new(writer))
    }
}

#[cfg(test)]
mod tests {
    #[cfg(windows)]
    use std::io::Cursor;
    #[cfg(windows)]
    use std::pin::Pin;
    #[cfg(not(target_os = "windows"))]
    use std::process::Stdio;
    #[cfg(windows)]
    use std::sync::Arc;
    #[cfg(windows)]
    use std::sync::Mutex;
    #[cfg(windows)]
    use std::task::Context;
    #[cfg(windows)]
    use std::task::Poll;
    use std::time::Duration;

    use futures::AsyncWriteExt;
    use nvim_rs::Handler;
    use nvim_rs::Neovim;
    use nvim_rs::UiAttachOptions;
    use nvim_rs::rpc::model;
    use nvim_rs::rpc::model::RpcMessage;
    use rmpv::Value;
    #[cfg(not(target_os = "windows"))]
    use tokio::io::AsyncBufReadExt;
    #[cfg(windows)]
    use tokio::io::AsyncRead;
    #[cfg(not(target_os = "windows"))]
    use tokio::io::BufReader;
    #[cfg(windows)]
    use tokio::io::ReadBuf;
    use tokio::net::TcpListener;
    use tokio::net::TcpStream;
    use tokio::process::Command;
    use tokio::sync::mpsc;
    #[cfg(not(target_os = "windows"))]
    use tokio::sync::oneshot;
    use tokio_util::compat::Compat;
    use tokio_util::compat::TokioAsyncReadCompatExt;
    #[cfg(windows)]
    use tokio_util::compat::TokioAsyncWriteCompatExt;

    #[cfg(windows)]
    use super::BoxedReader;
    use super::NeovimInstance;
    use super::NeovimSession;
    use super::NeovimWriter;
    use super::is_tcp_address;
    use super::normalize_windows_pipe_address;
    #[cfg(not(target_os = "windows"))]
    use super::spawn_process_supervisor;

    #[derive(Clone)]
    struct RecordingHandler(mpsc::UnboundedSender<(String, Vec<Value>)>);

    impl Handler for RecordingHandler {
        type Writer = NeovimWriter;

        async fn handle_request(
            &self,
            name: String,
            args: Vec<Value>,
            _nvim: Neovim<Self::Writer>,
        ) -> Result<Value, Value> {
            assert_eq!(name, "probe");
            Ok(Value::Array(args))
        }

        async fn handle_notify(&self, name: String, args: Vec<Value>, _nvim: Neovim<Self::Writer>) {
            tokio::task::yield_now().await;
            self.0.send((name, args)).unwrap();
        }
    }

    struct Peer {
        stream: Compat<TcpStream>,
        buffer: Vec<u8>,
    }

    impl Peer {
        async fn send(&mut self, message: RpcMessage) {
            let mut bytes = Vec::new();
            model::encode_sync(&mut bytes, message).unwrap();
            self.stream.write_all(&bytes).await.unwrap();
        }

        async fn receive(&mut self) -> RpcMessage {
            model::decode(&mut self.stream, &mut self.buffer).await.unwrap()
        }
    }

    async fn session() -> (NeovimSession, Peer, mpsc::UnboundedReceiver<(String, Vec<Value>)>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap().to_string();
        let (sender, receiver) = mpsc::unbounded_channel();
        let session = tokio::spawn(NeovimSession::new(
            NeovimInstance::Server { address },
            RecordingHandler(sender),
            None,
        ));

        let (stream, _) = listener.accept().await.unwrap();
        let mut peer = Peer { stream: stream.compat(), buffer: Vec::new() };
        assert!(matches!(peer.receive().await, RpcMessage::RpcRequest { msgid: 0, .. }));
        peer.send(RpcMessage::RpcResponse {
            msgid: 0,
            error: Value::Nil,
            result: Value::from("HandshakeMessage"),
        })
        .await;

        (session.await.unwrap().unwrap(), peer, receiver)
    }

    fn ui_event(name: &str, args: Vec<Value>) -> Value {
        Value::Array(vec![Value::from(name), Value::Array(args)])
    }

    #[tokio::test]
    async fn ui_detach_finishes_session_without_eof() {
        let flush = ui_event("flush", vec![]);
        let connect = ui_event("connect", vec![Value::from("/tmp/new.sock")]);
        let legacy_detach = ui_event("error_exit", vec![Value::from(0)]);
        let address_detach =
            ui_event("error_exit", vec![Value::from(0), Value::from("/tmp/old.sock"), Value::Nil]);
        let grouped_detach = Value::Array(vec![
            Value::from("error_exit"),
            Value::Array(vec![Value::from(42)]),
            Value::Array(vec![Value::from(0)]),
        ]);

        let cases = [
            (
                "legacy detach after connect",
                vec![vec![connect.clone(), legacy_detach.clone(), flush.clone()]],
            ),
            (
                "detach with extra arguments after connect",
                vec![vec![connect.clone(), address_detach.clone(), flush.clone()]],
            ),
            (
                "grouped detach after connect",
                vec![vec![connect.clone(), grouped_detach, flush.clone()]],
            ),
            (
                "legacy connect across redraw batches",
                vec![vec![connect, flush.clone()], vec![legacy_detach, flush.clone()]],
            ),
            ("standalone detach with address", vec![vec![address_detach, flush]]),
        ];

        for (case, redraw_batches) in cases {
            tokio::time::timeout(Duration::from_secs(3), async {
                let (session, mut peer, mut notifications) = session().await;
                let nvim = session.neovim.clone();
                let pending = tokio::spawn(async move { nvim.command("pending").await });
                assert!(
                    matches!(peer.receive().await, RpcMessage::RpcRequest { method, .. }
                        if method == "nvim_command"),
                    "{case}: expected a pending command before detachment"
                );

                for events in &redraw_batches {
                    peer.send(RpcMessage::RpcNotification {
                        method: "redraw".to_owned(),
                        params: events.clone(),
                    })
                    .await;
                }

                // keep the peer open until all checks finish. the session must end
                // and cancel pending RPC without waiting for the transport to close.
                session.io_handle.await.unwrap().unwrap();
                for events in redraw_batches {
                    let notification = notifications.try_recv().unwrap();
                    assert_eq!(notification, ("redraw".to_owned(), events), "{case}");
                }
                assert!(pending.await.unwrap().unwrap_err().is_channel_closed(), "{case}");
                drop(peer);
            })
            .await
            .unwrap_or_else(|error| {
                panic!("{case}: UI detach must finish without transport EOF: {error}")
            });
        }
    }

    #[tokio::test]
    async fn non_detach_events_keep_rpc_usable() {
        tokio::time::timeout(Duration::from_secs(3), async {
            let (session, mut peer, mut notifications) = session().await;
            let events = vec![
                Value::Nil,
                Value::Array(vec![]),
                Value::Array(vec![Value::from("error_exit")]),
                Value::Array(vec![Value::from("error_exit"), Value::from(0)]),
                ui_event("connect", vec![]),
                ui_event("connect", vec![Value::Nil]),
                ui_event("error_exit", vec![Value::from(0)]),
                ui_event("error_exit", vec![Value::from(0), Value::from("")]),
                ui_event("error_exit", vec![Value::from(0), Value::Nil]),
                ui_event("unrelated", vec![Value::from(0)]),
                ui_event("restart", vec![Value::from("/tmp/restart.sock")]),
                ui_event("connect", vec![Value::from("")]),
                ui_event("connect", vec![Value::from("/tmp/new.sock")]),
                ui_event("error_exit", vec![Value::from(42)]),
                ui_event("error_exit", vec![Value::from(42), Value::Nil]),
                ui_event("error_exit", vec![]),
                ui_event("error_exit", vec![Value::Nil]),
                ui_event("error_exit", vec![Value::from("0")]),
                ui_event("error_exit", vec![Value::from(0.0)]),
                ui_event("error_exit", vec![Value::from(false)]),
                ui_event("error_exit", vec![Value::from(-1)]),
            ];

            peer.send(RpcMessage::RpcNotification {
                method: "redraw".to_owned(),
                params: events.clone(),
            })
            .await;

            assert_eq!(notifications.recv().await.unwrap(), ("redraw".to_owned(), events));
            peer.send(RpcMessage::RpcNotification {
                method: "error_exit".to_owned(),
                params: vec![Value::from(0)],
            })
            .await;

            assert_eq!(
                notifications.recv().await.unwrap(),
                ("error_exit".to_owned(), vec![Value::from(0)])
            );

            peer.send(RpcMessage::RpcRequest {
                msgid: 42,
                method: "probe".to_owned(),
                params: vec![Value::from("still attached")],
            })
            .await;

            assert_eq!(
                peer.receive().await,
                RpcMessage::RpcResponse {
                    msgid: 42,
                    error: Value::Nil,
                    result: Value::Array(vec![Value::from("still attached")]),
                }
            );

            drop(peer);
            assert!(session.io_handle.await.unwrap().is_err());
        })
        .await
        .expect("non-detach events must leave RPC usable until EOF");
    }

    #[cfg(windows)]
    struct CaptureReader {
        inner: BoxedReader,
        bytes: Arc<Mutex<Vec<u8>>>,
    }

    #[cfg(windows)]
    impl AsyncRead for CaptureReader {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            let before = buf.filled().len();
            let result = Pin::new(&mut self.inner).poll_read(cx, buf);
            if matches!(result, Poll::Ready(Ok(()))) {
                self.bytes.lock().unwrap().extend_from_slice(&buf.filled()[before..]);
            }
            result
        }
    }

    #[cfg(windows)]
    #[derive(Clone)]
    struct ProbeHandler(tokio::sync::mpsc::UnboundedSender<String>);

    #[cfg(windows)]
    impl Handler for ProbeHandler {
        type Writer = NeovimWriter;

        async fn handle_notify(&self, name: String, args: Vec<Value>, _nvim: Neovim<NeovimWriter>) {
            if name == "redraw" {
                for item in args {
                    if let Value::Array(parts) = item
                        && let Some(name) = parts.first().and_then(Value::as_str)
                        && matches!(name, "connect" | "error_exit")
                    {
                        let _ = self.0.send(name.to_owned());
                    }
                }
            }
        }
    }

    #[cfg(windows)]
    fn has_connect(value: &Value) -> bool {
        match value {
            Value::Array(items) => {
                (items.first().and_then(Value::as_str) == Some("connect")
                    && items
                        .get(1)
                        .and_then(Value::as_array)
                        .and_then(|args| args.first())
                        .and_then(Value::as_str)
                        == Some("hey"))
                    || items.iter().any(has_connect)
            }
            _ => false,
        }
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn embedded_connect_reaches_handler_after_stdio_eof() {
        let mut command = Command::new("nvim");
        command.args(["--clean", "--embed"]);
        let (reader, writer, _stderr, child) =
            NeovimInstance::spawn_process(command).await.unwrap();
        let bytes = Arc::new(Mutex::new(Vec::new()));
        let reader = CaptureReader { inner: reader, bytes: bytes.clone() };
        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
        let (nvim, io) = Neovim::<NeovimWriter>::handshake(
            reader.compat(),
            Box::new(writer.compat_write()),
            ProbeHandler(sender),
            "HandshakeMessage",
        )
        .await
        .unwrap();
        let mut io_handle = tokio::spawn(io);
        let mut options = UiAttachOptions::new();
        options.set_linegrid_external(true);
        nvim.ui_attach(80, 24, &options).await.unwrap();
        // The command may close its own RPC channel before replying to input.
        let _ = nvim.input(":connect hey<CR>").await;
        let io_result = tokio::time::timeout(Duration::from_secs(3), &mut io_handle).await;
        if io_result.is_err() {
            io_handle.abort();
        }
        let captured = bytes.lock().unwrap().clone();
        let mut cursor = Cursor::new(captured.as_slice());
        let mut raw_connect = false;
        while let Ok(value) = rmpv::decode::read_value(&mut cursor) {
            raw_connect |= has_connect(&value);
        }
        let mut delivered = Vec::new();
        while let Ok(event) = receiver.try_recv() {
            delivered.push(event);
        }
        let mut child = child.unwrap();
        let _ = child.kill();
        let _ = child.wait();
        assert!(io_result.is_ok(), "stdio RPC did not close after :connect");
        assert!(raw_connect);
        assert!(delivered.iter().any(|event| event == "connect"));
        assert!(delivered.iter().any(|event| event == "error_exit"));
    }

    #[cfg(not(target_os = "windows"))]
    #[derive(Clone)]
    struct UiHandler;

    #[cfg(not(target_os = "windows"))]
    impl Handler for UiHandler {
        type Writer = NeovimWriter;

        async fn handle_notify(
            &self,
            _event_name: String,
            _arguments: Vec<Value>,
            _neovim: Neovim<NeovimWriter>,
        ) {
        }
    }

    #[cfg(not(target_os = "windows"))]
    #[tokio::test]
    async fn failed_restart_clears_exitreason_on_surviving_server() {
        let bin = std::env::var("NEOVIM_BIN").unwrap_or_else(|_| "nvim".to_owned());
        let mut command = Command::new(bin);
        command.args(["--clean", "--embed"]);
        let mut session =
            NeovimSession::new(NeovimInstance::Embedded(command), UiHandler, None).await.unwrap();
        let mut options = UiAttachOptions::new();
        options.set_linegrid_external(true);
        session.neovim.ui_attach(80, 24, &options).await.unwrap();
        session.neovim.command("set modified").await.unwrap();

        let error = session.neovim.command("restart").await.unwrap_err();
        assert!(error.to_string().contains("E37"));
        let reason = session.neovim.exec_lua("return vim.v.exitreason", vec![]).await.unwrap();
        assert!(reason.is_nil() || reason.as_str() == Some(""));

        let supervisor = session.supervise_process().unwrap();
        let _ = session.neovim.command("qa!").await;
        tokio::time::timeout(Duration::from_secs(5), supervisor).await.unwrap().unwrap().unwrap();
    }

    #[cfg(not(target_os = "windows"))]
    #[tokio::test]
    async fn unavailable_destination_returns_connection_error() {
        let address = std::env::temp_dir()
            .join(format!("neovide-no-server-{}", std::process::id()))
            .to_string_lossy()
            .into_owned();
        let result = NeovimInstance::Server { address }.connect().await;
        assert!(result.is_err());
    }

    #[cfg(not(target_os = "windows"))]
    #[tokio::test]
    async fn detached_supervisor_keeps_embedded_process_and_stderr_reader_alive() {
        let mut child = Command::new("sh")
            .args(["-c", "sleep 0.1; printf 'server still alive\\n' >&2"])
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let stderr = child.stderr.take().unwrap();
        let (sender, receiver) = oneshot::channel();
        let stderr_task = tokio::spawn(async move {
            let mut lines = BufReader::new(stderr).lines();
            let line = lines.next_line().await.unwrap().unwrap();
            let _ = sender.send(line.clone());
            vec![line]
        });

        // Dropping the join handle models run() after the old UI channel
        // closes.
        drop(spawn_process_supervisor(child, Some(stderr_task)));

        let line = tokio::time::timeout(Duration::from_secs(2), receiver).await.unwrap().unwrap();
        assert_eq!(line, "server still alive");
    }

    #[test]
    fn matches_neovim_address_selection() {
        assert!(is_tcp_address("127.0.0.1:6666"));
        assert!(is_tcp_address("[::1]:6666"));
        assert!(!is_tcp_address(":socket"));
        assert!(!is_tcp_address("C:/nvim/socket"));
        assert!(!is_tcp_address("/tmp/nvim.sock"));
    }

    #[test]
    fn preserves_canonical_windows_pipe_address() {
        let address = r"\\.\pipe\nvim.123".to_string();
        assert_eq!(normalize_windows_pipe_address(address.clone()), address);
    }

    #[test]
    fn normalizes_neovim_forward_slash_pipe_address() {
        assert_eq!(
            normalize_windows_pipe_address("//./pipe/nvim.123".to_string()),
            r"\\.\pipe\nvim.123"
        );
    }

    #[test]
    fn prefixes_bare_windows_pipe_name() {
        assert_eq!(normalize_windows_pipe_address("nvim.123".to_string()), r"\\.\pipe\nvim.123");
    }

    #[test]
    fn preserves_windows_drive_path() {
        let address = "C:/nvim/socket".to_string();
        assert_eq!(normalize_windows_pipe_address(address.clone()), address);
    }
}