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:
+93
-22
@@ -1,6 +1,7 @@
|
||||
//! Display-only client transport. No terminal parser, PTY, or shell lives here.
|
||||
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 std::{
|
||||
@@ -54,8 +55,7 @@ struct RemoteSession {
|
||||
}
|
||||
struct Connection {
|
||||
launcher_socket: PathBuf,
|
||||
remote: Option<String>,
|
||||
remote_executable: Option<String>,
|
||||
remote: Option<RemoteWindow>,
|
||||
commands: mpsc::Sender<ClientMessage>,
|
||||
socket: Option<UnixStream>,
|
||||
ssh: Mutex<Option<Child>>,
|
||||
@@ -146,7 +146,7 @@ impl Client {
|
||||
};
|
||||
let remote_command = format!("exec {} --bridge{attach}", shell_quote(executable));
|
||||
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);
|
||||
} else {
|
||||
ssh_command.env_remove("SSH_AUTH_SOCK");
|
||||
@@ -189,8 +189,10 @@ impl Client {
|
||||
let pending = Arc::new(Mutex::new(Update::default()));
|
||||
let connection = Arc::new(Connection {
|
||||
launcher_socket: launcher_socket.to_owned(),
|
||||
remote: remote.map(str::to_owned),
|
||||
remote_executable: options.executable,
|
||||
remote: remote.map(|destination| RemoteWindow {
|
||||
destination: destination.into(),
|
||||
ssh: options,
|
||||
}),
|
||||
commands,
|
||||
socket,
|
||||
ssh: Mutex::new(ssh),
|
||||
@@ -264,20 +266,23 @@ impl Client {
|
||||
}
|
||||
|
||||
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> {
|
||||
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.
|
||||
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
|
||||
.remote_session
|
||||
.as_ref()
|
||||
@@ -288,23 +293,25 @@ impl Client {
|
||||
crate::launcher::control(
|
||||
&self.connection.launcher_socket,
|
||||
ClientMessage::RememberDetachedRemote(protocol::DetachedRemote {
|
||||
destination,
|
||||
destination: remote.destination.clone(),
|
||||
identity: session.identity,
|
||||
executable: self.remote_executable().map(str::to_owned),
|
||||
executable: remote.ssh.executable.clone(),
|
||||
}),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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.connection.launcher_socket,
|
||||
ClientMessage::OpenWindow {
|
||||
target: remote,
|
||||
session: SessionTarget::New { cwd },
|
||||
},
|
||||
)?;
|
||||
pub fn open_window(
|
||||
&self,
|
||||
remote_tab: Option<(TabId, String)>,
|
||||
cwd: Option<String>,
|
||||
) -> Result<()> {
|
||||
let request = new_window_request(self.connection.remote.as_ref(), remote_tab, cwd);
|
||||
if matches!(request, ClientMessage::OpenWindowForRemoteTab { .. }) {
|
||||
return self.send(request);
|
||||
}
|
||||
crate::launcher::control(&self.connection.launcher_socket, request)?;
|
||||
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(
|
||||
mut reader: impl Read,
|
||||
pending: &Mutex<Update>,
|
||||
@@ -610,6 +644,43 @@ fn copy_and_flush(reader: &mut impl Read, writer: &mut impl Write) -> std::io::R
|
||||
mod tests {
|
||||
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]
|
||||
fn invalid_frame_does_not_disconnect_local_or_remote_workspaces() {
|
||||
let remote = RemoteSession {
|
||||
|
||||
+12
-3
@@ -227,7 +227,7 @@ fn role_command(executable: &Path, role: &str, socket: &Path, log_path: &Path) -
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn open_window(
|
||||
socket: &Path,
|
||||
remote: Option<String>,
|
||||
remote: Option<protocol::RemoteWindow>,
|
||||
session: protocol::SessionTarget,
|
||||
) -> Result<()> {
|
||||
let mut command = role_command(
|
||||
@@ -251,8 +251,17 @@ pub fn open_window(
|
||||
// SSH options, daemon identity checks, and connection errors are retained.
|
||||
protocol::SessionTarget::Remembered(_) => bail!("reattach through the invoking client"),
|
||||
}
|
||||
if let Some(host) = remote {
|
||||
command.arg("--remote").arg(host);
|
||||
if let Some(remote) = remote {
|
||||
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")?;
|
||||
thread::spawn(move || child.wait());
|
||||
|
||||
+107
-64
@@ -77,7 +77,7 @@ impl Zygote {
|
||||
|
||||
pub fn open_window(
|
||||
&mut self,
|
||||
remote: Option<String>,
|
||||
remote: Option<protocol::RemoteWindow>,
|
||||
session: protocol::SessionTarget,
|
||||
) -> Result<()> {
|
||||
let executable = executable_path()?;
|
||||
@@ -90,11 +90,20 @@ impl Zygote {
|
||||
// ready. If startup fails, a later launch can retry this stopped one.
|
||||
*self = Self::start(&self.server_socket)?;
|
||||
}
|
||||
match self.request(&LaunchRequest::Launch {
|
||||
server_socket: self.server_socket.clone(),
|
||||
remote,
|
||||
session,
|
||||
})? {
|
||||
let server_socket = self.server_socket.clone();
|
||||
let request = match remote {
|
||||
Some(remote) => LaunchRequest::LaunchRemote {
|
||||
server_socket,
|
||||
remote,
|
||||
session,
|
||||
},
|
||||
None => LaunchRequest::Launch {
|
||||
server_socket,
|
||||
remote: None,
|
||||
session,
|
||||
},
|
||||
};
|
||||
match self.request(&request)? {
|
||||
LaunchResponse::Launched { pid } => {
|
||||
log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id());
|
||||
Ok(())
|
||||
@@ -172,6 +181,12 @@ enum LaunchRequest {
|
||||
session: protocol::SessionTarget,
|
||||
},
|
||||
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)]
|
||||
@@ -214,13 +229,16 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match request {
|
||||
LaunchRequest::Ping => protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Ready {
|
||||
pid: std::process::id(),
|
||||
},
|
||||
)?,
|
||||
let (server_socket, remote, session, ssh) = match request {
|
||||
LaunchRequest::Ping => {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Ready {
|
||||
pid: std::process::id(),
|
||||
},
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
LaunchRequest::Shutdown => {
|
||||
protocol::write_message(&mut stream, &LaunchResponse::Stopped)?;
|
||||
return Ok(());
|
||||
@@ -229,58 +247,55 @@ pub fn run_zygote(socket: &Path) -> Result<()> {
|
||||
server_socket,
|
||||
remote,
|
||||
session,
|
||||
} => {
|
||||
if let Err(error) = ensure_single_threaded() {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(error.to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
// SAFETY: this process is single-threaded (checked above) and
|
||||
// has never initialized GPUI/Wayland/Vulkan or an executor. All
|
||||
// Rust allocator/logger locks can only have belonged to this
|
||||
// thread and are unlocked here. The child closes inherited IPC
|
||||
// descriptors, resets SIGCHLD, and owns its fresh GUI runtime.
|
||||
let pid = unsafe { libc::fork() };
|
||||
if pid == -1 {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(io::Error::last_os_error().to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if pid == 0 {
|
||||
// SAFETY: this only labels our forked GUI process for tools.
|
||||
unsafe {
|
||||
libc::prctl(libc::PR_SET_NAME, c"psyterm-gui".as_ptr());
|
||||
}
|
||||
drop(stream);
|
||||
drop(listener);
|
||||
let result = set_child_reaping(false).and_then(|()| {
|
||||
crate::run_gui(
|
||||
server_socket,
|
||||
remote,
|
||||
session,
|
||||
protocol::SshOptions::from_env(),
|
||||
)
|
||||
});
|
||||
let code = if let Err(error) = result {
|
||||
log::error!("GUI startup failed: {error:#}");
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// SAFETY: this fork child must not run parent scope cleanup
|
||||
// (particularly the shared listening socket's unlink guard).
|
||||
unsafe { libc::_exit(code) };
|
||||
}
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Launched { pid: pid as u32 },
|
||||
)?;
|
||||
}
|
||||
} => (
|
||||
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() {
|
||||
protocol::write_message(&mut stream, &LaunchResponse::Error(error.to_string()))?;
|
||||
continue;
|
||||
}
|
||||
// SAFETY: this process is single-threaded (checked above) and
|
||||
// has never initialized GPUI/Wayland/Vulkan or an executor. All
|
||||
// Rust allocator/logger locks can only have belonged to this
|
||||
// thread and are unlocked here. The child closes inherited IPC
|
||||
// descriptors, resets SIGCHLD, and owns its fresh GUI runtime.
|
||||
let pid = unsafe { libc::fork() };
|
||||
if pid == -1 {
|
||||
protocol::write_message(
|
||||
&mut stream,
|
||||
&LaunchResponse::Error(io::Error::last_os_error().to_string()),
|
||||
)?;
|
||||
continue;
|
||||
}
|
||||
if pid == 0 {
|
||||
// SAFETY: this only labels our forked GUI process for tools.
|
||||
unsafe {
|
||||
libc::prctl(libc::PR_SET_NAME, c"psyterm-gui".as_ptr());
|
||||
}
|
||||
drop(stream);
|
||||
drop(listener);
|
||||
let result = set_child_reaping(false)
|
||||
.and_then(|()| crate::run_gui(server_socket, remote, session, ssh));
|
||||
let code = if let Err(error) = result {
|
||||
log::error!("GUI startup failed: {error:#}");
|
||||
1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// SAFETY: this fork child must not run parent scope cleanup
|
||||
// (particularly the shared listening socket's unlink guard).
|
||||
unsafe { libc::_exit(code) };
|
||||
}
|
||||
protocol::write_message(&mut stream, &LaunchResponse::Launched { pid: pid as u32 })?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,6 +406,7 @@ mod tests {
|
||||
let request = LaunchRequest::Launch {
|
||||
server_socket: PathBuf::from("/private/psyterm.sock"),
|
||||
remote: Some("work-host".into()),
|
||||
session: protocol::SessionTarget::New { cwd: None },
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
protocol::write_message(&mut bytes, &request).unwrap();
|
||||
@@ -398,6 +414,33 @@ mod tests {
|
||||
assert!(
|
||||
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]
|
||||
|
||||
+9
-5
@@ -206,13 +206,17 @@ fn main() -> Result<()> {
|
||||
} else {
|
||||
launcher::ensure_server(&socket)?;
|
||||
}
|
||||
launcher::control(
|
||||
&socket,
|
||||
protocol::ClientMessage::OpenWindow {
|
||||
target: remote,
|
||||
let request = match remote {
|
||||
Some(destination) => protocol::ClientMessage::OpenRemoteWindow {
|
||||
target: protocol::RemoteWindow { destination, ssh },
|
||||
session,
|
||||
},
|
||||
)?;
|
||||
None => protocol::ClientMessage::OpenWindow {
|
||||
target: None,
|
||||
session,
|
||||
},
|
||||
};
|
||||
launcher::control(&socket, request)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+27
-1
@@ -33,13 +33,29 @@ pub enum SessionTarget {
|
||||
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)]
|
||||
pub struct SshOptions {
|
||||
pub executable: Option<String>,
|
||||
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.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DetachedRemote {
|
||||
@@ -162,6 +178,16 @@ pub enum ClientMessage {
|
||||
origin: Option<SessionIdentity>,
|
||||
},
|
||||
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)]
|
||||
|
||||
+60
-6
@@ -182,14 +182,14 @@ impl Outbox {
|
||||
/// Run the headless server. The caller handles platform-specific window launches.
|
||||
pub fn run(
|
||||
socket: &Path,
|
||||
open_window: impl FnMut(Option<String>, SessionTarget) -> Result<()>,
|
||||
open_window: impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
run_with_shell(socket, open_window, None)
|
||||
}
|
||||
|
||||
fn run_with_shell(
|
||||
socket: &Path,
|
||||
mut open_window: impl FnMut(Option<String>, SessionTarget) -> Result<()>,
|
||||
mut open_window: impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
|
||||
shell: Option<Shell>,
|
||||
) -> Result<()> {
|
||||
let (_socket_guard, listener) = bind_socket(socket)?;
|
||||
@@ -320,7 +320,7 @@ impl Server {
|
||||
fn run(
|
||||
&mut self,
|
||||
receiver: &mpsc::Receiver<Action>,
|
||||
open_window: &mut impl FnMut(Option<String>, SessionTarget) -> Result<()>,
|
||||
open_window: &mut impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
loop {
|
||||
let until_cwd = CWD_REFRESH_INTERVAL.saturating_sub(self.last_cwd_refresh.elapsed());
|
||||
@@ -502,7 +502,7 @@ impl Server {
|
||||
&mut self,
|
||||
id: u64,
|
||||
message: ClientMessage,
|
||||
open_window: &mut impl FnMut(Option<String>, SessionTarget) -> Result<()>,
|
||||
open_window: &mut impl FnMut(Option<RemoteWindow>, SessionTarget) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let Some(client) = self.clients.get_mut(&id) else {
|
||||
return Ok(());
|
||||
@@ -602,9 +602,23 @@ impl Server {
|
||||
{
|
||||
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);
|
||||
}
|
||||
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 } => {
|
||||
let state = self
|
||||
.sessions
|
||||
@@ -901,6 +915,8 @@ impl SessionState {
|
||||
| ClientMessage::Ping
|
||||
| ClientMessage::ListSessions
|
||||
| ClientMessage::OpenWindow { .. }
|
||||
| ClientMessage::OpenRemoteWindow { .. }
|
||||
| ClientMessage::OpenWindowForRemoteTab { .. }
|
||||
| ClientMessage::OpenRemoteTab { .. }
|
||||
| ClientMessage::DetachRemote { .. }
|
||||
| ClientMessage::LastDetachedRemote { .. }
|
||||
@@ -1403,6 +1419,12 @@ mod tests {
|
||||
}
|
||||
impl TestServer {
|
||||
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!(
|
||||
"pt-s-{:x}-{:x}",
|
||||
std::process::id(),
|
||||
@@ -1415,7 +1437,7 @@ mod tests {
|
||||
let thread = thread::spawn(move || {
|
||||
run_with_shell(
|
||||
&address,
|
||||
|_, _| Ok(()),
|
||||
launch,
|
||||
Some(Shell::new("/bin/sh".into(), Vec::new())),
|
||||
)
|
||||
});
|
||||
@@ -1752,6 +1774,38 @@ mod tests {
|
||||
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) {
|
||||
send(
|
||||
stream,
|
||||
|
||||
+92
-16
@@ -14,7 +14,7 @@ pub(super) enum RemoteEvent {
|
||||
}
|
||||
|
||||
pub(super) struct RemoteSession {
|
||||
destination: String,
|
||||
target: RemoteWindow,
|
||||
anchor: TabId,
|
||||
slot: TabId,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
@@ -52,6 +52,15 @@ impl RemoteSession {
|
||||
(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<()> {
|
||||
self.connection
|
||||
.as_ref()
|
||||
@@ -169,7 +178,7 @@ impl RemoteSession {
|
||||
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());
|
||||
tab.remote = Some(self.target.destination.clone());
|
||||
}
|
||||
for pane in &mut tab.panes {
|
||||
*pane = mapped(&mut new_pane_ids, *pane, next);
|
||||
@@ -285,6 +294,10 @@ impl SessionState {
|
||||
let session = self.id;
|
||||
let sender = self.sender.clone();
|
||||
let dest = destination.clone();
|
||||
let window_target = RemoteWindow {
|
||||
destination,
|
||||
ssh: ssh.clone(),
|
||||
};
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
let worker_cancelled = cancelled.clone();
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -329,7 +342,7 @@ impl SessionState {
|
||||
&mut self,
|
||||
index: usize,
|
||||
group: u64,
|
||||
destination: String,
|
||||
target: RemoteWindow,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
) {
|
||||
let anchor = self.tabs[index].id;
|
||||
@@ -338,7 +351,7 @@ impl SessionState {
|
||||
TabInfo {
|
||||
id: group,
|
||||
title: "Connecting…".into(),
|
||||
remote: Some(destination.clone()),
|
||||
remote: Some(target.destination.clone()),
|
||||
manual_title: None,
|
||||
panes: Vec::new(),
|
||||
active_pane: 0,
|
||||
@@ -352,7 +365,7 @@ impl SessionState {
|
||||
self.remotes.insert(
|
||||
group,
|
||||
RemoteSession {
|
||||
destination,
|
||||
target,
|
||||
anchor,
|
||||
slot: group,
|
||||
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>> {
|
||||
let (&group, remote) = self
|
||||
.remotes
|
||||
@@ -374,11 +409,8 @@ impl SessionState {
|
||||
.context("tab is not attached to an SSH session")?;
|
||||
// A nested SSH tab is owned by the upstream workspace. Detach it
|
||||
// there so the enclosing SSH session and its other tabs stay open.
|
||||
if let Some(frame) = &remote.latest
|
||||
&& let Some(id) = original(&remote.tabs, tab)
|
||||
&& frame.tabs.iter().any(|t| t.id == id && t.remote.is_some())
|
||||
{
|
||||
remote.send(ClientMessage::DetachRemote { tab: id })?;
|
||||
if let Some(nested) = remote.nested_tab(tab) {
|
||||
remote.send(ClientMessage::DetachRemote { tab: nested.id })?;
|
||||
return Ok(None);
|
||||
}
|
||||
let target = remote.connection.as_ref().and_then(|client| {
|
||||
@@ -386,9 +418,9 @@ impl SessionState {
|
||||
.remote_identity()
|
||||
.or_else(|| remote.latest.as_ref()?.lineage.first().copied())?;
|
||||
Some(DetachedRemote {
|
||||
destination: remote.destination.clone(),
|
||||
destination: remote.target.destination.clone(),
|
||||
identity,
|
||||
executable: client.remote_executable().map(str::to_owned),
|
||||
executable: remote.target.ssh.executable.clone(),
|
||||
})
|
||||
});
|
||||
self.remove_remote(group);
|
||||
@@ -526,7 +558,7 @@ impl Server {
|
||||
let mut closed = update.disconnected;
|
||||
let mut error = update
|
||||
.error
|
||||
.map(|error| format!("{}: {error}", remote.destination));
|
||||
.map(|error| format!("{}: {error}", remote.target.destination));
|
||||
if let Some(snapshot) = update.snapshot {
|
||||
closed |= snapshot.tabs.is_empty();
|
||||
match remote.apply(
|
||||
@@ -540,7 +572,7 @@ impl Server {
|
||||
closed = true;
|
||||
error = Some(format!(
|
||||
"Invalid layout from {}: {reason}",
|
||||
remote.destination
|
||||
remote.target.destination
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -587,7 +619,10 @@ mod tests {
|
||||
local.insert_remote_slot(
|
||||
anchor,
|
||||
group,
|
||||
"user@work".into(),
|
||||
RemoteWindow {
|
||||
destination: "user@work".into(),
|
||||
ssh: SshOptions::default(),
|
||||
},
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
);
|
||||
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> {
|
||||
let (frames, receive) = mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
|
||||
+1
-4
@@ -186,10 +186,7 @@ impl Workspace {
|
||||
.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 remote = active_tab.and_then(|tab| tab.remote.clone().map(|host| (tab.id, host)));
|
||||
let launch = cx
|
||||
.background_executor()
|
||||
.spawn(async move { client.open_window(remote, cwd) });
|
||||
|
||||
Reference in New Issue
Block a user