fleetcom 0.10.0

A fleet-view supervisor for arbitrary shell commands.
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
#![forbid(unsafe_code)]

//! `fleetcom`: a fleet-view supervisor for arbitrary shell commands. Each task is
//! a command in its own PTY; the dashboard groups them by status, and you can
//! peek at, attach to, and background any of them.

// fleetcom requires Unix PTYs, domain sockets, and process-group signaling.
#[cfg(not(unix))]
compile_error!("fleetcom supports Unix platforms only.");

// Terminal-attached client.
mod app;
mod editbuf;
mod selection;
mod ui;

// Task lifecycle and dashboard-preview core.
mod core;
mod preview;
mod supervisor;
mod task;

// Daemon transport, sessions, and wire protocol.
mod daemon;
mod protocol;
mod session;
mod transport;

mod format;
mod harness;
mod path;
mod terminal;

// Shared test scaffolding.
#[cfg(test)]
mod testutil;

pub(crate) use terminal::{ansi, emulator, frame, input};

use std::{
    io::{self, IsTerminal},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

use crossterm::{
    cursor::{Hide, Show},
    event::{
        DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, KeyboardEnhancementFlags,
        PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    },
    execute,
    style::Print,
    terminal::{
        Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
        enable_raw_mode, size, supports_keyboard_enhancement,
    },
};

use app::App;

/// Whether `PushKeyboardEnhancementFlags` actually executed, so restore pops
/// only what setup pushed. A static atomic because the panic hook is installed
/// before the terminal is touched and can fire on any thread; the hook and
/// `TerminalGuard` read the same source of truth. Only atomicity matters here
/// (the flag orders nothing else), so `Relaxed` suffices.
static KITTY_PUSHED: AtomicBool = AtomicBool::new(false);

const USAGE: &str = "\
fleetcom - a fleet-view supervisor for arbitrary shell commands

Usage:
  fleetcom [<session>]               connect to the daemon (autostarting it),
                                     optionally loading a saved session
  fleetcom --foreground [<session>]  run without a daemon; tasks die on quit
  fleetcom --kill                    kill the daemon and every task it owns
  fleetcom --daemon                  run the daemon (internal; the first
                                     fleetcom starts it automatically)

Options:
  -h, --help            print this help
  -V, --version         print the version
  --scrollback <lines>  per-task terminal scrollback in lines
                        (default 2000, max 100000, 0 disables)
";

/// What a command line asks for, one variant per mutually-exclusive mode.
/// Encoding the modes as variants (not independent bools) makes conflicting
/// flags unrepresentable past the parser.
#[derive(Debug, PartialEq, Eq)]
enum Invocation {
    Help,
    Version,
    Daemon,
    Kill,
    Client {
        foreground: bool,
        session: Option<String>,
        /// Validated `--scrollback` value; resolution clamps it later.
        scrollback: Option<usize>,
    },
}

/// Parse the command line. Errors on an unrecognized flag, a second session
/// name, or a flag combination with no coherent meaning. `--help`/`--version`
/// win over everything else, per convention.
fn parse_args(args: &[String]) -> Result<Invocation, String> {
    let (mut daemon, mut kill, mut foreground) = (false, false, false);
    let mut session: Option<String> = None;
    let mut scrollback: Option<usize> = None;
    let mut it = args.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "-h" | "--help" => return Ok(Invocation::Help),
            "-V" | "--version" => return Ok(Invocation::Version),
            "--daemon" => daemon = true,
            "--kill" => kill = true,
            "--foreground" => foreground = true,
            "--scrollback" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--scrollback requires a value".to_string())?;
                scrollback = Some(
                    v.parse()
                        .map_err(|_| format!("invalid --scrollback value '{v}'"))?,
                );
            }
            f if f.starts_with('-') => return Err(format!("unrecognized flag '{f}'")),
            name => {
                if session.is_some() {
                    return Err(format!(
                        "unexpected argument '{name}' (one session name max)"
                    ));
                }
                session = Some(name.to_string());
            }
        }
    }
    if daemon && (kill || foreground || session.is_some() || scrollback.is_some()) {
        return Err("--daemon takes no other arguments".to_string());
    }
    if kill && (foreground || session.is_some() || scrollback.is_some()) {
        return Err("--kill takes no other arguments".to_string());
    }
    match (daemon, kill) {
        (true, _) => Ok(Invocation::Daemon),
        (_, true) => Ok(Invocation::Kill),
        _ => Ok(Invocation::Client {
            foreground,
            session,
            scrollback,
        }),
    }
}

/// Format a fatal error with the program prefix and its `Display` form.
fn error_line(e: impl std::fmt::Display) -> String {
    format!("fleetcom: {e}")
}

fn main() {
    // Present propagated errors consistently and exit with failure.
    if let Err(e) = run() {
        eprintln!("{}", error_line(&e));
        std::process::exit(1);
    }
}

/// Run the program; `main` presents errors returned from this boundary.
fn run() -> io::Result<()> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let (foreground, session, scrollback) = match parse_args(&args) {
        Ok(Invocation::Help) => {
            print!("{USAGE}");
            return Ok(());
        }
        Ok(Invocation::Version) => {
            println!("fleetcom {}", env!("CARGO_PKG_VERSION"));
            return Ok(());
        }
        // Daemon mode is headless: no terminal setup, just serve the socket.
        Ok(Invocation::Daemon) => return daemon::run_daemon(),
        // `fleetcom --kill`: tell a running daemon to kill everything and exit.
        Ok(Invocation::Kill) => return daemon::run_kill(),
        Ok(Invocation::Client {
            foreground,
            session,
            scrollback,
        }) => (foreground, session, scrollback),
        Err(e) => {
            eprintln!("{}", error_line(e));
            eprintln!("try 'fleetcom --help'");
            std::process::exit(2);
        }
    };

    // The interactive client requires stdout for terminal frames. Headless
    // and informational modes return before this check.
    if !io::stdout().is_terminal() {
        eprintln!("{}", error_line("stdout is not a terminal"));
        std::process::exit(1);
    }

    // Install the value before constructing or autostarting a supervisor.
    if let Some(lines) = scrollback {
        supervisor::set_scrollback_flag(lines);
    }

    install_panic_hook();

    let (cols, rows) = size()?;
    // Connect *before* raw mode / alternate screen: the handshake can wait for
    // another client to detach, and the plain terminal is where its waiting
    // notice prints readably and Ctrl-C still aborts. Failures report without
    // any restore dance. `--foreground` runs the core in-process instead.
    let mut app = if foreground {
        App::new_foreground(rows, cols)
    } else {
        match App::connect(rows, cols) {
            Ok(a) => a,
            Err(e) => {
                eprintln!("fleetcom: could not reach the daemon: {e}");
                std::process::exit(1);
            }
        }
    };

    // Keep SIGINT's default behavior while a connection is waiting, then route
    // signals through the app before raw mode requires terminal restoration.
    install_signal_handlers(app.signal_flag())?;

    let mut out = io::stdout();
    enable_raw_mode()?;
    // Armed the moment raw mode is on: every exit past this point (the `?`s
    // below, a panic unwind, the normal return) must restore the terminal,
    // or the shell is left in raw mode with a hidden cursor. The panic hook
    // covers panics only, not `Err` returns.
    let guard = TerminalGuard;
    // Probe for the kitty keyboard protocol before entering the alternate
    // screen: the query round-trips through the tty, and raw mode (just
    // enabled) is what keeps the reply out of the line discipline. `false` on
    // any error: degrade to plain Enter, never to broken input.
    let kitty = supports_keyboard_enhancement().unwrap_or(false);
    execute!(out, EnterAlternateScreen, Clear(ClearType::All), Hide)?;
    // Keyboard enhancement distinguishes modified Enter; bracketed paste
    // delivers the clipboard as one event. Keyboard flags are screen-specific,
    // so enable them after entering the alternate screen. Mouse capture is
    // managed by `App::sync_input_modes`. Save and enable alternate scroll;
    // restoration occurs in `restore_terminal`.
    if kitty {
        execute!(
            out,
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        )?;
        // Recorded only after the execute succeeds: restore mirrors what
        // setup actually did, not what it attempted.
        KITTY_PUSHED.store(true, Ordering::Relaxed);
    }
    execute!(out, EnableBracketedPaste, Print("\x1b[?1007s\x1b[?1007h"))?;
    // `fleetcom [--foreground] <session>` loads that session at startup; the
    // result shows in the status line.
    if let Some(name) = &session {
        app.load_session(name);
    }
    let result = app.run(&mut out);

    // Consuming the guard restores here, at the same point the happy path
    // always restored; the drop-on-unwind path exists for the `?`s above.
    drop(guard);
    result
}

/// Restores the terminal when dropped. Constructed only after
/// `enable_raw_mode` succeeds: before that there is nothing to undo.
struct TerminalGuard;

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        restore_terminal(&mut io::stdout());
    }
}

/// Restore terminal modes changed by the application. Cleanup is best-effort
/// so a failed terminal write does not prevent raw mode from being disabled.
///
/// May run twice: on a panic the hook restores first (so the message prints
/// on the normal screen), then `TerminalGuard`'s drop restores again during
/// unwind. Every step tolerates the repeat (leaving the alternate screen
/// twice, disabling raw mode twice, and popping past an empty kitty stack are
/// all no-ops or ignored), so don't "fix" the double restore by dropping one.
fn restore_terminal(out: &mut io::Stdout) {
    let _ = emit_restore_sequences(out, KITTY_PUSHED.load(Ordering::Relaxed));
    let _ = disable_raw_mode();
}

/// Emit the escape sequences that undo terminal setup, mirroring what setup
/// actually did: the keyboard-enhancement pop only if the flags were pushed.
/// `disable_raw_mode` lives in `restore_terminal`, not here: it mutates
/// process-global tty state, and this function stays a pure emission so tests
/// can drive it against a buffer.
fn emit_restore_sequences(out: &mut impl io::Write, kitty_pushed: bool) -> io::Result<()> {
    if kitty_pushed {
        execute!(out, PopKeyboardEnhancementFlags)?;
    }
    execute!(
        out,
        DisableMouseCapture,
        DisableBracketedPaste,
        Print("\x1b[?1007r"),
        Show,
        LeaveAlternateScreen
    )
}

/// Route external termination signals (SIGTERM/SIGHUP/SIGINT) into a quit
/// flag so the observing loop runs its normal teardown: the client restores
/// the terminal instead of dying in raw mode, and the daemon kills its tasks
/// cleanly. `flag::register` only stores into an atomic, so it stays within
/// `#![forbid(unsafe_code)]`.
pub(crate) fn install_signal_handlers(flag: Arc<AtomicBool>) -> io::Result<()> {
    use signal_hook::consts::{SIGHUP, SIGINT, SIGTERM};
    signal_hook::flag::register(SIGTERM, Arc::clone(&flag))?;
    signal_hook::flag::register(SIGHUP, Arc::clone(&flag))?;
    signal_hook::flag::register(SIGINT, flag)?;
    Ok(())
}

/// Restore the terminal on panic. Otherwise a crash leaves the user in raw
/// mode on the alternate screen with no cursor. Restoring *before* the
/// default hook is what puts the panic message on the normal screen instead
/// of the vanishing alternate screen.
fn install_panic_hook() {
    let default = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore_terminal(&mut io::stdout());
        default(info);
    }));
}

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

    fn parse(args: &[&str]) -> Result<Invocation, String> {
        let owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        parse_args(&owned)
    }

    #[test]
    fn plain_and_session_invocations() {
        assert_eq!(
            parse(&[]),
            Ok(Invocation::Client {
                foreground: false,
                session: None,
                scrollback: None
            })
        );
        assert_eq!(
            parse(&["work"]),
            Ok(Invocation::Client {
                foreground: false,
                session: Some("work".into()),
                scrollback: None
            })
        );
        assert_eq!(
            parse(&["--foreground", "work"]),
            Ok(Invocation::Client {
                foreground: true,
                session: Some("work".into()),
                scrollback: None
            })
        );
    }

    /// `--scrollback` accepts a nonnegative integer and rejects invalid input.
    #[test]
    fn scrollback_flag_parses_and_rejects() {
        assert_eq!(
            parse(&["--scrollback", "5000"]),
            Ok(Invocation::Client {
                foreground: false,
                session: None,
                scrollback: Some(5000)
            })
        );
        assert_eq!(
            parse(&["--scrollback", "0", "work"]),
            Ok(Invocation::Client {
                foreground: false,
                session: Some("work".into()),
                scrollback: Some(0)
            })
        );
        assert!(parse(&["--scrollback", "garbage"]).is_err());
        assert!(parse(&["--scrollback"]).is_err());
        assert!(parse(&["--scrollback", "-5"]).is_err());
        assert!(parse(&["--daemon", "--scrollback", "5000"]).is_err());
        assert!(parse(&["--kill", "--scrollback", "5000"]).is_err());
    }

    #[test]
    fn modes_parse() {
        assert_eq!(parse(&["--daemon"]), Ok(Invocation::Daemon));
        assert_eq!(parse(&["--kill"]), Ok(Invocation::Kill));
        assert_eq!(parse(&["-h"]), Ok(Invocation::Help));
        assert_eq!(parse(&["--help"]), Ok(Invocation::Help));
        assert_eq!(parse(&["-V"]), Ok(Invocation::Version));
        assert_eq!(parse(&["--version"]), Ok(Invocation::Version));
    }

    /// A flag typo must be an error, never silently ignored: `--foregroud`
    /// silently connecting to the daemon changes what `Q` kills.
    #[test]
    fn unknown_flags_are_rejected() {
        assert!(parse(&["--foregroud"]).is_err());
        assert!(parse(&["-x"]).is_err());
        assert!(parse(&["--daemonize"]).is_err());
    }

    /// Help/version win even alongside other (even invalid) mode flags.
    #[test]
    fn help_and_version_win() {
        assert_eq!(parse(&["--daemon", "--help"]), Ok(Invocation::Help));
        assert_eq!(parse(&["--kill", "-V"]), Ok(Invocation::Version));
    }

    #[test]
    fn conflicting_modes_are_rejected() {
        assert!(parse(&["--daemon", "--kill"]).is_err());
        assert!(parse(&["--daemon", "work"]).is_err());
        assert!(parse(&["--daemon", "--foreground"]).is_err());
        assert!(parse(&["--kill", "--foreground"]).is_err());
        assert!(parse(&["--kill", "work"]).is_err());
    }

    #[test]
    fn second_session_name_is_rejected() {
        assert!(parse(&["one", "two"]).is_err());
    }

    /// Fatal error lines use the program prefix and `Display` representation.
    #[test]
    fn error_line_prefixes_display_form() {
        let e = io::Error::new(io::ErrorKind::TimedOut, "daemon did not exit after SIGTERM");
        assert_eq!(
            error_line(&e),
            "fleetcom: daemon did not exit after SIGTERM"
        );
        assert_eq!(
            error_line("stdout is not a terminal"),
            "fleetcom: stdout is not a terminal"
        );
    }

    fn contains(haystack: &[u8], needle: &[u8]) -> bool {
        haystack.windows(needle.len()).any(|w| w == needle)
    }

    /// Render a single crossterm command to bytes, so the assertions below
    /// track crossterm's actual encoding instead of hardcoding it.
    fn encode(cmd: impl crossterm::Command) -> Vec<u8> {
        let mut buf = Vec::new();
        execute!(buf, cmd).unwrap();
        buf
    }

    /// Restore must mirror setup: the keyboard-enhancement pop is emitted
    /// only when the flags were pushed, and its absence must not take the
    /// rest of the restore down with it.
    #[test]
    fn restore_pops_kitty_flags_only_when_pushed() {
        let pop = encode(PopKeyboardEnhancementFlags);

        let mut pushed = Vec::new();
        emit_restore_sequences(&mut pushed, true).unwrap();
        let mut unpushed = Vec::new();
        emit_restore_sequences(&mut unpushed, false).unwrap();

        assert!(contains(&pushed, &pop));
        assert!(!contains(&unpushed, &pop));

        // Both variants still emit the full remaining restore.
        let leave = encode(LeaveAlternateScreen);
        let show = encode(Show);
        for out in [&pushed, &unpushed] {
            assert!(contains(out, &leave));
            assert!(contains(out, &show));
            // Alternate-scroll restore is a raw Print, not a crossterm command.
            assert!(contains(out, b"\x1b[?1007r"));
        }
    }
}