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:
parent
5fa7f0c8b3
commit
a8daf269fb
45 changed files with 3935 additions and 49 deletions
176
crates/control/tests/terminal.rs
Normal file
176
crates/control/tests/terminal.rs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
//! The integrated terminal over a real TCP control connection:
|
||||
//! `terminal.create` answers at once, `terminalOutput` and `terminalExited`
|
||||
//! arrive as event lines from the pump, `terminal.input` reaches the shell.
|
||||
//!
|
||||
//! ConPTY asks for the cursor position (`ESC[6n`) when it starts and waits
|
||||
//! for the answer; the client answers like xterm.js does.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::indexing_slicing,
|
||||
clippy::panic
|
||||
)]
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lutra_testkit::EngineBackend;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A client that answers requests and collects terminal events.
|
||||
struct Client {
|
||||
reader: BufReader<TcpStream>,
|
||||
writer: TcpStream,
|
||||
output: String,
|
||||
exit: Option<Value>,
|
||||
answered: usize,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn connect(addr: std::net::SocketAddr) -> Self {
|
||||
let stream = TcpStream::connect(addr).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
Self {
|
||||
writer: stream.try_clone().unwrap(),
|
||||
reader: BufReader::new(stream),
|
||||
output: String::new(),
|
||||
exit: None,
|
||||
answered: 0,
|
||||
next: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn line(&mut self) -> Value {
|
||||
let mut line = String::new();
|
||||
self.reader.read_line(&mut line).expect("line within 10 s");
|
||||
serde_json::from_str(&line).unwrap()
|
||||
}
|
||||
|
||||
fn event(&mut self, event: &Value) {
|
||||
match event["kind"].as_str() {
|
||||
Some("terminalOutput") => self.output.push_str(event["data"].as_str().unwrap()),
|
||||
Some("terminalExited") => self.exit = Some(event.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next += 1;
|
||||
let request = json!({"id": self.next, "method": method, "params": params});
|
||||
self.writer
|
||||
.write_all(format!("{request}\n").as_bytes())
|
||||
.unwrap();
|
||||
loop {
|
||||
let line = self.line();
|
||||
if let Some(event) = line.get("event") {
|
||||
let event = event.clone();
|
||||
self.event(&event);
|
||||
} else {
|
||||
return line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn execute(&mut self, command: &str, params: Value) -> Value {
|
||||
self.call(
|
||||
"engine.execute",
|
||||
json!({"command": command, "params": params}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Reads events until `done` holds or the terminal exited, answering
|
||||
/// cursor-position queries.
|
||||
fn until(&mut self, id: u64, done: impl Fn(&str) -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while Instant::now() < deadline {
|
||||
while self.answered < self.output.matches("\x1b[6n").count() {
|
||||
let r = self.execute(
|
||||
"terminal.input",
|
||||
json!({"terminalId": id, "data": "\x1b[1;1R"}),
|
||||
);
|
||||
assert!(r.get("error").is_none(), "{r}");
|
||||
self.answered += 1;
|
||||
}
|
||||
if self.exit.is_some() || done(&self.output) {
|
||||
return;
|
||||
}
|
||||
let line = self.line();
|
||||
if let Some(event) = line.get("event") {
|
||||
let event = event.clone();
|
||||
self.event(&event);
|
||||
}
|
||||
}
|
||||
panic!("timed out; output so far: {:?}", self.output);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pumps the backend every 20 ms, like the desktop's pump thread, until
|
||||
/// dropped.
|
||||
struct Pump(Arc<AtomicBool>);
|
||||
|
||||
impl Pump {
|
||||
fn start(backend: Arc<EngineBackend>) -> Self {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let flag = stop.clone();
|
||||
std::thread::spawn(move || {
|
||||
while !flag.load(Ordering::Relaxed) {
|
||||
backend.pump();
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
Self(stop)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pump {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_output_input_exit() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let backend = Arc::new(EngineBackend::new());
|
||||
let server = lutra_control::start(0, backend.clone()).unwrap();
|
||||
let mut client = Client::connect(server.local_addr());
|
||||
client.call("events.subscribe", json!({}));
|
||||
let r = client.execute("project.open", json!({"path": dir.path()}));
|
||||
assert!(r["result"]["root"].is_string(), "{r}");
|
||||
let _pump = Pump::start(backend.clone());
|
||||
|
||||
let shell = if cfg!(windows) { "cmd.exe" } else { "sh" };
|
||||
let r = client.execute(
|
||||
"terminal.create",
|
||||
json!({"shell": shell, "cols": 100, "rows": 30}),
|
||||
);
|
||||
let id = r["result"]["terminalId"].as_u64().expect("terminalId");
|
||||
let r = client.execute(
|
||||
"terminal.input",
|
||||
json!({"terminalId": id, "data": "echo lutra-tcp\r"}),
|
||||
);
|
||||
assert!(r.get("error").is_none(), "{r}");
|
||||
client.until(id, |out| out.matches("lutra-tcp").count() >= 2);
|
||||
let r = client.execute(
|
||||
"terminal.resize",
|
||||
json!({"terminalId": id, "cols": 70, "rows": 20}),
|
||||
);
|
||||
assert!(r.get("error").is_none(), "{r}");
|
||||
client.execute(
|
||||
"terminal.input",
|
||||
json!({"terminalId": id, "data": "exit 4\r"}),
|
||||
);
|
||||
client.until(id, |_| false);
|
||||
let exit = client.exit.clone().unwrap();
|
||||
assert_eq!(
|
||||
exit,
|
||||
json!({"kind": "terminalExited", "terminalId": id, "code": 4})
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue