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:
+11
-1
@@ -14,6 +14,9 @@ pub fn action_for_key(key: &Keystroke) -> Option<CommandAction> {
|
||||
};
|
||||
if modifiers == window_modifiers {
|
||||
match name.as_str() {
|
||||
"n" if modifiers.shift == cfg!(not(target_os = "macos")) => {
|
||||
return Some(CommandAction::NewWindow);
|
||||
}
|
||||
// GPUI may fold Shift into the symbol. On XKB the keypad keys
|
||||
// have separate "add" and "subtract" names.
|
||||
"+" | "=" | "add" => return Some(CommandAction::IncreaseFontSize),
|
||||
@@ -148,9 +151,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_size_shortcuts_use_platform_conventions() {
|
||||
fn new_window_and_text_size_shortcuts_use_platform_conventions() {
|
||||
use CommandAction::*;
|
||||
|
||||
let new_window = if cfg!(target_os = "macos") {
|
||||
"cmd-n"
|
||||
} else {
|
||||
"ctrl-shift-n"
|
||||
};
|
||||
assert!(matches!(action(new_window), Some(NewWindow)));
|
||||
assert!(action("ctrl-n").is_none());
|
||||
for key in [
|
||||
"secondary-+",
|
||||
"secondary-=",
|
||||
|
||||
+321
-43
@@ -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'");
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::protocol::{ScrollKind, Snapshot};
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum CommandAction {
|
||||
TogglePalette,
|
||||
NewWindow,
|
||||
NewTab,
|
||||
IncreaseFontSize,
|
||||
DecreaseFontSize,
|
||||
@@ -112,6 +113,13 @@ pub fn root_items(snapshot: Option<&Snapshot>) -> Vec<PaletteItem> {
|
||||
shortcut("Cmd+T", "Ctrl+Shift+T"),
|
||||
NewTab,
|
||||
),
|
||||
PaletteItem::action(
|
||||
"new-window",
|
||||
"New window",
|
||||
"create independent terminal session",
|
||||
shortcut("Cmd+N", "Ctrl+Shift+N"),
|
||||
NewWindow,
|
||||
),
|
||||
PaletteItem::action(
|
||||
"split-pane",
|
||||
"Split pane right",
|
||||
|
||||
+27
-2
@@ -105,6 +105,13 @@ pub fn control(socket: &Path, command: ClientMessage) -> Result<ServerMessage> {
|
||||
result
|
||||
}
|
||||
|
||||
pub fn require_server(socket: &Path) -> Result<()> {
|
||||
if !probe_server(socket)? {
|
||||
bail!("no sessions to attach to at {}", socket.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn probe_server(socket: &Path) -> Result<bool> {
|
||||
match UnixStream::connect(socket) {
|
||||
Ok(stream) => {
|
||||
@@ -163,7 +170,9 @@ fn control_stream_version(
|
||||
loop {
|
||||
let message: ServerMessage = protocol::read_message(&mut stream)?;
|
||||
match message {
|
||||
ServerMessage::Pong | ServerMessage::Closing => return Ok(message),
|
||||
ServerMessage::Pong | ServerMessage::Closing | ServerMessage::Sessions(_) => {
|
||||
return Ok(message);
|
||||
}
|
||||
ServerMessage::Error(error) => bail!("{error}"),
|
||||
_ => {}
|
||||
}
|
||||
@@ -215,13 +224,29 @@ fn role_command(executable: &Path, role: &str, socket: &Path, log_path: &Path) -
|
||||
|
||||
// AppKit needs a fresh process for a server-requested window on macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn open_window(socket: &Path, remote: Option<String>) -> Result<()> {
|
||||
pub fn open_window(
|
||||
socket: &Path,
|
||||
remote: Option<String>,
|
||||
session: protocol::SessionTarget,
|
||||
) -> Result<()> {
|
||||
let mut command = role_command(
|
||||
&executable_path()?,
|
||||
"--gui",
|
||||
socket,
|
||||
&suffixed(socket, ".gui.log"),
|
||||
)?;
|
||||
match session {
|
||||
protocol::SessionTarget::New { cwd: Some(cwd) } => {
|
||||
command.arg("--cwd").arg(cwd);
|
||||
}
|
||||
protocol::SessionTarget::New { .. } => {}
|
||||
protocol::SessionTarget::Attach(id) => {
|
||||
command.arg("--attach");
|
||||
if let Some(id) = id {
|
||||
command.arg(id.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(host) = remote {
|
||||
command.arg("--remote").arg(host);
|
||||
}
|
||||
|
||||
@@ -75,7 +75,11 @@ impl Zygote {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_window(&mut self, remote: Option<String>) -> Result<()> {
|
||||
pub fn open_window(
|
||||
&mut self,
|
||||
remote: Option<String>,
|
||||
session: protocol::SessionTarget,
|
||||
) -> Result<()> {
|
||||
let executable = executable_path()?;
|
||||
let identity = ExecutableIdentity::read(&executable)?;
|
||||
let helper_exited = self.child.try_wait()?.is_some();
|
||||
@@ -89,6 +93,7 @@ impl Zygote {
|
||||
match self.request(&LaunchRequest::Launch {
|
||||
server_socket: self.server_socket.clone(),
|
||||
remote,
|
||||
session,
|
||||
})? {
|
||||
LaunchResponse::Launched { pid } => {
|
||||
log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id());
|
||||
@@ -164,6 +169,7 @@ enum LaunchRequest {
|
||||
Launch {
|
||||
server_socket: PathBuf,
|
||||
remote: Option<String>,
|
||||
session: protocol::SessionTarget,
|
||||
},
|
||||
Shutdown,
|
||||
}
|
||||
@@ -222,6 +228,7 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
|
||||
LaunchRequest::Launch {
|
||||
server_socket,
|
||||
remote,
|
||||
session,
|
||||
} => {
|
||||
if let Err(error) = ensure_single_threaded() {
|
||||
protocol::write_message(
|
||||
@@ -251,7 +258,7 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
|
||||
drop(stream);
|
||||
drop(listener);
|
||||
let result = set_child_reaping(false)
|
||||
.and_then(|()| crate::run_gui(server_socket, remote));
|
||||
.and_then(|()| crate::run_gui(server_socket, remote, session));
|
||||
let code = if let Err(error) = result {
|
||||
log::error!("GUI startup failed: {error:#}");
|
||||
1
|
||||
|
||||
+132
-65
@@ -19,24 +19,33 @@ mod transition;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use gpui::{prelude::*, *};
|
||||
use protocol::{SessionId, SessionTarget};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
gpui::actions!(psyterm, [Quit]);
|
||||
gpui::actions!(psyterm, [Quit, NewWindow]);
|
||||
|
||||
fn main() -> Result<()> {
|
||||
env_logger::init();
|
||||
// AppKit runs in the process that LaunchServices opens. Linux uses a prefork helper.
|
||||
let mut role = if cfg!(target_os = "macos") {
|
||||
"gui"
|
||||
} else {
|
||||
"launch"
|
||||
};
|
||||
let mut role = "launch";
|
||||
let mut socket = None;
|
||||
let mut remote = None;
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mut cwd = None;
|
||||
let mut attach: Option<Option<SessionId>> = None;
|
||||
let mut args = std::env::args().skip(1).peekable();
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--attach" => {
|
||||
let id = args
|
||||
.next_if(|arg| !arg.starts_with('-'))
|
||||
.map(|id| id.parse::<SessionId>())
|
||||
.transpose()
|
||||
.map_err(|_| {
|
||||
anyhow::anyhow!("--attach expects a numeric session ID from --list")
|
||||
})?;
|
||||
attach = Some(id);
|
||||
}
|
||||
"--server" => role = "server",
|
||||
#[cfg(target_os = "linux")]
|
||||
"--zygote" => role = "zygote",
|
||||
@@ -44,6 +53,12 @@ fn main() -> Result<()> {
|
||||
"--bridge" => role = "bridge",
|
||||
"--shutdown" => role = "shutdown",
|
||||
"--list" => role = "list",
|
||||
"--cwd" => {
|
||||
cwd = Some(
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("--cwd needs a directory"))?,
|
||||
);
|
||||
}
|
||||
"--socket" => {
|
||||
socket = Some(PathBuf::from(
|
||||
args.next()
|
||||
@@ -52,63 +67,116 @@ fn main() -> Result<()> {
|
||||
}
|
||||
"--remote" => {
|
||||
remote = Some(
|
||||
args.next()
|
||||
args.next_if(|arg| !arg.starts_with('-'))
|
||||
.ok_or_else(|| anyhow::anyhow!("--remote needs an SSH destination"))?,
|
||||
)
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a local terminal window\n psyterm --remote user@host Connect a local GUI to a server over SSH\n psyterm --list List server-owned tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Run the GUI in the current process\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n"
|
||||
"psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a new session in a new window\n psyterm --attach [ID] Join an existing session (prefer the latest detached session)\n psyterm --remote user@host Open an SSH session (an adjacent tab when run inside psyTerm)\n psyterm --list List local sessions, tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Run the GUI in the current process\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
_ => bail!("unknown argument: {arg}; see --help"),
|
||||
}
|
||||
}
|
||||
if attach.is_some() && !matches!(role, "gui" | "launch" | "bridge") {
|
||||
bail!("--attach applies to a window or an SSH bridge");
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if matches!(role, "launch" | "gui")
|
||||
&& unsafe { libc::getppid() } == 1
|
||||
&& std::env::current_dir()? == std::path::Path::new("/")
|
||||
&& let Some(home) = std::env::home_dir()
|
||||
{
|
||||
// Finder launches the bundled process from the filesystem root.
|
||||
std::env::set_current_dir(home)?;
|
||||
}
|
||||
let session = if let Some(id) = attach {
|
||||
SessionTarget::Attach(id)
|
||||
} else {
|
||||
SessionTarget::New {
|
||||
cwd: if cwd.is_some() {
|
||||
cwd
|
||||
} else if remote.is_none() && matches!(role, "gui" | "launch") {
|
||||
std::env::current_dir()?.into_os_string().into_string().ok()
|
||||
} else {
|
||||
None
|
||||
},
|
||||
}
|
||||
};
|
||||
if role == "launch"
|
||||
&& let Some(destination) = &remote
|
||||
&& let Some(origin) = session::PaneContext::from_env()?
|
||||
{
|
||||
if let Some(explicit) = &socket
|
||||
&& explicit.canonicalize()? != origin.socket.canonicalize()?
|
||||
{
|
||||
bail!("--socket points outside the invoking psyTerm pane");
|
||||
}
|
||||
launcher::control(
|
||||
&origin.socket,
|
||||
protocol::ClientMessage::OpenRemoteTab {
|
||||
session: origin.session,
|
||||
pane: origin.pane,
|
||||
destination: destination.clone(),
|
||||
target: session,
|
||||
ssh: protocol::SshOptions::from_env(),
|
||||
},
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let socket = socket.map(Ok).unwrap_or_else(launcher::default_socket)?;
|
||||
match role {
|
||||
#[cfg(target_os = "macos")]
|
||||
"server" => server::run(&socket, |remote| launcher::open_window(&socket, remote)),
|
||||
"server" => server::run(&socket, |remote, session| {
|
||||
launcher::open_window(&socket, remote, session)
|
||||
}),
|
||||
#[cfg(target_os = "linux")]
|
||||
"server" => {
|
||||
let zygote_socket = socket.clone();
|
||||
let mut zygote: Option<launcher::zygote::Zygote> = None;
|
||||
server::run(&socket, move |remote| {
|
||||
server::run(&socket, move |remote, session| {
|
||||
if zygote.is_none() {
|
||||
zygote = Some(launcher::zygote::Zygote::start(&zygote_socket)?);
|
||||
}
|
||||
zygote.as_mut().unwrap().open_window(remote)
|
||||
zygote.as_mut().unwrap().open_window(remote, session)
|
||||
})
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
"zygote" => launcher::zygote::run_zygote(&socket),
|
||||
"gui" => {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// LaunchServices starts Finder-launched apps in / with launchd as parent.
|
||||
// Give that first shell a useful directory while preserving CLI launch paths.
|
||||
// SAFETY: getppid has no preconditions.
|
||||
if unsafe { libc::getppid() } == 1
|
||||
&& std::env::current_dir()? == std::path::Path::new("/")
|
||||
&& let Some(home) = std::env::home_dir()
|
||||
{
|
||||
std::env::set_current_dir(home)?;
|
||||
}
|
||||
// Check remote attach synchronously so a failed SSH/session lookup reaches the CLI.
|
||||
"gui" | "launch"
|
||||
if cfg!(target_os = "macos")
|
||||
|| role == "gui"
|
||||
|| (remote.is_some() && attach.is_some()) =>
|
||||
{
|
||||
if remote.is_none() && attach.is_some() {
|
||||
launcher::require_server(&socket)?;
|
||||
} else {
|
||||
launcher::ensure_server(&socket)?;
|
||||
}
|
||||
launcher::ensure_server(&socket)?;
|
||||
run_gui(socket, remote)
|
||||
run_gui(socket, remote, session)
|
||||
}
|
||||
"bridge" => client::bridge(&socket),
|
||||
"bridge" => client::bridge(&socket, attach.is_some()),
|
||||
"shutdown" => {
|
||||
launcher::control(&socket, protocol::ClientMessage::Shutdown)?;
|
||||
Ok(())
|
||||
}
|
||||
"list" => list_sessions(&socket),
|
||||
_ => {
|
||||
launcher::ensure_server(&socket)?;
|
||||
if attach.is_some() {
|
||||
launcher::require_server(&socket)?;
|
||||
} else {
|
||||
launcher::ensure_server(&socket)?;
|
||||
}
|
||||
launcher::control(
|
||||
&socket,
|
||||
protocol::ClientMessage::OpenWindow { target: remote },
|
||||
protocol::ClientMessage::OpenWindow {
|
||||
target: remote,
|
||||
session,
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -116,44 +184,34 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
fn list_sessions(socket: &std::path::Path) -> Result<()> {
|
||||
let mut stream = std::os::unix::net::UnixStream::connect(socket)?;
|
||||
launcher::verify_peer(&stream)?;
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&protocol::ClientMessage::Hello {
|
||||
version: protocol::VERSION,
|
||||
},
|
||||
)?;
|
||||
let hello: protocol::ServerMessage = protocol::read_message(&mut stream)?;
|
||||
println!("{hello:?}");
|
||||
protocol::write_message(&mut stream, &protocol::ClientMessage::List)?;
|
||||
loop {
|
||||
match protocol::read_message(&mut stream)? {
|
||||
protocol::ServerMessage::Snapshot(snapshot) => {
|
||||
for tab in snapshot.tabs {
|
||||
println!("tab {} {} panes {:?}", tab.id, tab.title, tab.panes);
|
||||
for (index, stack) in tab.stacks.iter().enumerate() {
|
||||
println!(
|
||||
" stack {} expanded {} panes {:?}",
|
||||
index + 1,
|
||||
stack.active_pane,
|
||||
stack.panes.iter().map(|pane| pane.id).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
let response = launcher::control(socket, protocol::ClientMessage::ListSessions)?;
|
||||
let protocol::ServerMessage::Sessions(sessions) = response else {
|
||||
bail!("expected session list");
|
||||
};
|
||||
for session in sessions {
|
||||
println!("session {} ({} attached)", session.id, session.attached);
|
||||
for tab in session.tabs {
|
||||
println!("tab {} {} panes {:?}", tab.id, tab.title, tab.panes);
|
||||
for (index, stack) in tab.stacks.iter().enumerate() {
|
||||
println!(
|
||||
" stack {} expanded {} panes {:?}",
|
||||
index + 1,
|
||||
stack.active_pane,
|
||||
stack.panes.iter().map(|pane| pane.id).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
protocol::ServerMessage::Error(error) => bail!("{error}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initialize GPUI on the main thread of the GUI process.
|
||||
pub(crate) fn run_gui(socket: PathBuf, remote: Option<String>) -> Result<()> {
|
||||
let (client, updates) = client::Client::connect(&socket, remote.as_deref())?;
|
||||
pub(crate) fn run_gui(
|
||||
socket: PathBuf,
|
||||
remote: Option<String>,
|
||||
session: SessionTarget,
|
||||
) -> Result<()> {
|
||||
let (client, updates) = client::Client::connect(&socket, remote.as_deref(), session)?;
|
||||
let connection: SharedString = remote
|
||||
.map(|host| format!("SSH · {host}"))
|
||||
.unwrap_or_else(|| "Local".into())
|
||||
@@ -162,11 +220,20 @@ pub(crate) fn run_gui(socket: PathBuf, remote: Option<String>) -> Result<()> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
cx.on_action(|_: &Quit, cx| cx.quit());
|
||||
cx.bind_keys([KeyBinding::new("cmd-q", Quit, None)]);
|
||||
cx.set_menus(vec![Menu {
|
||||
name: "psyTerm".into(),
|
||||
items: vec![MenuItem::action("Quit psyTerm", Quit)],
|
||||
}]);
|
||||
cx.bind_keys([
|
||||
KeyBinding::new("cmd-q", Quit, None),
|
||||
KeyBinding::new("cmd-n", NewWindow, None),
|
||||
]);
|
||||
cx.set_menus(vec![
|
||||
Menu {
|
||||
name: "psyTerm".into(),
|
||||
items: vec![MenuItem::action("Quit psyTerm", Quit)],
|
||||
},
|
||||
Menu {
|
||||
name: "File".into(),
|
||||
items: vec![MenuItem::action("New Window", NewWindow)],
|
||||
},
|
||||
]);
|
||||
}
|
||||
cx.on_window_closed(|cx| {
|
||||
if cx.windows().is_empty() {
|
||||
|
||||
+63
-3
@@ -10,10 +10,37 @@ use anyhow::{Context, Result, bail};
|
||||
use bincode::Options;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
|
||||
pub const VERSION: u32 = 4;
|
||||
pub const VERSION: u32 = 6;
|
||||
pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024;
|
||||
pub type PaneId = u64;
|
||||
pub type TabId = u64;
|
||||
pub type SessionId = u64;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
|
||||
pub struct SessionIdentity {
|
||||
pub server: [u8; 16],
|
||||
pub session: SessionId,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum SessionTarget {
|
||||
New { cwd: Option<String> },
|
||||
Attach(Option<SessionId>),
|
||||
}
|
||||
|
||||
/// SSH settings inherited from the shell that requested a remote tab.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct SshOptions {
|
||||
pub executable: Option<String>,
|
||||
pub agent_socket: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SessionInfo {
|
||||
pub id: SessionId,
|
||||
pub attached: usize,
|
||||
pub tabs: Vec<TabInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
// Keep variants append-only: the shutdown command can retire an older server.
|
||||
@@ -21,7 +48,7 @@ pub enum ClientMessage {
|
||||
Hello {
|
||||
version: u32,
|
||||
},
|
||||
Attach,
|
||||
Connect(SessionTarget),
|
||||
Input {
|
||||
pane: PaneId,
|
||||
bytes: Vec<u8>,
|
||||
@@ -62,11 +89,12 @@ pub enum ClientMessage {
|
||||
},
|
||||
OpenWindow {
|
||||
target: Option<String>,
|
||||
session: SessionTarget,
|
||||
},
|
||||
Detach,
|
||||
Shutdown,
|
||||
Ping,
|
||||
/// Read current layout without attaching or creating a shell.
|
||||
/// Inspect the layout of the session this client has joined.
|
||||
List,
|
||||
/// A blank/absent name returns to program-title/CWD naming.
|
||||
RenamePane {
|
||||
@@ -101,6 +129,17 @@ pub enum ClientMessage {
|
||||
tab: TabId,
|
||||
name: Option<String>,
|
||||
},
|
||||
ListSessions,
|
||||
OpenRemoteTab {
|
||||
session: SessionIdentity,
|
||||
pane: PaneId,
|
||||
destination: String,
|
||||
target: SessionTarget,
|
||||
ssh: SshOptions,
|
||||
},
|
||||
ClosePendingTab {
|
||||
tab: TabId,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -164,10 +203,14 @@ pub enum ServerMessage {
|
||||
Error(String),
|
||||
Pong,
|
||||
Closing,
|
||||
Connected { session: SessionId },
|
||||
Sessions(Vec<SessionInfo>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Snapshot {
|
||||
/// This session and the other sessions contributing tabs to its layout.
|
||||
pub lineage: Vec<SessionIdentity>,
|
||||
pub revision: u64,
|
||||
pub tabs: Vec<TabInfo>,
|
||||
pub active_tab: TabId,
|
||||
@@ -175,9 +218,17 @@ pub struct Snapshot {
|
||||
pub panes: Vec<PaneSnapshot>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
pub fn active_tab(&self) -> Option<&TabInfo> {
|
||||
self.tabs.iter().find(|tab| tab.id == self.active_tab)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TabInfo {
|
||||
pub id: TabId,
|
||||
/// SSH destination for a tab mounted from another host.
|
||||
pub remote: Option<String>,
|
||||
/// Effective display name: manual override, then the selected pane's name.
|
||||
pub title: String,
|
||||
pub manual_title: Option<String>,
|
||||
@@ -188,6 +239,15 @@ pub struct TabInfo {
|
||||
pub stacks: Vec<StackInfo>,
|
||||
}
|
||||
|
||||
impl TabInfo {
|
||||
pub fn is_connecting(&self) -> bool {
|
||||
self.remote.is_some()
|
||||
&& self.panes.is_empty()
|
||||
&& self.stacks.is_empty()
|
||||
&& self.active_pane == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StackInfo {
|
||||
pub panes: Vec<StackPaneInfo>,
|
||||
|
||||
+506
-126
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,743 @@
|
||||
//! Mirror an SSH session into its parent session's tab bar. The SSH host owns
|
||||
//! its PTYs and layout. IDs in each mirror are independent of both daemons.
|
||||
use super::*;
|
||||
use crate::client::{Client as Transport, Update};
|
||||
use std::sync::{
|
||||
Weak,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
pub(super) enum RemoteEvent {
|
||||
Connected(Transport),
|
||||
Updated(Update),
|
||||
Ended(Option<String>),
|
||||
}
|
||||
|
||||
pub(super) struct RemoteSession {
|
||||
destination: String,
|
||||
anchor: TabId,
|
||||
slot: TabId,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
connection: Option<Transport>,
|
||||
// Remote IDs map to stable IDs allocated from the parent session's pool.
|
||||
tabs: HashMap<TabId, TabId>,
|
||||
panes: HashMap<PaneId, PaneId>,
|
||||
latest: Option<Arc<Snapshot>>,
|
||||
requested_tab: Option<TabId>,
|
||||
clipboard: VecDeque<(PaneId, Weak<Outbox>)>,
|
||||
}
|
||||
|
||||
impl Drop for RemoteSession {
|
||||
fn drop(&mut self) {
|
||||
self.cancelled.store(true, Ordering::Release);
|
||||
self.cancel_copies();
|
||||
}
|
||||
}
|
||||
|
||||
fn original(ids: &HashMap<u64, u64>, local: u64) -> Option<u64> {
|
||||
ids.iter()
|
||||
.find_map(|(&remote, &id)| (id == local).then_some(remote))
|
||||
}
|
||||
|
||||
fn mapped(ids: &mut HashMap<u64, u64>, remote: u64, next: &mut u64) -> u64 {
|
||||
*ids.entry(remote).or_insert_with(|| {
|
||||
let id = *next;
|
||||
*next += 1;
|
||||
id
|
||||
})
|
||||
}
|
||||
|
||||
impl RemoteSession {
|
||||
pub(super) fn owns_tab(&self, local: TabId) -> bool {
|
||||
(self.latest.is_none() && self.slot == local) || original(&self.tabs, local).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn send(&self, command: ClientMessage) -> Result<()> {
|
||||
self.connection
|
||||
.as_ref()
|
||||
.context("SSH session is connecting")?
|
||||
.send(command)
|
||||
}
|
||||
|
||||
// Keep one copy in flight on this connection. An attached session can
|
||||
// contain multiple SSH hosts whose clipboard replies arrive out of order.
|
||||
fn copy(&mut self, pane: PaneId, output: &Arc<Outbox>) -> Result<()> {
|
||||
if self.clipboard.len() >= 16 {
|
||||
output.reliable(ServerMessage::Clipboard(String::new()));
|
||||
anyhow::bail!("too many pending clipboard requests");
|
||||
}
|
||||
self.clipboard.push_back((pane, Arc::downgrade(output)));
|
||||
if self.clipboard.len() == 1 {
|
||||
self.send_next_copy()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_copy(&mut self, text: String) -> Result<()> {
|
||||
if let Some((_, output)) = self.clipboard.pop_front()
|
||||
&& let Some(output) = output.upgrade()
|
||||
{
|
||||
output.reliable(ServerMessage::Clipboard(text));
|
||||
}
|
||||
self.send_next_copy()
|
||||
}
|
||||
|
||||
fn send_next_copy(&mut self) -> Result<()> {
|
||||
if let Some(&(pane, _)) = self.clipboard.front()
|
||||
&& let Err(error) = self.send(ClientMessage::Copy { pane })
|
||||
{
|
||||
self.cancel_copies();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cancel_copies(&mut self) {
|
||||
for (_, output) in self.clipboard.drain(..) {
|
||||
if let Some(output) = output.upgrade() {
|
||||
output.reliable(ServerMessage::Clipboard(String::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn visible_panes(&self, local: TabId) -> Vec<PaneSnapshot> {
|
||||
self.latest
|
||||
.as_ref()
|
||||
.filter(|s| self.tabs.get(&s.active_tab) == Some(&local))
|
||||
.map(|s| {
|
||||
s.panes
|
||||
.iter()
|
||||
.filter_map(|pane| {
|
||||
let mut copy = pane.clone();
|
||||
copy.id = *self.panes.get(&pane.id)?;
|
||||
Some(copy)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Reconcile a whole remote session, including other tabs that may already
|
||||
/// exist when explicitly attaching. Only the active remote tab has grids.
|
||||
fn apply(
|
||||
&mut self,
|
||||
snapshot: Arc<Snapshot>,
|
||||
tabs: &mut Vec<TabInfo>,
|
||||
active: &mut TabId,
|
||||
next: &mut u64,
|
||||
) -> Result<bool> {
|
||||
let first = self.latest.is_none();
|
||||
let selected = self.owns_tab(*active);
|
||||
if self.latest.as_ref().is_some_and(|old| {
|
||||
old.tabs == snapshot.tabs
|
||||
&& old.active_tab == snapshot.active_tab
|
||||
&& old.lineage == snapshot.lineage
|
||||
}) {
|
||||
if self.requested_tab == Some(snapshot.active_tab) {
|
||||
self.requested_tab = None;
|
||||
}
|
||||
self.latest = Some(snapshot);
|
||||
return Ok(selected);
|
||||
}
|
||||
let index = tabs
|
||||
.iter()
|
||||
.position(|tab| self.owns_tab(tab.id))
|
||||
.context("SSH tab has closed")?;
|
||||
let previous_count = if first { 1 } else { self.tabs.len() };
|
||||
ensure!(
|
||||
tabs.len() - previous_count + snapshot.tabs.len() <= 256,
|
||||
"a window supports at most 256 tabs"
|
||||
);
|
||||
let mut new_tab_ids = self.tabs.clone();
|
||||
let mut new_pane_ids = self.panes.clone();
|
||||
new_tab_ids.retain(|id, _| snapshot.tabs.iter().any(|tab| tab.id == *id));
|
||||
new_pane_ids.retain(|id, _| snapshot.tabs.iter().any(|tab| tab.panes.contains(id)));
|
||||
if first && !snapshot.tabs.is_empty() {
|
||||
new_tab_ids.insert(snapshot.active_tab, self.slot);
|
||||
}
|
||||
let mut mapped_tabs = snapshot.tabs.clone();
|
||||
for tab in &mut mapped_tabs {
|
||||
tab.id = mapped(&mut new_tab_ids, tab.id, next);
|
||||
if tab.remote.is_none() {
|
||||
tab.remote = Some(self.destination.clone());
|
||||
}
|
||||
for pane in &mut tab.panes {
|
||||
*pane = mapped(&mut new_pane_ids, *pane, next);
|
||||
}
|
||||
if tab.panes.is_empty() {
|
||||
continue; // Nested SSH connection still establishing its first shell.
|
||||
}
|
||||
tab.active_pane = *new_pane_ids
|
||||
.get(&tab.active_pane)
|
||||
.context("invalid active SSH pane")?;
|
||||
for stack in &mut tab.stacks {
|
||||
stack.active_pane = *new_pane_ids
|
||||
.get(&stack.active_pane)
|
||||
.context("invalid SSH stack")?;
|
||||
for pane in &mut stack.panes {
|
||||
pane.id = *new_pane_ids.get(&pane.id).context("invalid SSH pane")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let remote_active = if snapshot.tabs.is_empty() {
|
||||
0
|
||||
} else {
|
||||
*new_tab_ids
|
||||
.get(&snapshot.active_tab)
|
||||
.context("invalid active SSH tab")?
|
||||
};
|
||||
self.tabs = new_tab_ids;
|
||||
self.panes = new_pane_ids;
|
||||
let changed = tabs[index..index + previous_count] != mapped_tabs;
|
||||
if changed {
|
||||
tabs.splice(index..index + previous_count, mapped_tabs);
|
||||
}
|
||||
if !snapshot.tabs.is_empty() {
|
||||
// Ignore intermediate focus acknowledgements when a user cycles
|
||||
// tabs several times before an SSH round trip finishes.
|
||||
if self
|
||||
.requested_tab
|
||||
.is_some_and(|id| id == snapshot.active_tab || !self.tabs.contains_key(&id))
|
||||
{
|
||||
self.requested_tab = None;
|
||||
}
|
||||
if selected && self.requested_tab.is_none() {
|
||||
*active = remote_active;
|
||||
}
|
||||
} else if selected {
|
||||
*active = tabs
|
||||
.get(index.min(tabs.len().saturating_sub(1)))
|
||||
.map_or(0, |tab| tab.id);
|
||||
}
|
||||
let ancestry_changed = self
|
||||
.latest
|
||||
.as_ref()
|
||||
.is_none_or(|old| old.lineage != snapshot.lineage);
|
||||
self.latest = Some(snapshot);
|
||||
Ok(changed || selected || first || ancestry_changed)
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionState {
|
||||
/// Propagate identities through nested SSH connections. This also catches
|
||||
/// a user attaching a localhost SSH tab to its own parent session.
|
||||
pub(super) fn lineage(&self) -> Vec<SessionIdentity> {
|
||||
let descendants = self
|
||||
.remotes
|
||||
.values()
|
||||
.filter_map(|remote| remote.latest.as_ref())
|
||||
.flat_map(|snapshot| snapshot.lineage.iter().copied())
|
||||
.collect::<BTreeSet<_>>();
|
||||
std::iter::once(self.identity).chain(descendants).collect()
|
||||
}
|
||||
|
||||
fn check_lineage(&self, group: u64, incoming: &[SessionIdentity]) -> Result<()> {
|
||||
ensure!(
|
||||
!incoming.is_empty() && !incoming.contains(&self.identity),
|
||||
"cannot attach an SSH session inside itself"
|
||||
);
|
||||
let count = self
|
||||
.remotes
|
||||
.iter()
|
||||
.filter(|(id, _)| **id != group)
|
||||
.filter_map(|(_, remote)| remote.latest.as_ref())
|
||||
.flat_map(|snapshot| &snapshot.lineage)
|
||||
.chain(incoming)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len();
|
||||
ensure!(count < 256, "too many nested SSH sessions");
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn is_live(&self) -> bool {
|
||||
!self.tabs.is_empty() || !self.remotes.is_empty()
|
||||
}
|
||||
|
||||
pub(super) fn open_remote(
|
||||
&mut self,
|
||||
pane: PaneId,
|
||||
destination: String,
|
||||
target: SessionTarget,
|
||||
ssh: SshOptions,
|
||||
) -> Result<()> {
|
||||
crate::client::validate_destination(&destination)?;
|
||||
ensure!(
|
||||
self.panes.contains_key(&pane),
|
||||
"originating shell has ended"
|
||||
);
|
||||
ensure!(
|
||||
self.remotes.len() < MAX_PANES && self.tabs.len() < 256,
|
||||
"too many SSH sessions or tabs"
|
||||
);
|
||||
let (index, _, _) = self.pane_position(pane)?;
|
||||
let group = self.next_id;
|
||||
self.next_id += 1;
|
||||
let socket = self.socket.clone();
|
||||
let session = self.id;
|
||||
let sender = self.sender.clone();
|
||||
let dest = destination.clone();
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
let worker_cancelled = cancelled.clone();
|
||||
thread::Builder::new()
|
||||
.name("psyterm-remote-tab".into())
|
||||
.spawn(move || {
|
||||
// Permit one outstanding actor update per connection. The
|
||||
// transport coalesces newer grids while the actor is busy.
|
||||
let notify = |event| {
|
||||
let (ack, processed) = mpsc::channel();
|
||||
sender
|
||||
.send(Action::Remote(session, group, event, ack))
|
||||
.is_ok()
|
||||
&& processed.recv().is_ok()
|
||||
};
|
||||
match Transport::connect_remote(&socket, &dest, target, ssh, worker_cancelled) {
|
||||
Ok((client, updates)) => {
|
||||
// Ownership of the transport moves to the server actor so
|
||||
// dropping a mirror also tears down its SSH child/reader.
|
||||
if !notify(RemoteEvent::Connected(client)) {
|
||||
return;
|
||||
}
|
||||
while let Some(update) = updates.recv_blocking() {
|
||||
let closed = update.disconnected;
|
||||
if !notify(RemoteEvent::Updated(update)) || closed {
|
||||
return;
|
||||
}
|
||||
}
|
||||
notify(RemoteEvent::Ended(None));
|
||||
}
|
||||
Err(error) => {
|
||||
notify(RemoteEvent::Ended(Some(format!(
|
||||
"Could not connect to {dest}: {error:#}"
|
||||
))));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
self.insert_remote_slot(index, group, destination, cancelled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_remote_slot(
|
||||
&mut self,
|
||||
index: usize,
|
||||
group: u64,
|
||||
destination: String,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
) {
|
||||
let anchor = self.tabs[index].id;
|
||||
self.tabs.insert(
|
||||
index + 1,
|
||||
TabInfo {
|
||||
id: group,
|
||||
title: "Connecting…".into(),
|
||||
remote: Some(destination.clone()),
|
||||
manual_title: None,
|
||||
panes: Vec::new(),
|
||||
active_pane: 0,
|
||||
stacks: Vec::new(),
|
||||
},
|
||||
);
|
||||
if self.active_tab == anchor {
|
||||
self.active_tab = group;
|
||||
}
|
||||
self.dirty = true;
|
||||
self.remotes.insert(
|
||||
group,
|
||||
RemoteSession {
|
||||
destination,
|
||||
anchor,
|
||||
slot: group,
|
||||
cancelled,
|
||||
connection: None,
|
||||
tabs: HashMap::new(),
|
||||
panes: HashMap::new(),
|
||||
latest: None,
|
||||
requested_tab: None,
|
||||
clipboard: VecDeque::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn cancel_pending_tab(&mut self, tab: TabId) -> Result<()> {
|
||||
if self
|
||||
.remotes
|
||||
.get(&tab)
|
||||
.is_some_and(|remote| remote.latest.is_none())
|
||||
{
|
||||
self.remove_remote(tab);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some((remote, id)) = self
|
||||
.remotes
|
||||
.values()
|
||||
.find_map(|remote| original(&remote.tabs, tab).map(|id| (remote, id)))
|
||||
{
|
||||
return remote.send(ClientMessage::ClosePendingTab { tab: id });
|
||||
}
|
||||
anyhow::bail!("SSH tab is no longer connecting")
|
||||
}
|
||||
|
||||
fn remove_remote(&mut self, group: u64) {
|
||||
let Some(remote) = self.remotes.remove(&group) else {
|
||||
return;
|
||||
};
|
||||
let index = self
|
||||
.tabs
|
||||
.iter()
|
||||
.position(|tab| remote.owns_tab(tab.id))
|
||||
.unwrap_or(0);
|
||||
self.tabs.retain(|tab| !remote.owns_tab(tab.id));
|
||||
if remote.owns_tab(self.active_tab) {
|
||||
self.active_tab = self
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|tab| remote.latest.is_none() && tab.id == remote.anchor)
|
||||
.or_else(|| self.tabs.get(index.min(self.tabs.len().saturating_sub(1))))
|
||||
.map_or(0, |tab| tab.id);
|
||||
}
|
||||
if self.active_tab != 0 {
|
||||
let _ = self.focus_tab(self.active_tab);
|
||||
}
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub(super) fn focus_tab(&mut self, tab: TabId) -> Result<()> {
|
||||
ensure!(self.tabs.iter().any(|entry| entry.id == tab), "unknown tab");
|
||||
if let Some((remote, original)) = self
|
||||
.remotes
|
||||
.values_mut()
|
||||
.find_map(|remote| original(&remote.tabs, tab).map(|id| (remote, id)))
|
||||
&& (remote.requested_tab.is_some()
|
||||
|| remote
|
||||
.latest
|
||||
.as_ref()
|
||||
.is_none_or(|s| s.active_tab != original))
|
||||
{
|
||||
remote.send(ClientMessage::FocusTab { tab: original })?;
|
||||
remote.requested_tab = Some(original);
|
||||
}
|
||||
self.active_tab = tab;
|
||||
self.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn remote_pane(&mut self, pane: PaneId) -> Option<(&mut RemoteSession, PaneId)> {
|
||||
self.remotes
|
||||
.values_mut()
|
||||
.find_map(|remote| original(&remote.panes, pane).map(|id| (remote, id)))
|
||||
}
|
||||
|
||||
/// Absolute pane actions use the pane's owner even if an older frame is
|
||||
/// being acted on. Relative navigation is resolved in the mixed tab order.
|
||||
pub(super) fn route_command(
|
||||
&mut self,
|
||||
mut command: ClientMessage,
|
||||
output: &Arc<Outbox>,
|
||||
) -> Result<Option<ClientMessage>> {
|
||||
use ClientMessage::*;
|
||||
let remote = match &mut command {
|
||||
RenameTab { tab, .. } => self.remotes.values_mut().find_map(|remote| {
|
||||
*tab = original(&remote.tabs, *tab)?;
|
||||
Some(remote)
|
||||
}),
|
||||
NewStackPane { pane, .. } => {
|
||||
let Some(local) = (*pane).or_else(|| {
|
||||
self.tabs
|
||||
.iter()
|
||||
.find(|t| t.id == self.active_tab)
|
||||
.map(|t| t.active_pane)
|
||||
}) else {
|
||||
return Ok(Some(command));
|
||||
};
|
||||
self.remote_pane(local).map(|(remote, original)| {
|
||||
*pane = Some(original);
|
||||
remote
|
||||
})
|
||||
}
|
||||
Input { pane, .. }
|
||||
| Resize { pane, .. }
|
||||
| Selection { pane, .. }
|
||||
| Copy { pane }
|
||||
| Scroll { pane, .. }
|
||||
| Split { pane, .. }
|
||||
| ClosePane { pane }
|
||||
| RenamePane { pane, .. } => self.remote_pane(*pane).map(|(remote, original)| {
|
||||
*pane = original;
|
||||
remote
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let Some(remote) = remote else {
|
||||
return Ok(Some(command));
|
||||
};
|
||||
if let Copy { pane } = command {
|
||||
remote.copy(pane, output)?;
|
||||
} else {
|
||||
remote.send(command)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub(super) fn remote_event(&mut self, session: SessionId, group: u64, event: RemoteEvent) {
|
||||
let Some(state) = self.sessions.get_mut(&session) else {
|
||||
return;
|
||||
};
|
||||
if let RemoteEvent::Updated(update) = &event
|
||||
&& let Some(snapshot) = &update.snapshot
|
||||
&& let Err(reason) = state.check_lineage(group, &snapshot.lineage)
|
||||
{
|
||||
self.remote_event(session, group, RemoteEvent::Ended(Some(reason.to_string())));
|
||||
return;
|
||||
}
|
||||
let Some(remote) = state.remotes.get_mut(&group) else {
|
||||
return;
|
||||
};
|
||||
let (closed, error) = match event {
|
||||
RemoteEvent::Connected(client) => {
|
||||
remote.connection = Some(client);
|
||||
return;
|
||||
}
|
||||
RemoteEvent::Ended(error) => (true, error),
|
||||
RemoteEvent::Updated(update) => {
|
||||
for text in update.clipboard {
|
||||
if let Err(error) = remote.finish_copy(text) {
|
||||
log::warn!("SSH clipboard: {error}");
|
||||
}
|
||||
}
|
||||
let mut closed = update.disconnected;
|
||||
let mut error = update
|
||||
.error
|
||||
.map(|error| format!("{}: {error}", remote.destination));
|
||||
if let Some(snapshot) = update.snapshot {
|
||||
closed |= snapshot.tabs.is_empty();
|
||||
match remote.apply(
|
||||
snapshot,
|
||||
&mut state.tabs,
|
||||
&mut state.active_tab,
|
||||
&mut state.next_id,
|
||||
) {
|
||||
Ok(changed) => state.dirty |= changed,
|
||||
Err(reason) => {
|
||||
closed = true;
|
||||
error = Some(format!(
|
||||
"Invalid layout from {}: {reason}",
|
||||
remote.destination
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
(closed, error)
|
||||
}
|
||||
};
|
||||
if closed {
|
||||
state.remove_remote(group);
|
||||
self.remove_empty_session(session);
|
||||
}
|
||||
if let Some(error) = error {
|
||||
for client in self
|
||||
.clients
|
||||
.values()
|
||||
.filter(|client| client.session == Some(session))
|
||||
{
|
||||
client.output.reliable(ServerMessage::Error(error.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn session(server: u8) -> SessionState {
|
||||
let (sender, _) = mpsc::sync_channel(64);
|
||||
SessionState::new(
|
||||
SessionIdentity {
|
||||
server: [server; 16],
|
||||
session: 1,
|
||||
},
|
||||
PathBuf::from("/tmp/psyterm-unused-test-socket"),
|
||||
Some(Shell::new("/bin/sh".into(), vec![])),
|
||||
sender,
|
||||
)
|
||||
}
|
||||
|
||||
fn reserve(local: &mut SessionState, anchor: usize) -> TabId {
|
||||
let group = local.next_id;
|
||||
local.next_id += 1;
|
||||
local.insert_remote_slot(
|
||||
anchor,
|
||||
group,
|
||||
"user@work".into(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
);
|
||||
group
|
||||
}
|
||||
|
||||
fn apply(local: &mut SessionState, group: u64, snapshot: Snapshot) -> Result<bool> {
|
||||
local.check_lineage(group, &snapshot.lineage)?;
|
||||
local.remotes.get_mut(&group).unwrap().apply(
|
||||
Arc::new(snapshot),
|
||||
&mut local.tabs,
|
||||
&mut local.active_tab,
|
||||
&mut local.next_id,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_ids_remain_stable_and_do_not_collide_with_local_tabs_or_other_mirrors() {
|
||||
let mut local = session(1);
|
||||
let mut remote = session(2);
|
||||
local.new_tab(None).unwrap();
|
||||
local.new_tab(None).unwrap();
|
||||
let left = local.tabs[0].clone();
|
||||
let right = local.tabs[1].clone();
|
||||
local.focus_tab(left.id).unwrap();
|
||||
let group = reserve(&mut local, 0);
|
||||
assert_eq!(local.active_tab, group);
|
||||
assert!(local.snapshot().panes.is_empty());
|
||||
remote.new_tab(None).unwrap();
|
||||
remote.new_tab(None).unwrap();
|
||||
// The peers allocated exactly the same tab/pane IDs.
|
||||
assert_eq!(remote.tabs[0].id, left.id);
|
||||
apply(&mut local, group, remote.snapshot()).unwrap();
|
||||
assert_eq!(local.tabs[0].id, left.id);
|
||||
assert_eq!(local.tabs[2].id, group);
|
||||
assert_eq!(local.tabs[3].id, right.id);
|
||||
assert_eq!(local.active_tab, group);
|
||||
assert!(
|
||||
local.tabs[1..3]
|
||||
.iter()
|
||||
.all(|t| t.remote.as_deref() == Some("user@work"))
|
||||
);
|
||||
let remote_pane = local.tabs[2].active_pane;
|
||||
assert_eq!(local.snapshot().panes[0].id, remote_pane);
|
||||
assert_ne!(remote_pane, right.active_pane);
|
||||
let first_remote = local.tabs[1].id;
|
||||
local.focus_tab(left.id).unwrap();
|
||||
let second = reserve(&mut local, 0);
|
||||
apply(&mut local, second, remote.snapshot()).unwrap();
|
||||
assert_eq!(
|
||||
local
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|t| t.id)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len(),
|
||||
6
|
||||
);
|
||||
let second_pane = local.snapshot().panes[0].id;
|
||||
assert_ne!(second_pane, remote_pane);
|
||||
remote.tabs[0].manual_title = Some("renamed elsewhere".into());
|
||||
apply(&mut local, group, remote.snapshot()).unwrap();
|
||||
let renamed = local.tabs.iter().find(|t| t.id == first_remote).unwrap();
|
||||
assert_eq!(renamed.title, "renamed elsewhere");
|
||||
assert_eq!(local.active_tab, second);
|
||||
local.remove_remote(group);
|
||||
assert_eq!(local.tabs.len(), 4);
|
||||
assert_eq!(local.snapshot().panes[0].id, second_pane);
|
||||
local.remove_remote(second);
|
||||
assert_eq!(
|
||||
local.tabs.iter().map(|t| t.id).collect::<Vec<_>>(),
|
||||
[left.id, right.id]
|
||||
);
|
||||
assert_eq!(local.active_tab, right.id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_from_different_views_are_serialized_and_disconnect_completes_waiters() {
|
||||
let upstream = super::super::tests::TestServer::start();
|
||||
let (client, updates) =
|
||||
Transport::connect(&upstream.socket, None, SessionTarget::New { cwd: None }).unwrap();
|
||||
let (frames, receive) = mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
while let Some(update) = updates.recv_blocking() {
|
||||
if frames.send(update).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut local = session(1);
|
||||
local.new_tab(None).unwrap();
|
||||
let group = reserve(&mut local, 0);
|
||||
let remote = local.remotes.get_mut(&group).unwrap();
|
||||
remote.connection = Some(client);
|
||||
let first = Arc::new(Outbox::default());
|
||||
let second = Arc::new(Outbox::default());
|
||||
remote.copy(1, &first).unwrap();
|
||||
remote.copy(1, &second).unwrap();
|
||||
|
||||
// An ordered rename acts as a fence after the copy commands on the
|
||||
// upstream wire. Only one copy should have reached that server.
|
||||
remote
|
||||
.send(ClientMessage::RenameTab {
|
||||
tab: 2,
|
||||
name: Some("fence".into()),
|
||||
})
|
||||
.unwrap();
|
||||
let mut replies = Vec::new();
|
||||
loop {
|
||||
let update = receive.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
replies.extend(update.clipboard);
|
||||
if update
|
||||
.snapshot
|
||||
.is_some_and(|snapshot| snapshot.tabs[0].title == "fence")
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(replies, [""]);
|
||||
remote
|
||||
.finish_copy("text for the first window".into())
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(first.next(), Some(ServerMessage::Clipboard(text)) if text == "text for the first window")
|
||||
);
|
||||
let mut remote_replied = false;
|
||||
while !remote_replied {
|
||||
let update = receive.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
remote_replied = !update.clipboard.is_empty();
|
||||
}
|
||||
// An SSH disconnect while the second result is in flight must never
|
||||
// direct the first window's clipboard into the second window.
|
||||
local.remove_remote(group);
|
||||
assert!(matches!(second.next(), Some(ServerMessage::Clipboard(text)) if text.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_cancelled_and_recursive_attachments_preserve_the_origin() {
|
||||
let mut local = session(7);
|
||||
local.new_tab(None).unwrap();
|
||||
let anchor = local.active_tab;
|
||||
let group = reserve(&mut local, 0);
|
||||
let cancelled = local.remotes[&group].cancelled.clone();
|
||||
let own_snapshot = local.snapshot();
|
||||
assert!(
|
||||
apply(&mut local, group, own_snapshot)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("inside itself")
|
||||
);
|
||||
local.cancel_pending_tab(group).unwrap();
|
||||
assert!(cancelled.load(Ordering::Acquire));
|
||||
assert_eq!(local.active_tab, anchor);
|
||||
assert_eq!(local.tabs.len(), 1);
|
||||
|
||||
let mut upstream = session(8);
|
||||
upstream.new_tab(None).unwrap();
|
||||
let group = reserve(&mut local, 0);
|
||||
apply(&mut local, group, upstream.snapshot()).unwrap();
|
||||
assert_eq!(local.lineage(), [local.identity, upstream.identity]);
|
||||
let mut cyclic = upstream.snapshot();
|
||||
cyclic.lineage.push(local.identity);
|
||||
assert!(apply(&mut local, group, cyclic).is_err());
|
||||
let before = local.tabs.clone();
|
||||
let mut broken = upstream.snapshot();
|
||||
broken.tabs[0].active_pane = u64::MAX;
|
||||
assert!(apply(&mut local, group, broken).is_err());
|
||||
assert_eq!(local.tabs, before);
|
||||
local.remove_remote(group);
|
||||
assert_eq!(local.lineage(), [local.identity]);
|
||||
assert_eq!(local.active_tab, anchor);
|
||||
}
|
||||
}
|
||||
+112
-14
@@ -8,7 +8,9 @@ mod macos;
|
||||
#[cfg(target_os = "macos")]
|
||||
use macos::MacProcess;
|
||||
|
||||
use crate::protocol::{PaneId, SessionIdentity};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::{self, JoinHandle};
|
||||
@@ -19,7 +21,7 @@ use alacritty_terminal::grid::Dimensions;
|
||||
use alacritty_terminal::sync::FairMutex;
|
||||
use alacritty_terminal::term::{Config, Term};
|
||||
use alacritty_terminal::tty::{self, Options, Shell};
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EventProxy {
|
||||
@@ -67,6 +69,77 @@ impl Dimensions for GridSize {
|
||||
}
|
||||
}
|
||||
|
||||
/// The route inherited by a shell and its children, scoped to the spawning daemon.
|
||||
pub(crate) struct PaneContext {
|
||||
pub socket: PathBuf,
|
||||
pub session: SessionIdentity,
|
||||
pub pane: PaneId,
|
||||
}
|
||||
|
||||
impl PaneContext {
|
||||
const ENV: &str = "PSYTERM_PANE";
|
||||
|
||||
fn encode(&self) -> Result<String> {
|
||||
let socket = self
|
||||
.socket
|
||||
.to_str()
|
||||
.context("psyTerm socket must have a UTF-8 path")?;
|
||||
Ok(format!(
|
||||
"{:032x}:{}:{}:{}",
|
||||
u128::from_be_bytes(self.session.server),
|
||||
self.session.session,
|
||||
self.pane,
|
||||
socket
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn from_env() -> Result<Option<Self>> {
|
||||
std::env::var_os(Self::ENV)
|
||||
.map(|value| Self::decode(value.to_str().context("expected UTF-8")?))
|
||||
.transpose()
|
||||
.context("invalid PSYTERM_PANE")
|
||||
}
|
||||
|
||||
fn decode(value: &str) -> Result<Self> {
|
||||
let mut parts = value.splitn(4, ':');
|
||||
let server =
|
||||
u128::from_str_radix(parts.next().context("missing server ID")?, 16)?.to_be_bytes();
|
||||
let session = parts.next().context("missing session ID")?.parse()?;
|
||||
let pane = parts.next().context("missing pane ID")?.parse()?;
|
||||
let socket = PathBuf::from(parts.next().context("missing socket path")?);
|
||||
ensure!(socket.is_absolute(), "expected an absolute socket path");
|
||||
Ok(Self {
|
||||
socket,
|
||||
session: SessionIdentity { server, session },
|
||||
pane,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow a shell opened from Finder or a development build to invoke the CLI
|
||||
/// by name. Shell startup files still run normally and can customize this PATH.
|
||||
fn shell_path_with_cli() -> Option<String> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let executable = std::env::current_exe().ok()?;
|
||||
let directory = executable.parent()?;
|
||||
if executable.file_name()? != "psyterm" {
|
||||
return None;
|
||||
}
|
||||
let path = std::env::var_os("PATH").unwrap_or_else(|| "/usr/bin:/bin".into());
|
||||
let mut entries: Vec<_> = std::env::split_paths(&path).collect();
|
||||
let resolved = entries.iter().map(|dir| dir.join("psyterm")).find(|file| {
|
||||
file.metadata()
|
||||
.is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
|
||||
});
|
||||
if resolved.and_then(|file| file.canonicalize().ok()) == executable.canonicalize().ok() {
|
||||
return None;
|
||||
}
|
||||
entries.retain(|entry| entry != directory);
|
||||
entries.insert(0, directory.to_owned());
|
||||
std::env::join_paths(entries).ok()?.into_string().ok()
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
pub term: Arc<FairMutex<Term<EventProxy>>>,
|
||||
sender: EventLoopSender,
|
||||
@@ -85,24 +158,26 @@ pub struct Session {
|
||||
|
||||
impl Session {
|
||||
pub fn in_directory(
|
||||
directory: Option<std::path::PathBuf>,
|
||||
directory: Option<PathBuf>,
|
||||
context: &PaneContext,
|
||||
) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||
let program = std::env::var("SHELL").ok().filter(|s| !s.is_empty());
|
||||
#[cfg(target_os = "macos")]
|
||||
let shell = macos::login_shell(program);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let shell = Shell::new(program.unwrap_or_else(|| "/bin/sh".into()), Vec::new());
|
||||
Self::with_shell_and_directory(shell, directory)
|
||||
Self::with_shell_and_directory(shell, directory, Some(context))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn with_shell(shell: Shell) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||
Self::with_shell_and_directory(shell, None)
|
||||
Self::with_shell_and_directory(shell, None, None)
|
||||
}
|
||||
|
||||
pub(crate) fn with_shell_and_directory(
|
||||
shell: Shell,
|
||||
working_directory: Option<std::path::PathBuf>,
|
||||
working_directory: Option<PathBuf>,
|
||||
context: Option<&PaneContext>,
|
||||
) -> Result<(Self, async_channel::Receiver<Event>)> {
|
||||
let size = WindowSize {
|
||||
num_cols: 80,
|
||||
@@ -118,15 +193,22 @@ impl Session {
|
||||
&GridSize(size),
|
||||
proxy.clone(),
|
||||
)));
|
||||
let mut env = HashMap::from([
|
||||
("TERM".into(), "xterm-256color".into()),
|
||||
("COLORTERM".into(), "truecolor".into()),
|
||||
]);
|
||||
if let Some(context) = context {
|
||||
env.insert(PaneContext::ENV.into(), context.encode()?);
|
||||
if let Some(path) = shell_path_with_cli() {
|
||||
env.insert("PATH".into(), path);
|
||||
}
|
||||
}
|
||||
let options = Options {
|
||||
shell: Some(shell),
|
||||
// None preserves the directory from which the application launched.
|
||||
working_directory,
|
||||
drain_on_exit: true,
|
||||
env: HashMap::from([
|
||||
("TERM".into(), "xterm-256color".into()),
|
||||
("COLORTERM".into(), "truecolor".into()),
|
||||
]),
|
||||
env,
|
||||
};
|
||||
let pty = tty::new(&options, size, 0).context("Could not start the shell PTY")?;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -530,11 +612,20 @@ mod tests {
|
||||
#[test]
|
||||
fn real_pty_transports_input_resize_environment_and_exit() {
|
||||
// Reading first lets the test resize before the child examines its TTY.
|
||||
let script = "read value; printf '\\033[2J\\033[H%s %s %s ' \"$value\" \"$TERM\" \"$COLORTERM\"; stty size";
|
||||
let (mut session, events) = Session::with_shell(Shell::new(
|
||||
"/bin/sh".into(),
|
||||
vec!["-c".into(), script.into()],
|
||||
))
|
||||
let script = r#"read value; printf '\033[2J\033[H%s %s %s ' "$value" "$TERM" "$COLORTERM"; stty size; printf '%s' "$PSYTERM_PANE""#;
|
||||
let context = PaneContext {
|
||||
socket: PathBuf::from("/tmp/pty:example/socket"),
|
||||
session: SessionIdentity {
|
||||
server: [23; 16],
|
||||
session: 11,
|
||||
},
|
||||
pane: 23,
|
||||
};
|
||||
let (mut session, events) = Session::with_shell_and_directory(
|
||||
Shell::new("/bin/sh".into(), vec!["-c".into(), script.into()]),
|
||||
None,
|
||||
Some(&context),
|
||||
)
|
||||
.expect("start real PTY");
|
||||
session.resize(100, 30, 9, 18);
|
||||
session.write(b"PTY_OK\n".to_vec());
|
||||
@@ -562,6 +653,13 @@ mod tests {
|
||||
first_line.contains("PTY_OK xterm-256color truecolor 30 100"),
|
||||
"{first_line:?}"
|
||||
);
|
||||
let env_line: String = (0..term.columns())
|
||||
.map(|column| term.grid()[Point::new(Line(1), Column(column))].c)
|
||||
.collect();
|
||||
let inherited = PaneContext::decode(env_line.trim_end()).unwrap();
|
||||
assert_eq!(inherited.session, context.session);
|
||||
assert_eq!(inherited.pane, context.pane);
|
||||
assert_eq!(inherited.socket, context.socket);
|
||||
assert_eq!((term.columns(), term.screen_lines()), (100, 30));
|
||||
}
|
||||
}
|
||||
|
||||
+76
-15
@@ -54,12 +54,12 @@ pub struct Workspace {
|
||||
}
|
||||
impl Workspace {
|
||||
fn begin_tab_rename(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(tab) = self.snapshot.as_ref().and_then(|snapshot| {
|
||||
snapshot
|
||||
.tabs
|
||||
.iter()
|
||||
.find(|tab| tab.id == snapshot.active_tab)
|
||||
}) else {
|
||||
let Some(tab) = self
|
||||
.snapshot
|
||||
.as_deref()
|
||||
.and_then(Snapshot::active_tab)
|
||||
.filter(|tab| !tab.is_connecting())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let id = tab.id;
|
||||
@@ -166,6 +166,7 @@ impl Workspace {
|
||||
if !matches!(
|
||||
action,
|
||||
CommandAction::TogglePalette
|
||||
| CommandAction::NewWindow
|
||||
| CommandAction::IncreaseFontSize
|
||||
| CommandAction::DecreaseFontSize
|
||||
) && (self.palette.is_some()
|
||||
@@ -180,6 +181,30 @@ impl Workspace {
|
||||
cx.stop_propagation();
|
||||
}
|
||||
|
||||
fn open_window(&self, cx: &mut Context<Self>) {
|
||||
let client = self.client.clone();
|
||||
let cwd = self
|
||||
.focused_pane()
|
||||
.map(|pane| pane.read(cx).data().cwd.clone());
|
||||
let active_tab = self.snapshot.as_deref().and_then(Snapshot::active_tab);
|
||||
let remote = client
|
||||
.remote()
|
||||
.or_else(|| active_tab?.remote.as_deref())
|
||||
.map(str::to_owned);
|
||||
let launch = cx
|
||||
.background_executor()
|
||||
.spawn(async move { client.open_window(remote, cwd) });
|
||||
cx.spawn(async move |view, cx| {
|
||||
if let Err(error) = launch.await {
|
||||
let _ = view.update(cx, |view, cx| {
|
||||
view.error = Some(format!("Could not open a new window: {error:#}"));
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn execute(&mut self, action: CommandAction, window: &mut Window, cx: &mut Context<Self>) {
|
||||
use CommandAction::*;
|
||||
let pane = self.focused_pane();
|
||||
@@ -189,6 +214,10 @@ impl Workspace {
|
||||
self.open_palette(window, cx);
|
||||
None
|
||||
}
|
||||
NewWindow => {
|
||||
self.open_window(cx);
|
||||
None
|
||||
}
|
||||
IncreaseFontSize | DecreaseFontSize => {
|
||||
let delta = if matches!(action, IncreaseFontSize) {
|
||||
1.
|
||||
@@ -225,7 +254,13 @@ impl Workspace {
|
||||
Direction::Down
|
||||
},
|
||||
}),
|
||||
ClosePane => pane_id.map(|pane| ClientMessage::ClosePane { pane }),
|
||||
ClosePane => pane_id
|
||||
.map(|pane| ClientMessage::ClosePane { pane })
|
||||
.or_else(|| {
|
||||
let tab = self.snapshot.as_deref()?.active_tab()?;
|
||||
tab.is_connecting()
|
||||
.then_some(ClientMessage::ClosePendingTab { tab: tab.id })
|
||||
}),
|
||||
ResetPaneName => pane_id.map(|pane| ClientMessage::RenamePane { pane, name: None }),
|
||||
ResetTabName => self
|
||||
.snapshot
|
||||
@@ -307,7 +342,8 @@ impl Workspace {
|
||||
if cx
|
||||
.update(|window, cx| {
|
||||
view.update(cx, |view, cx| {
|
||||
for text in update.clipboard {
|
||||
for text in update.clipboard.into_iter().filter(|text| !text.is_empty())
|
||||
{
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(text));
|
||||
}
|
||||
if let Some(error) = update.error {
|
||||
@@ -535,12 +571,18 @@ impl Render for Workspace {
|
||||
if let Some(snapshot) = &self.snapshot {
|
||||
incoming = pane_scene(snapshot, &self.panes, incoming_offset, Some(&self.client));
|
||||
if snapshot.panes.is_empty() {
|
||||
incoming = incoming.child(
|
||||
div()
|
||||
.p_4()
|
||||
.text_color(rgb(chrome::MUTED))
|
||||
.child("No sessions. Use + to open a terminal."),
|
||||
);
|
||||
let status = match snapshot.active_tab() {
|
||||
Some(tab) if tab.is_connecting() => tab
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|host| format!("Connecting to {host}…")),
|
||||
Some(_) => None, // The selected tab's grid is still in transit.
|
||||
None => Some("No sessions. Use + to open a terminal.".to_owned()),
|
||||
};
|
||||
if let Some(status) = status {
|
||||
incoming =
|
||||
incoming.child(div().p_4().text_color(rgb(chrome::MUTED)).child(status));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
incoming = incoming.child(
|
||||
@@ -561,15 +603,34 @@ impl Render for Workspace {
|
||||
.bg(rgb(chrome::APP_BACKGROUND))
|
||||
.child(header)
|
||||
.child(body);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
root = root.on_action(cx.listener(|view, _: &crate::NewWindow, _, cx| {
|
||||
view.open_window(cx);
|
||||
}));
|
||||
}
|
||||
if let Some(error) = &self.error {
|
||||
root = root.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.px_3()
|
||||
.py_1()
|
||||
.text_size(px(12.))
|
||||
.text_color(rgb(chrome::TEXT))
|
||||
.bg(rgb(chrome::BORDER))
|
||||
.child(error.clone()),
|
||||
.child(div().flex_1().min_w_0().child(error.clone()))
|
||||
.child(
|
||||
div()
|
||||
.id("dismiss-error")
|
||||
.px_2()
|
||||
.cursor_pointer()
|
||||
.child("Dismiss")
|
||||
.on_click(cx.listener(|view, _, _, cx| {
|
||||
view.error = None;
|
||||
cx.notify();
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
if let Some(palette) = &self.palette {
|
||||
|
||||
@@ -115,6 +115,7 @@ mod tests {
|
||||
fn stack(ids: &[u64], active: u64) -> crate::protocol::TabInfo {
|
||||
crate::protocol::TabInfo {
|
||||
id: 1,
|
||||
remote: None,
|
||||
title: String::new(),
|
||||
manual_title: None,
|
||||
panes: ids.to_vec(),
|
||||
|
||||
Reference in New Issue
Block a user