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
//! Client relay loops: screen-to-client rendering and client-to-PTY input forwarding.

use crate::protocol::{self, ClientMsg, FrameReader, ServerMsg};
use crate::session::SessionHandles;
use std::io::Write;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tokio::io::AsyncWriteExt;
use tracing::debug;

use super::session_setup::resize_pty;
use super::shared::{
    lock_mutex, prepend_passthrough, render_and_send, store_dims, RENDER_THROTTLE,
};

/// Read the child's captured exit code (set by the persistent reader after EOF).
/// Returns `None` if the code is unknown or the mutex is contended/poisoned.
fn session_exit_code(h: &SessionHandles) -> Option<i32> {
    h.exit_code.lock().ok().and_then(|c| *c)
}

/// Screen -> client relay loop: waits for the persistent reader to signal new
/// data, then renders and sends updates to the client.
pub(super) async fn screen_to_client(
    h: SessionHandles,
    mut renderer: retach::screen::AnsiRenderer,
    refresh_notify: Arc<tokio::sync::Notify>,
    mut evict_rx: tokio::sync::watch::Receiver<bool>,
    mut writer: tokio::net::unix::OwnedWriteHalf,
) -> anyhow::Result<()> {
    use std::pin::pin;
    use std::time::Duration;
    use tokio::time::Instant;

    // If the reader is already dead (child exited before we connected),
    // send final state and SessionEnded immediately.
    if !h.reader_alive.load(Ordering::Acquire) {
        render_and_send(&h.screen, &mut renderer, &mut writer).await?;
        let msg = protocol::encode(&ServerMsg::SessionEnded {
            exit_code: session_exit_code(&h),
        })?;
        writer.write_all(&msg).await?;
        return Ok(());
    }

    let mut throttle_sleep = pin!(tokio::time::sleep(Duration::ZERO));
    let mut pending_render = false;

    loop {
        tokio::select! {
            _ = h.screen_notify.notified() => {
                if !h.reader_alive.load(Ordering::Acquire) {
                    // Reader exited (PTY EOF). Do a final render + send SessionEnded.
                    let (render_data, passthrough) = {
                        let mut screen = lock_mutex(&h.screen, "screen")?;
                        renderer.take_and_render(&mut *screen)
                    };
                    let update = prepend_passthrough(passthrough, render_data);
                    let msg = protocol::encode(&ServerMsg::ScreenUpdate(update))?;
                    writer.write_all(&msg).await?;
                    let msg = protocol::encode(&ServerMsg::SessionEnded {
                        exit_code: session_exit_code(&h),
                    })?;
                    writer.write_all(&msg).await?;
                    break;
                }
                pending_render = true;
                throttle_sleep.as_mut().reset(Instant::now() + RENDER_THROTTLE);
            }
            _ = &mut throttle_sleep, if pending_render => {
                let (render_data, passthrough) = {
                    let mut screen = lock_mutex(&h.screen, "screen")?;
                    renderer.take_and_render(&mut *screen)
                };
                // Prepend passthrough sequences (e.g. \e[3J) to the screen
                // update so the terminal processes them in a single write.
                // Sending \e[3J as a separate Passthrough message with flush()
                // before ScreenUpdate causes rendering glitches in Blink — the
                // terminal clears the viewport before the new content arrives.
                let update = prepend_passthrough(passthrough, render_data);
                // Skip sending empty updates (no rows dirty, no mode/cursor/title
                // changes). This prevents no-op sync blocks that cause flicker
                // on terminals without DEC 2026 support (e.g. xterm.js).
                if !update.is_empty() {
                    let msg = protocol::encode(&ServerMsg::ScreenUpdate(update))?;
                    writer.write_all(&msg).await?;
                }
                pending_render = false;
            }
            _ = refresh_notify.notified() => {
                render_and_send(&h.screen, &mut renderer, &mut writer).await?;
            }
            result = evict_rx.changed() => {
                match result {
                    Ok(()) => {
                        debug!(session = %h.name, "client evicted by new connection");
                        let msg = protocol::encode(&ServerMsg::Error("evicted by new client".into()))?;
                        if let Err(e) = writer.write_all(&msg).await {
                            debug!(session = %h.name, error = %e, "failed to send eviction notice to client");
                        }
                    }
                    Err(_) => {
                        // Sender dropped — session was killed via KillSession
                        debug!(session = %h.name, "session killed while client connected");
                        let msg = protocol::encode(&ServerMsg::SessionEnded { exit_code: None })?;
                        if let Err(e) = writer.write_all(&msg).await {
                            debug!(session = %h.name, error = %e, "failed to send session-ended to killed client");
                        }
                    }
                }
                break;
            }
        }
    }
    // has_client cleanup is handled by ClientGuard in handle_session
    Ok(())
}

/// Client -> PTY relay loop: reads client messages and dispatches them.
pub(super) async fn client_to_pty(
    h: SessionHandles,
    mut sock_reader: tokio::net::unix::OwnedReadHalf,
    refresh_notify: Arc<tokio::sync::Notify>,
    leftover: Vec<u8>,
) -> anyhow::Result<()> {
    let mut frames = FrameReader::with_leftover(leftover);

    loop {
        if !frames.fill_from(&mut sock_reader).await? {
            debug!(session = %h.name, "client socket closed");
            break;
        }
        while let Some(msg) = frames.decode_next::<ClientMsg>()? {
            match msg {
                ClientMsg::Input(input) => {
                    let pw = h.pty_writer.clone();
                    tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
                        let mut w = lock_mutex(&pw, "pty_writer")?;
                        w.write_all(&input)?;
                        w.flush()?;
                        Ok(())
                    })
                    .await??;
                }
                ClientMsg::Resize { cols, rows } => {
                    let master_clone = h.master.clone();
                    let screen_clone = h.screen.clone();
                    let dims_clone = h.dims.clone();
                    let name_clone = h.name.clone();
                    tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
                        resize_pty(&master_clone, &screen_clone, cols, rows)?;
                        store_dims(&dims_clone, cols, rows, &name_clone);
                        Ok(())
                    })
                    .await??;
                }
                ClientMsg::RefreshScreen => {
                    refresh_notify.notify_one();
                }
                ClientMsg::Detach => {
                    debug!(session = %h.name, "client detached");
                    return Ok(());
                }
                // Connect, ListSessions, KillSession are handled in client_handler
                // before the session bridge loop — they never reach here.
                ClientMsg::Connect { .. }
                | ClientMsg::ListSessions { .. }
                | ClientMsg::KillSession { .. } => {
                    tracing::debug!("ignoring unexpected client message in session relay");
                }
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pty::Pty;
    use retach::screen::{AnsiRenderer, Screen};
    use std::sync::atomic::AtomicBool;
    use std::sync::Mutex as StdMutex;
    use std::time::Duration;

    /// A real `Pty` whose writer/master back the test handles. Kept alive for the
    /// duration of a test so the PTY slave (and thus the writer) stays open.
    fn test_handles(
        reader_alive: bool,
        exit_code: Option<i32>,
    ) -> (
        Pty,
        SessionHandles,
        Arc<tokio::sync::Notify>,
        tokio::sync::watch::Sender<bool>,
        tokio::sync::watch::Receiver<bool>,
    ) {
        let pty = Pty::spawn(80, 24).unwrap();
        let screen = Arc::new(StdMutex::new(Screen::new(80, 24, 1000)));
        let screen_notify = Arc::new(tokio::sync::Notify::new());
        let (evict_tx, evict_rx) = tokio::sync::watch::channel(true);
        let handles = SessionHandles {
            screen,
            pty_writer: pty.writer_arc(),
            master: pty.master_arc(),
            dims: Arc::new(StdMutex::new(retach::screen::TerminalSize {
                cols: 80,
                rows: 24,
            })),
            screen_notify: screen_notify.clone(),
            reader_alive: Arc::new(AtomicBool::new(reader_alive)),
            exit_code: Arc::new(StdMutex::new(exit_code)),
            name: "relay-test".into(),
        };
        (pty, handles, screen_notify, evict_tx, evict_rx)
    }

    /// Drain all `ServerMsg`s sent on the client end of a `UnixStream` pair until EOF.
    async fn drain_server_msgs(client: tokio::net::UnixStream) -> Vec<ServerMsg> {
        let (mut reader, _w) = client.into_split();
        let mut frames = FrameReader::new();
        let mut out = Vec::new();
        while frames.fill_from(&mut reader).await.unwrap_or(false) {
            while let Some(msg) = frames.decode_next::<ServerMsg>().unwrap() {
                out.push(msg);
            }
        }
        while let Some(msg) = frames.decode_next::<ServerMsg>().unwrap() {
            out.push(msg);
        }
        out
    }

    /// (1) When the reader is already dead at connect time, screen_to_client
    /// sends a final render plus SessionEnded carrying the captured exit code,
    /// then returns.
    #[tokio::test]
    async fn screen_to_client_dead_reader_sends_session_ended_with_exit_code() {
        let (_pty, handles, refresh_notify, _evict_tx, evict_rx) = test_handles(false, Some(7));
        {
            let mut scr = handles.screen.lock().unwrap();
            scr.process(b"FINAL OUTPUT");
        }
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let (_r, w) = server.into_split();

        let task = tokio::spawn(screen_to_client(
            handles,
            AnsiRenderer::new(),
            refresh_notify,
            evict_rx,
            w,
        ));
        let msgs = drain_server_msgs(client).await;
        task.await.unwrap().unwrap();

        assert!(
            matches!(
                msgs.last(),
                Some(ServerMsg::SessionEnded { exit_code: Some(7) })
            ),
            "last message must be SessionEnded with the captured exit code: {:?}",
            msgs
        );
        assert!(
            msgs.iter().any(|m| matches!(m, ServerMsg::ScreenUpdate(_))),
            "a final ScreenUpdate must precede SessionEnded: {:?}",
            msgs
        );
    }

    /// (1b) When the reader dies *while* a client is attached, the screen_notify
    /// wake path emits a final ScreenUpdate + SessionEnded and terminates.
    #[tokio::test]
    async fn screen_to_client_reader_dies_while_attached() {
        let (_pty, handles, refresh_notify, _evict_tx, evict_rx) = test_handles(true, Some(3));
        let reader_alive = handles.reader_alive.clone();
        let screen_notify = handles.screen_notify.clone();
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let (_r, w) = server.into_split();

        let task = tokio::spawn(screen_to_client(
            handles,
            AnsiRenderer::new(),
            refresh_notify,
            evict_rx,
            w,
        ));

        // Simulate the persistent reader detecting EOF: clear reader_alive then wake.
        reader_alive.store(false, Ordering::Release);
        screen_notify.notify_one();

        let msgs = drain_server_msgs(client).await;
        task.await.unwrap().unwrap();

        assert!(
            matches!(
                msgs.last(),
                Some(ServerMsg::SessionEnded { exit_code: Some(3) })
            ),
            "reader death while attached must end with SessionEnded(exit 3): {:?}",
            msgs
        );
    }

    /// (2) Eviction via the watch channel pushes an Error to the old client and
    /// terminates its screen_to_client relay.
    #[tokio::test]
    async fn screen_to_client_eviction_notifies_old_client() {
        let (_pty, handles, refresh_notify, evict_tx, evict_rx) = test_handles(true, None);
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let (_r, w) = server.into_split();

        let task = tokio::spawn(screen_to_client(
            handles,
            AnsiRenderer::new(),
            refresh_notify,
            evict_rx,
            w,
        ));

        // A new client connecting would send `false` on the evict channel.
        evict_tx.send(false).unwrap();

        let msgs = drain_server_msgs(client).await;
        // The relay must terminate (task completes) and the old client gets an Error.
        task.await.unwrap().unwrap();
        assert!(
            msgs.iter()
                .any(|m| matches!(m, ServerMsg::Error(s) if s.contains("evicted"))),
            "evicted client must receive an eviction Error: {:?}",
            msgs
        );
    }

    /// (3) ClientMsg::Detach makes client_to_pty return cleanly.
    #[tokio::test]
    async fn client_to_pty_detach_terminates_cleanly() {
        let (_pty, handles, refresh_notify, _evict_tx, _evict_rx) = test_handles(true, None);
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let (sock_reader, _w) = server.into_split();
        let (_cr, mut cw) = client.into_split();

        let task = tokio::spawn(client_to_pty(
            handles,
            sock_reader,
            refresh_notify,
            Vec::new(),
        ));

        let msg = protocol::encode(&ClientMsg::Detach).unwrap();
        cw.write_all(&msg).await.unwrap();

        // Detach must make the loop return Ok without needing the socket to close.
        let result = tokio::time::timeout(Duration::from_secs(2), task)
            .await
            .expect("client_to_pty must return promptly on Detach");
        result.unwrap().unwrap();
    }

    /// (4) Data the persistent reader processes (here driven directly into the
    /// screen) is rendered and delivered to an attached client after the throttle.
    #[tokio::test]
    async fn screen_to_client_delivers_throttled_render() {
        let (_pty, handles, refresh_notify, evict_tx, evict_rx) = test_handles(true, None);
        let screen = handles.screen.clone();
        let screen_notify = handles.screen_notify.clone();
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let (_r, w) = server.into_split();

        let task = tokio::spawn(screen_to_client(
            handles,
            AnsiRenderer::new(),
            refresh_notify,
            evict_rx,
            w,
        ));

        // Persistent reader equivalent: process bytes, then wake the relay.
        {
            let mut scr = screen.lock().unwrap();
            scr.process(b"HELLO_RELAY");
        }
        screen_notify.notify_one();

        // Read on the client end until a ScreenUpdate containing our bytes arrives.
        let (mut reader, _cw) = client.into_split();
        let mut frames = FrameReader::new();
        let mut got = false;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
        'outer: while tokio::time::Instant::now() < deadline {
            let fill =
                tokio::time::timeout(Duration::from_millis(500), frames.fill_from(&mut reader));
            if let Ok(Ok(true)) = fill.await {
                while let Some(msg) = frames.decode_next::<ServerMsg>().unwrap() {
                    if let ServerMsg::ScreenUpdate(data) = msg {
                        if data
                            .windows(b"HELLO_RELAY".len())
                            .any(|w| w == b"HELLO_RELAY")
                        {
                            got = true;
                            break 'outer;
                        }
                    }
                }
            }
        }
        assert!(
            got,
            "client must receive a ScreenUpdate carrying the rendered bytes"
        );

        // Tear down the relay cleanly.
        evict_tx.send(false).unwrap();
        let _ = task.await;
    }
}