term-session 0.9.9-alpha

Run and share terminal sessions in a detached daemon and attach locally or over SSH.
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
//! Binary/daemon tests for the `term-session` gateway.
//!
//! These exercise the real compiled binary (`CARGO_BIN_EXE_term-session`):
//! detachment proof via `--daemon-selfcheck`, daemon resilience to client
//! disconnects and parent death, and clean teardown via `ShutdownGateway`.
//!
//! Each test uses a unique `TERM_WM_GATEWAY` so parallel runs never collide.

use std::io;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};

use muxio_tokio_rpc_ipc_client::RpcCallPrebuffered;
use term_session_muxio_service_definitions::{
    Attach, AttachRequest, ChannelName, ListChannels, ShutdownGateway, Spawn, SpawnRequest,
    SpawnResponse, path_wire, probe_ipc_endpoint,
};

/// The compiled `term-session` binary under test.
fn bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_term-session"))
}

/// Path to the mock PTY binary used as a session child. Delegates to the
/// shared helper in the mock crate's library.
fn mock_bin() -> PathBuf {
    term_session_mock::get_mock_bin()
}

/// A unique per-test gateway name.
fn unique_gateway(tag: &str) -> String {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("term-wm/dtest-{tag}-{id}")
}

/// Spawn the real daemon with the given gateway and an optional selfcheck
/// marker. Returns `(child, marker_path)`.
fn spawn_daemon(gateway: &str, selfcheck: bool) -> (Child, Option<PathBuf>) {
    let marker = if selfcheck {
        let path = std::env::temp_dir().join(format!(
            "term-session-selfcheck-{}.txt",
            gateway.replace('/', "-")
        ));
        let _ = std::fs::remove_file(&path);
        Some(path)
    } else {
        None
    };
    let mut cmd = Command::new(bin());
    cmd.env("TERM_WM_GATEWAY", gateway).arg("--daemon");
    if let Some(ref m) = marker {
        cmd.arg("--daemon-selfcheck").arg(m);
    }
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    let child = cmd.spawn().expect("spawn daemon");
    (child, marker)
}

/// Spawn the daemon with an explicit current directory (distinct from the
/// test harness's cwd), so cwd-propagation tests can detect whether a session
/// inherits the daemon's startup directory or the client's launch directory.
fn spawn_daemon_in(gateway: &str, cwd: &std::path::Path) -> Child {
    let mut cmd = Command::new(bin());
    cmd.env("TERM_WM_GATEWAY", gateway)
        .arg("--daemon")
        .current_dir(cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    cmd.spawn().expect("spawn daemon")
}

/// Attach a client to a channel and return its server-assigned conn id,
/// using the mock identity fields the other helpers expect.
async fn attach_to(
    client: &muxio_tokio_rpc_ipc_client::RpcIpcClient,
    channel: &str,
    hostname: &str,
) -> usize {
    Attach::call(
        client,
        AttachRequest {
            channel: channel.to_string(),
            hostname: hostname.to_string(),
            pid: std::process::id() as u64,
            user: "test-user".to_string(),
            version: "test-version".to_string(),
            ssh_ip: None,
        },
    )
    .await
    .expect("attach")
}

/// Poll until a client can connect to the gateway, or panic after a timeout.
async fn wait_connectable(gateway: &str) -> Arc<muxio_tokio_rpc_ipc_client::RpcIpcClient> {
    let start = Instant::now();
    loop {
        match muxio_tokio_rpc_ipc_client::RpcIpcClient::new(gateway).await {
            Ok(c) => return c,
            Err(_) if start.elapsed() < Duration::from_secs(20) => {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
            Err(e) => panic!("gateway {gateway} not reachable after 20s: {e}"),
        }
    }
}

#[tokio::test]
async fn daemon_detaches_and_reports_proof() {
    let gateway = unique_gateway("detach");
    let (mut child, marker) = spawn_daemon(&gateway, true);
    let marker = marker.expect("marker requested");

    // Wait for the marker (daemon writes it once bound).
    let start = Instant::now();
    let proof = loop {
        if let Ok(content) = std::fs::read_to_string(&marker) {
            break content.trim().to_string();
        }
        assert!(
            start.elapsed() < Duration::from_secs(8),
            "daemon never wrote selfcheck marker"
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    };

    // Platform-specific detachment proof.
    #[cfg(windows)]
    assert_eq!(proof, "windows-no-console", "marker: {proof}");
    #[cfg(unix)]
    assert_eq!(proof, "unix-session-leader", "marker: {proof}");

    // Clean up.
    let client = wait_connectable(&gateway).await;
    ShutdownGateway::call(&*client, true).await.unwrap();
    let _ = child.wait();
}

#[tokio::test]
async fn daemon_survives_all_clients_disconnecting() {
    let gateway = unique_gateway("survive");
    let (mut child, _marker) = spawn_daemon(&gateway, false);

    let client = wait_connectable(&gateway).await;
    let channel = "test/daemon_survive";
    attach_to(&client, channel, "t").await;
    Spawn::call(
        &*client,
        SpawnRequest {
            cmd: Some(vec![
                mock_bin().to_string_lossy().to_string(),
                "sleep".into(),
                "60000".into(),
            ]),
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();
    drop(client);

    // After ALL clients disconnect, the daemon must still be reachable and a
    // fresh attach/spawn must succeed (session respawns / persists).
    let client2 = wait_connectable(&gateway).await;
    attach_to(&client2, channel, "t").await;
    Spawn::call(
        &*client2,
        SpawnRequest {
            cmd: None,
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();

    ShutdownGateway::call(&*client2, true).await.unwrap();
    let _ = child.wait();
}

#[tokio::test]
async fn daemon_survives_parent_death() {
    let gateway = unique_gateway("parent_death");
    let channel = "test/daemon_parent_death";
    let mock = mock_bin().to_string_lossy().to_string();

    // Spawn a client that auto-spawns the daemon, running a LONG-LIVED
    // session so its process survives the parent dying.
    let mut client = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["--channel", channel, "--", &mock, "sleep", "60000"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn auto-attach client");

    // Give it time to auto-spawn the daemon and attach.
    tokio::time::sleep(Duration::from_millis(2000)).await;
    let _ = client.kill();
    let _ = client.wait();

    // The daemon it spawned must still be reachable and the session alive
    // (the `sleep` process is still running, so the daemon must not have
    // exited — sessions are torn down only when their process ends).
    let client = wait_connectable(&gateway).await;
    attach_to(&client, channel, "t").await;
    let SpawnResponse {
        id,
        cols: _,
        rows: _,
    } = Spawn::call(
        &*client,
        SpawnRequest {
            cmd: None,
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();
    assert_eq!(id, 1, "session from the orphaned daemon must persist");

    ShutdownGateway::call(&*client, true).await.unwrap();
    // Give the daemon time to run its teardown and exit.
    tokio::time::sleep(Duration::from_millis(1000)).await;
}

#[tokio::test]
async fn session_starts_in_client_cwd() {
    // A fresh gateway per run: `unique_gateway`'s counter resets per process,
    // so a daemon left over from a failed run on the same name would hold the
    // socket and this test would attach to the wrong (stale) gateway. Deriving
    // the name from the current time guarantees no collision with leftovers.
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let gateway = format!("term-wm/dtest-client_cwd-{nonce}");
    let channel = "test/client_cwd";

    // Distinct directories: the daemon's startup cwd vs the client's launch
    // cwd. The session must start in the latter, not the daemon's. TempDirs
    // auto-cleanup on drop (after the daemon has been shut down).
    let daemon_dir = tempfile::tempdir().expect("daemon tempdir");
    let client_dir = tempfile::tempdir().expect("client tempdir");
    let report_dir = tempfile::tempdir().expect("report tempdir");
    let report = report_dir.path().join("pwd.txt");

    let mut child = spawn_daemon_in(&gateway, daemon_dir.path());
    let client = wait_connectable(&gateway).await;
    attach_to(&client, channel, "cwd").await;

    // Spawn `mock pwd <report>` with the client's launch directory. The mock
    // writes the child's actual cwd to `report` (an absolute path) and exits.
    Spawn::call(
        &*client,
        SpawnRequest {
            cmd: Some(vec![
                mock_bin().to_string_lossy().to_string(),
                "pwd".into(),
                report.to_string_lossy().to_string(),
            ]),
            cols: 80u16,
            rows: 24u16,
            cwd: Some(path_wire::encode_path(client_dir.path())),
        },
    )
    .await
    .unwrap();

    // Poll for the report: the mock writes it right before exiting. The mock
    // reports its cwd as raw wire bytes (lossless), so read them byte-for-byte.
    let start = Instant::now();
    let got = loop {
        if let Ok(content) = std::fs::read(&report) {
            break content;
        }
        assert!(
            start.elapsed() < Duration::from_secs(10),
            "mock pwd never wrote the report"
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    };
    // The child's `current_dir()` is the OS-canonical path (on macOS `/var`
    // resolves to `/private/var`), so canonicalize the expected dir.
    let expected = std::fs::canonicalize(client_dir.path()).unwrap();
    assert_eq!(
        path_wire::decode_path(&path_wire::PathWire::from(got)),
        expected,
        "session must start in the client's launch directory, not the daemon's \
         startup directory ({:?})",
        daemon_dir.path()
    );

    ShutdownGateway::call(&*client, true).await.unwrap();
    let _ = child.wait();
}

/// The daemon must never inherit the parent's open handles. Regression guard
/// for the Windows `bInheritHandles = FALSE` auto-spawn: `std::process::Command`
/// always passes `TRUE`, so a future switch back to it would leak every
/// inheritable handle (pipe ends, sockets) into the daemon.
///
/// The test creates an inheritable pipe, auto-spawns the daemon through the
/// real `connect_or_spawn_server` path, closes the parent's write end, and
/// asserts the read end reaches EOF. If the daemon inherited the write handle
/// it stays open forever and the assertion times out.
#[tokio::test]
async fn daemon_does_not_inherit_parent_handles() {
    use term_session::auto_spawn::connect_or_spawn_server;

    let gateway = unique_gateway("no_inherit");
    // `connect_or_spawn_server` resolves the gateway from `TERM_WM_GATEWAY` in
    // this process's environment; point it at the unique per-test channel.
    // `set_var` is `unsafe` under edition 2024.
    unsafe {
        std::env::set_var("TERM_WM_GATEWAY", &gateway);
    }

    #[cfg(windows)]
    let (read_end, write_end) = create_inheritable_pipe();
    #[cfg(unix)]
    let (read_end, write_end) = create_cloexec_pipe();
    #[cfg(not(any(unix, windows)))]
    panic!("handle-inheritance test not supported on this platform");

    // Auto-spawn the detached daemon via the real auto-spawn path.
    connect_or_spawn_server(Some(&bin())).expect("auto-spawn daemon");

    // Close the parent's write end. A correctly detached daemon holds no copy,
    // so the read end reaches EOF; a daemon that inherited the handle keeps the
    // pipe open indefinitely.
    close_write_end(write_end);

    assert_eof_on_read_end(read_end, Duration::from_secs(5))
        .expect("daemon inherited the parent's pipe write end");

    close_read_end(read_end);

    // Clean up the daemon.
    let client = wait_connectable(&gateway).await;
    ShutdownGateway::call(&*client, true).await.unwrap();
}

/// Create an inheritable named pipe whose read end we keep. Both ends are
/// marked inheritable via `SECURITY_ATTRIBUTES`, so if the daemon is spawned
/// with `bInheritHandles = TRUE` (the regression under test) it keeps the
/// write end and the pipe never breaks.
#[cfg(windows)]
fn create_inheritable_pipe() -> (
    windows_sys::Win32::Foundation::HANDLE,
    windows_sys::Win32::Foundation::HANDLE,
) {
    use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
    use windows_sys::Win32::System::Pipes::CreatePipe;

    let sa = SECURITY_ATTRIBUTES {
        nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: std::ptr::null_mut(),
        bInheritHandle: 1,
    };
    let mut read = std::ptr::null_mut();
    let mut write = std::ptr::null_mut();
    let ok = unsafe { CreatePipe(&mut read, &mut write, &sa, 0) };
    assert_ne!(ok, 0, "CreatePipe failed: {}", io::Error::last_os_error());
    (read, write)
}

/// Create a pipe with both ends CLOEXEC. The std `Command` spawn path never
/// clears CLOEXEC, so a correctly detached daemon never holds the write end.
#[cfg(unix)]
fn create_cloexec_pipe() -> (libc::c_int, libc::c_int) {
    use std::os::unix::io::RawFd;

    let mut fds = [0 as RawFd; 2];
    assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0, "pipe() failed");
    for &fd in &fds {
        let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
        assert!(flags >= 0, "F_GETFD failed");
        let rc = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
        assert_eq!(rc, 0, "F_SETFD failed");
    }
    (fds[0], fds[1])
}

/// Assert the read end reaches EOF (write end fully closed) within `timeout`.
#[cfg(windows)]
fn assert_eof_on_read_end(
    read: windows_sys::Win32::Foundation::HANDLE,
    timeout: Duration,
) -> io::Result<()> {
    use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE;
    use windows_sys::Win32::System::Pipes::PeekNamedPipe;

    let start = Instant::now();
    loop {
        let mut total_avail: u32 = 0;
        let ok = unsafe {
            PeekNamedPipe(
                read,
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                &mut total_avail,
                std::ptr::null_mut(),
            )
        };
        if ok == 0 {
            let err = io::Error::last_os_error();
            if err.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
                // Every write-end handle is gone: the daemon inherited none.
                return Ok(());
            }
            return Err(err);
        }
        if start.elapsed() >= timeout {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "read end never reached EOF (daemon inherited the write handle)",
            ));
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// Assert the read end reaches EOF (write end fully closed) within `timeout`.
#[cfg(unix)]
fn assert_eof_on_read_end(fd: libc::c_int, timeout: Duration) -> io::Result<()> {
    let start = Instant::now();
    loop {
        let mut poll_fds = [libc::pollfd {
            fd,
            events: libc::POLLIN | libc::POLLHUP,
            revents: 0,
        }];
        let n = unsafe { libc::poll(poll_fds.as_mut_ptr(), 1, 50) };
        if n < 0 {
            return Err(io::Error::last_os_error());
        }
        if n > 0 {
            // Drain any buffered bytes; EOF is a zero-length read.
            let mut buf = [0u8; 64];
            loop {
                let r = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
                if r < 0 {
                    if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
                        continue;
                    }
                    return Err(io::Error::last_os_error());
                }
                if r == 0 {
                    return Ok(());
                }
                if (r as usize) < buf.len() {
                    break;
                }
            }
        }
        if start.elapsed() >= timeout {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "read end never reached EOF (child inherited the write fd)",
            ));
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

#[cfg(windows)]
fn close_read_end(read: windows_sys::Win32::Foundation::HANDLE) {
    unsafe {
        let _ = windows_sys::Win32::Foundation::CloseHandle(read);
    }
}

#[cfg(windows)]
fn close_write_end(write: windows_sys::Win32::Foundation::HANDLE) {
    unsafe {
        let _ = windows_sys::Win32::Foundation::CloseHandle(write);
    }
}

#[cfg(unix)]
fn close_read_end(read: libc::c_int) {
    unsafe {
        let _ = libc::close(read);
    }
}

#[cfg(unix)]
fn close_write_end(write: libc::c_int) {
    unsafe {
        let _ = libc::close(write);
    }
}

#[tokio::test]
async fn cli_kill_client_detaches_one_client() {
    let gateway = unique_gateway("kill_client");
    let channel = "test/kill_client";
    let (mut child, _marker) = spawn_daemon(&gateway, false);

    // Two attached clients on the same channel.
    let c1 = wait_connectable(&gateway).await;
    let c2 = wait_connectable(&gateway).await;
    attach_to(&c1, channel, "one").await;
    attach_to(&c2, channel, "two").await;
    Spawn::call(
        &*c1,
        SpawnRequest {
            cmd: Some(vec![
                mock_bin().to_string_lossy().to_string(),
                "sleep".into(),
                "60000".into(),
            ]),
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();
    Spawn::call(
        &*c2,
        SpawnRequest {
            cmd: None,
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();

    // Read the conn ids from `list` (as an operator would).
    let resp = ListChannels::call(&*c1, ()).await.unwrap();
    let ch = resp
        .channels
        .iter()
        .find(|c| c.name == channel)
        .expect("channel listed");
    assert_eq!(ch.clients.len(), 2, "two clients attached");
    let target = ch.clients[0].conn_id;

    // Kill one client through the real CLI subcommand.
    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["kill-client", channel, &target.to_string()])
        .output()
        .expect("run kill-client");
    assert!(
        out.status.success(),
        "kill-client failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // One client remains.
    let resp = ListChannels::call(&*c1, ()).await.unwrap();
    let ch = resp
        .channels
        .iter()
        .find(|c| c.name == channel)
        .expect("channel listed");
    assert_eq!(
        ch.clients.len(),
        1,
        "one client should remain after kill-client"
    );

    ShutdownGateway::call(&*c1, true).await.unwrap();
    let _ = child.wait();
}

#[test]
fn bare_term_session_shows_help_and_does_not_connect() {
    let gateway = unique_gateway("bare");
    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .output()
        .expect("run bare term-session");
    assert_eq!(
        out.status.code(),
        Some(2),
        "bare run must exit 2 (help, not auto-connect), got: {:?}",
        out.status.code()
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--channel"),
        "help should mention --channel, got: {stderr}"
    );
    assert!(
        stderr.contains("ls"),
        "help should list the ls subcommand, got: {stderr}"
    );
    assert!(
        stderr.contains("stop"),
        "help should list stop, got: {stderr}"
    );
    // A bare run must NOT have auto-spawned a daemon on the gateway.
    let gw = ChannelName::parse(&gateway).expect("gateway name");
    assert!(
        !probe_ipc_endpoint(&gw),
        "bare run must not auto-spawn a daemon"
    );
}

#[tokio::test]
async fn top_level_channel_auto_attaches() {
    let gateway = unique_gateway("autoattach");
    let channel = "test/autoattach";
    let mock = mock_bin().to_string_lossy().to_string();
    // `term-session --channel <ch> -- <mock> sleep 60000` (no subcommand):
    // giving a channel must still auto-attach and auto-spawn the daemon.
    let mut client = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["--channel", channel, "--", &mock, "sleep", "60000"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn auto-attach client");

    // The auto-spawned daemon becomes reachable and hosts a live session.
    let rpc = wait_connectable(&gateway).await;
    let start = Instant::now();
    loop {
        let resp = ListChannels::call(&*rpc, ()).await.unwrap();
        let live = resp
            .channels
            .iter()
            .any(|c| c.name == channel && c.session.as_ref().is_some_and(|s| !s.exited));
        if live {
            break;
        }
        assert!(
            start.elapsed() < Duration::from_secs(20),
            "session never appeared on the auto-attached channel"
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    // Cleanup: kill the client process; the daemon (and its live session)
    // survives, so stop it explicitly with force.
    let _ = client.kill();
    let _ = client.wait();
    ShutdownGateway::call(&*rpc, true).await.unwrap();
}

#[tokio::test]
async fn dash_dash_disambiguates_command_from_subcommand() {
    let gateway = unique_gateway("disambig");
    let gw = ChannelName::parse(&gateway).expect("gateway name");

    // `term-session list` (no `--`) parses `list` as the admin SUBCOMMAND: it
    // connects to a gateway and never auto-spawns one.
    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .arg("list")
        .output()
        .expect("run list");
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("No gateway"),
        "`list` must parse as the admin subcommand, got: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !probe_ipc_endpoint(&gw),
        "admin subcommand must not auto-spawn"
    );

    // `term-session -- list` (after `--`) parses `list` as a COMMAND to run:
    // the implicit attach path auto-spawns a gateway.
    let mut client = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["--", "list"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("run -- list");

    // The auto-spawned gateway becomes reachable (the `list` command itself
    // does not exist, so the session spawn fails — but the daemon persists).
    let rpc = wait_connectable(&gateway).await;
    ShutdownGateway::call(&*rpc, true).await.unwrap();
    let _ = client.kill();
    let _ = client.wait();
}

#[tokio::test]
async fn unknown_flag_errors_without_spawning_gateway() {
    // A leading-hyphen token that is not a real flag (e.g. `--list`, a typo for
    // the `list` subcommand) must be rejected by clap, never swallowed into the
    // trailing command and auto-attached. Each must exit non-zero and leave no
    // gateway behind.
    for flag in ["--list", "--bogus", "-x"] {
        let gateway = unique_gateway("unknown_flag");
        let gw = ChannelName::parse(&gateway).expect("gateway name");
        let out = Command::new(bin())
            .env("TERM_WM_GATEWAY", &gateway)
            .arg(flag)
            .output()
            .expect("run with unknown flag");
        assert_ne!(
            out.status.code(),
            Some(0),
            "`{flag}` must not exit successfully"
        );
        assert!(
            String::from_utf8_lossy(&out.stderr).contains("unexpected argument"),
            "`{flag}` must be reported as an unexpected argument, got: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            !probe_ipc_endpoint(&gw),
            "`{flag}` must not auto-spawn a gateway"
        );
    }
}

#[tokio::test]
async fn cli_list_renders_client_identity() {
    let gateway = unique_gateway("list_identity");
    let channel = "test/list_identity";
    let (mut daemon, _marker) = spawn_daemon(&gateway, false);

    // A client that stays connected, with explicit identity fields.
    let client = wait_connectable(&gateway).await;
    Attach::call(
        &*client,
        AttachRequest {
            channel: channel.to_string(),
            hostname: "render-host".to_string(),
            pid: 4242,
            user: "bob".to_string(),
            version: "v7".to_string(),
            ssh_ip: Some("203.0.113.9".to_string()),
        },
    )
    .await
    .unwrap();
    Spawn::call(
        &*client,
        SpawnRequest {
            cmd: None,
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();

    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .arg("list")
        .output()
        .expect("run list");
    assert!(
        out.status.success(),
        "list failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("user: bob"),
        "list must render the client user, got: {stdout}"
    );
    assert!(
        stdout.contains("version: v7"),
        "list must render the client version, got: {stdout}"
    );
    assert!(
        stdout.contains("ssh ip from: 203.0.113.9"),
        "list must render the remote ssh ip, got: {stdout}"
    );

    ShutdownGateway::call(&*client, true).await.unwrap();
    let _ = daemon.wait();
}

#[tokio::test]
async fn cli_stop_requires_force_when_live_sessions() {
    let gateway = unique_gateway("stop_force");
    let channel = "test/stop_force";
    let (mut child, _marker) = spawn_daemon(&gateway, false);

    let client = wait_connectable(&gateway).await;
    attach_to(&client, channel, "cli").await;
    Spawn::call(
        &*client,
        SpawnRequest {
            cmd: Some(vec![
                mock_bin().to_string_lossy().to_string(),
                "sleep".into(),
                "60000".into(),
            ]),
            cols: 80u16,
            rows: 24u16,
            cwd: None,
        },
    )
    .await
    .unwrap();

    // `stop` without --force: refused, non-zero exit, daemon keeps running.
    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .arg("stop")
        .output()
        .expect("run stop");
    assert!(
        !out.status.success(),
        "stop must refuse while a live session runs"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("live session"),
        "refusal message should mention live sessions, got: {stderr}"
    );

    // Gateway still reachable after the refusal.
    ListChannels::call(&*client, ())
        .await
        .expect("gateway alive");

    // `stop --force` succeeds and the daemon process exits on its own.
    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["stop", "--force"])
        .output()
        .expect("run stop --force");
    assert!(
        out.status.success(),
        "stop --force failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let _ = child.wait();
}

/// Regression: a connection/handshake failure must surface on the client's
/// stderr instead of being silently swallowed by the stderr→tracing redirect
/// (see `redirect_fd_to_tracing` in `term-session-client`). The gateway is
/// "occupied" by a socket that accepts and immediately feeds garbage + closes
/// each connection (no muxio handshake), so Attach fails deterministically
/// without auto-spawning a new daemon (probe succeeds because something is
/// bound). Unix-only: the redirect is a unix `dup2` mechanism.
#[cfg(unix)]
#[test]
fn connection_error_is_printed_to_stderr() {
    use interprocess::local_socket::{GenericNamespaced, ListenerOptions, ToNsName, prelude::*};
    use std::io::Write;

    let gateway = unique_gateway("silent-exit");
    let name = gateway
        .as_str()
        .to_ns_name::<GenericNamespaced>()
        .expect("gateway ns name");
    let listener = ListenerOptions::new()
        .name(name)
        .try_overwrite(true)
        .create_sync()
        .expect("bind dummy gateway");
    let acceptor = std::thread::spawn(move || {
        while let Ok(mut stream) = listener.accept() {
            // Garbage + close: muxio decode fails rather than silently EOF.
            let _ = stream.write_all(b"not-a-muxio-frame");
        }
    });

    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["--channel", "test/silent-exit"])
        .output()
        .expect("run client");

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        !stderr.trim().is_empty(),
        "client must emit a diagnostic on a failed connection (silent-exit regression), got empty stderr"
    );
    assert!(
        !out.status.success(),
        "client must exit non-zero, got status: {:?}",
        out.status.code()
    );
    drop(acceptor);
}