Create independent sessions and open SSH sessions in adjacent tabs

Start new windows with a fresh shell and add explicit session selection through --attach. Route in-pane SSH launches back to the originating session, preserving remote shells and tab order across local detach and reattach.
This commit is contained in:
James Magahern
2026-11-17 14:50:29 -08:00
parent 10fa542937
commit d980799648
14 changed files with 2064 additions and 302 deletions
+321 -43
View File
@@ -1,15 +1,20 @@
//! Display-only client transport. No terminal parser, PTY, or shell lives here.
use crate::protocol::{self, ClientMessage, ServerMessage, Snapshot};
use crate::protocol::{self, ClientMessage, ServerMessage, SessionTarget, Snapshot, SshOptions};
use anyhow::{Context, Result, bail};
use std::{
collections::VecDeque,
io::{Read, Write},
collections::{HashSet, VecDeque},
io::{self, Read, Write},
net::Shutdown,
os::unix::net::UnixStream,
path::Path,
process::{Child, Command, Stdio},
sync::{Arc, Mutex, mpsc},
os::{fd::OwnedFd, unix::net::UnixStream},
path::{Path, PathBuf},
process::{Child, ChildStderr, Command, Stdio},
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
mpsc,
},
thread,
time::{Duration, Instant},
};
#[derive(Default)]
@@ -17,6 +22,7 @@ pub struct Update {
pub snapshot: Option<Arc<Snapshot>>,
pub clipboard: VecDeque<String>,
pub error: Option<String>,
pub disconnected: bool,
}
pub struct Updates {
@@ -24,6 +30,11 @@ pub struct Updates {
pending: Arc<Mutex<Update>>,
}
impl Updates {
pub fn recv_blocking(&self) -> Option<Update> {
self.signal.recv_blocking().ok()?;
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
}
pub async fn recv(&self) -> Option<Update> {
self.signal.recv().await.ok()?;
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
@@ -33,6 +44,8 @@ impl Updates {
#[derive(Clone)]
pub struct Client(Arc<Connection>);
struct Connection {
launcher_socket: PathBuf,
remote: Option<String>,
commands: mpsc::Sender<ClientMessage>,
socket: Option<UnixStream>,
ssh: Mutex<Option<Child>>,
@@ -50,17 +63,86 @@ impl Drop for Connection {
}
}
impl SshOptions {
pub fn from_env() -> Self {
Self {
executable: std::env::var("PSYTERM_REMOTE_BIN").ok(),
agent_socket: std::env::var_os("SSH_AUTH_SOCK").map(PathBuf::from),
}
}
}
pub fn validate_destination(destination: &str) -> Result<()> {
if destination.is_empty()
|| destination.len() > 1024
|| destination.starts_with('-')
|| destination
.chars()
.any(|c| c.is_control() || c.is_whitespace())
{
bail!("invalid SSH destination");
}
Ok(())
}
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>, _, _) =
pub fn connect(
launcher_socket: &Path,
remote: Option<&str>,
session: SessionTarget,
) -> Result<(Self, Updates)> {
Self::connect_with(
launcher_socket,
remote,
session,
SshOptions::from_env(),
None,
)
}
pub fn connect_remote(
launcher_socket: &Path,
destination: &str,
session: SessionTarget,
ssh: SshOptions,
cancelled: Arc<AtomicBool>,
) -> Result<(Self, Updates)> {
Self::connect_with(
launcher_socket,
Some(destination),
session,
ssh,
Some(cancelled),
)
}
fn connect_with(
launcher_socket: &Path,
remote: Option<&str>,
session: SessionTarget,
options: SshOptions,
cancelled: Option<Arc<AtomicBool>>,
) -> Result<(Self, Updates)> {
let (mut reader, mut writer, socket, mut ssh): (_, Box<dyn Write + Send>, _, _) =
if let Some(remote) = remote {
if remote.is_empty() || remote.starts_with('-') || remote.contains(['\n', '\r']) {
bail!("invalid SSH destination");
validate_destination(remote)?;
let executable = options.executable.as_deref().unwrap_or("psyterm");
let attach = if matches!(session, SessionTarget::Attach(_)) {
" --attach"
} else {
""
};
let remote_command = format!("exec {} --bridge{attach}", shell_quote(executable));
let mut ssh_command = Command::new("ssh");
if let Some(socket) = options.agent_socket {
ssh_command.env("SSH_AUTH_SOCK", socket);
} else {
ssh_command.env_remove("SSH_AUTH_SOCK");
}
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")
// A socketpair allows a bounded, cancellable greeting even when the
// SSH connection succeeds but the remote bridge stalls.
let (reader, stdout) = UnixStream::pair()?;
let mut child = ssh_command
.args([
"-T",
"-o",
@@ -72,31 +154,52 @@ impl Client {
&remote_command,
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.stdout(Stdio::from(OwnedFd::from(stdout)))
.stderr(Stdio::piped())
.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")?;
let stream =
UnixStream::connect(launcher_socket).context("connect to psyTerm server")?;
crate::launcher::verify_peer(&stream)?;
(
Box::new(stream.try_clone()?) as Box<dyn Read + Send>,
stream.try_clone()?,
Box::new(stream.try_clone()?) as Box<dyn Write + Send>,
Some(stream),
None,
)
};
let stderr = ssh.as_mut().and_then(|child| child.stderr.take());
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 {
launcher_socket: launcher_socket.to_owned(),
remote: remote.map(str::to_owned),
commands,
socket,
ssh: Mutex::new(ssh),
}));
let diagnostic = stderr.map(ssh_diagnostics).transpose()?;
reader.set_read_timeout(Some(Duration::from_millis(150)))?;
let mut greeting = GreetingReader {
reader: &mut reader,
deadline: Instant::now() + Duration::from_secs(if remote.is_some() { 30 } else { 5 }),
cancelled: cancelled.as_deref(),
};
if let Err(error) = greet(&mut greeting, &mut writer, session) {
drop(connection);
if let Some(detail) = diagnostic
.and_then(|rx| rx.recv_timeout(Duration::from_millis(150)).ok())
.filter(|s| !s.is_empty())
{
bail!("{error:#}: {detail}");
}
return Err(error);
}
reader.set_read_timeout(None)?;
let errors = pending.clone();
let notify = signal.clone();
thread::Builder::new()
@@ -116,24 +219,13 @@ impl Client {
.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 => {
Ok(ServerMessage::Snapshot(snapshot)) => {
if let Err(error) = validate_snapshot(&snapshot) {
update.disconnected = true;
update.error = Some(error.to_string());
let _ = signal.try_send(());
break;
@@ -141,13 +233,14 @@ impl Client {
// A slow window never accumulates a queue of obsolete frames.
update.snapshot = Some(Arc::new(snapshot));
}
Ok(ServerMessage::Clipboard(text)) if greeted => {
Ok(ServerMessage::Clipboard(text)) => {
if update.clipboard.len() < 16 {
update.clipboard.push_back(text);
}
}
Ok(ServerMessage::Error(error)) => update.error = Some(error),
Ok(ServerMessage::Closing) => {
update.disconnected = true;
update.error =
Some("Server stopped. Shell sessions have ended.".into());
let _ = signal.try_send(());
@@ -155,9 +248,11 @@ impl Client {
}
Ok(ServerMessage::Pong) => {}
Ok(_) => {
update.error = Some("Server sent data before its handshake".into());
update.error =
Some("Unexpected server response after session handshake".into());
}
Err(error) => {
update.disconnected = true;
update.error = Some(format!(
"Disconnected — sessions remain on the server. {error:#}"
));
@@ -169,10 +264,6 @@ impl Client {
let _ = signal.try_send(());
}
})?;
connection.send(ClientMessage::Hello {
version: protocol::VERSION,
})?;
connection.send(ClientMessage::Attach)?;
Ok((
connection,
Updates {
@@ -182,6 +273,22 @@ impl Client {
))
}
pub fn remote(&self) -> Option<&str> {
self.0.remote.as_deref()
}
/// Launch through the local daemon even when this terminal connects over SSH.
pub fn open_window(&self, remote: Option<String>, cwd: Option<String>) -> Result<()> {
crate::launcher::control(
&self.0.launcher_socket,
ClientMessage::OpenWindow {
target: remote,
session: SessionTarget::New { cwd },
},
)?;
Ok(())
}
pub fn send(&self, message: ClientMessage) -> Result<()> {
self.0
.commands
@@ -199,17 +306,150 @@ impl Client {
}
}
/// Drain SSH stderr throughout the connection. Keep a bounded tail to explain
/// startup failures in the invoking window as well as in the daemon log.
fn ssh_diagnostics(mut stderr: ChildStderr) -> io::Result<mpsc::Receiver<String>> {
let (tx, rx) = mpsc::channel();
thread::Builder::new()
.name("psyterm-ssh-stderr".into())
.spawn(move || {
let mut tail = Vec::new();
let mut buf = [0; 1024];
while let Ok(n) = stderr.read(&mut buf) {
if n == 0 {
break;
}
let _ = io::stderr().write_all(&buf[..n]);
tail.extend_from_slice(&buf[..n]);
tail.drain(..tail.len().saturating_sub(1024));
}
let detail = String::from_utf8_lossy(&tail);
let _ = tx.send(
detail
.trim()
.lines()
.next_back()
.unwrap_or_default()
.to_owned(),
);
})?;
Ok(rx)
}
struct GreetingReader<'a> {
reader: &'a mut UnixStream,
deadline: Instant,
cancelled: Option<&'a AtomicBool>,
}
impl GreetingReader<'_> {
fn check(&self) -> io::Result<()> {
if self
.cancelled
.is_some_and(|flag| flag.load(Ordering::Acquire))
{
return Err(io::Error::new(
io::ErrorKind::ConnectionAborted,
"connection cancelled",
));
}
if Instant::now() >= self.deadline {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out waiting for the psyTerm server",
));
}
Ok(())
}
}
impl Read for GreetingReader<'_> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
loop {
self.check()?;
match self.reader.read(buffer) {
Err(e)
if matches!(
e.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) => {}
result => return result,
}
}
}
}
fn greet(
reader: &mut GreetingReader<'_>,
writer: &mut impl Write,
session: SessionTarget,
) -> Result<()> {
reader.check()?;
protocol::write_message(
writer,
&ClientMessage::Hello {
version: protocol::VERSION,
},
)?;
match protocol::read_message::<ServerMessage>(reader)? {
ServerMessage::Hello { version, .. } if version == protocol::VERSION => {}
ServerMessage::Error(error) => bail!("{error}"),
_ => bail!("server protocol differs from this client"),
}
reader.check()?;
protocol::write_message(writer, &ClientMessage::Connect(session))?;
match protocol::read_message::<ServerMessage>(reader)? {
ServerMessage::Connected { .. } => Ok(()),
ServerMessage::Error(error) => bail!("{error}"),
_ => bail!("server did not acknowledge the session"),
}
}
fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn validate_snapshot(snapshot: &Snapshot) -> Result<()> {
if snapshot.tabs.len() > 256 || snapshot.panes.len() > 64 {
if snapshot.tabs.len() > 256 || snapshot.lineage.len() > 256 || snapshot.panes.len() > 64 {
bail!("Server layout exceeds client limits");
}
let mut tab_ids = HashSet::new();
let mut pane_ids = HashSet::new();
let mut expanded = HashSet::new();
for tab in &snapshot.tabs {
if !tab_ids.insert(tab.id) {
bail!("Server sent a duplicate tab ID");
}
if tab.is_connecting() {
continue;
}
let ordered = tab.stacks.iter().flat_map(|s| s.panes.iter().map(|p| p.id));
if tab.panes.is_empty()
|| tab.panes.len() > 64
|| !tab.panes.iter().all(|id| pane_ids.insert(*id))
|| ordered.ne(tab.panes.iter().copied())
|| !tab.stacks.iter().any(|s| s.active_pane == tab.active_pane)
{
bail!("Server sent an invalid tab layout");
}
for stack in &tab.stacks {
if !stack.panes.iter().any(|p| p.id == stack.active_pane) {
bail!("Server sent an invalid pane stack");
}
if tab.id == snapshot.active_tab {
expanded.insert(stack.active_pane);
}
}
}
if !(tab_ids.contains(&snapshot.active_tab) || (tab_ids.is_empty() && snapshot.active_tab == 0))
{
bail!("Server sent an invalid active tab");
}
for pane in &snapshot.panes {
let count = usize::from(pane.columns) * usize::from(pane.lines);
if pane.columns < 2
if !expanded.remove(&pane.id)
|| pane.columns < 2
|| pane.lines == 0
|| count > 1_000_000
|| pane.cells.len() != count
@@ -223,8 +463,12 @@ fn validate_snapshot(snapshot: &Snapshot) -> Result<()> {
}
/// 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)?;
pub fn bridge(socket: &Path, attach: bool) -> Result<()> {
if attach {
crate::launcher::require_server(socket)?;
} else {
crate::launcher::ensure_server(socket)?;
}
let stream = UnixStream::connect(socket)?;
let mut output = stream.try_clone()?;
let copy_input = thread::spawn(move || {
@@ -282,6 +526,40 @@ mod tests {
assert_eq!(output.bytes, b"binary-without-newlines");
assert!(output.flushes > 0);
}
#[test]
fn stalled_bridge_can_be_cancelled_during_a_partial_greeting() {
let (mut socket, mut peer) = UnixStream::pair().unwrap();
socket
.set_read_timeout(Some(Duration::from_millis(15)))
.unwrap();
let cancelled = AtomicBool::new(false);
thread::scope(|threads| {
let (ready, start) = mpsc::channel();
let (done, wait) = mpsc::channel::<()>();
let flag = &cancelled;
threads.spawn(move || {
peer.write_all(&[8, 0]).unwrap();
start.recv().unwrap();
flag.store(true, Ordering::Release);
// Keep the peer open until the reader notices cancellation.
let _ = wait.recv();
});
let mut greeting = GreetingReader {
reader: &mut socket,
deadline: Instant::now() + Duration::from_secs(5),
cancelled: Some(&cancelled),
};
let mut header = [0; 4];
greeting.read_exact(&mut header[..2]).unwrap();
ready.send(()).unwrap();
assert_eq!(
greeting.read_exact(&mut header[2..]).unwrap_err().kind(),
io::ErrorKind::ConnectionAborted
);
drop(done);
});
}
#[test]
fn remote_binary_paths_are_shell_quoted() {
assert_eq!(shell_quote("/tmp/a'b; x"), "'/tmp/a'\\''b; x'");