Files
psyTerm/src/server/remote.rs
T
James Magahern d980799648 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.
2026-11-17 14:50:29 -08:00

744 lines
26 KiB
Rust

//! 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);
}
}