M3.6: integrated terminal with PTY sessions and xterm.js sub-tabs

- crates/terminal: portable-pty sessions (ConPTY on Windows) with reader,
  writer and waiter threads, UTF-8 chunking, a 1 MiB output buffer with
  backpressure, a non-blocking input queue, resize, kill and exit codes;
  default shell pwsh -> powershell -> cmd on Windows, $SHELL or /bin/sh.
- Engine: terminal.create/input/resize/close, terminalOutput (capped per
  terminal and per pump, round-robin) and terminalExited through the pump;
  terminals close with the project and on app.quit.
- UI: Terminal tab in the bottom panel (tabs next to Find), xterm.js with
  the fit addon, sub-tabs, copy/paste, a focus rule that leaves plain Ctrl
  keys to the shell, terminal.open (Mod+Shift+T), --lt-terminal-* ANSI
  tokens in both themes (text colours AA) and a 4.5:1 minimum contrast.
- Tests: real-shell crate tests (UTF-8, backpressure), engine and TCP
  control tests, Vitest with a mocked xterm; live check on port 7936;
  docs and parity rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-18 11:25:30 +02:00
parent 5fa7f0c8b3
commit a8daf269fb
45 changed files with 3935 additions and 49 deletions

View file

@ -0,0 +1,263 @@
//! Sessions with a real shell: `cmd.exe` on Windows, `/bin/sh` elsewhere.
//!
//! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits
//! for the answer; xterm.js gives it in the app, [`drive`] gives it here.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::ffi::OsString;
use std::time::{Duration, Instant};
use lutra_terminal::{Exit, OUTPUT_CAP, Session, Shell, SpawnOptions, TerminalError, find_in_path};
/// The platform's plain shell.
fn plain_shell() -> std::path::PathBuf {
if cfg!(windows) {
find_in_path("cmd.exe").unwrap()
} else {
"/bin/sh".into()
}
}
/// Runs a one-line command with `cmd /c` or `sh -c`.
fn command(windows: &[&str], unix: &str) -> Shell {
let args: Vec<OsString> = if cfg!(windows) {
std::iter::once("/c")
.chain(windows.iter().copied())
.map(OsString::from)
.collect()
} else {
vec!["-c".into(), unix.into()]
};
Shell {
program: plain_shell(),
args,
}
}
/// An interactive plain shell.
fn interactive() -> Shell {
let args = if cfg!(windows) {
vec![OsString::from("/q")]
} else {
Vec::new()
};
Shell {
program: plain_shell(),
args,
}
}
fn spawn(shell: Shell, cols: u16) -> Session {
Session::spawn(SpawnOptions {
shell,
cwd: std::env::temp_dir(),
cols,
rows: 24,
env: Vec::new(),
})
.unwrap()
}
/// Takes output until `done` holds for it or the session exited (then the
/// exit is returned), answering cursor-position queries, for at most 30 s.
fn drive(session: &Session, done: impl Fn(&str) -> bool) -> (String, Option<Exit>) {
let deadline = Instant::now() + Duration::from_secs(30);
let mut all = String::new();
let mut answered = 0;
loop {
all.push_str(&session.take_output(64 * 1024));
let asked = all.matches("\x1b[6n").count();
while answered < asked {
let _ = session.write(b"\x1b[1;1R");
answered += 1;
}
if let Some(exit) = session.exit() {
return (all, Some(exit));
}
if done(&all) || Instant::now() > deadline {
return (all, None);
}
std::thread::sleep(Duration::from_millis(10));
}
}
/// Drives the session to its end.
fn finish(session: &Session) -> (String, Exit) {
let (out, exit) = drive(session, |_| false);
(out, exit.expect("the session did not exit in time"))
}
#[test]
fn echo_output_and_exit_code() {
let s = spawn(command(&["echo", "lutra-ok"], "echo lutra-ok"), 80);
assert!(s.pid().is_some());
let (out, exit) = finish(&s);
assert!(out.contains("lutra-ok"), "{out:?}");
assert_eq!(exit.code, Some(0));
assert_eq!(s.write(b"x"), Err(TerminalError::Exited));
}
#[test]
fn reports_the_exit_code() {
let s = spawn(command(&["exit", "3"], "exit 3"), 80);
assert_eq!(finish(&s).1.code, Some(3));
}
#[test]
fn input_reaches_the_shell() {
let s = spawn(interactive(), 120);
s.write(b"echo lutra-in-%OS%-$0\r").unwrap();
let (out, exit) = drive(&s, |out| out.contains("lutra-in-"));
assert!(exit.is_none());
assert!(out.contains("lutra-in-"), "{out:?}");
s.write(b"exit 5\r").unwrap();
assert_eq!(finish(&s).1.code, Some(5));
}
#[test]
fn multibyte_output_survives_read_boundaries() {
let text = "äöü€".repeat(1500);
let s = spawn(
command(&["echo", &text], &format!("printf '%s' '{text}'")),
200,
);
let (out, exit) = finish(&s);
assert_eq!(exit.code, Some(0));
assert!(!out.contains('\u{fffd}'), "replacement character in output");
assert!(out.matches('€').count() >= 1500, "characters were lost");
}
/// Padding of each line in the backpressure test, so that the output is
/// well over twice [`OUTPUT_CAP`] even if ConPTY drops a few bytes.
const PAD: &str =
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
/// The shell prints a file of about 3 MB with `type` / `cat`, which is
/// fast, so the test depends on the buffer and not on how quickly a shell
/// loop runs on a busy machine.
#[test]
fn a_full_buffer_stops_the_shell_without_dropping_output() {
let lines = 30_000;
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("lines.txt");
let text: String = (1..=lines)
.map(|i| {
format!(
"line-{i}-{PAD}
"
)
})
.collect();
assert!(
text.len() > 2 * OUTPUT_CAP,
"the output must overfill the buffer by far"
);
std::fs::write(&file, text).unwrap();
let path = file.to_string_lossy().into_owned();
let s = spawn(command(&["type", &path], &format!("cat '{path}'")), 200);
let (mut out, exit) = drive(&s, |out| out.contains("line-1-"));
assert!(exit.is_none(), "the shell ended early: {out:?}");
let deadline = Instant::now() + Duration::from_secs(60);
while s.buffered_bytes() < OUTPUT_CAP {
assert!(Instant::now() < deadline, "the buffer never filled");
std::thread::sleep(Duration::from_millis(20));
}
std::thread::sleep(Duration::from_millis(500));
let buffered = s.buffered_bytes();
assert!(
buffered <= OUTPUT_CAP + 64 * 1024,
"buffered {buffered} bytes"
);
assert!(
s.exit().is_none(),
"the shell went on while the buffer was full"
);
let first = s.take_output(10);
assert!(first.len() <= 10 && !first.is_empty());
out.push_str(&first);
let deadline = Instant::now() + Duration::from_secs(120);
let exit = loop {
out.push_str(&s.take_output(256 * 1024));
if let Some(exit) = s.exit() {
break exit;
}
assert!(Instant::now() < deadline, "the shell did not finish");
std::thread::sleep(Duration::from_millis(5));
};
assert_eq!(exit.code, Some(0));
assert!(
out.contains(&format!("line-{lines}-")),
"the last line is missing"
);
let seen = (1..=lines)
.step_by(997)
.filter(|i| out.contains(&format!("line-{i}-")))
.count();
assert_eq!(seen, (1..=lines).step_by(997).count(), "lines were dropped");
}
#[test]
fn resizes_and_rejects_bad_sizes() {
let s = spawn(interactive(), 80);
s.resize(120, 40).unwrap();
assert!(matches!(
s.resize(0, 10),
Err(TerminalError::InvalidSize { .. })
));
assert!(matches!(
s.resize(80, 1001),
Err(TerminalError::InvalidSize { .. })
));
let _ = drive(&s, |out| !out.is_empty());
s.write(b"exit\r").unwrap();
finish(&s);
assert_eq!(s.resize(80, 24), Err(TerminalError::Exited));
}
#[test]
fn kill_ends_the_session() {
let mut s = spawn(interactive(), 80);
let _ = drive(&s, |out| !out.is_empty());
s.kill();
assert_eq!(s.write(b"x"), Err(TerminalError::Exited));
let deadline = Instant::now() + Duration::from_secs(10);
while s.exit().is_none() {
assert!(Instant::now() < deadline, "no exit after kill");
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(s.buffered_bytes(), 0);
}
#[test]
fn spawn_errors() {
let options = |shell: Shell, cwd: std::path::PathBuf, cols| SpawnOptions {
shell,
cwd,
cols,
rows: 24,
env: Vec::new(),
};
let tmp = std::env::temp_dir();
assert!(matches!(
Session::spawn(options(interactive(), tmp.join("lutra-no-such-dir"), 80)),
Err(TerminalError::Spawn(_))
));
assert!(matches!(
Session::spawn(options(
Shell::new("lutra-no-such-shell-x"),
tmp.clone(),
80
)),
Err(TerminalError::Spawn(_))
));
assert!(matches!(
Session::spawn(options(interactive(), tmp, 0)),
Err(TerminalError::InvalidSize { cols: 0, rows: 24 })
));
}