retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
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
//! Client-side logic for connecting to the retach server, managing sessions, and relaying I/O.

pub mod raw_mode;
pub mod server_launcher;

use crate::protocol::{
    self, read_one_message, ClientMsg, FrameReader, ServerMsg, PROTOCOL_VERSION,
};
use std::io::{self, BufWriter, Read, Write};
use tokio::io::AsyncWriteExt;
use tokio::net::UnixStream;

use raw_mode::RawMode;
use server_launcher::ensure_server_running;

/// Detach key: Ctrl+\ (0x1c).
const DETACH_KEY: u8 = 0x1c;
/// POSIX signal numbers used to derive the conventional 128+signo exit status
/// when a detach is triggered by a signal (so supervisors can tell a kill from
/// a clean exit).
const SIGINT: i32 = 2;
const SIGTERM: i32 = 15;

/// Conventional shell exit status for a process terminated by `signo`.
fn signal_exit_code(signo: i32) -> i32 {
    128 + signo
}
/// Focus-in event: ESC [ I
const FOCUS_IN: u8 = b'I';
/// Focus-out event: ESC [ O
const FOCUS_OUT: u8 = b'O';

/// RAII guard that removes the custom panic hook on drop.
struct PanicHookGuard;

impl Drop for PanicHookGuard {
    fn drop(&mut self) {
        // Remove our custom panic hook. This discards it (including the
        // captured prev_hook) and installs Rust's default panic hook.
        // The previous hook cannot be restored because it was moved into
        // our custom hook's closure. In practice, retach's binary has no
        // custom panic hook before connect(), so this is a no-op loss.
        if !std::thread::panicking() {
            let _ = std::panic::take_hook();
        }
    }
}

/// RAII guard that runs `cleanup_terminal()` on drop, ensuring the
/// escape-sequence reset (focus reporting off, cursor/mouse/wrap/SGR) runs on
/// every exit path once the modes have been enabled — including early returns
/// from fallible signal-handler setup.
struct TerminalModeGuard;

impl Drop for TerminalModeGuard {
    fn drop(&mut self) {
        cleanup_terminal();
    }
}

/// Result of dispatching a server message to stdout.
enum DispatchResult {
    Continue,
    /// Terminal message. Carries the child's exit code when known so the client
    /// can propagate it as its own process exit status.
    Done {
        exit_code: Option<i32>,
    },
}

/// Write a single ServerMsg to stdout. Returns `Done` for terminal messages.
fn dispatch_server_msg(msg: &ServerMsg, stdout: &mut impl Write) -> io::Result<DispatchResult> {
    match msg {
        ServerMsg::ScreenUpdate(data) => {
            stdout.write_all(data)?;
        }
        ServerMsg::Passthrough(data) => {
            stdout.write_all(data)?;
            stdout.flush()?;
        }
        ServerMsg::History(lines) => {
            for line in lines {
                stdout.write_all(line)?;
                stdout.write_all(b"\r\n")?;
            }
        }
        ServerMsg::SessionEnded { exit_code } => {
            stdout.flush()?;
            eprint!("[retach: session ended]\r\n");
            return Ok(DispatchResult::Done {
                exit_code: *exit_code,
            });
        }
        ServerMsg::Error(e) => {
            stdout.flush()?;
            eprint!("[retach error: {}]\r\n", e);
            return Ok(DispatchResult::Done { exit_code: None });
        }
        other => {
            tracing::debug!(
                "ignoring unexpected server message: {:?}",
                std::mem::discriminant(other)
            );
        }
    }
    Ok(DispatchResult::Continue)
}

fn get_terminal_size() -> (u16, u16) {
    if let Some(size) = terminal_size::terminal_size() {
        (size.0 .0, size.1 .0)
    } else {
        (crate::session::DEFAULT_COLS, crate::session::DEFAULT_ROWS)
    }
}

type SocketWriter = std::sync::Arc<tokio::sync::Mutex<tokio::net::unix::OwnedWriteHalf>>;

/// Action produced by the input filter.
#[derive(Debug, PartialEq)]
enum FilterAction {
    /// Forward filtered bytes to the server.
    Forward(Vec<u8>),
    /// Client requested detach (Ctrl+\).
    Detach,
    /// Terminal reported focus gained — trigger screen refresh.
    FocusIn,
}

/// Filters stdin input: handles detach key, focus events, and split escape sequences.
struct InputFilter {
    carry: Vec<u8>,
}

impl InputFilter {
    fn new() -> Self {
        Self {
            carry: Vec::with_capacity(2),
        }
    }

    /// Push accumulated bytes as a Forward action if non-empty.
    fn flush_filtered(actions: &mut Vec<FilterAction>, filtered: &mut Vec<u8>) {
        if !filtered.is_empty() {
            actions.push(FilterAction::Forward(std::mem::take(filtered)));
        }
    }

    /// Process raw input bytes, returning a list of actions.
    fn process(&mut self, input: &[u8]) -> Vec<FilterAction> {
        let raw: Vec<u8> = if self.carry.is_empty() {
            input.to_vec()
        } else {
            let mut combined = std::mem::take(&mut self.carry);
            combined.extend_from_slice(input);
            combined
        };

        // Detach only on a standalone Ctrl+\ keypress (a lone 0x1c byte). When
        // 0x1c appears mid-stream — e.g. inside a bracketed paste or binary
        // input — it is forwarded as ordinary data, not treated as detach.
        if raw.first() == Some(&DETACH_KEY) && raw.len() == 1 {
            return vec![FilterAction::Detach];
        }

        let mut actions = Vec::new();
        let mut filtered = Vec::with_capacity(raw.len());
        let mut i = 0;
        while i < raw.len() {
            if raw[i] != 0x1b {
                filtered.push(raw[i]);
                i += 1;
                continue;
            }

            // ESC at end of buffer — carry for next call
            let remaining = raw.len() - i;
            if remaining < 2 {
                Self::flush_filtered(&mut actions, &mut filtered);
                self.carry.extend_from_slice(&raw[i..]);
                return actions;
            }

            // ESC <non-[> — pass through both bytes as-is.
            // Single-byte advance would work by coincidence (the second byte is not
            // 0x1b so it passes through next iteration), but advancing by 2 makes
            // the intent explicit and prevents breakage if filtering rules change.
            if raw[i + 1] != b'[' {
                filtered.push(raw[i]);
                filtered.push(raw[i + 1]);
                i += 2;
                continue;
            }

            // ESC [ at end of buffer — carry for next call
            if remaining < 3 {
                Self::flush_filtered(&mut actions, &mut filtered);
                self.carry.extend_from_slice(&raw[i..]);
                return actions;
            }

            // ESC [ I — focus in
            if raw[i + 2] == FOCUS_IN {
                Self::flush_filtered(&mut actions, &mut filtered);
                actions.push(FilterAction::FocusIn);
                i += 3;
                continue;
            }

            // ESC [ O — focus out (consumed, not forwarded)
            if raw[i + 2] == FOCUS_OUT {
                i += 3;
                continue;
            }

            // ESC [ <other> — pass through
            filtered.push(raw[i]);
            i += 1;
        }
        Self::flush_filtered(&mut actions, &mut filtered);
        actions
    }

    /// Flush any remaining carry bytes as a Forward action.
    fn flush(&mut self) -> Option<FilterAction> {
        if self.carry.is_empty() {
            None
        } else {
            Some(FilterAction::Forward(std::mem::take(&mut self.carry)))
        }
    }
}

/// Stdin → socket relay: reads stdin, handles detach key and focus events,
/// and forwards input to the server.
async fn run_stdin_to_socket(sw: SocketWriter) -> anyhow::Result<()> {
    let mut filter = InputFilter::new();

    'stdin: loop {
        let result = tokio::task::spawn_blocking(|| {
            // 1 KiB stdin buffer — matches typical terminal input rates. Even fast
            // paste operations are chunked by the OS at ~4 KiB pipe buffer boundaries,
            // so 1 KiB reads keep latency low without excessive syscalls.
            let mut buf = [0u8; 1024];
            let n = io::stdin().read(&mut buf)?;
            Ok::<_, io::Error>((buf, n))
        })
        .await;

        match result {
            Ok(Ok((_buf, 0))) => {
                if let Some(FilterAction::Forward(data)) = filter.flush() {
                    let msg = protocol::encode(&ClientMsg::Input(data))?;
                    let mut w = sw.lock().await;
                    w.write_all(&msg).await?;
                }
                break;
            }
            Ok(Ok((buf, n))) => {
                for action in filter.process(&buf[..n]) {
                    match action {
                        FilterAction::Forward(data) => {
                            let msg = protocol::encode(&ClientMsg::Input(data))?;
                            let mut w = sw.lock().await;
                            w.write_all(&msg).await?;
                        }
                        FilterAction::Detach => {
                            let mut w = sw.lock().await;
                            if let Ok(msg) = protocol::encode(&ClientMsg::Detach) {
                                w.write_all(&msg).await?;
                            }
                            drop(w);
                            return Ok(());
                        }
                        FilterAction::FocusIn => {
                            if let Ok(msg) = protocol::encode(&ClientMsg::RefreshScreen) {
                                let mut w = sw.lock().await;
                                if let Err(e) = w.write_all(&msg).await {
                                    tracing::debug!(error = %e, "failed to send focus-in refresh");
                                    break 'stdin;
                                }
                            }
                        }
                    }
                }
            }
            Ok(Err(e)) => return Err(anyhow::Error::from(e)),
            Err(e) => return Err(anyhow::Error::from(e)),
        }
    }
    Ok(())
}

/// Spawn SIGWINCH handler that sends Resize + RefreshScreen on terminal size change.
fn spawn_sigwinch_handler(
    sock_writer: SocketWriter,
) -> anyhow::Result<tokio::task::JoinHandle<()>> {
    let mut sigwinch =
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::window_change())?;
    let sw = sock_writer;
    Ok(tokio::spawn(async move {
        while sigwinch.recv().await.is_some() {
            let (cols, rows) = get_terminal_size();
            let mut w = sw.lock().await;
            if let Ok(msg) = protocol::encode(&ClientMsg::Resize { cols, rows }) {
                if let Err(e) = w.write_all(&msg).await {
                    tracing::debug!(error = %e, "failed to send resize");
                    break;
                }
            }
            if let Ok(msg) = protocol::encode(&ClientMsg::RefreshScreen) {
                if let Err(e) = w.write_all(&msg).await {
                    tracing::debug!(error = %e, "failed to send refresh after resize");
                    break;
                }
            }
        }
    }))
}

/// Socket → stdout relay: reads server messages, dispatches them to stdout.
/// Returns `Some(code)` when the session ended with a known child exit code,
/// `None` on detach or when no code is available.
async fn run_socket_to_stdout(
    mut sock_reader: tokio::net::unix::OwnedReadHalf,
    leftover: Vec<u8>,
) -> anyhow::Result<Option<i32>> {
    let mut frames = FrameReader::with_leftover(leftover);
    let mut stdout = BufWriter::new(io::stdout());

    // Process any complete frames already in the leftover buffer
    while let Some(msg) = frames.decode_next::<ServerMsg>()? {
        if let DispatchResult::Done { exit_code } = dispatch_server_msg(&msg, &mut stdout)? {
            return Ok(exit_code);
        }
    }
    stdout.flush()?;

    loop {
        if !frames.fill_from(&mut sock_reader).await? {
            eprint!("[retach: detached]\r\n");
            break;
        }
        while let Some(msg) = frames.decode_next::<ServerMsg>()? {
            if let DispatchResult::Done { exit_code } = dispatch_server_msg(&msg, &mut stdout)? {
                return Ok(exit_code);
            }
        }
        stdout.flush()?;
    }
    Ok(None)
}

/// Connect to (or create) a named session and enter interactive raw-mode I/O.
/// Returns the child's exit code when the session's process exits while
/// attached (so the caller can mirror it), or `None` on detach/error.
pub async fn connect(
    name: &str,
    history: usize,
    mode: crate::protocol::ConnectMode,
) -> anyhow::Result<Option<i32>> {
    ensure_server_running().await?;

    let mut stream = UnixStream::connect(crate::server::socket_path()?).await?;

    let (cols, rows) = get_terminal_size();
    let msg = protocol::encode(&ClientMsg::Connect {
        version: PROTOCOL_VERSION,
        name: name.to_string(),
        history,
        cols,
        rows,
        mode,
    })?;
    stream.write_all(&msg).await?;

    // Wait for Connected/Error before entering raw mode so errors display correctly.
    let mut frames = FrameReader::new();
    loop {
        if !frames.fill_from(&mut stream).await? {
            anyhow::bail!("server closed connection before handshake completed");
        }
        if let Some(msg) = frames.decode_next::<ServerMsg>()? {
            match msg {
                ServerMsg::Connected {
                    name: ref session_name,
                    new_session,
                } => {
                    if new_session {
                        eprintln!("[retach: new session '{}' (detach: Ctrl+\\)]", session_name);
                    } else {
                        eprintln!(
                            "[retach: reattached to '{}' (detach: Ctrl+\\)]",
                            session_name
                        );
                    }
                    break;
                }
                ServerMsg::Error(e) => {
                    anyhow::bail!("{}", e);
                }
                _ => {
                    anyhow::bail!("unexpected response from server");
                }
            }
        }
    }
    let leftover = frames.into_leftover();

    // Install panic hook to restore terminal even if we panic while in raw mode.
    // The guard ensures the hook is removed on all exit paths (including early returns).
    let prev_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        raw_mode::emergency_restore();
        cleanup_terminal();
        prev_hook(info);
    }));
    let _hook_guard = PanicHookGuard;

    let _raw = RawMode::enter()?;

    // Enable focus reporting on the outer terminal so we receive
    // ESC [ I (focus-in) and ESC [ O (focus-out) events from stdin.
    // Without this, the focus event filtering code below is dead code.
    if let Err(e) = io::stdout().write_all(b"\x1b[?1004h") {
        tracing::debug!(error = %e, "failed to enable focus reporting");
    }
    if let Err(e) = io::stdout().flush() {
        tracing::debug!(error = %e, "failed to flush stdout after enabling focus reporting");
    }

    // Guard so cleanup_terminal() runs on every exit path from here on — even
    // if the fallible signal-handler setup below returns early via `?`.
    let _mode_guard = TerminalModeGuard;

    let (sock_reader, sock_writer) = stream.into_split();
    let sock_writer = std::sync::Arc::new(tokio::sync::Mutex::new(sock_writer));

    let sigwinch_handle = spawn_sigwinch_handler(sock_writer.clone())?;

    let mut stdin_task = tokio::spawn(run_stdin_to_socket(sock_writer.clone()));
    let mut socket_task = tokio::spawn(run_socket_to_stdout(sock_reader, leftover));

    let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?;
    let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;

    // Track which task completed so we don't re-poll it (JoinHandle panics
    // if polled after completion).
    enum Completed {
        Stdin,
        Socket,
        Neither,
    }
    // Exit code from the session's child process, propagated to the caller so
    // `retach open`/`attach` mirrors the child's status (scripts can check $?).
    let mut session_exit_code: Option<i32> = None;
    let completed = tokio::select! {
        r = &mut stdin_task => {
            if let Ok(Err(e)) = r {
                tracing::debug!(error = %e, "stdin task error");
            }
            Completed::Stdin
        }
        r = &mut socket_task => {
            match r {
                Ok(Ok(code)) => session_exit_code = code,
                Ok(Err(e)) => {
                    tracing::warn!(error = %e, "socket task error");
                    eprint!("[retach error: {}]\r\n", e);
                }
                Err(e) => {
                    tracing::warn!(error = %e, "socket task join error");
                }
            }
            Completed::Socket
        }
        _ = sigint.recv() => {
            tracing::debug!("received SIGINT, detaching");
            if let Ok(msg) = protocol::encode(&ClientMsg::Detach) {
                let mut w = sock_writer.lock().await;
                if let Err(e) = w.write_all(&msg).await {
                    tracing::debug!(error = %e, "failed to send detach on SIGINT");
                }
            }
            session_exit_code = Some(signal_exit_code(SIGINT));
            Completed::Neither
        }
        _ = sigterm.recv() => {
            tracing::debug!("received SIGTERM, detaching");
            if let Ok(msg) = protocol::encode(&ClientMsg::Detach) {
                let mut w = sock_writer.lock().await;
                if let Err(e) = w.write_all(&msg).await {
                    tracing::debug!(error = %e, "failed to send detach on SIGTERM");
                }
            }
            session_exit_code = Some(signal_exit_code(SIGTERM));
            Completed::Neither
        }
    };

    // Abort the still-running task(s) and wait for them to stop before
    // touching terminal state. Only await tasks that haven't already been
    // polled to completion — re-polling a finished JoinHandle panics.
    match completed {
        Completed::Stdin => {
            socket_task.abort();
            let _ = socket_task.await;
        }
        Completed::Socket => {
            stdin_task.abort();
            let _ = stdin_task.await;
        }
        Completed::Neither => {
            stdin_task.abort();
            socket_task.abort();
            let _ = tokio::join!(stdin_task, socket_task);
        }
    }

    sigwinch_handle.abort();

    // Explicit drops enforce the correct ordering: emit the escape-sequence
    // reset (focus reporting off, cursor/mouse/wrap/SGR), then restore raw
    // mode, then remove the panic hook — all while the panic hook is still
    // active so a panic mid-teardown still restores the terminal.
    drop(_mode_guard);
    drop(_raw);
    drop(_hook_guard);

    Ok(session_exit_code)
}

/// Reset terminal modes after detach/disconnect so the user's shell isn't left
/// with hidden cursor, mouse capture, bracketed paste, etc.
fn cleanup_terminal() {
    let mut stdout = io::stdout();
    // Best-effort terminal cleanup — errors are expected if stdout is broken
    let _ = stdout.write_all(
        concat!(
            "\x1b[r",      // reset scroll region to full screen (also moves cursor to home)
            "\x1b[2J",     // clear screen
            "\x1b[H",      // cursor to home
            "\x1b[?25h",   // show cursor
            "\x1b[?7h",    // re-enable auto-wrap
            "\x1b[?1l",    // normal cursor keys (DECCKM reset)
            "\x1b[?2004l", // disable bracketed paste
            "\x1b[?1000l", // disable mouse click tracking
            "\x1b[?1002l", // disable mouse button tracking
            "\x1b[?1003l", // disable mouse any-event tracking
            "\x1b[?1005l", // disable UTF-8 mouse encoding
            "\x1b[?1006l", // disable SGR mouse encoding
            "\x1b[?1004l", // disable focus reporting
            "\x1b[?2026l", // disable synchronized output
            "\x1b>",       // normal keypad mode (DECKPNM)
            "\x1b[0 q",    // default cursor shape
            "\x1b[0m",     // reset all SGR attributes
        )
        .as_bytes(),
    );
    // Best-effort terminal cleanup — errors are expected if stdout is broken
    let _ = stdout.flush();
}

/// Query the server for active sessions and print them to stdout.
pub async fn list_sessions() -> anyhow::Result<()> {
    let path = crate::server::socket_path()?;
    let mut stream = match UnixStream::connect(&path).await {
        Ok(s) => s,
        Err(e)
            if e.kind() == std::io::ErrorKind::ConnectionRefused
                || e.kind() == std::io::ErrorKind::NotFound =>
        {
            println!("No active sessions");
            return Ok(());
        }
        Err(e) => return Err(e.into()),
    };
    let msg = protocol::encode(&ClientMsg::ListSessions {
        version: PROTOCOL_VERSION,
    })?;
    stream.write_all(&msg).await?;

    let resp: ServerMsg = read_one_message(&mut stream).await?;
    match resp {
        ServerMsg::SessionList(sessions) => {
            if sessions.is_empty() {
                println!("No active sessions");
            } else {
                for s in sessions {
                    println!("{} ({}x{})", s.name, s.cols, s.rows);
                }
            }
        }
        ServerMsg::Error(e) => anyhow::bail!("{}", e),
        other => anyhow::bail!(
            "unexpected server response: {:?}",
            std::mem::discriminant(&other)
        ),
    }
    Ok(())
}

/// Ask the server to terminate the named session.
pub async fn kill_session(name: &str) -> anyhow::Result<()> {
    let path = crate::server::socket_path()?;
    let mut stream = match UnixStream::connect(&path).await {
        Ok(s) => s,
        Err(_) => anyhow::bail!("server not running"),
    };
    let msg = protocol::encode(&ClientMsg::KillSession {
        version: PROTOCOL_VERSION,
        name: name.to_string(),
    })?;
    stream.write_all(&msg).await?;

    let resp: ServerMsg = read_one_message(&mut stream).await?;
    match resp {
        ServerMsg::SessionKilled { name } => println!("killed session '{}'", name),
        ServerMsg::Error(e) => anyhow::bail!("{}", e),
        other => anyhow::bail!(
            "unexpected server response: {:?}",
            std::mem::discriminant(&other)
        ),
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dispatch_server_msg_error_returns_done() {
        let msg = ServerMsg::Error("test error".into());
        let mut buf = Vec::new();
        let result = dispatch_server_msg(&msg, &mut buf).unwrap();
        assert!(matches!(result, DispatchResult::Done { exit_code: None }));
    }

    #[test]
    fn dispatch_server_msg_session_ended_returns_done() {
        let msg = ServerMsg::SessionEnded { exit_code: Some(0) };
        let mut buf = Vec::new();
        let result = dispatch_server_msg(&msg, &mut buf).unwrap();
        assert!(matches!(
            result,
            DispatchResult::Done { exit_code: Some(0) }
        ));
    }

    #[test]
    fn dispatch_server_msg_session_ended_propagates_exit_code() {
        let msg = ServerMsg::SessionEnded {
            exit_code: Some(42),
        };
        let mut buf = Vec::new();
        match dispatch_server_msg(&msg, &mut buf).unwrap() {
            DispatchResult::Done { exit_code } => assert_eq!(exit_code, Some(42)),
            DispatchResult::Continue => panic!("expected Done"),
        }
    }

    #[test]
    fn dispatch_server_msg_screen_update_continues() {
        let msg = ServerMsg::ScreenUpdate(b"hello".to_vec());
        let mut buf = Vec::new();
        let result = dispatch_server_msg(&msg, &mut buf).unwrap();
        assert!(matches!(result, DispatchResult::Continue));
        assert_eq!(buf, b"hello");
    }

    #[test]
    fn signal_exit_code_matches_shell_convention() {
        assert_eq!(signal_exit_code(SIGINT), 130);
        assert_eq!(signal_exit_code(SIGTERM), 143);
    }

    #[test]
    fn input_filter_passthrough() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"hello");
        assert_eq!(result, vec![FilterAction::Forward(b"hello".to_vec())]);
    }

    #[test]
    fn input_filter_detach_only_on_lone_keypress() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"\x1c");
        assert_eq!(result, vec![FilterAction::Detach]);
    }

    #[test]
    fn input_filter_detach_byte_mid_buffer_passes_through() {
        // A paste or binary chunk containing 0x1c mid-stream must be forwarded
        // intact, not interpreted as a detach that drops the trailing bytes.
        let mut filter = InputFilter::new();
        let result = filter.process(b"abc\x1cdef");
        assert_eq!(result, vec![FilterAction::Forward(b"abc\x1cdef".to_vec())]);
    }

    #[test]
    fn input_filter_detach_byte_at_start_of_multibyte_passes_through() {
        // 0x1c as the first byte of a larger chunk is data, not a keypress.
        let mut filter = InputFilter::new();
        let result = filter.process(b"\x1cabc");
        assert_eq!(result, vec![FilterAction::Forward(b"\x1cabc".to_vec())]);
    }

    #[test]
    fn input_filter_bracketed_paste_with_detach_byte_intact() {
        let mut filter = InputFilter::new();
        let paste = b"\x1b[200~hello\x1cworld\x1b[201~";
        let result = filter.process(paste);
        assert_eq!(result, vec![FilterAction::Forward(paste.to_vec())]);
    }

    #[test]
    fn input_filter_focus_in() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"\x1b[I");
        assert_eq!(result, vec![FilterAction::FocusIn]);
    }

    #[test]
    fn input_filter_focus_out_dropped() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"\x1b[O");
        assert!(result.is_empty());
    }

    #[test]
    fn input_filter_carry_lone_esc() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"abc\x1b");
        assert_eq!(result, vec![FilterAction::Forward(b"abc".to_vec())]);
        // Complete the sequence
        let result = filter.process(b"[Amore");
        assert_eq!(result, vec![FilterAction::Forward(b"\x1b[Amore".to_vec())]);
    }

    #[test]
    fn input_filter_carry_esc_bracket() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"\x1b[");
        assert!(result.is_empty());
        let result = filter.process(b"Irest");
        assert_eq!(
            result,
            vec![
                FilterAction::FocusIn,
                FilterAction::Forward(b"rest".to_vec()),
            ]
        );
    }

    #[test]
    fn input_filter_flush() {
        let mut filter = InputFilter::new();
        let _ = filter.process(b"\x1b");
        let flushed = filter.flush();
        assert_eq!(flushed, Some(FilterAction::Forward(vec![0x1b])));
        // Double flush is empty
        assert_eq!(filter.flush(), None);
    }

    #[test]
    fn input_filter_esc_non_bracket_passthrough() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"\x1bOA"); // ESC O A (arrow key in app mode)
        assert_eq!(result, vec![FilterAction::Forward(b"\x1bOA".to_vec())]);
    }

    #[test]
    fn input_filter_mixed() {
        let mut filter = InputFilter::new();
        let result = filter.process(b"text\x1b[Imore");
        assert_eq!(
            result,
            vec![
                FilterAction::Forward(b"text".to_vec()),
                FilterAction::FocusIn,
                FilterAction::Forward(b"more".to_vec()),
            ]
        );
    }

    #[test]
    fn input_filter_esc_bracket_at_boundary() {
        let mut f = InputFilter::new();
        // ESC [ split across two calls
        let a1 = f.process(b"\x1b");
        assert!(a1.is_empty(), "lone ESC should be carried");
        let a2 = f.process(b"[I");
        assert_eq!(a2, vec![FilterAction::FocusIn]);
    }

    #[test]
    fn input_filter_multiple_focus_events() {
        let mut f = InputFilter::new();
        let actions = f.process(b"a\x1b[Ib\x1b[Oc");
        assert_eq!(
            actions,
            vec![
                FilterAction::Forward(b"a".to_vec()),
                FilterAction::FocusIn,
                FilterAction::Forward(b"bc".to_vec()),
            ]
        );
    }
}