Build server-backed psyTerm with multiplexing and themed UI

Move terminal sessions, tabs, panes, and state into a persistent headless
server with local socket and SSH clients. Launch GUIs through a managed
single-threaded zygote while keeping rendering responsive.

Add animated cursors, themed chrome, teal pane focus outlines, uniform
tabs, and middle-truncated names. Support program/CWD titles, manual
renaming, home-directory abbreviation, and automatic pane/tab removal
when shells exit.

Document the process architecture, controls, and third-party cursor
sources. Validated with 57 tests, strict Clippy, and live Wayland checks.
This commit is contained in:
2026-11-17 01:08:35 -08:00
parent de1d5776b6
commit d7e9be973c
18 changed files with 5257 additions and 410 deletions
+289
View File
@@ -0,0 +1,289 @@
//! Display-only client transport. No terminal parser, PTY, or shell lives here.
use crate::protocol::{self, ClientMessage, ServerMessage, Snapshot};
use anyhow::{Context, Result, bail};
use std::{
collections::VecDeque,
io::{Read, Write},
net::Shutdown,
os::unix::net::UnixStream,
path::Path,
process::{Child, Command, Stdio},
sync::{Arc, Mutex, mpsc},
thread,
};
#[derive(Default)]
pub struct Update {
pub snapshot: Option<Arc<Snapshot>>,
pub clipboard: VecDeque<String>,
pub error: Option<String>,
}
pub struct Updates {
signal: async_channel::Receiver<()>,
pending: Arc<Mutex<Update>>,
}
impl Updates {
pub async fn recv(&self) -> Option<Update> {
self.signal.recv().await.ok()?;
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
}
}
#[derive(Clone)]
pub struct Client(Arc<Connection>);
struct Connection {
commands: mpsc::Sender<ClientMessage>,
socket: Option<UnixStream>,
ssh: Mutex<Option<Child>>,
}
impl Drop for Connection {
fn drop(&mut self) {
// Detach closes this transport, never a server-owned PTY.
if let Some(socket) = &self.socket {
let _ = socket.shutdown(Shutdown::Both);
}
if let Some(mut child) = self.ssh.lock().unwrap().take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
impl Client {
pub fn connect(socket: &Path, remote: Option<&str>) -> Result<(Self, Updates)> {
let (reader, writer, socket, ssh): (Box<dyn Read + Send>, Box<dyn Write + Send>, _, _) =
if let Some(remote) = remote {
if remote.is_empty() || remote.starts_with('-') || remote.contains(['\n', '\r']) {
bail!("invalid SSH destination");
}
let executable =
std::env::var("PSYTERM_REMOTE_BIN").unwrap_or_else(|_| "psyterm".into());
let remote_command = format!("exec {} --bridge", shell_quote(&executable));
let mut child = Command::new("ssh")
.args([
"-T",
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=10",
"--",
remote,
&remote_command,
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.context("start SSH terminal transport")?;
let reader = Box::new(child.stdout.take().unwrap()) as Box<dyn Read + Send>;
let writer = Box::new(child.stdin.take().unwrap()) as Box<dyn Write + Send>;
(reader, writer, None, Some(child))
} else {
let stream = UnixStream::connect(socket).context("connect to psyTerm server")?;
crate::launcher::verify_peer(&stream)?;
(
Box::new(stream.try_clone()?) as Box<dyn Read + Send>,
Box::new(stream.try_clone()?) as Box<dyn Write + Send>,
Some(stream),
None,
)
};
let (commands, receive) = mpsc::channel();
let (signal, notifications) = async_channel::bounded(1);
let pending = Arc::new(Mutex::new(Update::default()));
let connection = Self(Arc::new(Connection {
commands,
socket,
ssh: Mutex::new(ssh),
}));
let errors = pending.clone();
let notify = signal.clone();
thread::Builder::new()
.name("psyterm-client-writer".into())
.spawn(move || {
let mut writer = writer;
while let Ok(message) = receive.recv() {
if let Err(error) = protocol::write_message(&mut writer, &message) {
errors.lock().unwrap().error = Some(format!("Connection lost: {error:#}"));
let _ = notify.try_send(());
break;
}
}
})?;
let incoming = pending.clone();
thread::Builder::new()
.name("psyterm-client-reader".into())
.spawn(move || {
let mut reader = reader;
let mut greeted = false;
loop {
let message = protocol::read_message::<ServerMessage>(&mut reader);
let mut update = incoming.lock().unwrap();
match message {
Ok(ServerMessage::Hello { version, .. })
if version == protocol::VERSION =>
{
greeted = true
}
Ok(ServerMessage::Hello { .. }) => {
update.error =
Some("Server protocol version differs from this GUI".into());
let _ = signal.try_send(());
break;
}
Ok(ServerMessage::Snapshot(snapshot)) if greeted => {
if let Err(error) = validate_snapshot(&snapshot) {
update.error = Some(error.to_string());
let _ = signal.try_send(());
break;
}
// A slow window never accumulates a queue of obsolete frames.
update.snapshot = Some(Arc::new(snapshot));
}
Ok(ServerMessage::Clipboard(text)) if greeted => {
if update.clipboard.len() < 16 {
update.clipboard.push_back(text);
}
}
Ok(ServerMessage::Error(error)) => update.error = Some(error),
Ok(ServerMessage::Closing) => {
update.error =
Some("Server stopped. Shell sessions have ended.".into());
let _ = signal.try_send(());
break;
}
Ok(ServerMessage::Pong) => {}
Ok(_) => {
update.error = Some("Server sent data before its handshake".into());
}
Err(error) => {
update.error = Some(format!(
"Disconnected — sessions remain on the server. {error:#}"
));
let _ = signal.try_send(());
break;
}
}
drop(update);
let _ = signal.try_send(());
}
})?;
connection.send(ClientMessage::Hello {
version: protocol::VERSION,
})?;
connection.send(ClientMessage::Attach)?;
Ok((
connection,
Updates {
signal: notifications,
pending,
},
))
}
pub fn send(&self, message: ClientMessage) -> Result<()> {
self.0
.commands
.send(message)
.context("server transport is closed")
}
pub fn input(&self, pane: u64, bytes: Vec<u8>) -> Result<()> {
for chunk in bytes.chunks(64 * 1024) {
self.send(ClientMessage::Input {
pane,
bytes: chunk.to_vec(),
})?;
}
Ok(())
}
}
fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn validate_snapshot(snapshot: &Snapshot) -> Result<()> {
if snapshot.tabs.len() > 256 || snapshot.panes.len() > 64 {
bail!("Server layout exceeds client limits");
}
for pane in &snapshot.panes {
let count = usize::from(pane.columns) * usize::from(pane.lines);
if pane.columns < 2
|| pane.lines == 0
|| count > 1_000_000
|| pane.cells.len() != count
|| pane.selected.len() != count
|| pane.colors.len() > alacritty_terminal::term::color::COUNT
{
bail!("Server sent an invalid terminal grid");
}
}
Ok(())
}
/// SSH starts this command on the remote host. Only framed protocol bytes use stdout.
pub fn bridge(socket: &Path) -> Result<()> {
crate::launcher::ensure_server(socket)?;
let stream = UnixStream::connect(socket)?;
let mut output = stream.try_clone()?;
let copy_input = thread::spawn(move || {
let result = copy_and_flush(&mut std::io::stdin().lock(), &mut output);
let _ = output.shutdown(Shutdown::Write);
result
});
let mut input = stream;
copy_and_flush(&mut input, &mut std::io::stdout().lock())?;
// Don't wait indefinitely for stdin after a remote server disconnects.
drop(copy_input);
Ok(())
}
// stdout is line-buffered even over SSH. Flush each binary chunk; waiting for a
// newline or EOF can withhold a frame tail and deadlock an otherwise idle GUI.
fn copy_and_flush(reader: &mut impl Read, writer: &mut impl Write) -> std::io::Result<()> {
let mut buffer = [0u8; 64 * 1024];
loop {
let count = match reader.read(&mut buffer) {
Ok(0) => return Ok(()),
Ok(count) => count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
writer.write_all(&buffer[..count])?;
writer.flush()?;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn binary_bridge_flushes_without_newlines() {
struct Output {
bytes: Vec<u8>,
flushes: usize,
}
impl Write for Output {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.bytes.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.flushes += 1;
Ok(())
}
}
let mut output = Output {
bytes: Vec::new(),
flushes: 0,
};
copy_and_flush(&mut b"binary-without-newlines".as_slice(), &mut output).unwrap();
assert_eq!(output.bytes, b"binary-without-newlines");
assert!(output.flushes > 0);
}
#[test]
fn remote_binary_paths_are_shell_quoted() {
assert_eq!(shell_quote("/tmp/a'b; x"), "'/tmp/a'\\''b; x'");
}
}