2026-11-17 01:08:35 -08:00
|
|
|
//! Display-only client transport. No terminal parser, PTY, or shell lives here.
|
2026-11-17 16:15:28 -08:00
|
|
|
use crate::protocol::{
|
2026-11-17 19:36:19 -08:00
|
|
|
self, ClientMessage, RemoteSessionInfo, RemoteWindow, ServerMessage, SessionIdentity,
|
|
|
|
|
SessionInfo, SessionRoute, SessionSummary, SessionTarget, Snapshot, SshOptions, TabId,
|
2026-11-17 16:15:28 -08:00
|
|
|
};
|
|
|
|
|
use anyhow::{Context, Result, bail, ensure};
|
2026-11-17 01:08:35 -08:00
|
|
|
use std::{
|
2026-11-17 14:50:29 -08:00
|
|
|
collections::{HashSet, VecDeque},
|
|
|
|
|
io::{self, Read, Write},
|
2026-11-17 01:08:35 -08:00
|
|
|
net::Shutdown,
|
2026-11-17 14:50:29 -08:00
|
|
|
os::{fd::OwnedFd, unix::net::UnixStream},
|
|
|
|
|
path::{Path, PathBuf},
|
|
|
|
|
process::{Child, ChildStderr, Command, Stdio},
|
|
|
|
|
sync::{
|
|
|
|
|
Arc, Mutex,
|
|
|
|
|
atomic::{AtomicBool, Ordering},
|
|
|
|
|
mpsc,
|
|
|
|
|
},
|
2026-11-17 01:08:35 -08:00
|
|
|
thread,
|
2026-11-17 14:50:29 -08:00
|
|
|
time::{Duration, Instant},
|
2026-11-17 01:08:35 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
|
pub struct Update {
|
|
|
|
|
pub snapshot: Option<Arc<Snapshot>>,
|
|
|
|
|
pub clipboard: VecDeque<String>,
|
|
|
|
|
pub error: Option<String>,
|
2026-11-17 14:50:29 -08:00
|
|
|
pub disconnected: bool,
|
2026-11-17 01:08:35 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub struct Updates {
|
|
|
|
|
signal: async_channel::Receiver<()>,
|
|
|
|
|
pending: Arc<Mutex<Update>>,
|
|
|
|
|
}
|
|
|
|
|
impl Updates {
|
2026-11-17 14:50:29 -08:00
|
|
|
pub fn recv_blocking(&self) -> Option<Update> {
|
|
|
|
|
self.signal.recv_blocking().ok()?;
|
|
|
|
|
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
pub async fn recv(&self) -> Option<Update> {
|
|
|
|
|
self.signal.recv().await.ok()?;
|
|
|
|
|
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
2026-11-17 16:15:28 -08:00
|
|
|
pub struct Client {
|
|
|
|
|
connection: Arc<Connection>,
|
|
|
|
|
remote_session: Option<Arc<RemoteSession>>,
|
|
|
|
|
}
|
|
|
|
|
struct RemoteSession {
|
|
|
|
|
identity: SessionIdentity,
|
|
|
|
|
live: AtomicBool,
|
2026-11-17 19:36:19 -08:00
|
|
|
directory: Mutex<RemoteDirectory>,
|
2026-11-17 16:15:28 -08:00
|
|
|
}
|
2026-11-17 19:36:19 -08:00
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
|
struct RemoteDirectory {
|
|
|
|
|
sessions: Vec<RemoteSessionInfo>,
|
|
|
|
|
requested_at: Option<Instant>,
|
|
|
|
|
pending: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl RemoteDirectory {
|
|
|
|
|
fn refresh(&mut self, commands: &mpsc::Sender<ClientMessage>) {
|
|
|
|
|
// A slow host should have at most one request in flight. Allow retries
|
|
|
|
|
// if the peer never answered, and coalesce simultaneous picker queries.
|
|
|
|
|
let interval = Duration::from_secs(if self.pending { 30 } else { 1 });
|
|
|
|
|
if self
|
|
|
|
|
.requested_at
|
|
|
|
|
.is_none_or(|last| last.elapsed() >= interval)
|
|
|
|
|
&& commands.send(ClientMessage::ListSessions).is_ok()
|
|
|
|
|
{
|
|
|
|
|
self.requested_at = Some(Instant::now());
|
|
|
|
|
self.pending = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn received(&mut self, sessions: Vec<SessionInfo>) {
|
|
|
|
|
self.pending = false;
|
|
|
|
|
self.sessions = sessions
|
|
|
|
|
.into_iter()
|
|
|
|
|
.filter_map(|session| {
|
|
|
|
|
// v6's directory describes every tab, but omits the active tab.
|
|
|
|
|
let first = session.tabs.first()?;
|
|
|
|
|
Some(RemoteSessionInfo {
|
|
|
|
|
id: session.id,
|
|
|
|
|
summary: SessionSummary::from_tabs(&session.tabs, first.id),
|
|
|
|
|
attached: session.attached,
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
.collect();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(crate) struct RemoteWindowListing {
|
|
|
|
|
pub summary: SessionSummary,
|
|
|
|
|
pub sessions: Option<Vec<RemoteSessionInfo>>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A direct SSH window has no session on the local daemon. Publish its
|
|
|
|
|
/// layout summary separately so local directory I/O never blocks the grid.
|
|
|
|
|
struct RemoteListing {
|
|
|
|
|
latest: Arc<Mutex<RemoteWindowListing>>,
|
|
|
|
|
notify: UnixStream,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl RemoteListing {
|
|
|
|
|
fn start(
|
|
|
|
|
socket: PathBuf,
|
|
|
|
|
target: RemoteWindow,
|
|
|
|
|
frame: &Snapshot,
|
|
|
|
|
commands: mpsc::Sender<ClientMessage>,
|
|
|
|
|
) -> Result<Self> {
|
|
|
|
|
let identity = frame.lineage[0]; // Verified in greet().
|
|
|
|
|
let latest = Arc::new(Mutex::new(RemoteWindowListing {
|
|
|
|
|
summary: SessionSummary::from_tabs(&frame.tabs, frame.active_tab),
|
|
|
|
|
sessions: None,
|
|
|
|
|
}));
|
|
|
|
|
let published = latest.clone();
|
|
|
|
|
let (notify, changes) = UnixStream::pair()?;
|
|
|
|
|
notify.set_nonblocking(true)?;
|
|
|
|
|
thread::Builder::new()
|
|
|
|
|
.name("psyterm-remote-listing".into())
|
|
|
|
|
.spawn(move || {
|
|
|
|
|
if let Err(error) = crate::launcher::publish_remote_window(
|
|
|
|
|
&socket,
|
|
|
|
|
target,
|
|
|
|
|
identity,
|
|
|
|
|
changes,
|
|
|
|
|
published,
|
|
|
|
|
|| {
|
|
|
|
|
let _ = commands.send(ClientMessage::ListSessions);
|
|
|
|
|
},
|
|
|
|
|
) {
|
|
|
|
|
log::warn!("Could not list SSH window on local server: {error:#}");
|
|
|
|
|
}
|
|
|
|
|
})?;
|
|
|
|
|
Ok(Self { latest, notify })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn update(&mut self, frame: &Snapshot) {
|
|
|
|
|
let summary = SessionSummary::from_tabs(&frame.tabs, frame.active_tab);
|
|
|
|
|
let mut latest = self.latest.lock().unwrap();
|
|
|
|
|
if summary != latest.summary {
|
|
|
|
|
latest.summary = summary;
|
|
|
|
|
// If the nonblocking socket is full, the worker is already due to
|
|
|
|
|
// wake and will publish the latest summary.
|
|
|
|
|
let _ = self.notify.write(&[1]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn update_sessions(&mut self, sessions: &[RemoteSessionInfo]) {
|
|
|
|
|
self.latest.lock().unwrap().sessions = Some(sessions.to_vec());
|
|
|
|
|
// Publish every answer, including an unchanged or empty host directory.
|
|
|
|
|
let _ = self.notify.write(&[1]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
struct Connection {
|
2026-11-17 14:50:29 -08:00
|
|
|
launcher_socket: PathBuf,
|
2026-11-17 16:20:54 -08:00
|
|
|
remote: Option<RemoteWindow>,
|
2026-11-17 01:08:35 -08:00
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 14:50:29 -08:00
|
|
|
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(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
impl Client {
|
2026-11-17 14:50:29 -08:00
|
|
|
pub fn connect(
|
|
|
|
|
launcher_socket: &Path,
|
|
|
|
|
remote: Option<&str>,
|
|
|
|
|
session: SessionTarget,
|
2026-11-17 16:15:28 -08:00
|
|
|
options: SshOptions,
|
2026-11-17 14:50:29 -08:00
|
|
|
) -> Result<(Self, Updates)> {
|
2026-11-17 16:15:28 -08:00
|
|
|
Self::connect_with(launcher_socket, remote, session, options, None)
|
2026-11-17 14:50:29 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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)> {
|
2026-11-17 16:15:28 -08:00
|
|
|
let (session, expected) = match session {
|
|
|
|
|
SessionTarget::Remembered(identity) => (
|
|
|
|
|
SessionTarget::Attach(Some(identity.session)),
|
|
|
|
|
Some(identity),
|
|
|
|
|
),
|
|
|
|
|
other => (other, None),
|
|
|
|
|
};
|
2026-11-17 14:50:29 -08:00
|
|
|
let (mut reader, mut writer, socket, mut ssh): (_, Box<dyn Write + Send>, _, _) =
|
2026-11-17 01:08:35 -08:00
|
|
|
if let Some(remote) = remote {
|
2026-11-17 14:50:29 -08:00
|
|
|
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");
|
2026-11-17 16:20:54 -08:00
|
|
|
if let Some(socket) = &options.agent_socket {
|
2026-11-17 14:50:29 -08:00
|
|
|
ssh_command.env("SSH_AUTH_SOCK", socket);
|
|
|
|
|
} else {
|
|
|
|
|
ssh_command.env_remove("SSH_AUTH_SOCK");
|
2026-11-17 01:08:35 -08:00
|
|
|
}
|
2026-11-17 14:50:29 -08:00
|
|
|
// 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
|
2026-11-17 01:08:35 -08:00
|
|
|
.args([
|
|
|
|
|
"-T",
|
|
|
|
|
"-o",
|
|
|
|
|
"BatchMode=yes",
|
|
|
|
|
"-o",
|
|
|
|
|
"ConnectTimeout=10",
|
|
|
|
|
"--",
|
|
|
|
|
remote,
|
|
|
|
|
&remote_command,
|
|
|
|
|
])
|
|
|
|
|
.stdin(Stdio::piped())
|
2026-11-17 14:50:29 -08:00
|
|
|
.stdout(Stdio::from(OwnedFd::from(stdout)))
|
|
|
|
|
.stderr(Stdio::piped())
|
2026-11-17 01:08:35 -08:00
|
|
|
.spawn()
|
|
|
|
|
.context("start SSH terminal transport")?;
|
|
|
|
|
let writer = Box::new(child.stdin.take().unwrap()) as Box<dyn Write + Send>;
|
|
|
|
|
(reader, writer, None, Some(child))
|
|
|
|
|
} else {
|
2026-11-17 14:50:29 -08:00
|
|
|
let stream =
|
|
|
|
|
UnixStream::connect(launcher_socket).context("connect to psyTerm server")?;
|
2026-11-17 01:08:35 -08:00
|
|
|
crate::launcher::verify_peer(&stream)?;
|
|
|
|
|
(
|
2026-11-17 14:50:29 -08:00
|
|
|
stream.try_clone()?,
|
2026-11-17 01:08:35 -08:00
|
|
|
Box::new(stream.try_clone()?) as Box<dyn Write + Send>,
|
|
|
|
|
Some(stream),
|
|
|
|
|
None,
|
|
|
|
|
)
|
|
|
|
|
};
|
2026-11-17 14:50:29 -08:00
|
|
|
let stderr = ssh.as_mut().and_then(|child| child.stderr.take());
|
2026-11-17 01:08:35 -08:00
|
|
|
let (commands, receive) = mpsc::channel();
|
|
|
|
|
let (signal, notifications) = async_channel::bounded(1);
|
|
|
|
|
let pending = Arc::new(Mutex::new(Update::default()));
|
2026-11-17 16:15:28 -08:00
|
|
|
let connection = Arc::new(Connection {
|
2026-11-17 14:50:29 -08:00
|
|
|
launcher_socket: launcher_socket.to_owned(),
|
2026-11-17 16:20:54 -08:00
|
|
|
remote: remote.map(|destination| RemoteWindow {
|
|
|
|
|
destination: destination.into(),
|
|
|
|
|
ssh: options,
|
|
|
|
|
}),
|
2026-11-17 01:08:35 -08:00
|
|
|
commands,
|
|
|
|
|
socket,
|
|
|
|
|
ssh: Mutex::new(ssh),
|
2026-11-17 16:15:28 -08:00
|
|
|
});
|
2026-11-17 14:50:29 -08:00
|
|
|
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(),
|
|
|
|
|
};
|
2026-11-17 16:15:28 -08:00
|
|
|
let first_frame = match greet(
|
|
|
|
|
&mut greeting,
|
|
|
|
|
&mut writer,
|
|
|
|
|
session,
|
|
|
|
|
remote.is_some(),
|
|
|
|
|
expected,
|
|
|
|
|
) {
|
|
|
|
|
Ok(greeting) => greeting,
|
|
|
|
|
Err(error) => {
|
|
|
|
|
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);
|
2026-11-17 14:50:29 -08:00
|
|
|
}
|
2026-11-17 16:15:28 -08:00
|
|
|
};
|
2026-11-17 19:36:19 -08:00
|
|
|
let remote_session = first_frame
|
|
|
|
|
.as_ref()
|
|
|
|
|
.filter(|_| remote.is_some())
|
|
|
|
|
.map(|frame| {
|
|
|
|
|
Arc::new(RemoteSession {
|
|
|
|
|
identity: frame.lineage[0],
|
|
|
|
|
live: AtomicBool::new(!frame.tabs.is_empty()),
|
|
|
|
|
directory: Mutex::default(),
|
|
|
|
|
})
|
|
|
|
|
});
|
|
|
|
|
// Mounted SSH connections are already listed by their owning daemon.
|
|
|
|
|
let listing = if cancelled.is_none()
|
|
|
|
|
&& let (Some(target), Some(frame)) = (&connection.remote, &first_frame)
|
|
|
|
|
&& !frame.tabs.is_empty()
|
|
|
|
|
{
|
|
|
|
|
RemoteListing::start(
|
|
|
|
|
launcher_socket.to_owned(),
|
|
|
|
|
target.clone(),
|
|
|
|
|
frame,
|
|
|
|
|
connection.commands.clone(),
|
|
|
|
|
)
|
|
|
|
|
.inspect_err(|error| log::warn!("Could not start SSH window listing: {error:#}"))
|
|
|
|
|
.ok()
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
};
|
2026-11-17 16:15:28 -08:00
|
|
|
if let Some(frame) = first_frame {
|
|
|
|
|
pending.lock().unwrap().snapshot = Some(Arc::new(frame));
|
|
|
|
|
let _ = signal.try_send(());
|
2026-11-17 14:50:29 -08:00
|
|
|
}
|
|
|
|
|
reader.set_read_timeout(None)?;
|
2026-11-17 01:08:35 -08:00
|
|
|
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();
|
2026-11-17 16:15:28 -08:00
|
|
|
let reader_session = remote_session.clone();
|
2026-11-17 01:08:35 -08:00
|
|
|
thread::Builder::new()
|
|
|
|
|
.name("psyterm-client-reader".into())
|
2026-11-17 19:36:19 -08:00
|
|
|
.spawn(move || {
|
|
|
|
|
read_updates(
|
|
|
|
|
reader,
|
|
|
|
|
&incoming,
|
|
|
|
|
signal,
|
|
|
|
|
reader_session.as_deref(),
|
|
|
|
|
listing,
|
|
|
|
|
)
|
|
|
|
|
})?;
|
2026-11-17 01:08:35 -08:00
|
|
|
Ok((
|
2026-11-17 16:15:28 -08:00
|
|
|
Self {
|
|
|
|
|
connection,
|
|
|
|
|
remote_session,
|
|
|
|
|
},
|
2026-11-17 01:08:35 -08:00
|
|
|
Updates {
|
|
|
|
|
signal: notifications,
|
|
|
|
|
pending,
|
|
|
|
|
},
|
|
|
|
|
))
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 14:50:29 -08:00
|
|
|
pub fn remote(&self) -> Option<&str> {
|
2026-11-17 16:20:54 -08:00
|
|
|
self.connection
|
|
|
|
|
.remote
|
|
|
|
|
.as_ref()
|
|
|
|
|
.map(|remote| remote.destination.as_str())
|
2026-11-17 16:15:28 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn remote_identity(&self) -> Option<SessionIdentity> {
|
|
|
|
|
self.remote_session.as_ref().map(|session| session.identity)
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 19:36:19 -08:00
|
|
|
/// Queue a host-wide lookup on the live SSH bridge and return its latest
|
|
|
|
|
/// answer immediately, so listing sessions never stalls the daemon actor.
|
|
|
|
|
pub fn remote_directory(&self) -> Vec<RemoteSessionInfo> {
|
|
|
|
|
let Some(remote) = &self.remote_session else {
|
|
|
|
|
return Vec::new();
|
|
|
|
|
};
|
|
|
|
|
let mut directory = remote.directory.lock().unwrap();
|
|
|
|
|
directory.refresh(&self.connection.commands);
|
|
|
|
|
directory.sessions.clone()
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 16:15:28 -08:00
|
|
|
/// Remember a direct SSH window on its local launcher before detaching it.
|
|
|
|
|
pub fn remember_remote_detach(&self) -> Result<()> {
|
2026-11-17 16:20:54 -08:00
|
|
|
let remote = self
|
|
|
|
|
.connection
|
|
|
|
|
.remote
|
|
|
|
|
.as_ref()
|
|
|
|
|
.context("this window is local")?;
|
2026-11-17 16:15:28 -08:00
|
|
|
let session = self
|
|
|
|
|
.remote_session
|
|
|
|
|
.as_ref()
|
|
|
|
|
.context("missing SSH session identity")?;
|
|
|
|
|
if !session.live.load(Ordering::Acquire) {
|
|
|
|
|
return Ok(());
|
|
|
|
|
}
|
|
|
|
|
crate::launcher::control(
|
|
|
|
|
&self.connection.launcher_socket,
|
|
|
|
|
ClientMessage::RememberDetachedRemote(protocol::DetachedRemote {
|
2026-11-17 16:20:54 -08:00
|
|
|
destination: remote.destination.clone(),
|
2026-11-17 16:15:28 -08:00
|
|
|
identity: session.identity,
|
2026-11-17 16:20:54 -08:00
|
|
|
executable: remote.ssh.executable.clone(),
|
2026-11-17 16:15:28 -08:00
|
|
|
}),
|
|
|
|
|
)?;
|
|
|
|
|
Ok(())
|
2026-11-17 14:50:29 -08:00
|
|
|
}
|
|
|
|
|
|
2026-11-17 19:36:19 -08:00
|
|
|
pub fn session_directory(&self) -> Result<crate::launcher::SessionDirectoryPage> {
|
|
|
|
|
crate::launcher::session_directory(&self.connection.launcher_socket)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn open_listed_session(
|
|
|
|
|
&self,
|
|
|
|
|
route: SessionRoute,
|
|
|
|
|
workspace: Option<SessionIdentity>,
|
|
|
|
|
) -> Result<()> {
|
|
|
|
|
let request = match route {
|
|
|
|
|
SessionRoute::Remote(identity) => ClientMessage::OpenPeerSession {
|
|
|
|
|
identity,
|
|
|
|
|
workspace,
|
|
|
|
|
},
|
|
|
|
|
_ => ClientMessage::OpenListedSession(route),
|
|
|
|
|
};
|
|
|
|
|
let response = crate::launcher::control(&self.connection.launcher_socket, request)?;
|
|
|
|
|
ensure!(
|
|
|
|
|
matches!(response, ServerMessage::Pong),
|
|
|
|
|
"local daemon did not open the session"
|
|
|
|
|
);
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 14:50:29 -08:00
|
|
|
/// Launch through the local daemon even when this terminal connects over SSH.
|
2026-11-17 16:20:54 -08:00
|
|
|
pub fn open_window(
|
|
|
|
|
&self,
|
|
|
|
|
remote_tab: Option<(TabId, String)>,
|
|
|
|
|
cwd: Option<String>,
|
|
|
|
|
) -> Result<()> {
|
|
|
|
|
let request = new_window_request(self.connection.remote.as_ref(), remote_tab, cwd);
|
|
|
|
|
if matches!(request, ClientMessage::OpenWindowForRemoteTab { .. }) {
|
|
|
|
|
return self.send(request);
|
|
|
|
|
}
|
|
|
|
|
crate::launcher::control(&self.connection.launcher_socket, request)?;
|
2026-11-17 14:50:29 -08:00
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
pub fn send(&self, message: ClientMessage) -> Result<()> {
|
2026-11-17 16:15:28 -08:00
|
|
|
self.connection
|
2026-11-17 01:08:35 -08:00
|
|
|
.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(())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 16:20:54 -08:00
|
|
|
fn new_window_request(
|
|
|
|
|
direct: Option<&RemoteWindow>,
|
|
|
|
|
remote_tab: Option<(TabId, String)>,
|
|
|
|
|
cwd: Option<String>,
|
|
|
|
|
) -> ClientMessage {
|
|
|
|
|
match (direct, remote_tab) {
|
|
|
|
|
// The local daemon owns the mounted connection, including its SSH options.
|
|
|
|
|
(None, Some((tab, _))) => ClientMessage::OpenWindowForRemoteTab {
|
|
|
|
|
tab,
|
|
|
|
|
cwd,
|
|
|
|
|
fallback: SshOptions::from_env(),
|
|
|
|
|
},
|
|
|
|
|
(None, None) => ClientMessage::OpenWindow {
|
|
|
|
|
target: None,
|
|
|
|
|
session: SessionTarget::New { cwd },
|
|
|
|
|
},
|
|
|
|
|
(Some(direct), None) => ClientMessage::OpenRemoteWindow {
|
|
|
|
|
target: direct.clone(),
|
|
|
|
|
session: SessionTarget::New { cwd },
|
|
|
|
|
},
|
|
|
|
|
(Some(_), Some((_, destination))) => ClientMessage::OpenRemoteWindow {
|
|
|
|
|
target: RemoteWindow::from_env(destination),
|
|
|
|
|
session: SessionTarget::New { cwd },
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 16:15:28 -08:00
|
|
|
fn read_updates(
|
|
|
|
|
mut reader: impl Read,
|
|
|
|
|
pending: &Mutex<Update>,
|
|
|
|
|
signal: async_channel::Sender<()>,
|
|
|
|
|
remote_session: Option<&RemoteSession>,
|
2026-11-17 19:36:19 -08:00
|
|
|
mut listing: Option<RemoteListing>,
|
2026-11-17 16:15:28 -08:00
|
|
|
) {
|
|
|
|
|
loop {
|
|
|
|
|
let message = protocol::read_message::<ServerMessage>(&mut reader);
|
2026-11-17 19:36:19 -08:00
|
|
|
if let Ok(ServerMessage::Sessions(sessions)) = message {
|
|
|
|
|
if let Some(remote) = remote_session {
|
|
|
|
|
let mut directory = remote.directory.lock().unwrap();
|
|
|
|
|
directory.received(sessions);
|
|
|
|
|
if let Some(listing) = &mut listing {
|
|
|
|
|
listing.update_sessions(&directory.sessions);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-11-17 16:15:28 -08:00
|
|
|
let mut update = pending.lock().unwrap();
|
|
|
|
|
match message {
|
|
|
|
|
Ok(ServerMessage::Snapshot(snapshot)) => {
|
|
|
|
|
match validate_snapshot(&snapshot) {
|
|
|
|
|
Ok(()) => {
|
|
|
|
|
if let Some(session) = remote_session {
|
|
|
|
|
session
|
|
|
|
|
.live
|
|
|
|
|
.store(!snapshot.tabs.is_empty(), Ordering::Release);
|
|
|
|
|
}
|
2026-11-17 19:36:19 -08:00
|
|
|
if snapshot.tabs.is_empty() {
|
|
|
|
|
listing = None;
|
|
|
|
|
} else if let Some(listing) = &mut listing {
|
|
|
|
|
listing.update(&snapshot);
|
|
|
|
|
}
|
2026-11-17 16:15:28 -08:00
|
|
|
update.snapshot = Some(Arc::new(snapshot));
|
|
|
|
|
}
|
|
|
|
|
Err(error) => {
|
|
|
|
|
// Older daemons can briefly mix layouts and grids during SSH
|
|
|
|
|
// navigation. A complete frame leaves the stream synchronized.
|
|
|
|
|
update.error = Some(format!("Discarded workspace update: {error}"));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
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) => {
|
|
|
|
|
if let Some(session) = remote_session {
|
|
|
|
|
session.live.store(false, Ordering::Release);
|
|
|
|
|
}
|
|
|
|
|
update.disconnected = true;
|
|
|
|
|
update.error = Some("Server stopped. Shell sessions have ended.".into());
|
|
|
|
|
}
|
|
|
|
|
Ok(ServerMessage::Pong) => {}
|
|
|
|
|
Ok(_) => {
|
|
|
|
|
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:#}"
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
let disconnected = update.disconnected;
|
|
|
|
|
drop(update);
|
|
|
|
|
let _ = signal.try_send(());
|
|
|
|
|
if disconnected {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 14:50:29 -08:00
|
|
|
/// 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,
|
2026-11-17 16:15:28 -08:00
|
|
|
from_ssh: bool,
|
|
|
|
|
expected: Option<SessionIdentity>,
|
|
|
|
|
) -> Result<Option<Snapshot>> {
|
2026-11-17 14:50:29 -08:00
|
|
|
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))?;
|
2026-11-17 16:15:28 -08:00
|
|
|
let session = match protocol::read_message::<ServerMessage>(reader)? {
|
|
|
|
|
ServerMessage::Connected { session } => session,
|
2026-11-17 14:50:29 -08:00
|
|
|
ServerMessage::Error(error) => bail!("{error}"),
|
|
|
|
|
_ => bail!("server did not acknowledge the session"),
|
2026-11-17 16:15:28 -08:00
|
|
|
};
|
|
|
|
|
if !from_ssh && expected.is_none() {
|
|
|
|
|
return Ok(None);
|
2026-11-17 14:50:29 -08:00
|
|
|
}
|
2026-11-17 16:15:28 -08:00
|
|
|
// Session numbers start over after a daemon restart. Check the identity
|
|
|
|
|
// before handing a display or an input channel to the attaching client.
|
|
|
|
|
let frame = match protocol::read_message::<ServerMessage>(reader)? {
|
|
|
|
|
ServerMessage::Snapshot(frame) => frame,
|
|
|
|
|
ServerMessage::Error(error) => bail!("{error}"),
|
2026-11-17 19:36:19 -08:00
|
|
|
_ => bail!("expected initial session snapshot"),
|
2026-11-17 16:15:28 -08:00
|
|
|
};
|
|
|
|
|
validate_snapshot(&frame)?;
|
2026-11-17 19:36:19 -08:00
|
|
|
let identity = frame.lineage.first().context("missing session identity")?;
|
|
|
|
|
ensure!(identity.session == session, "incorrect session identity");
|
2026-11-17 16:15:28 -08:00
|
|
|
if let Some(expected) = expected {
|
2026-11-17 19:36:19 -08:00
|
|
|
ensure!(*identity == expected, "the remembered session has ended");
|
2026-11-17 16:15:28 -08:00
|
|
|
}
|
|
|
|
|
Ok(Some(frame))
|
2026-11-17 14:50:29 -08:00
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
fn shell_quote(value: &str) -> String {
|
|
|
|
|
format!("'{}'", value.replace('\'', "'\\''"))
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 16:13:02 -08:00
|
|
|
pub(crate) fn validate_snapshot(snapshot: &Snapshot) -> Result<()> {
|
2026-11-17 14:50:29 -08:00
|
|
|
if snapshot.tabs.len() > 256 || snapshot.lineage.len() > 256 || snapshot.panes.len() > 64 {
|
2026-11-17 01:08:35 -08:00
|
|
|
bail!("Server layout exceeds client limits");
|
|
|
|
|
}
|
2026-11-17 14:50:29 -08:00
|
|
|
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");
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
for pane in &snapshot.panes {
|
|
|
|
|
let count = usize::from(pane.columns) * usize::from(pane.lines);
|
2026-11-17 14:50:29 -08:00
|
|
|
if !expanded.remove(&pane.id)
|
|
|
|
|
|| pane.columns < 2
|
2026-11-17 01:08:35 -08:00
|
|
|
|| 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.
|
2026-11-17 14:50:29 -08:00
|
|
|
pub fn bridge(socket: &Path, attach: bool) -> Result<()> {
|
|
|
|
|
if attach {
|
|
|
|
|
crate::launcher::require_server(socket)?;
|
|
|
|
|
} else {
|
|
|
|
|
crate::launcher::ensure_server(socket)?;
|
|
|
|
|
}
|
2026-11-17 01:08:35 -08:00
|
|
|
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::*;
|
2026-11-17 16:15:28 -08:00
|
|
|
|
2026-11-17 19:36:19 -08:00
|
|
|
#[test]
|
|
|
|
|
fn ssh_directory_reads_v6_session_lists_alongside_terminal_messages() {
|
|
|
|
|
let remote = RemoteSession {
|
|
|
|
|
identity: SessionIdentity {
|
|
|
|
|
server: [9; 16],
|
|
|
|
|
session: 1,
|
|
|
|
|
},
|
|
|
|
|
live: AtomicBool::new(true),
|
|
|
|
|
directory: Mutex::default(),
|
|
|
|
|
};
|
|
|
|
|
let (commands, sent) = mpsc::channel();
|
|
|
|
|
{
|
|
|
|
|
let mut directory = remote.directory.lock().unwrap();
|
|
|
|
|
directory.refresh(&commands);
|
|
|
|
|
directory.refresh(&commands);
|
|
|
|
|
}
|
|
|
|
|
assert!(matches!(sent.try_recv(), Ok(ClientMessage::ListSessions)));
|
|
|
|
|
assert!(sent.try_recv().is_err());
|
|
|
|
|
|
|
|
|
|
let tab = |id, title: &str| protocol::TabInfo {
|
|
|
|
|
id,
|
|
|
|
|
title: title.into(),
|
|
|
|
|
manual_title: None,
|
|
|
|
|
remote: None,
|
|
|
|
|
panes: vec![id],
|
|
|
|
|
active_pane: id,
|
|
|
|
|
stacks: Vec::new(),
|
|
|
|
|
};
|
|
|
|
|
let (peer, reader) = UnixStream::pair().unwrap();
|
|
|
|
|
reader
|
|
|
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
|
|
|
.unwrap();
|
|
|
|
|
let (signal, changes) = async_channel::bounded(1);
|
|
|
|
|
let pending = Mutex::new(Update::default());
|
|
|
|
|
thread::scope(|scope| {
|
|
|
|
|
let mut peer = peer;
|
|
|
|
|
scope.spawn(|| read_updates(reader, &pending, signal, Some(&remote), None));
|
|
|
|
|
let directory = vec![
|
|
|
|
|
SessionInfo {
|
|
|
|
|
id: 1,
|
|
|
|
|
attached: 1,
|
|
|
|
|
tabs: vec![tab(21, "Current")],
|
|
|
|
|
},
|
|
|
|
|
SessionInfo {
|
|
|
|
|
id: 2,
|
|
|
|
|
attached: 0,
|
|
|
|
|
tabs: vec![tab(31, "Build"), tab(32, "Logs")],
|
|
|
|
|
},
|
|
|
|
|
];
|
|
|
|
|
protocol::write_message(&mut peer, &ServerMessage::Sessions(directory)).unwrap();
|
|
|
|
|
protocol::write_message(&mut peer, &ServerMessage::Clipboard("copied".into())).unwrap();
|
|
|
|
|
changes.recv_blocking().unwrap();
|
|
|
|
|
let mut update = pending.lock().unwrap();
|
|
|
|
|
assert!(update.error.is_none());
|
|
|
|
|
assert_eq!(update.clipboard.pop_front().as_deref(), Some("copied"));
|
|
|
|
|
let list = &remote.directory.lock().unwrap().sessions;
|
|
|
|
|
assert_eq!(list.len(), 2);
|
|
|
|
|
assert_eq!((list[1].id, list[1].attached), (2, 0));
|
|
|
|
|
assert_eq!(list[1].summary.title, "Build");
|
|
|
|
|
assert_eq!((list[1].summary.tabs, list[1].summary.panes), (2, 2));
|
|
|
|
|
peer.shutdown(Shutdown::Write).unwrap();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 16:20:54 -08:00
|
|
|
#[test]
|
|
|
|
|
fn new_window_routes_local_direct_mounted_and_nested_tabs() {
|
|
|
|
|
let direct = RemoteWindow {
|
|
|
|
|
destination: "outer".into(),
|
|
|
|
|
ssh: SshOptions {
|
|
|
|
|
executable: Some("/custom/bin/psyterm".into()),
|
|
|
|
|
agent_socket: Some("/custom/agent.sock".into()),
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
let request = |host, tab| new_window_request(host, tab, Some("/work".into()));
|
|
|
|
|
assert!(matches!(
|
|
|
|
|
request(None, None),
|
|
|
|
|
ClientMessage::OpenWindow { target: None, .. }
|
|
|
|
|
));
|
|
|
|
|
assert!(matches!(
|
|
|
|
|
request(None, Some((42, "outer".into()))),
|
|
|
|
|
ClientMessage::OpenWindowForRemoteTab { tab: 42, .. }
|
|
|
|
|
));
|
|
|
|
|
let ClientMessage::OpenRemoteWindow { target, session } = request(Some(&direct), None)
|
|
|
|
|
else {
|
|
|
|
|
panic!("expected direct SSH window")
|
|
|
|
|
};
|
|
|
|
|
assert!(matches!(session, SessionTarget::New { cwd: Some(cwd) } if cwd == "/work"));
|
|
|
|
|
assert_eq!(target.destination, direct.destination);
|
|
|
|
|
assert_eq!(target.ssh.executable, direct.ssh.executable);
|
|
|
|
|
assert_eq!(target.ssh.agent_socket, direct.ssh.agent_socket);
|
|
|
|
|
let ClientMessage::OpenRemoteWindow { target, .. } =
|
|
|
|
|
request(Some(&direct), Some((42, "inner".into())))
|
|
|
|
|
else {
|
|
|
|
|
panic!("expected nested SSH window")
|
|
|
|
|
};
|
|
|
|
|
assert_eq!(target.destination, "inner");
|
|
|
|
|
let fallback = SshOptions::from_env();
|
|
|
|
|
assert_eq!(target.ssh.executable, fallback.executable);
|
|
|
|
|
assert_eq!(target.ssh.agent_socket, fallback.agent_socket);
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 16:15:28 -08:00
|
|
|
#[test]
|
|
|
|
|
fn invalid_frame_does_not_disconnect_local_or_remote_workspaces() {
|
|
|
|
|
let remote = RemoteSession {
|
|
|
|
|
identity: SessionIdentity {
|
|
|
|
|
server: [1; 16],
|
|
|
|
|
session: 1,
|
|
|
|
|
},
|
|
|
|
|
live: AtomicBool::new(true),
|
2026-11-17 19:36:19 -08:00
|
|
|
directory: Mutex::default(),
|
2026-11-17 16:15:28 -08:00
|
|
|
};
|
|
|
|
|
for session in [None, Some(&remote)] {
|
|
|
|
|
let (client, mut server) = UnixStream::pair().unwrap();
|
|
|
|
|
client
|
|
|
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
|
|
|
.unwrap();
|
|
|
|
|
let pending = Mutex::new(Update::default());
|
|
|
|
|
let (signal, received) = async_channel::bounded(1);
|
|
|
|
|
thread::scope(|threads| {
|
2026-11-17 19:36:19 -08:00
|
|
|
threads.spawn(|| read_updates(client, &pending, signal, session, None));
|
2026-11-17 16:15:28 -08:00
|
|
|
let mut send_snapshot = |snapshot| {
|
|
|
|
|
protocol::write_message(&mut server, &ServerMessage::Snapshot(snapshot))
|
|
|
|
|
.unwrap();
|
|
|
|
|
received.recv_blocking().unwrap();
|
|
|
|
|
std::mem::take(&mut *pending.lock().unwrap())
|
|
|
|
|
};
|
|
|
|
|
let frame = Snapshot {
|
|
|
|
|
lineage: vec![remote.identity],
|
|
|
|
|
revision: 1,
|
|
|
|
|
tabs: vec![protocol::TabInfo {
|
|
|
|
|
id: 1,
|
|
|
|
|
remote: Some("work".into()),
|
|
|
|
|
title: "work".into(),
|
|
|
|
|
manual_title: None,
|
|
|
|
|
panes: Vec::new(),
|
|
|
|
|
active_pane: 0,
|
|
|
|
|
stacks: Vec::new(),
|
|
|
|
|
}],
|
|
|
|
|
active_tab: 1,
|
|
|
|
|
panes: Vec::new(),
|
|
|
|
|
};
|
|
|
|
|
assert_eq!(send_snapshot(frame.clone()).snapshot.unwrap().revision, 1);
|
|
|
|
|
|
|
|
|
|
let skipped = send_snapshot(Snapshot {
|
|
|
|
|
revision: 2,
|
|
|
|
|
active_tab: 42,
|
|
|
|
|
..frame.clone()
|
|
|
|
|
});
|
|
|
|
|
assert!(skipped.snapshot.is_none());
|
|
|
|
|
assert!(skipped.error.unwrap().contains("invalid active tab"));
|
|
|
|
|
assert!(!skipped.disconnected);
|
|
|
|
|
|
|
|
|
|
let resumed = send_snapshot(Snapshot {
|
|
|
|
|
revision: 3,
|
|
|
|
|
..frame
|
|
|
|
|
});
|
|
|
|
|
assert_eq!(resumed.snapshot.unwrap().revision, 3);
|
|
|
|
|
assert!(!resumed.disconnected);
|
|
|
|
|
|
|
|
|
|
server.shutdown(Shutdown::Write).unwrap();
|
|
|
|
|
received.recv_blocking().unwrap();
|
|
|
|
|
assert!(pending.lock().unwrap().disconnected);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn remote_session_can_be_remembered_after_transport_loss_but_not_after_exit() {
|
|
|
|
|
let empty = ServerMessage::Snapshot(Snapshot {
|
|
|
|
|
revision: 2,
|
|
|
|
|
lineage: Vec::new(),
|
|
|
|
|
tabs: Vec::new(),
|
|
|
|
|
active_tab: 0,
|
|
|
|
|
panes: Vec::new(),
|
|
|
|
|
});
|
|
|
|
|
for (last_message, resumable) in [
|
|
|
|
|
(ServerMessage::Pong, true),
|
|
|
|
|
(empty, false),
|
|
|
|
|
(ServerMessage::Closing, false),
|
|
|
|
|
] {
|
|
|
|
|
let remote = RemoteSession {
|
|
|
|
|
identity: SessionIdentity {
|
|
|
|
|
server: [1; 16],
|
|
|
|
|
session: 1,
|
|
|
|
|
},
|
|
|
|
|
live: AtomicBool::new(true),
|
2026-11-17 19:36:19 -08:00
|
|
|
directory: Mutex::default(),
|
2026-11-17 16:15:28 -08:00
|
|
|
};
|
|
|
|
|
let mut bytes = Vec::new();
|
|
|
|
|
protocol::write_message(&mut bytes, &last_message).unwrap();
|
|
|
|
|
let (signal, _updates) = async_channel::bounded(1);
|
|
|
|
|
read_updates(
|
|
|
|
|
bytes.as_slice(),
|
|
|
|
|
&Mutex::new(Update::default()),
|
|
|
|
|
signal,
|
|
|
|
|
Some(&remote),
|
2026-11-17 19:36:19 -08:00
|
|
|
None,
|
2026-11-17 16:15:28 -08:00
|
|
|
);
|
|
|
|
|
assert_eq!(remote.live.load(Ordering::Acquire), resumable);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
#[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);
|
|
|
|
|
}
|
2026-11-17 14:50:29 -08:00
|
|
|
#[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);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 01:08:35 -08:00
|
|
|
#[test]
|
|
|
|
|
fn remote_binary_paths_are_shell_quoted() {
|
|
|
|
|
assert_eq!(shell_quote("/tmp/a'b; x"), "'/tmp/a'\\''b; x'");
|
|
|
|
|
}
|
|
|
|
|
}
|