Files
psyTerm/src/server/remote.rs
T

1228 lines
44 KiB
Rust
Raw Normal View History

//! 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 {
pub(super) target: RemoteWindow,
anchor: TabId,
slot: TabId,
cancelled: Arc<AtomicBool>,
pub(super) 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>>,
attaching: Option<SessionIdentity>,
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 listed_session(
&self,
owner: SessionIdentity,
attached: usize,
) -> Option<ListedSession> {
let snapshot = self.latest.as_ref()?;
let identity = *snapshot.lineage.first()?;
let active = self.requested_tab.unwrap_or(snapshot.active_tab);
let tab = *self.tabs.get(&active)?;
Some(ListedSession {
route: SessionRoute::Mounted {
owner,
tab,
identity,
},
host: Some(self.target.destination.clone()),
summary: SessionSummary::from_tabs(&snapshot.tabs, active),
attached,
})
}
pub(super) fn selection_tab(&self, identity: SessionIdentity, tab: TabId) -> Option<TabId> {
let Some(snapshot) = &self.latest else {
return (self.attaching == Some(identity)).then_some(self.slot);
};
if snapshot.lineage.first() != Some(&identity) {
return None;
}
// If the tab closed while the picker was open, the same SSH session
// may still have another tab with a live shell.
if self.owns_tab(tab) {
Some(tab)
} else {
self.tabs.get(&snapshot.active_tab).copied()
}
}
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()
.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, tab: &mut TabInfo) -> Vec<PaneSnapshot> {
let Some(frame) = self.latest.as_ref() else {
return Vec::new();
};
let Some(confirmed) = frame
.active_tab()
.filter(|remote| self.tabs.get(&remote.id) == Some(&tab.id) && !remote.is_connecting())
else {
return Vec::new();
};
// The actor tracks requested focus so consecutive shortcuts can navigate
// before an SSH round trip. Publish focus and grids from the same frame.
tab.active_pane = self.panes[&confirmed.active_pane];
for (stack, confirmed) in tab.stacks.iter_mut().zip(&confirmed.stacks) {
stack.active_pane = self.panes[&confirmed.active_pane];
}
frame
.panes
.iter()
.map(|pane| {
let mut copy = pane.clone();
copy.id = self.panes[&pane.id];
copy
})
.collect()
}
/// 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.target.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<()> {
ensure!(
self.panes.contains_key(&pane),
"originating shell has ended"
);
let (index, _, _) = self.pane_position(pane)?;
self.open_remote_at(
self.tabs[index].id,
RemoteWindow { destination, ssh },
target,
)
}
pub(super) fn open_remote_at(
&mut self,
anchor: TabId,
window_target: RemoteWindow,
target: SessionTarget,
) -> Result<()> {
crate::client::validate_destination(&window_target.destination)?;
let index = self
.tabs
.iter()
.position(|tab| tab.id == anchor)
.context("originating tab has closed")?;
ensure!(
self.remotes.len() < MAX_PANES && self.tabs.len() < 256,
"too many SSH sessions or tabs"
);
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 = window_target.destination.clone();
let ssh = window_target.ssh.clone();
let cancelled = Arc::new(AtomicBool::new(false));
let worker_cancelled = cancelled.clone();
let attaching = match target {
SessionTarget::Remembered(id) => Some(id),
_ => None,
};
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, window_target, cancelled, attaching);
Ok(())
}
fn insert_remote_slot(
&mut self,
index: usize,
group: u64,
target: RemoteWindow,
cancelled: Arc<AtomicBool>,
attaching: Option<SessionIdentity>,
) {
let anchor = self.tabs[index].id;
// Keep the tabs mirrored by each SSH connection contiguous across layout updates.
let index = self
.remotes
.values()
.find(|mount| mount.owns_tab(anchor))
.and_then(|mount| self.tabs.iter().rposition(|tab| mount.owns_tab(tab.id)))
.unwrap_or(index);
self.tabs.insert(
index + 1,
TabInfo {
id: group,
title: "Connecting…".into(),
remote: Some(target.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 {
target,
anchor,
slot: group,
cancelled,
connection: None,
tabs: HashMap::new(),
panes: HashMap::new(),
latest: None,
attaching,
requested_tab: None,
clipboard: VecDeque::new(),
},
);
}
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
.iter()
.find(|(_, remote)| remote.owns_tab(tab))
.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(nested) = remote.nested_tab(tab) {
remote.send(ClientMessage::DetachRemote { tab: nested.id })?;
return Ok(None);
}
let target = remote.connection.as_ref().and_then(|client| {
let identity = client
.remote_identity()
.or_else(|| remote.latest.as_ref()?.lineage.first().copied())?;
Some(DetachedRemote {
destination: remote.target.destination.clone(),
identity,
executable: remote.target.ssh.executable.clone(),
})
});
self.remove_remote(group);
Ok(target)
}
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)
}),
// These commands stay within a tab. Let the owner resolve the
// current pane after all preceding focus requests on its stream.
FocusDirection {
direction: Direction::Up | Direction::Down,
}
| CyclePane { .. }
| NewStackPane { pane: None, .. } => self
.remotes
.values_mut()
.find(|remote| original(&remote.tabs, self.active_tab).is_some()),
NewStackPane {
pane: Some(pane), ..
}
| Input { pane, .. }
| Resize { pane, .. }
| Selection { pane, .. }
| Copy { pane }
| Scroll { pane, .. }
| Split { pane, .. }
| Close { id: 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.target.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.target.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,
RemoteWindow {
destination: "user@work".into(),
ssh: SshOptions::default(),
},
Arc::new(AtomicBool::new(false)),
None,
);
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 mounted_directory_entry_keeps_one_identity_and_focus_tab_for_the_whole_session() {
let mut local = session(1);
local.new_tab(None).unwrap();
let group = reserve(&mut local, 0);
let mut upstream = session(2);
upstream.new_tab(None).unwrap();
upstream.new_tab(None).unwrap();
assert!(
local.remotes[&group]
.listed_session(local.identity, 1)
.is_none()
);
let frame = upstream.snapshot();
let expected = SessionSummary::from_tabs(&frame.tabs, frame.active_tab);
apply(&mut local, group, frame).unwrap();
let mount = &local.remotes[&group];
let listed = mount.listed_session(local.identity, 1).unwrap();
let tab = local.active_tab;
assert_eq!(
listed.route,
SessionRoute::Mounted {
owner: local.identity,
tab,
identity: upstream.identity
}
);
assert_eq!(listed.host.as_deref(), Some("user@work"));
assert_eq!(listed.summary, expected);
assert_eq!((listed.summary.tabs, listed.summary.panes), (2, 2));
assert_eq!(mount.selection_tab(upstream.identity, tab), Some(tab));
assert_eq!(mount.selection_tab(upstream.identity, u64::MAX), Some(tab));
assert!(mount.selection_tab(local.identity, tab).is_none());
}
#[test]
fn sibling_session_attaches_after_all_mirrored_tabs_and_restores_focus_on_failure() {
let mut local = session(1);
local.new_tab(None).unwrap();
let first = reserve(&mut local, 0);
let mut upstream = session(2);
upstream.new_tab(None).unwrap();
upstream.new_tab(None).unwrap();
apply(&mut local, first, upstream.snapshot()).unwrap();
let anchor = local.tabs[1].id;
local.active_tab = anchor;
let sibling = reserve(&mut local, 1);
let target = SessionIdentity {
session: 7,
..upstream.identity
};
local.remotes.get_mut(&sibling).unwrap().attaching = Some(target);
assert_eq!(
local.remotes[&sibling].selection_tab(target, anchor),
Some(sibling)
);
assert_eq!(local.active_tab, sibling);
assert_eq!(local.tabs[3].id, sibling);
upstream.new_tab(None).unwrap();
apply(&mut local, first, upstream.snapshot()).unwrap();
assert_eq!(local.tabs[4].id, sibling);
assert!(
local.tabs[1..4]
.iter()
.all(|tab| local.remotes[&first].owns_tab(tab.id))
);
local.remove_remote(sibling);
assert_eq!(local.active_tab, anchor);
}
#[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 || {
while let Some(update) = updates.recv_blocking() {
if frames.send(update).is_err() {
break;
}
}
});
receive
}
fn next_frame(
receive: &mpsc::Receiver<Update>,
accept: impl Fn(&Snapshot) -> bool,
) -> Arc<Snapshot> {
loop {
let update = receive.recv_timeout(Duration::from_secs(5)).unwrap();
assert!(update.error.is_none(), "{:?}", update.error);
if let Some(frame) = update.snapshot
&& accept(&frame)
{
return frame;
}
}
}
#[test]
fn detaching_a_mirror_keeps_its_tabs_and_live_shell_for_reattach() {
use super::super::tests::contains;
let upstream = super::super::tests::TestServer::start();
let (client, updates) = Transport::connect(
&upstream.socket,
None,
SessionTarget::New { cwd: None },
SshOptions::default(),
)
.unwrap();
let receive = receive_updates(updates);
client.send(ClientMessage::NewTab { cwd: None }).unwrap();
let before = next_frame(&receive, |frame| frame.tabs.len() == 2);
let pane = before.active_tab().unwrap().active_pane;
client
.send(ClientMessage::Input {
pane,
bytes: b"psyterm_check=alive; printf 'SET_%s\\n' DONE\n".to_vec(),
})
.unwrap();
next_frame(&receive, |frame| contains(frame, "SET_DONE"));
let mut local = session(1);
local.new_tab(None).unwrap();
let origin = local.active_tab;
let group = reserve(&mut local, 0);
local.remotes.get_mut(&group).unwrap().connection = Some(client);
apply(&mut local, group, (*before).clone()).unwrap();
assert!(local.detach_remote(origin).is_err());
local.focus_tab(origin).unwrap();
let clicked = local.tabs[1].id;
assert_ne!(clicked, group);
let target = local.detach_remote(clicked).unwrap().unwrap();
assert_eq!(target.destination, "user@work");
assert_eq!(target.identity, before.lineage[0]);
assert_eq!(local.tabs.len(), 1);
assert_eq!(local.active_tab, origin);
let (resumed, updates) = Transport::connect(
&upstream.socket,
None,
SessionTarget::Remembered(target.identity),
SshOptions::default(),
)
.unwrap();
let receive = receive_updates(updates);
let restored = next_frame(&receive, |_| true);
assert_eq!(restored.tabs.len(), 2);
assert_eq!(restored.active_tab, before.active_tab);
resumed
.send(ClientMessage::Input {
pane,
bytes: b"printf 'REATTACHED_%s\\n' \"$psyterm_check\"\n".to_vec(),
})
.unwrap();
next_frame(&receive, |frame| contains(frame, "REATTACHED_alive"));
// A replacement daemon can allocate the same session and pane
// numbers. Refuse its input channel even if the numeric attach succeeds.
let replacement = super::super::tests::TestServer::start();
let (_other, updates) = Transport::connect(
&replacement.socket,
None,
SessionTarget::New { cwd: None },
SshOptions::default(),
)
.unwrap();
let other = next_frame(&receive_updates(updates), |_| true).lineage[0];
assert_eq!(other.session, target.identity.session);
assert_ne!(other.server, target.identity.server);
let error = Transport::connect(
&replacement.socket,
None,
SessionTarget::Remembered(target.identity),
SshOptions::default(),
)
.err()
.expect("refuse a recycled session ID");
assert!(
error.to_string().contains("remembered session has ended"),
"{error:#}"
);
}
#[test]
fn stacked_remote_focus_publishes_matching_grids_while_requests_are_in_flight() {
let upstream = super::super::tests::TestServer::start();
let (client, updates) = Transport::connect(
&upstream.socket,
None,
SessionTarget::New { cwd: None },
SshOptions::default(),
)
.unwrap();
let receive = receive_updates(updates);
for _ in 0..3 {
client
.send(ClientMessage::NewStackPane {
pane: None,
direction: VerticalDirection::Down,
cwd: None,
})
.unwrap();
}
let initial = next_frame(&receive, |frame| {
frame.active_tab().unwrap().panes.len() == 4
});
let upstream_top = initial.active_tab().unwrap().panes[0];
let upstream_third = initial.active_tab().unwrap().panes[2];
let mut local = session(1);
local.new_tab(None).unwrap();
let origin = local.active_tab;
let group = reserve(&mut local, 0);
local.remotes.get_mut(&group).unwrap().connection = Some(client);
apply(&mut local, group, (*initial).clone()).unwrap();
let top = local.tabs[1].panes[0];
let second = local.tabs[1].panes[1];
assert_eq!(local.tabs[1].active_pane, local.tabs[1].panes[3]);
let output = Arc::new(Outbox::default());
let check_frame = |local: &mut SessionState| {
let frame = local.snapshot();
crate::client::validate_snapshot(&frame).unwrap();
let tab = frame.active_tab().unwrap();
assert_eq!(frame.panes[0].id, tab.stacks[0].active_pane);
assert_eq!(frame.panes[0].id, tab.active_pane);
};
let up = || ClientMessage::FocusDirection {
direction: Direction::Up,
};
local.command(up(), &output).unwrap();
check_frame(&mut local);
// Hold the reply to Option+Up while a click selects a different
// collapsed pane. Both intermediate snapshots must remain renderable.
let third = next_frame(&receive, |frame| {
frame.active_tab().unwrap().active_pane == upstream_third
});
local
.command(ClientMessage::FocusPane { pane: second }, &output)
.unwrap();
check_frame(&mut local);
apply(&mut local, group, (*third).clone()).unwrap();
// The next Option+Up must move from the clicked pane, even though
// the most recent upstream frame still shows the third pane.
local.command(up(), &output).unwrap();
check_frame(&mut local);
local.focus_tab(origin).unwrap();
let ack = next_frame(&receive, |frame| {
frame.active_tab().unwrap().active_pane == upstream_top
});
apply(&mut local, group, (*ack).clone()).unwrap();
assert_eq!(local.snapshot().active_tab, origin);
local.focus_tab(group).unwrap();
let frame = local.snapshot();
crate::client::validate_snapshot(&frame).unwrap();
assert_eq!(frame.active_tab().unwrap().active_pane, top);
assert_eq!(frame.panes[0].id, top);
}
#[test]
fn discarded_ssh_frame_keeps_the_mounted_workspace_and_accepts_the_next_frame() {
let mut upstream = session(2);
upstream.new_tab(None).unwrap();
let mut local = session(1);
local.new_tab(None).unwrap();
let origin = local.active_tab;
let group = reserve(&mut local, 0);
apply(&mut local, group, upstream.snapshot()).unwrap();
let id = local.id;
let mut server = Server {
identity: local.identity.server,
socket: local.socket.clone(),
shell: None,
sender: local.sender.clone(),
sessions: BTreeMap::from([(id, local)]),
clients: HashMap::new(),
next_session: id + 1,
last_detached_remote: None,
last_frame: Instant::now(),
last_cwd_refresh: Instant::now(),
};
server.remote_event(
id,
group,
RemoteEvent::Updated(Update {
error: Some("Discarded workspace update: invalid terminal grid".into()),
..Update::default()
}),
);
assert_eq!(server.sessions[&id].active_tab, group);
upstream.new_tab(None).unwrap();
server.remote_event(
id,
group,
RemoteEvent::Updated(Update {
snapshot: Some(Arc::new(upstream.snapshot())),
..Update::default()
}),
);
assert_eq!(server.sessions[&id].remotes[&group].tabs.len(), 2);
server.remote_event(
id,
group,
RemoteEvent::Updated(Update {
disconnected: true,
..Update::default()
}),
);
assert_eq!(server.sessions[&id].active_tab, origin);
assert!(!server.sessions[&id].remotes.contains_key(&group));
}
#[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());
let output = Arc::new(Outbox::default());
assert!(
local
.command(ClientMessage::Close { id: group }, &output)
.is_err()
);
assert!(local.remotes.contains_key(&group));
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;
assert!(
local
.command(ClientMessage::Close { id: first_remote }, &output)
.is_err()
);
assert!(local.remotes.contains_key(&group));
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 },
SshOptions::default(),
)
.unwrap();
let receive = receive_updates(updates);
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")
);
assert_eq!(local.detach_remote(group).unwrap(), None);
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);
}
}