Preserve SSH connection settings when opening new windows

Forward the invoking shell's remote executable and agent through the Linux prefork launcher. Resolve mounted tabs by stable ID for the New Window shortcut and reconnect to nested destinations from the local host.
This commit is contained in:
James Magahern
2026-11-17 16:20:54 -08:00
parent 153838061e
commit cc2acb51e4
9 changed files with 408 additions and 125 deletions
+7 -4
View File
@@ -84,7 +84,10 @@ GUI, and returns. Each invocation starts an independent session unless you pass
Each new session starts with one tab and one shell. Windows opened with the Each new session starts with one tab and one shell. Windows opened with the
New Window shortcut start a fresh session in the focused pane’s directory on New Window shortcut start a fresh session in the focused pane’s directory on
the same host. Closing a window leaves its session available for reattachment. the same host. A remote window reuses the focused SSH connection’s executable
and agent settings. For a nested SSH tab, the new window connects directly
from your computer, so the nested host must be reachable using your local
SSH configuration. Closing a window leaves its session available for reattachment.
To choose a session, run `psyterm --list` and pass its ID to `psyterm --attach ID`. With no ID, To choose a session, run `psyterm --list` and pass its ID to `psyterm --attach ID`. With no ID,
`--attach` prefers the most recently used detached session and otherwise `--attach` prefers the most recently used detached session and otherwise
selects the most recently used attached session. selects the most recently used attached session.
@@ -157,9 +160,9 @@ in a window. The local daemon remembers these targets until it exits.
If you detach a nested SSH session, run the command on the host that opened it. If you detach a nested SSH session, run the command on the host that opened it.
You can also select a session explicitly with `psyterm --remote user@host --attach ID`. You can also select a session explicitly with `psyterm --remote user@host --attach ID`.
The workspace’s daemon must be running this build for the tab close button The local daemon must be running this build to close tabs, remember detached
and remote detach history. Existing protocol-v6 sessions on the SSH host sessions, and pass SSH settings to new windows. Existing protocol-v6 sessions
can stay running. on the SSH host can stay running.
SSH uses `BatchMode=yes`. Configure key or agent authentication and trust the SSH uses `BatchMode=yes`. Configure key or agent authentication and trust the
host key before connecting. The remote host needs a compatible `psyterm` host key before connecting. The remote host needs a compatible `psyterm`
+93 -22
View File
@@ -1,6 +1,7 @@
//! Display-only client transport. No terminal parser, PTY, or shell lives here. //! Display-only client transport. No terminal parser, PTY, or shell lives here.
use crate::protocol::{ use crate::protocol::{
self, ClientMessage, ServerMessage, SessionIdentity, SessionTarget, Snapshot, SshOptions, self, ClientMessage, RemoteWindow, ServerMessage, SessionIdentity, SessionTarget, Snapshot,
SshOptions, TabId,
}; };
use anyhow::{Context, Result, bail, ensure}; use anyhow::{Context, Result, bail, ensure};
use std::{ use std::{
@@ -54,8 +55,7 @@ struct RemoteSession {
} }
struct Connection { struct Connection {
launcher_socket: PathBuf, launcher_socket: PathBuf,
remote: Option<String>, remote: Option<RemoteWindow>,
remote_executable: Option<String>,
commands: mpsc::Sender<ClientMessage>, commands: mpsc::Sender<ClientMessage>,
socket: Option<UnixStream>, socket: Option<UnixStream>,
ssh: Mutex<Option<Child>>, ssh: Mutex<Option<Child>>,
@@ -146,7 +146,7 @@ impl Client {
}; };
let remote_command = format!("exec {} --bridge{attach}", shell_quote(executable)); let remote_command = format!("exec {} --bridge{attach}", shell_quote(executable));
let mut ssh_command = Command::new("ssh"); let mut ssh_command = Command::new("ssh");
if let Some(socket) = options.agent_socket { if let Some(socket) = &options.agent_socket {
ssh_command.env("SSH_AUTH_SOCK", socket); ssh_command.env("SSH_AUTH_SOCK", socket);
} else { } else {
ssh_command.env_remove("SSH_AUTH_SOCK"); ssh_command.env_remove("SSH_AUTH_SOCK");
@@ -189,8 +189,10 @@ impl Client {
let pending = Arc::new(Mutex::new(Update::default())); let pending = Arc::new(Mutex::new(Update::default()));
let connection = Arc::new(Connection { let connection = Arc::new(Connection {
launcher_socket: launcher_socket.to_owned(), launcher_socket: launcher_socket.to_owned(),
remote: remote.map(str::to_owned), remote: remote.map(|destination| RemoteWindow {
remote_executable: options.executable, destination: destination.into(),
ssh: options,
}),
commands, commands,
socket, socket,
ssh: Mutex::new(ssh), ssh: Mutex::new(ssh),
@@ -264,20 +266,23 @@ impl Client {
} }
pub fn remote(&self) -> Option<&str> { pub fn remote(&self) -> Option<&str> {
self.connection.remote.as_deref() self.connection
.remote
.as_ref()
.map(|remote| remote.destination.as_str())
} }
pub fn remote_identity(&self) -> Option<SessionIdentity> { pub fn remote_identity(&self) -> Option<SessionIdentity> {
self.remote_session.as_ref().map(|session| session.identity) self.remote_session.as_ref().map(|session| session.identity)
} }
pub fn remote_executable(&self) -> Option<&str> {
self.connection.remote_executable.as_deref()
}
/// Remember a direct SSH window on its local launcher before detaching it. /// Remember a direct SSH window on its local launcher before detaching it.
pub fn remember_remote_detach(&self) -> Result<()> { pub fn remember_remote_detach(&self) -> Result<()> {
let destination = self.remote().context("this window is local")?.to_owned(); let remote = self
.connection
.remote
.as_ref()
.context("this window is local")?;
let session = self let session = self
.remote_session .remote_session
.as_ref() .as_ref()
@@ -288,23 +293,25 @@ impl Client {
crate::launcher::control( crate::launcher::control(
&self.connection.launcher_socket, &self.connection.launcher_socket,
ClientMessage::RememberDetachedRemote(protocol::DetachedRemote { ClientMessage::RememberDetachedRemote(protocol::DetachedRemote {
destination, destination: remote.destination.clone(),
identity: session.identity, identity: session.identity,
executable: self.remote_executable().map(str::to_owned), executable: remote.ssh.executable.clone(),
}), }),
)?; )?;
Ok(()) Ok(())
} }
/// Launch through the local daemon even when this terminal connects over SSH. /// Launch through the local daemon even when this terminal connects over SSH.
pub fn open_window(&self, remote: Option<String>, cwd: Option<String>) -> Result<()> { pub fn open_window(
crate::launcher::control( &self,
&self.connection.launcher_socket, remote_tab: Option<(TabId, String)>,
ClientMessage::OpenWindow { cwd: Option<String>,
target: remote, ) -> Result<()> {
session: SessionTarget::New { cwd }, 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)?;
Ok(()) Ok(())
} }
@@ -325,6 +332,33 @@ impl Client {
} }
} }
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 },
},
}
}
fn read_updates( fn read_updates(
mut reader: impl Read, mut reader: impl Read,
pending: &Mutex<Update>, pending: &Mutex<Update>,
@@ -610,6 +644,43 @@ fn copy_and_flush(reader: &mut impl Read, writer: &mut impl Write) -> std::io::R
mod tests { mod tests {
use super::*; use super::*;
#[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);
}
#[test] #[test]
fn invalid_frame_does_not_disconnect_local_or_remote_workspaces() { fn invalid_frame_does_not_disconnect_local_or_remote_workspaces() {
let remote = RemoteSession { let remote = RemoteSession {
+12 -3
View File
@@ -227,7 +227,7 @@ fn role_command(executable: &Path, role: &str, socket: &Path, log_path: &Path) -
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn open_window( pub fn open_window(
socket: &Path, socket: &Path,
remote: Option<String>, remote: Option<protocol::RemoteWindow>,
session: protocol::SessionTarget, session: protocol::SessionTarget,
) -> Result<()> { ) -> Result<()> {
let mut command = role_command( let mut command = role_command(
@@ -251,8 +251,17 @@ pub fn open_window(
// SSH options, daemon identity checks, and connection errors are retained. // SSH options, daemon identity checks, and connection errors are retained.
protocol::SessionTarget::Remembered(_) => bail!("reattach through the invoking client"), protocol::SessionTarget::Remembered(_) => bail!("reattach through the invoking client"),
} }
if let Some(host) = remote { if let Some(remote) = remote {
command.arg("--remote").arg(host); command.arg("--remote").arg(remote.destination);
command
.env_remove("PSYTERM_REMOTE_BIN")
.env_remove("SSH_AUTH_SOCK");
if let Some(executable) = remote.ssh.executable {
command.env("PSYTERM_REMOTE_BIN", executable);
}
if let Some(socket) = remote.ssh.agent_socket {
command.env("SSH_AUTH_SOCK", socket);
}
} }
let mut child = command.spawn().context("launch psyTerm GUI")?; let mut child = command.spawn().context("launch psyTerm GUI")?;
thread::spawn(move || child.wait()); thread::spawn(move || child.wait());
+69 -26
View File
@@ -77,7 +77,7 @@ impl Zygote {
pub fn open_window( pub fn open_window(
&mut self, &mut self,
remote: Option<String>, remote: Option<protocol::RemoteWindow>,
session: protocol::SessionTarget, session: protocol::SessionTarget,
) -> Result<()> { ) -> Result<()> {
let executable = executable_path()?; let executable = executable_path()?;
@@ -90,11 +90,20 @@ impl Zygote {
// ready. If startup fails, a later launch can retry this stopped one. // ready. If startup fails, a later launch can retry this stopped one.
*self = Self::start(&self.server_socket)?; *self = Self::start(&self.server_socket)?;
} }
match self.request(&LaunchRequest::Launch { let server_socket = self.server_socket.clone();
server_socket: self.server_socket.clone(), let request = match remote {
Some(remote) => LaunchRequest::LaunchRemote {
server_socket,
remote, remote,
session, session,
})? { },
None => LaunchRequest::Launch {
server_socket,
remote: None,
session,
},
};
match self.request(&request)? {
LaunchResponse::Launched { pid } => { LaunchResponse::Launched { pid } => {
log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id()); log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id());
Ok(()) Ok(())
@@ -172,6 +181,12 @@ enum LaunchRequest {
session: protocol::SessionTarget, session: protocol::SessionTarget,
}, },
Shutdown, Shutdown,
// Keep Launch readable when a running older daemon refreshes its helper.
LaunchRemote {
server_socket: PathBuf,
remote: protocol::RemoteWindow,
session: protocol::SessionTarget,
},
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -214,13 +229,16 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
continue; continue;
} }
}; };
match request { let (server_socket, remote, session, ssh) = match request {
LaunchRequest::Ping => protocol::write_message( LaunchRequest::Ping => {
protocol::write_message(
&mut stream, &mut stream,
&LaunchResponse::Ready { &LaunchResponse::Ready {
pid: std::process::id(), pid: std::process::id(),
}, },
)?, )?;
continue;
}
LaunchRequest::Shutdown => { LaunchRequest::Shutdown => {
protocol::write_message(&mut stream, &LaunchResponse::Stopped)?; protocol::write_message(&mut stream, &LaunchResponse::Stopped)?;
return Ok(()); return Ok(());
@@ -229,12 +247,20 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
server_socket, server_socket,
remote, remote,
session, session,
} => { } => (
server_socket,
remote,
session,
protocol::SshOptions::from_env(),
),
LaunchRequest::LaunchRemote {
server_socket,
remote,
session,
} => (server_socket, Some(remote.destination), session, remote.ssh),
};
if let Err(error) = ensure_single_threaded() { if let Err(error) = ensure_single_threaded() {
protocol::write_message( protocol::write_message(&mut stream, &LaunchResponse::Error(error.to_string()))?;
&mut stream,
&LaunchResponse::Error(error.to_string()),
)?;
continue; continue;
} }
// SAFETY: this process is single-threaded (checked above) and // SAFETY: this process is single-threaded (checked above) and
@@ -257,14 +283,8 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
} }
drop(stream); drop(stream);
drop(listener); drop(listener);
let result = set_child_reaping(false).and_then(|()| { let result = set_child_reaping(false)
crate::run_gui( .and_then(|()| crate::run_gui(server_socket, remote, session, ssh));
server_socket,
remote,
session,
protocol::SshOptions::from_env(),
)
});
let code = if let Err(error) = result { let code = if let Err(error) = result {
log::error!("GUI startup failed: {error:#}"); log::error!("GUI startup failed: {error:#}");
1 1
@@ -275,12 +295,7 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
// (particularly the shared listening socket's unlink guard). // (particularly the shared listening socket's unlink guard).
unsafe { libc::_exit(code) }; unsafe { libc::_exit(code) };
} }
protocol::write_message( protocol::write_message(&mut stream, &LaunchResponse::Launched { pid: pid as u32 })?;
&mut stream,
&LaunchResponse::Launched { pid: pid as u32 },
)?;
}
}
} }
} }
@@ -391,6 +406,7 @@ mod tests {
let request = LaunchRequest::Launch { let request = LaunchRequest::Launch {
server_socket: PathBuf::from("/private/psyterm.sock"), server_socket: PathBuf::from("/private/psyterm.sock"),
remote: Some("work-host".into()), remote: Some("work-host".into()),
session: protocol::SessionTarget::New { cwd: None },
}; };
let mut bytes = Vec::new(); let mut bytes = Vec::new();
protocol::write_message(&mut bytes, &request).unwrap(); protocol::write_message(&mut bytes, &request).unwrap();
@@ -398,6 +414,33 @@ mod tests {
assert!( assert!(
matches!(decoded, LaunchRequest::Launch { remote: Some(host), .. } if host == "work-host") matches!(decoded, LaunchRequest::Launch { remote: Some(host), .. } if host == "work-host")
); );
let request = LaunchRequest::LaunchRemote {
server_socket: PathBuf::from("/private/psyterm.sock"),
remote: protocol::RemoteWindow {
destination: "work-host".into(),
ssh: protocol::SshOptions {
executable: Some("/opt/remote apps/psyterm".into()),
agent_socket: Some(PathBuf::from("/private/agent.sock")),
},
},
session: protocol::SessionTarget::New { cwd: None },
};
let mut bytes = Vec::new();
protocol::write_message(&mut bytes, &request).unwrap();
let decoded: LaunchRequest = protocol::read_message(&mut bytes.as_slice()).unwrap();
let LaunchRequest::LaunchRemote { remote, .. } = decoded else {
panic!()
};
assert_eq!(remote.destination, "work-host");
assert_eq!(
remote.ssh.executable.as_deref(),
Some("/opt/remote apps/psyterm")
);
assert_eq!(
remote.ssh.agent_socket.as_deref(),
Some(Path::new("/private/agent.sock"))
);
} }
#[test] #[test]
+9 -5
View File
@@ -206,13 +206,17 @@ fn main() -> Result<()> {
} else { } else {
launcher::ensure_server(&socket)?; launcher::ensure_server(&socket)?;
} }
launcher::control( let request = match remote {
&socket, Some(destination) => protocol::ClientMessage::OpenRemoteWindow {
protocol::ClientMessage::OpenWindow { target: protocol::RemoteWindow { destination, ssh },
target: remote,
session, session,
}, },
)?; None => protocol::ClientMessage::OpenWindow {
target: None,
session,
},
};
launcher::control(&socket, request)?;
Ok(()) Ok(())
} }
} }
+27 -1
View File
@@ -33,13 +33,29 @@ pub enum SessionTarget {
Remembered(SessionIdentity), Remembered(SessionIdentity),
} }
/// SSH settings inherited from the shell that requested a remote tab. /// SSH settings inherited from the shell that requested a remote session.
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SshOptions { pub struct SshOptions {
pub executable: Option<String>, pub executable: Option<String>,
pub agent_socket: Option<std::path::PathBuf>, pub agent_socket: Option<std::path::PathBuf>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteWindow {
pub destination: String,
pub ssh: SshOptions,
}
impl RemoteWindow {
/// Older launch requests carry only the host and inherit the launcher's settings.
pub fn from_env(destination: String) -> Self {
Self {
destination,
ssh: SshOptions::from_env(),
}
}
}
/// Reconnect using the original remote binary and verify the daemon that owned the shell. /// Reconnect using the original remote binary and verify the daemon that owned the shell.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DetachedRemote { pub struct DetachedRemote {
@@ -162,6 +178,16 @@ pub enum ClientMessage {
origin: Option<SessionIdentity>, origin: Option<SessionIdentity>,
}, },
RememberDetachedRemote(DetachedRemote), RememberDetachedRemote(DetachedRemote),
OpenRemoteWindow {
target: RemoteWindow,
session: SessionTarget,
},
/// Resolve a mounted connection on the user's joined local workspace.
OpenWindowForRemoteTab {
tab: TabId,
cwd: Option<String>,
fallback: SshOptions,
},
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+60 -6
View File
@@ -182,14 +182,14 @@ impl Outbox {
/// Run the headless server. The caller handles platform-specific window launches. /// Run the headless server. The caller handles platform-specific window launches.
pub fn run( pub fn run(
socket: &Path, socket: &Path,
open_window: impl FnMut(Option<String>, SessionTarget) -> Result<()>, open_window: impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
) -> Result<()> { ) -> Result<()> {
run_with_shell(socket, open_window, None) run_with_shell(socket, open_window, None)
} }
fn run_with_shell( fn run_with_shell(
socket: &Path, socket: &Path,
mut open_window: impl FnMut(Option<String>, SessionTarget) -> Result<()>, mut open_window: impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
shell: Option<Shell>, shell: Option<Shell>,
) -> Result<()> { ) -> Result<()> {
let (_socket_guard, listener) = bind_socket(socket)?; let (_socket_guard, listener) = bind_socket(socket)?;
@@ -320,7 +320,7 @@ impl Server {
fn run( fn run(
&mut self, &mut self,
receiver: &mpsc::Receiver<Action>, receiver: &mpsc::Receiver<Action>,
open_window: &mut impl FnMut(Option<String>, SessionTarget) -> Result<()>, open_window: &mut impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
) -> Result<()> { ) -> Result<()> {
loop { loop {
let until_cwd = CWD_REFRESH_INTERVAL.saturating_sub(self.last_cwd_refresh.elapsed()); let until_cwd = CWD_REFRESH_INTERVAL.saturating_sub(self.last_cwd_refresh.elapsed());
@@ -502,7 +502,7 @@ impl Server {
&mut self, &mut self,
id: u64, id: u64,
message: ClientMessage, message: ClientMessage,
open_window: &mut impl FnMut(Option<String>, SessionTarget) -> Result<()>, open_window: &mut impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
) -> Result<()> { ) -> Result<()> {
let Some(client) = self.clients.get_mut(&id) else { let Some(client) = self.clients.get_mut(&id) else {
return Ok(()); return Ok(());
@@ -602,9 +602,23 @@ impl Server {
{ {
session = SessionTarget::Attach(Some(self.attach_target(requested)?)); session = SessionTarget::Attach(Some(self.attach_target(requested)?));
} }
open_window(target, session)?; open_window(target.map(RemoteWindow::from_env), session)?;
self.clients[&id].output.reliable(ServerMessage::Pong); self.clients[&id].output.reliable(ServerMessage::Pong);
} }
ClientMessage::OpenRemoteWindow { target, session } => {
crate::client::validate_destination(&target.destination)?;
open_window(Some(target), session)?;
client.output.reliable(ServerMessage::Pong);
}
ClientMessage::OpenWindowForRemoteTab { tab, cwd, fallback } => {
let state = self
.sessions
.get(&client.session.context("join a session first")?)
.context("session has ended")?;
let target = state.remote_window_for_tab(tab, fallback)?;
crate::client::validate_destination(&target.destination)?;
open_window(Some(target), SessionTarget::New { cwd })?;
}
ClientMessage::DetachRemote { tab } => { ClientMessage::DetachRemote { tab } => {
let state = self let state = self
.sessions .sessions
@@ -901,6 +915,8 @@ impl SessionState {
| ClientMessage::Ping | ClientMessage::Ping
| ClientMessage::ListSessions | ClientMessage::ListSessions
| ClientMessage::OpenWindow { .. } | ClientMessage::OpenWindow { .. }
| ClientMessage::OpenRemoteWindow { .. }
| ClientMessage::OpenWindowForRemoteTab { .. }
| ClientMessage::OpenRemoteTab { .. } | ClientMessage::OpenRemoteTab { .. }
| ClientMessage::DetachRemote { .. } | ClientMessage::DetachRemote { .. }
| ClientMessage::LastDetachedRemote { .. } | ClientMessage::LastDetachedRemote { .. }
@@ -1403,6 +1419,12 @@ mod tests {
} }
impl TestServer { impl TestServer {
pub(super) fn start() -> Self { pub(super) fn start() -> Self {
Self::start_with_launcher(|_, _| Ok(()))
}
fn start_with_launcher(
launch: impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()> + Send + 'static,
) -> Self {
let directory = std::env::temp_dir().join(format!( let directory = std::env::temp_dir().join(format!(
"pt-s-{:x}-{:x}", "pt-s-{:x}-{:x}",
std::process::id(), std::process::id(),
@@ -1415,7 +1437,7 @@ mod tests {
let thread = thread::spawn(move || { let thread = thread::spawn(move || {
run_with_shell( run_with_shell(
&address, &address,
|_, _| Ok(()), launch,
Some(Shell::new("/bin/sh".into(), Vec::new())), Some(Shell::new("/bin/sh".into(), Vec::new())),
) )
}); });
@@ -1752,6 +1774,38 @@ mod tests {
assert_eq!(mode & 0o777, 0o600); assert_eq!(mode & 0o777, 0o600);
} }
#[test]
fn remote_window_launch_passes_the_requesting_shells_ssh_settings() {
let (sent, received) = mpsc::channel();
let server = TestServer::start_with_launcher(move |remote, session| {
sent.send((remote, session))?;
Ok(())
});
let ssh = SshOptions {
executable: Some("/opt/remote apps/psyterm".into()),
agent_socket: Some(PathBuf::from("/private/agent.sock")),
};
crate::launcher::control(
&server.socket,
ClientMessage::OpenRemoteWindow {
target: RemoteWindow {
destination: "work-host".into(),
ssh: ssh.clone(),
},
session: SessionTarget::New {
cwd: Some("/work".into()),
},
},
)
.unwrap();
let (remote, session) = received.try_recv().unwrap();
let remote = remote.unwrap();
assert_eq!(remote.destination, "work-host");
assert_eq!(remote.ssh.executable, ssh.executable);
assert_eq!(remote.ssh.agent_socket, ssh.agent_socket);
assert!(matches!(session, SessionTarget::New { cwd: Some(cwd) } if cwd == "/work"));
}
fn input(stream: &mut UnixStream, pane: PaneId, command: &str) { fn input(stream: &mut UnixStream, pane: PaneId, command: &str) {
send( send(
stream, stream,
+92 -16
View File
@@ -14,7 +14,7 @@ pub(super) enum RemoteEvent {
} }
pub(super) struct RemoteSession { pub(super) struct RemoteSession {
destination: String, target: RemoteWindow,
anchor: TabId, anchor: TabId,
slot: TabId, slot: TabId,
cancelled: Arc<AtomicBool>, cancelled: Arc<AtomicBool>,
@@ -52,6 +52,15 @@ impl RemoteSession {
(self.latest.is_none() && self.slot == local) || original(&self.tabs, local).is_some() (self.latest.is_none() && self.slot == local) || original(&self.tabs, local).is_some()
} }
fn nested_tab(&self, local: TabId) -> Option<&TabInfo> {
let id = original(&self.tabs, local)?;
self.latest
.as_ref()?
.tabs
.iter()
.find(|tab| tab.id == id && tab.remote.is_some())
}
pub(super) fn send(&self, command: ClientMessage) -> Result<()> { pub(super) fn send(&self, command: ClientMessage) -> Result<()> {
self.connection self.connection
.as_ref() .as_ref()
@@ -169,7 +178,7 @@ impl RemoteSession {
for tab in &mut mapped_tabs { for tab in &mut mapped_tabs {
tab.id = mapped(&mut new_tab_ids, tab.id, next); tab.id = mapped(&mut new_tab_ids, tab.id, next);
if tab.remote.is_none() { if tab.remote.is_none() {
tab.remote = Some(self.destination.clone()); tab.remote = Some(self.target.destination.clone());
} }
for pane in &mut tab.panes { for pane in &mut tab.panes {
*pane = mapped(&mut new_pane_ids, *pane, next); *pane = mapped(&mut new_pane_ids, *pane, next);
@@ -285,6 +294,10 @@ impl SessionState {
let session = self.id; let session = self.id;
let sender = self.sender.clone(); let sender = self.sender.clone();
let dest = destination.clone(); let dest = destination.clone();
let window_target = RemoteWindow {
destination,
ssh: ssh.clone(),
};
let cancelled = Arc::new(AtomicBool::new(false)); let cancelled = Arc::new(AtomicBool::new(false));
let worker_cancelled = cancelled.clone(); let worker_cancelled = cancelled.clone();
thread::Builder::new() thread::Builder::new()
@@ -321,7 +334,7 @@ impl SessionState {
} }
} }
})?; })?;
self.insert_remote_slot(index, group, destination, cancelled); self.insert_remote_slot(index, group, window_target, cancelled);
Ok(()) Ok(())
} }
@@ -329,7 +342,7 @@ impl SessionState {
&mut self, &mut self,
index: usize, index: usize,
group: u64, group: u64,
destination: String, target: RemoteWindow,
cancelled: Arc<AtomicBool>, cancelled: Arc<AtomicBool>,
) { ) {
let anchor = self.tabs[index].id; let anchor = self.tabs[index].id;
@@ -338,7 +351,7 @@ impl SessionState {
TabInfo { TabInfo {
id: group, id: group,
title: "Connecting…".into(), title: "Connecting…".into(),
remote: Some(destination.clone()), remote: Some(target.destination.clone()),
manual_title: None, manual_title: None,
panes: Vec::new(), panes: Vec::new(),
active_pane: 0, active_pane: 0,
@@ -352,7 +365,7 @@ impl SessionState {
self.remotes.insert( self.remotes.insert(
group, group,
RemoteSession { RemoteSession {
destination, target,
anchor, anchor,
slot: group, slot: group,
cancelled, cancelled,
@@ -366,6 +379,28 @@ impl SessionState {
); );
} }
pub(super) fn remote_window_for_tab(
&self,
tab: TabId,
fallback: SshOptions,
) -> Result<RemoteWindow> {
let remote = self
.remotes
.values()
.find(|remote| remote.owns_tab(tab))
.context("tab is no longer attached to an SSH session")?;
if let Some(destination) = remote
.nested_tab(tab)
.and_then(|nested| nested.remote.clone())
{
return Ok(RemoteWindow {
destination,
ssh: fallback,
});
}
Ok(remote.target.clone())
}
pub(super) fn detach_remote(&mut self, tab: TabId) -> Result<Option<DetachedRemote>> { pub(super) fn detach_remote(&mut self, tab: TabId) -> Result<Option<DetachedRemote>> {
let (&group, remote) = self let (&group, remote) = self
.remotes .remotes
@@ -374,11 +409,8 @@ impl SessionState {
.context("tab is not attached to an SSH session")?; .context("tab is not attached to an SSH session")?;
// A nested SSH tab is owned by the upstream workspace. Detach it // A nested SSH tab is owned by the upstream workspace. Detach it
// there so the enclosing SSH session and its other tabs stay open. // there so the enclosing SSH session and its other tabs stay open.
if let Some(frame) = &remote.latest if let Some(nested) = remote.nested_tab(tab) {
&& let Some(id) = original(&remote.tabs, tab) remote.send(ClientMessage::DetachRemote { tab: nested.id })?;
&& frame.tabs.iter().any(|t| t.id == id && t.remote.is_some())
{
remote.send(ClientMessage::DetachRemote { tab: id })?;
return Ok(None); return Ok(None);
} }
let target = remote.connection.as_ref().and_then(|client| { let target = remote.connection.as_ref().and_then(|client| {
@@ -386,9 +418,9 @@ impl SessionState {
.remote_identity() .remote_identity()
.or_else(|| remote.latest.as_ref()?.lineage.first().copied())?; .or_else(|| remote.latest.as_ref()?.lineage.first().copied())?;
Some(DetachedRemote { Some(DetachedRemote {
destination: remote.destination.clone(), destination: remote.target.destination.clone(),
identity, identity,
executable: client.remote_executable().map(str::to_owned), executable: remote.target.ssh.executable.clone(),
}) })
}); });
self.remove_remote(group); self.remove_remote(group);
@@ -526,7 +558,7 @@ impl Server {
let mut closed = update.disconnected; let mut closed = update.disconnected;
let mut error = update let mut error = update
.error .error
.map(|error| format!("{}: {error}", remote.destination)); .map(|error| format!("{}: {error}", remote.target.destination));
if let Some(snapshot) = update.snapshot { if let Some(snapshot) = update.snapshot {
closed |= snapshot.tabs.is_empty(); closed |= snapshot.tabs.is_empty();
match remote.apply( match remote.apply(
@@ -540,7 +572,7 @@ impl Server {
closed = true; closed = true;
error = Some(format!( error = Some(format!(
"Invalid layout from {}: {reason}", "Invalid layout from {}: {reason}",
remote.destination remote.target.destination
)); ));
} }
} }
@@ -587,7 +619,10 @@ mod tests {
local.insert_remote_slot( local.insert_remote_slot(
anchor, anchor,
group, group,
"user@work".into(), RemoteWindow {
destination: "user@work".into(),
ssh: SshOptions::default(),
},
Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)),
); );
group group
@@ -603,6 +638,47 @@ mod tests {
) )
} }
#[test]
fn remote_window_uses_the_selected_mount_and_nested_destination() {
let mut local = session(1);
local.new_tab(None).unwrap();
let first = reserve(&mut local, 0);
let second = reserve(&mut local, 0); // Same host, different credentials.
let ssh = SshOptions {
executable: Some("/mount/bin/psyterm".into()),
agent_socket: Some("/mount/agent.sock".into()),
};
local.remotes.get_mut(&second).unwrap().target.ssh = ssh.clone();
let fallback = SshOptions {
executable: Some("/caller/bin/psyterm".into()),
agent_socket: Some("/caller/agent.sock".into()),
};
let target = local
.remote_window_for_tab(first, fallback.clone())
.unwrap();
assert!(target.ssh.executable.is_none());
let target = local
.remote_window_for_tab(second, fallback.clone())
.unwrap();
assert_eq!(target.destination, "user@work");
assert_eq!(target.ssh.executable, ssh.executable);
assert_eq!(target.ssh.agent_socket, ssh.agent_socket);
let mut outer = session(2);
outer.new_tab(None).unwrap();
let mut frame = outer.snapshot();
frame.tabs[0].remote = Some("inner".into());
apply(&mut local, second, frame).unwrap();
let target = local
.remote_window_for_tab(second, fallback.clone())
.unwrap();
assert_eq!(target.destination, "inner");
assert_eq!(target.ssh.executable, fallback.executable);
assert_eq!(target.ssh.agent_socket, fallback.agent_socket);
local.remove_remote(second);
assert!(local.remote_window_for_tab(second, fallback).is_err());
}
fn receive_updates(updates: crate::client::Updates) -> mpsc::Receiver<Update> { fn receive_updates(updates: crate::client::Updates) -> mpsc::Receiver<Update> {
let (frames, receive) = mpsc::channel(); let (frames, receive) = mpsc::channel();
thread::spawn(move || { thread::spawn(move || {
+1 -4
View File
@@ -186,10 +186,7 @@ impl Workspace {
.focused_pane() .focused_pane()
.map(|pane| pane.read(cx).data().cwd.clone()); .map(|pane| pane.read(cx).data().cwd.clone());
let active_tab = self.snapshot.as_deref().and_then(Snapshot::active_tab); let active_tab = self.snapshot.as_deref().and_then(Snapshot::active_tab);
let remote = client let remote = active_tab.and_then(|tab| tab.remote.clone().map(|host| (tab.id, host)));
.remote()
.or_else(|| active_tab?.remote.as_deref())
.map(str::to_owned);
let launch = cx let launch = cx
.background_executor() .background_executor()
.spawn(async move { client.open_window(remote, cwd) }); .spawn(async move { client.open_window(remote, cwd) });