From 804ab007ee62eebab850681047e1c2c27610b1fa Mon Sep 17 00:00:00 2001 From: James Magahern Date: Tue, 17 Nov 2026 19:36:19 -0800 Subject: [PATCH] Add a command palette picker for local and SSH sessions Discover attached and detached sessions over existing SSH connections. Focus an open view or attach to the selected session using its daemon identity, preserving the original shells. --- README.md | 18 +- src/bindings.rs | 4 +- src/client.rs | 288 +++++++++++++++-- src/commands.rs | 144 ++++++++- src/launcher.rs | 391 ++++++++++++++++++++++- src/palette.rs | 141 +++++++-- src/protocol.rs | 89 +++++- src/server.rs | 545 +++++++++++++++++++++++++++++++++ src/server/remote.rs | 162 +++++++++- src/terminal.rs | 25 +- src/terminal/session_picker.rs | 147 +++++++++ 11 files changed, 1869 insertions(+), 85 deletions(-) create mode 100644 src/terminal/session_picker.rs diff --git a/README.md b/README.md index f949849..bf74dd7 100644 --- a/README.md +++ b/README.md @@ -109,8 +109,22 @@ on the same host. A remote window reuses the focused SSH connection’s executab 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, -`--attach` prefers the most recently used detached session and otherwise + +Choose **Switch to session…** in the command palette to see your local sessions +and the sessions on each directly connected SSH host, including detached +sessions. For example, with one tab connected to `vigilant`, search for +`vigilant` to see every live session on that host’s psyTerm daemon. Select one +and press Enter. From a local workspace, another session on that host opens +in an adjacent SSH tab. From a standalone SSH window, it opens in a window. +An already open session can be focused directly. + +The picker uses the existing SSH connection for discovery and refreshes while +open. Tabs reached through a nested SSH connection are grouped under the session +that hosts them. Remote discovery needs the updated local daemon and works with +existing v6 SSH hosts. + +From the CLI, run `psyterm --list` and pass the session ID to +`psyterm --attach ID`. With no ID, `--attach` prefers the most recently used detached session and otherwise selects the most recently used attached session. Shells inherit the server's environment and receive diff --git a/src/bindings.rs b/src/bindings.rs index f285968..945379c 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -204,10 +204,10 @@ mod tests { #[test] fn palette_lists_the_shortcut_that_dispatches_each_workspace_command() { - use crate::commands::{PaletteItemKind, root_items}; + use crate::commands::{PaletteItemKind, SessionDirectory, root_items}; use std::mem::discriminant; - for item in root_items(None, false) { + for item in root_items(None, false, &SessionDirectory::Loading) { let (Some(hint), PaletteItemKind::Action(expected)) = (item.shortcut, &item.kind) else { continue; diff --git a/src/client.rs b/src/client.rs index 0f2e646..d0d3174 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,7 +1,7 @@ //! Display-only client transport. No terminal parser, PTY, or shell lives here. use crate::protocol::{ - self, ClientMessage, RemoteWindow, ServerMessage, SessionIdentity, SessionTarget, Snapshot, - SshOptions, TabId, + self, ClientMessage, RemoteSessionInfo, RemoteWindow, ServerMessage, SessionIdentity, + SessionInfo, SessionRoute, SessionSummary, SessionTarget, Snapshot, SshOptions, TabId, }; use anyhow::{Context, Result, bail, ensure}; use std::{ @@ -52,7 +52,112 @@ pub struct Client { struct RemoteSession { identity: SessionIdentity, live: AtomicBool, + directory: Mutex, } + +#[derive(Default)] +struct RemoteDirectory { + sessions: Vec, + requested_at: Option, + pending: bool, +} + +impl RemoteDirectory { + fn refresh(&mut self, commands: &mpsc::Sender) { + // A slow host should have at most one request in flight. Allow retries + // if the peer never answered, and coalesce simultaneous picker queries. + let interval = Duration::from_secs(if self.pending { 30 } else { 1 }); + if self + .requested_at + .is_none_or(|last| last.elapsed() >= interval) + && commands.send(ClientMessage::ListSessions).is_ok() + { + self.requested_at = Some(Instant::now()); + self.pending = true; + } + } + + fn received(&mut self, sessions: Vec) { + self.pending = false; + self.sessions = sessions + .into_iter() + .filter_map(|session| { + // v6's directory describes every tab, but omits the active tab. + let first = session.tabs.first()?; + Some(RemoteSessionInfo { + id: session.id, + summary: SessionSummary::from_tabs(&session.tabs, first.id), + attached: session.attached, + }) + }) + .collect(); + } +} + +pub(crate) struct RemoteWindowListing { + pub summary: SessionSummary, + pub sessions: Option>, +} + +/// A direct SSH window has no session on the local daemon. Publish its +/// layout summary separately so local directory I/O never blocks the grid. +struct RemoteListing { + latest: Arc>, + notify: UnixStream, +} + +impl RemoteListing { + fn start( + socket: PathBuf, + target: RemoteWindow, + frame: &Snapshot, + commands: mpsc::Sender, + ) -> Result { + let identity = frame.lineage[0]; // Verified in greet(). + let latest = Arc::new(Mutex::new(RemoteWindowListing { + summary: SessionSummary::from_tabs(&frame.tabs, frame.active_tab), + sessions: None, + })); + let published = latest.clone(); + let (notify, changes) = UnixStream::pair()?; + notify.set_nonblocking(true)?; + thread::Builder::new() + .name("psyterm-remote-listing".into()) + .spawn(move || { + if let Err(error) = crate::launcher::publish_remote_window( + &socket, + target, + identity, + changes, + published, + || { + let _ = commands.send(ClientMessage::ListSessions); + }, + ) { + log::warn!("Could not list SSH window on local server: {error:#}"); + } + })?; + Ok(Self { latest, notify }) + } + + fn update(&mut self, frame: &Snapshot) { + let summary = SessionSummary::from_tabs(&frame.tabs, frame.active_tab); + let mut latest = self.latest.lock().unwrap(); + if summary != latest.summary { + latest.summary = summary; + // If the nonblocking socket is full, the worker is already due to + // wake and will publish the latest summary. + let _ = self.notify.write(&[1]); + } + } + + fn update_sessions(&mut self, sessions: &[RemoteSessionInfo]) { + self.latest.lock().unwrap().sessions = Some(sessions.to_vec()); + // Publish every answer, including an unchanged or empty host directory. + let _ = self.notify.write(&[1]); + } +} + struct Connection { launcher_socket: PathBuf, remote: Option, @@ -223,12 +328,32 @@ impl Client { return Err(error); } }; - let remote_session = first_frame.as_ref().map(|frame| { - Arc::new(RemoteSession { - identity: frame.lineage[0], - live: AtomicBool::new(!frame.tabs.is_empty()), - }) - }); + let remote_session = first_frame + .as_ref() + .filter(|_| remote.is_some()) + .map(|frame| { + Arc::new(RemoteSession { + identity: frame.lineage[0], + live: AtomicBool::new(!frame.tabs.is_empty()), + directory: Mutex::default(), + }) + }); + // Mounted SSH connections are already listed by their owning daemon. + let listing = if cancelled.is_none() + && let (Some(target), Some(frame)) = (&connection.remote, &first_frame) + && !frame.tabs.is_empty() + { + RemoteListing::start( + launcher_socket.to_owned(), + target.clone(), + frame, + connection.commands.clone(), + ) + .inspect_err(|error| log::warn!("Could not start SSH window listing: {error:#}")) + .ok() + } else { + None + }; if let Some(frame) = first_frame { pending.lock().unwrap().snapshot = Some(Arc::new(frame)); let _ = signal.try_send(()); @@ -252,7 +377,15 @@ impl Client { let reader_session = remote_session.clone(); thread::Builder::new() .name("psyterm-client-reader".into()) - .spawn(move || read_updates(reader, &incoming, signal, reader_session.as_deref()))?; + .spawn(move || { + read_updates( + reader, + &incoming, + signal, + reader_session.as_deref(), + listing, + ) + })?; Ok(( Self { connection, @@ -276,6 +409,17 @@ impl Client { self.remote_session.as_ref().map(|session| session.identity) } + /// Queue a host-wide lookup on the live SSH bridge and return its latest + /// answer immediately, so listing sessions never stalls the daemon actor. + pub fn remote_directory(&self) -> Vec { + let Some(remote) = &self.remote_session else { + return Vec::new(); + }; + let mut directory = remote.directory.lock().unwrap(); + directory.refresh(&self.connection.commands); + directory.sessions.clone() + } + /// Remember a direct SSH window on its local launcher before detaching it. pub fn remember_remote_detach(&self) -> Result<()> { let remote = self @@ -301,6 +445,30 @@ impl Client { Ok(()) } + pub fn session_directory(&self) -> Result { + crate::launcher::session_directory(&self.connection.launcher_socket) + } + + pub fn open_listed_session( + &self, + route: SessionRoute, + workspace: Option, + ) -> Result<()> { + let request = match route { + SessionRoute::Remote(identity) => ClientMessage::OpenPeerSession { + identity, + workspace, + }, + _ => ClientMessage::OpenListedSession(route), + }; + let response = crate::launcher::control(&self.connection.launcher_socket, request)?; + ensure!( + matches!(response, ServerMessage::Pong), + "local daemon did not open the session" + ); + Ok(()) + } + /// Launch through the local daemon even when this terminal connects over SSH. pub fn open_window( &self, @@ -364,9 +532,20 @@ fn read_updates( pending: &Mutex, signal: async_channel::Sender<()>, remote_session: Option<&RemoteSession>, + mut listing: Option, ) { loop { let message = protocol::read_message::(&mut reader); + if let Ok(ServerMessage::Sessions(sessions)) = message { + if let Some(remote) = remote_session { + let mut directory = remote.directory.lock().unwrap(); + directory.received(sessions); + if let Some(listing) = &mut listing { + listing.update_sessions(&directory.sessions); + } + } + continue; + } let mut update = pending.lock().unwrap(); match message { Ok(ServerMessage::Snapshot(snapshot)) => { @@ -377,6 +556,11 @@ fn read_updates( .live .store(!snapshot.tabs.is_empty(), Ordering::Release); } + if snapshot.tabs.is_empty() { + listing = None; + } else if let Some(listing) = &mut listing { + listing.update(&snapshot); + } update.snapshot = Some(Arc::new(snapshot)); } Err(error) => { @@ -526,22 +710,13 @@ fn greet( let frame = match protocol::read_message::(reader)? { ServerMessage::Snapshot(frame) => frame, ServerMessage::Error(error) => bail!("{error}"), - _ => bail!("expected initial SSH session snapshot"), + _ => bail!("expected initial session snapshot"), }; validate_snapshot(&frame)?; - let identity = frame - .lineage - .first() - .context("missing SSH session identity")?; - ensure!( - identity.session == session, - "incorrect SSH session identity" - ); + let identity = frame.lineage.first().context("missing session identity")?; + ensure!(identity.session == session, "incorrect session identity"); if let Some(expected) = expected { - ensure!( - *identity == expected, - "the remembered remote session has ended" - ); + ensure!(*identity == expected, "the remembered session has ended"); } Ok(Some(frame)) } @@ -644,6 +819,70 @@ fn copy_and_flush(reader: &mut impl Read, writer: &mut impl Write) -> std::io::R mod tests { use super::*; + #[test] + fn ssh_directory_reads_v6_session_lists_alongside_terminal_messages() { + let remote = RemoteSession { + identity: SessionIdentity { + server: [9; 16], + session: 1, + }, + live: AtomicBool::new(true), + directory: Mutex::default(), + }; + let (commands, sent) = mpsc::channel(); + { + let mut directory = remote.directory.lock().unwrap(); + directory.refresh(&commands); + directory.refresh(&commands); + } + assert!(matches!(sent.try_recv(), Ok(ClientMessage::ListSessions))); + assert!(sent.try_recv().is_err()); + + let tab = |id, title: &str| protocol::TabInfo { + id, + title: title.into(), + manual_title: None, + remote: None, + panes: vec![id], + active_pane: id, + stacks: Vec::new(), + }; + let (peer, reader) = UnixStream::pair().unwrap(); + reader + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let (signal, changes) = async_channel::bounded(1); + let pending = Mutex::new(Update::default()); + thread::scope(|scope| { + let mut peer = peer; + scope.spawn(|| read_updates(reader, &pending, signal, Some(&remote), None)); + let directory = vec![ + SessionInfo { + id: 1, + attached: 1, + tabs: vec![tab(21, "Current")], + }, + SessionInfo { + id: 2, + attached: 0, + tabs: vec![tab(31, "Build"), tab(32, "Logs")], + }, + ]; + protocol::write_message(&mut peer, &ServerMessage::Sessions(directory)).unwrap(); + protocol::write_message(&mut peer, &ServerMessage::Clipboard("copied".into())).unwrap(); + changes.recv_blocking().unwrap(); + let mut update = pending.lock().unwrap(); + assert!(update.error.is_none()); + assert_eq!(update.clipboard.pop_front().as_deref(), Some("copied")); + let list = &remote.directory.lock().unwrap().sessions; + assert_eq!(list.len(), 2); + assert_eq!((list[1].id, list[1].attached), (2, 0)); + assert_eq!(list[1].summary.title, "Build"); + assert_eq!((list[1].summary.tabs, list[1].summary.panes), (2, 2)); + peer.shutdown(Shutdown::Write).unwrap(); + }); + } + #[test] fn new_window_routes_local_direct_mounted_and_nested_tabs() { let direct = RemoteWindow { @@ -689,6 +928,7 @@ mod tests { session: 1, }, live: AtomicBool::new(true), + directory: Mutex::default(), }; for session in [None, Some(&remote)] { let (client, mut server) = UnixStream::pair().unwrap(); @@ -698,7 +938,7 @@ mod tests { let pending = Mutex::new(Update::default()); let (signal, received) = async_channel::bounded(1); thread::scope(|threads| { - threads.spawn(|| read_updates(client, &pending, signal, session)); + threads.spawn(|| read_updates(client, &pending, signal, session, None)); let mut send_snapshot = |snapshot| { protocol::write_message(&mut server, &ServerMessage::Snapshot(snapshot)) .unwrap(); @@ -765,6 +1005,7 @@ mod tests { session: 1, }, live: AtomicBool::new(true), + directory: Mutex::default(), }; let mut bytes = Vec::new(); protocol::write_message(&mut bytes, &last_message).unwrap(); @@ -774,6 +1015,7 @@ mod tests { &Mutex::new(Update::default()), signal, Some(&remote), + None, ); assert_eq!(remote.live.load(Ordering::Acquire), resumable); } diff --git a/src/commands.rs b/src/commands.rs index a7a3f8b..eaa720c 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -2,7 +2,7 @@ //! //! Add an action and a registry entry here to expose a command. A shortcut is //! optional; menus use the same item model and may be nested to any depth. -use crate::protocol::{ScrollKind, Snapshot}; +use crate::protocol::{ListedSession, ScrollKind, SessionRoute, Snapshot}; #[derive(Clone, Debug)] pub enum CommandAction { @@ -29,6 +29,7 @@ pub enum CommandAction { NextPane, FocusLeft, FocusRight, + SwitchSession(SessionRoute), FocusTab(u64), FocusPane(u64), Scroll(ScrollKind), @@ -40,6 +41,7 @@ pub enum CommandAction { pub enum PaletteItemKind { Action(CommandAction), Menu(Vec), + Info, } #[derive(Clone, Debug)] @@ -48,6 +50,7 @@ pub struct PaletteItem { pub id: String, pub title: String, pub keywords: String, + pub detail: Option, pub shortcut: Option<&'static str>, pub enabled: bool, pub kind: PaletteItemKind, @@ -65,6 +68,7 @@ impl PaletteItem { id: id.into(), title: title.into(), keywords: keywords.into(), + detail: None, shortcut, enabled: true, kind: PaletteItemKind::Action(action), @@ -81,12 +85,25 @@ impl PaletteItem { id: id.into(), title: title.into(), keywords: keywords.into(), + detail: None, shortcut: None, enabled: !items.is_empty(), kind: PaletteItemKind::Menu(items), } } + fn info(title: impl Into) -> Self { + Self { + id: "session-status".into(), + title: title.into(), + detail: None, + keywords: String::new(), + shortcut: None, + enabled: false, + kind: PaletteItemKind::Info, + } + } + fn available(mut self, enabled: bool) -> Self { self.enabled = enabled; self @@ -101,8 +118,128 @@ fn shortcut(mac: &'static str, linux: &'static str) -> Option<&'static str> { }) } +#[derive(Default, PartialEq, Eq)] +pub enum SessionDirectory { + #[default] + Loading, + Ready(crate::launcher::SessionDirectoryPage), + Unavailable(String), +} + +fn count_label(count: usize, name: &str) -> String { + format!("{count} {name}{}", if count == 1 { "" } else { "s" }) +} + +impl SessionDirectory { + fn menu(&self, snapshot: Option<&Snapshot>, remote_window: bool) -> PaletteItem { + let items = match self { + Self::Loading => vec![PaletteItem::info("Loading sessions…")], + Self::Unavailable(error) => vec![PaletteItem::info(error)], + Self::Ready(page) => { + let mut rows: Vec<_> = page + .sessions + .iter() + .map(|session| session_item(session, snapshot, remote_window)) + .collect(); + if !page.loading_hosts.is_empty() { + rows.push(PaletteItem::info(format!( + "Loading sessions from {}…", + page.loading_hosts.join(", ") + ))); + } else if page.legacy && page.sessions.iter().any(|entry| entry.host.is_some()) { + rows.push(PaletteItem::info( + "To see other sessions on SSH hosts, finish your local sessions and restart the local daemon with the updated psyTerm." + )); + } + if rows.is_empty() { + rows.push(PaletteItem::info("No live sessions")); + } + rows + } + }; + PaletteItem::menu( + "switch-session", + "Switch to session…", + "list sessions local remote ssh attach workspaces", + items, + ) + } +} + +fn session_item( + session: &ListedSession, + snapshot: Option<&Snapshot>, + remote_window: bool, +) -> PaletteItem { + let identity = session.route.identity(); + let source = match &session.host { + Some(host) => format!("SSH {host}"), + None => "Local".to_owned(), + }; + let mut detail = vec![ + format!("{source} #{}", identity.session), + count_label(session.summary.tabs, "tab"), + count_label(session.summary.panes, "pane"), + ]; + if session.host.is_none() { + detail.push(if session.attached == 0 { + "Detached".into() + } else { + count_label(session.attached, "window") + }); + } + if matches!(session.route, SessionRoute::Remote(_)) { + detail.push(if session.attached == 0 { + "Detached".into() + } else { + "Attached".into() + }); + } + if let Some(frame) = snapshot { + let root = frame.lineage.first(); + if root == Some(&identity) && remote_window == session.host.is_some() { + detail.push("This window".into()); + } else if matches!(session.route, SessionRoute::Mounted { owner, tab, .. } + if !remote_window && root == Some(&owner) && frame.active_tab == tab) + { + detail.push("Current tab".into()); + } + } + let detail = detail.join(" · "); + let mut item = PaletteItem::action( + format!( + "{}-{:032x}-{}", + if session.host.is_some() { + "ssh" + } else { + "local" + }, + u128::from_be_bytes(identity.server), + identity.session + ), + if session.summary.title.is_empty() { + format!("{source} session #{}", identity.session) + } else { + session.summary.title.clone() + }, + if session.host.is_some() { + "remote ssh attach" + } else { + "local attach" + }, + None, + CommandAction::SwitchSession(session.route), + ); + item.detail = Some(detail); + item +} + /// The complete command list. UI state affects availability, never discovery. -pub fn root_items(snapshot: Option<&Snapshot>, remote_window: bool) -> Vec { +pub fn root_items( + snapshot: Option<&Snapshot>, + remote_window: bool, + directory: &SessionDirectory, +) -> Vec { use CommandAction::*; let pane = snapshot.is_some_and(|s| !s.panes.is_empty()); let tabs = snapshot.is_some_and(|s| !s.tabs.is_empty()); @@ -387,6 +524,7 @@ pub fn root_items(snapshot: Option<&Snapshot>, remote_window: bool) -> Vec Result { result } +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct SessionDirectoryPage { + pub sessions: Vec, + pub loading_hosts: Vec, + pub legacy: bool, +} + +fn closed_control_stream(error: &anyhow::Error) -> bool { + error.downcast_ref::().is_some_and(|io| { + matches!( + io.kind(), + io::ErrorKind::UnexpectedEof + | io::ErrorKind::ConnectionReset + | io::ErrorKind::BrokenPipe + ) + }) +} + +pub(crate) fn session_directory(socket: &Path) -> Result { + match control(socket, ClientMessage::ListHostSessionDirectory) { + Ok(ServerMessage::HostSessionDirectory { + sessions, + loading_hosts, + }) => { + return Ok(SessionDirectoryPage { + sessions, + loading_hosts, + legacy: false, + }); + } + Ok(_) => bail!("unexpected session directory response"), + Err(error) if !closed_control_stream(&error) => return Err(error), + Err(_) => {} + } + // Older v6 daemons close the stream when they see an unknown request. + match control(socket, ClientMessage::ListSessionDirectory) { + Ok(ServerMessage::SessionDirectory(sessions)) => Ok(SessionDirectoryPage { + sessions, + loading_hosts: Vec::new(), + legacy: true, + }), + Ok(_) => bail!("unexpected session directory response"), + Err(error) + if closed_control_stream(&error) + && matches!( + control(socket, ClientMessage::ListSessions), + Ok(ServerMessage::Sessions(_)) + ) => + { + bail!( + "The local daemon predates the session picker. Restart it with the current psyTerm after finishing its sessions." + ) + } + Err(error) => Err(error), + } +} + pub fn require_server(socket: &Path) -> Result<()> { if !probe_server(socket)? { bail!("no sessions to attach to at {}", socket.display()); @@ -178,16 +235,25 @@ fn control_stream_version( timeout: Duration, expected_version: u32, ) -> Result { - verify_peer(&stream)?; + control_handshake(&mut stream, timeout, expected_version)?; + control_request(&mut stream, command) +} + +fn control_handshake( + stream: &mut UnixStream, + timeout: Duration, + expected_version: u32, +) -> Result<()> { + verify_peer(stream)?; stream.set_read_timeout(Some(timeout))?; stream.set_write_timeout(Some(timeout))?; protocol::write_message( - &mut stream, + stream, &ClientMessage::Hello { version: expected_version, }, )?; - match protocol::read_message::(&mut stream)? { + match protocol::read_message::(stream)? { ServerMessage::Hello { version, .. } if version == expected_version => {} ServerMessage::Hello { version, .. } => bail!( "server protocol {version} does not match client protocol {}", @@ -198,13 +264,19 @@ fn control_stream_version( ), _ => bail!("server did not send a protocol greeting"), } - protocol::write_message(&mut stream, &command)?; + Ok(()) +} + +fn control_request(stream: &mut UnixStream, command: ClientMessage) -> Result { + protocol::write_message(stream, &command)?; loop { - let message: ServerMessage = protocol::read_message(&mut stream)?; + let message: ServerMessage = protocol::read_message(stream)?; match message { ServerMessage::Pong | ServerMessage::Closing | ServerMessage::Sessions(_) + | ServerMessage::SessionDirectory(_) + | ServerMessage::HostSessionDirectory { .. } | ServerMessage::DetachedRemote(_) => return Ok(message), ServerMessage::Error(error) => bail!("{error}"), _ => {} @@ -212,6 +284,162 @@ fn control_stream_version( } } +/// The control connection is the lease. Closing it removes this direct SSH +/// window from the local directory, even if the GUI exits unexpectedly. +pub(crate) fn publish_remote_window( + socket: &Path, + target: protocol::RemoteWindow, + identity: protocol::SessionIdentity, + mut changes: UnixStream, + listing: std::sync::Arc>, + request_sessions: impl Fn(), +) -> Result<()> { + let registration = |summary| ClientMessage::RegisterRemoteWindow { + target: target.clone(), + identity, + summary, + }; + let mut legacy = false; + let mut serve = |changes: &mut UnixStream| -> Result { + let mut lease = UnixStream::connect(socket)?; + control_handshake(&mut lease, REQUEST_TIMEOUT, protocol::VERSION)?; + let mut published = { + let mut listing = listing.lock().unwrap(); + listing.sessions.take(); + listing.summary.clone() + }; + if !matches!( + control_request(&mut lease, registration(published.clone()))?, + ServerMessage::Pong + ) { + bail!("local daemon did not register the SSH window"); + } + if !legacy { + // Advertise support for requests on this lease. A pre-discovery + // daemon closes it here, so reconnect once using its original protocol. + match control_request(&mut lease, ClientMessage::RemoteWindowSessions(Vec::new())) { + Ok(ServerMessage::Pong) => {} + Err(error) if closed_control_stream(&error) => { + legacy = true; + return Ok(true); + } + Err(error) => return Err(error), + Ok(_) => bail!("unexpected SSH directory registration response"), + } + } + let supports_directory = !legacy; + legacy = false; + loop { + match listing_event(changes, Some(&lease), None)? { + ListingEvent::Closed => return Ok(false), + ListingEvent::Daemon => { + match protocol::read_message::(&mut lease)? { + ServerMessage::RequestRemoteSessions if supports_directory => { + request_sessions() + } + ServerMessage::Closing => return Ok(true), + ServerMessage::Pong => {} + ServerMessage::Error(error) => bail!("{error}"), + _ => bail!("unexpected SSH window registration message"), + } + } + ListingEvent::Changed => { + let (summary, sessions) = { + let mut listing = listing.lock().unwrap(); + (listing.summary.clone(), listing.sessions.take()) + }; + if summary != published { + protocol::write_message(&mut lease, ®istration(summary.clone()))?; + published = summary; + } + if supports_directory && let Some(sessions) = sessions { + protocol::write_message( + &mut lease, + &ClientMessage::RemoteWindowSessions(sessions), + )?; + } + } + ListingEvent::Retry => unreachable!("an active registration has no retry deadline"), + } + } + }; + + let initial_delay = Duration::from_millis(250); + let mut delay = initial_delay; + loop { + match serve(&mut changes) { + Ok(false) => return Ok(()), + Ok(true) => { + delay = initial_delay; + continue; + } + Err(error) if delay == initial_delay => { + log::debug!("Local SSH window registration unavailable: {error:#}"); + } + Err(_) => {} + } + let retry_at = Instant::now() + delay; + delay = (delay * 2).min(Duration::from_secs(30)); + if matches!( + listing_event(&mut changes, None, Some(retry_at))?, + ListingEvent::Closed + ) { + return Ok(()); + } + } +} + +enum ListingEvent { + Closed, + Changed, + Daemon, + Retry, +} + +fn listing_event( + changes: &mut UnixStream, + lease: Option<&UnixStream>, + retry_at: Option, +) -> io::Result { + let mut fds = + [changes.as_raw_fd(), lease.map_or(-1, AsRawFd::as_raw_fd)].map(|fd| libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }); + loop { + let timeout = retry_at.map_or(-1, |deadline| { + deadline + .saturating_duration_since(Instant::now()) + .as_millis() + .max(1) as i32 + }); + // SAFETY: Both pollfd entries live for this call. poll ignores fd -1. + let ready = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) }; + if ready < 0 { + let error = io::Error::last_os_error(); + if error.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(error); + } + if fds[0].revents != 0 { + if fds[0].revents & libc::POLLHUP != 0 || changes.read(&mut [0; 1024])? == 0 { + return Ok(ListingEvent::Closed); + } + if lease.is_some() { + return Ok(ListingEvent::Changed); + } + } + if fds[1].revents != 0 { + return Ok(ListingEvent::Daemon); + } + if retry_at.is_some_and(|deadline| Instant::now() >= deadline) { + return Ok(ListingEvent::Retry); + } + } +} + fn spawn_role_from(executable: &Path, role: &str, socket: &Path, log_path: &Path) -> Result { role_command(executable, role, socket, log_path)? .spawn() @@ -448,16 +676,147 @@ mod tests { use std::os::unix::{fs::PermissionsExt, net::UnixListener}; pub(super) fn test_dir() -> PathBuf { - let path = std::env::temp_dir().join(format!( - "pt-{:x}-{:x}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - ensure_private_directory(&path).unwrap(); - path + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = std::env::temp_dir().join(format!( + "pt-{:x}-{:x}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + match DirBuilder::new().mode(0o700).create(&path) { + Ok(()) => return path, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("create test directory {}: {error}", path.display()), + } + } + } + + #[test] + fn directory_explains_a_local_daemon_that_only_supports_the_old_list() { + let root = test_dir(); + let socket = root.join("server.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + let peer = thread::spawn(move || { + for query in 0..3 { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(REQUEST_TIMEOUT)).unwrap(); + assert!(matches!( + protocol::read_message::(&mut stream).unwrap(), + ClientMessage::Hello { .. } + )); + protocol::write_message( + &mut stream, + &ServerMessage::Hello { + version: protocol::VERSION, + server_pid: 1, + }, + ) + .unwrap(); + let message = protocol::read_message::(&mut stream).unwrap(); + match (query, message) { + (0, ClientMessage::ListHostSessionDirectory) + | (1, ClientMessage::ListSessionDirectory) => {} + (2, ClientMessage::ListSessions) => { + protocol::write_message(&mut stream, &ServerMessage::Sessions(vec![])) + .unwrap(); + } + (_, message) => panic!("unexpected daemon probe {message:?}"), + } + } + }); + let error = session_directory(&socket).unwrap_err(); + assert!( + error.to_string().contains("predates the session picker"), + "{error:#}" + ); + peer.join().unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn idle_direct_ssh_window_registers_again_when_its_local_daemon_restarts() { + use std::sync::{Arc, Mutex}; + let root = test_dir(); + let socket = root.join("server.sock"); + let (notify, changes) = UnixStream::pair().unwrap(); + let identity = protocol::SessionIdentity { + server: [42; 16], + session: 5, + }; + let summary = Arc::new(Mutex::new(crate::client::RemoteWindowListing { + summary: protocol::SessionSummary { + title: "persistent".into(), + tabs: 1, + panes: 2, + }, + sessions: None, + })); + let (queried, queries) = std::sync::mpsc::channel(); + let register_at = socket.clone(); + let publisher = thread::spawn(move || { + publish_remote_window( + ®ister_at, + protocol::RemoteWindow::from_env("work".into()), + identity, + changes, + summary, + || queried.send(()).unwrap(), + ) + }); + // Replace the listening socket at the same path between generations. + // Each peer speaks the real handshake and registration protocol. + for _ in 0..2 { + let listener = UnixListener::bind(&socket).unwrap(); + let (accepted, waiting) = std::sync::mpsc::channel(); + let accept = thread::spawn(move || accepted.send(listener.accept().unwrap().0)); + let mut stream = waiting + .recv_timeout(REQUEST_TIMEOUT) + .expect("SSH window did not register"); + accept.join().unwrap().unwrap(); + stream.set_read_timeout(Some(REQUEST_TIMEOUT)).unwrap(); + assert!(matches!( + protocol::read_message::(&mut stream).unwrap(), + ClientMessage::Hello { + version: protocol::VERSION + } + )); + protocol::write_message( + &mut stream, + &ServerMessage::Hello { + version: protocol::VERSION, + server_pid: 1, + }, + ) + .unwrap(); + let ClientMessage::RegisterRemoteWindow { + target, + identity: registered, + summary, + } = protocol::read_message(&mut stream).unwrap() + else { + panic!("expected SSH window registration") + }; + assert_eq!(registered, identity); + assert_eq!(target.destination, "work"); + assert_eq!( + (summary.title.as_str(), summary.tabs, summary.panes), + ("persistent", 1, 2) + ); + protocol::write_message(&mut stream, &ServerMessage::Pong).unwrap(); + assert!(matches!( + protocol::read_message::(&mut stream).unwrap(), + ClientMessage::RemoteWindowSessions(sessions) if sessions.is_empty() + )); + protocol::write_message(&mut stream, &ServerMessage::Pong).unwrap(); + protocol::write_message(&mut stream, &ServerMessage::RequestRemoteSessions).unwrap(); + queries.recv_timeout(REQUEST_TIMEOUT).unwrap(); + fs::remove_file(&socket).unwrap(); + protocol::write_message(&mut stream, &ServerMessage::Closing).unwrap(); + } + drop(notify); + publisher.join().unwrap().unwrap(); + fs::remove_dir_all(root).unwrap(); } #[test] diff --git a/src/palette.rs b/src/palette.rs index 0ceaece..7658b87 100644 --- a/src/palette.rs +++ b/src/palette.rs @@ -95,6 +95,7 @@ impl PaletteModel { } match &result.item.kind { PaletteItemKind::Action(action) => Some(action.clone()), + PaletteItemKind::Info => None, PaletteItemKind::Menu(_) => { self.path = result.path.clone(); self.query.clear(); @@ -121,6 +122,10 @@ impl PaletteModel { } } + fn in_session_menu(&self) -> bool { + self.path.last().is_some_and(|id| id == "switch-session") + } + fn breadcrumbs(&self) -> Vec { let mut labels = Vec::new(); let mut items = self.items.as_slice(); @@ -161,8 +166,19 @@ fn gather_matches( let mut path = parent_path.to_vec(); path.push(item.id.clone()); let context = ancestors.join(" › "); - let keywords = format!("{} {}", item.keywords, context); - if let Some(score) = match_score(query, &item.title, &keywords) { + let keywords = format!( + "{} {} {}", + item.keywords, + item.detail.as_deref().unwrap_or_default(), + context + ); + let score = if matches!(item.kind, PaletteItemKind::Info) { + // Keep the submenu's loading or error message visible while typing. + ancestors.is_empty().then_some(0) + } else { + match_score(query, &item.title, &keywords) + }; + if let Some(score) = score { output.push(Match { item: item.clone(), path: path.clone(), @@ -417,7 +433,11 @@ impl CommandPalette { self.query_bounds = bounds; let empty = self.editor.text.is_empty(); let text = if empty { - "Search commands…" + if self.model.in_session_menu() { + "Search sessions…" + } else { + "Search commands…" + } } else { &self.editor.text }; @@ -609,36 +629,39 @@ impl Render for CommandPalette { .overflow_y_scroll() .track_scroll(&self.results_scroll); if self.model.matches.is_empty() { - results = results.child( - div() - .p(px(16.)) - .text_color(rgb(chrome::MUTED)) - .child("No matching commands"), - ); + results = results.child(div().p(px(16.)).text_color(rgb(chrome::MUTED)).child( + if self.model.in_session_menu() { + "No matching sessions" + } else { + "No matching commands" + }, + )); } for (index, matched) in self.model.matches.iter().enumerate() { let selected = index == self.model.selected; let enabled = matched.item.enabled; let menu = matches!(matched.item.kind, PaletteItemKind::Menu(_)); + let label = div().min_w_0().child(matched.item.title.clone()); + let label = if matches!(matched.item.kind, PaletteItemKind::Info) { + label.line_height(px(17.)) + } else { + label.text_ellipsis() + }; let mut title = div() .flex_1() .min_w_0() .flex() .flex_col() .justify_center() - .child( - div() - .min_w_0() - .text_ellipsis() - .child(matched.item.title.clone()), - ); - if !matched.context.is_empty() { + .child(label); + let detail = matched.item.detail.as_deref().unwrap_or(&matched.context); + if !detail.is_empty() { title = title.child( div() .text_size(px(10.)) .text_color(rgb(chrome::MUTED)) .text_ellipsis() - .child(matched.context.clone()), + .child(detail.to_owned()), ); } let mut row = div() @@ -663,7 +686,7 @@ impl Render for CommandPalette { chrome::PANEL_BACKGROUND })) .text_color(rgb(if enabled { chrome::TEXT } else { chrome::MUTED })) - .cursor_pointer() + .when(enabled, |row| row.cursor_pointer()) .on_hover(cx.listener(move |palette, hovered, _, cx| { if *hovered && palette.model.selected != index { palette.model.selected = index; @@ -675,6 +698,27 @@ impl Render for CommandPalette { palette.model.selected = index; palette.activate(window, cx); })) + .when_some( + match &matched.item.kind { + PaletteItemKind::Action(CommandAction::SwitchSession(route)) => Some( + if matches!(route, crate::protocol::SessionRoute::Local(_)) { + chrome::ACCENT + } else { + chrome::PANE_FOCUS + }, + ), + _ => None, + }, + |row, color| { + row.child( + div() + .size(px(7.)) + .rounded_full() + .flex_shrink_0() + .bg(rgb(color)), + ) + }, + ) .child(title); if let Some(shortcut) = matched.item.shortcut { row = row.child( @@ -931,6 +975,67 @@ mod tests { assert!(model.matches.is_empty()); } + #[test] + fn session_search_finds_hosts_and_keeps_selection_through_refresh() { + use crate::{ + commands::{SessionDirectory, root_items}, + protocol::{ListedSession, SessionIdentity, SessionRoute, SessionSummary}, + }; + let identity = |server| SessionIdentity { + server: [server; 16], + session: 7, + }; + let entry = |route, host: Option<&str>| ListedSession { + route, + host: host.map(str::to_owned), + attached: 0, + summary: SessionSummary { + title: "Build".into(), + tabs: 2, + panes: 3, + }, + }; + let local = entry(SessionRoute::Local(identity(1)), None); + let remote = entry(SessionRoute::Direct(identity(2)), Some("work@builder")); + let menu = |sessions| { + root_items( + None, + false, + &SessionDirectory::Ready(crate::launcher::SessionDirectoryPage { + sessions, + loading_hosts: vec![], + legacy: false, + }), + ) + }; + let mut model = PaletteModel::new(menu(vec![local.clone(), remote.clone()])); + model.set_query("work@builder".into()); + assert_eq!(model.matches.len(), 1); + assert!( + matches!(model.activate(), Some(CommandAction::SwitchSession(route)) if route == remote.route) + ); + model.set_query("switch to session".into()); + model.activate(); + assert!(model.in_session_menu()); + model.move_selection(1); + model.set_items(menu(vec![remote.clone(), local.clone()])); + assert!( + matches!(model.activate(), Some(CommandAction::SwitchSession(route)) if route == remote.route) + ); + let sibling = entry(SessionRoute::Remote(identity(3)), Some("work@builder")); + model.set_items(menu(vec![remote, local.clone(), sibling.clone()])); + model.set_query("work@builder detached #7".into()); + assert_eq!(model.matches.len(), 1); + assert!( + matches!(model.activate(), Some(CommandAction::SwitchSession(route)) if route == sibling.route) + ); + model.set_query("local detached #7".into()); + assert_eq!(model.matches.len(), 1); + assert!( + matches!(model.activate(), Some(CommandAction::SwitchSession(route)) if route == local.route) + ); + } + #[test] fn disabled_commands_never_execute_and_empty_navigation_is_safe() { let mut items = fixture(); diff --git a/src/protocol.rs b/src/protocol.rs index 7fa3772..347ab4f 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -73,6 +73,65 @@ pub struct SessionInfo { pub tabs: Vec, } +/// A picker selection carries the daemon identity as well as the numeric session +/// ID, so an old list cannot activate a different session after a restart. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionRoute { + Local(SessionIdentity), + Mounted { + owner: SessionIdentity, + tab: TabId, + identity: SessionIdentity, + }, + Direct(SessionIdentity), + /// A sibling session discovered on a connected SSH daemon. + Remote(SessionIdentity), +} + +impl SessionRoute { + pub fn identity(self) -> SessionIdentity { + match self { + Self::Local(identity) + | Self::Direct(identity) + | Self::Remote(identity) + | Self::Mounted { identity, .. } => identity, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionSummary { + pub title: String, + pub tabs: usize, + pub panes: usize, +} + +impl SessionSummary { + pub fn from_tabs(tabs: &[TabInfo], active_tab: TabId) -> Self { + let active = tabs.iter().find(|tab| tab.id == active_tab); + Self { + title: active.map_or_else(String::new, |tab| tab.title.clone()), + tabs: tabs.len(), + panes: tabs.iter().map(|tab| tab.panes.len()).sum(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteSessionInfo { + pub id: SessionId, + pub summary: SessionSummary, + pub attached: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ListedSession { + pub route: SessionRoute, + pub host: Option, + pub summary: SessionSummary, + pub attached: usize, +} + #[derive(Debug, Clone, Serialize, Deserialize)] // Keep variants append-only: the shutdown command can retire an older server. pub enum ClientMessage { @@ -190,6 +249,21 @@ pub enum ClientMessage { cwd: Option, fallback: SshOptions, }, + // Local control requests. SSH bridges can keep using the existing v6 messages. + ListSessionDirectory, + RegisterRemoteWindow { + target: RemoteWindow, + identity: SessionIdentity, + summary: SessionSummary, + }, + OpenListedSession(SessionRoute), + ListHostSessionDirectory, + /// Published on the direct SSH window's existing registration lease. + RemoteWindowSessions(Vec), + OpenPeerSession { + identity: SessionIdentity, + workspace: Option, + }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -247,15 +321,26 @@ pub enum SelectionCommand { #[derive(Debug, Clone, Serialize, Deserialize)] // Hello and Closing also retain their v1 wire representation during upgrades. pub enum ServerMessage { - Hello { version: u32, server_pid: u32 }, + Hello { + version: u32, + server_pid: u32, + }, Snapshot(Snapshot), Clipboard(String), Error(String), Pong, Closing, - Connected { session: SessionId }, + Connected { + session: SessionId, + }, Sessions(Vec), DetachedRemote(DetachedRemote), + SessionDirectory(Vec), + RequestRemoteSessions, + HostSessionDirectory { + sessions: Vec, + loading_hosts: Vec, + }, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/src/server.rs b/src/server.rs index b7d78f4..c4b1184 100644 --- a/src/server.rs +++ b/src/server.rs @@ -107,8 +107,19 @@ fn flatten_panes(tab: &mut TabInfo) { .collect(); } +struct RegisteredRemoteWindow { + target: RemoteWindow, + identity: SessionIdentity, + summary: SessionSummary, + // Older direct windows publish only their own summary. + host_sessions: Option>, + last_query: Option, +} + struct Client { authenticated: bool, + // A direct SSH window holds a separate local connection for its lifetime. + remote_window: Option, session: Option, output: Arc, writer: JoinHandle<()>, @@ -440,6 +451,7 @@ impl Server { id, Client { authenticated: false, + remote_window: None, session: None, output, writer, @@ -498,6 +510,216 @@ impl Server { .context(NO_SESSIONS_TO_ATTACH) } + fn session_directory(&mut self, include_hosts: bool) -> (Vec, Vec) { + fn add_remote( + remotes: &mut BTreeMap, + entry: ListedSession, + ) { + let id = entry.route.identity(); + if let Some(old) = remotes.get_mut(&id) { + let total = old.attached + entry.attached; + if old.attached == 0 && entry.attached != 0 { + *old = entry; + } + old.attached = total; + } else { + remotes.insert(id, entry); + } + } + + let mut local = Vec::new(); + let mut remotes = BTreeMap::new(); + // An SSH daemon may be visible through multiple windows, mounts or host aliases. + let mut hosts = BTreeMap::new(); + for session in self.sessions.values_mut().filter(|s| s.is_live()) { + session.update_titles(); + let attached = self + .clients + .values() + .filter(|c| c.session == Some(session.id)) + .count(); + local.push(ListedSession { + route: SessionRoute::Local(session.identity), + host: None, + summary: SessionSummary::from_tabs(&session.tabs, session.active_tab), + attached, + }); + + // A workspace can mount the same SSH session more than once. Count + // its windows once and prefer its currently visible copy. + let mut mounts: Vec<_> = session.remotes.iter().collect(); + mounts.sort_unstable_by_key(|&(slot, mount)| { + (!mount.owns_tab(session.active_tab), *slot) + }); + let mut seen = BTreeSet::new(); + for (_, mount) in mounts { + if let Some(entry) = mount.listed_session(session.identity, attached) { + let id = entry.route.identity(); + if include_hosts && let Some(connection) = &mount.connection { + hosts.entry(id.server).or_insert_with(|| { + ( + mount.target.destination.clone(), + connection.remote_directory(), + ) + }); + } + if seen.insert(id) { + add_remote(&mut remotes, entry); + } + } + } + } + let mut clients: Vec<_> = self.clients.iter_mut().collect(); + clients.sort_unstable_by_key(|(id, _)| **id); + for (_, client) in clients { + let Some(view) = &mut client.remote_window else { + continue; + }; + if include_hosts && let Some(rows) = &view.host_sessions { + hosts.entry(view.identity.server).or_insert_with(|| { + if view + .last_query + .is_none_or(|last| last.elapsed() >= Duration::from_secs(1)) + { + view.last_query = Some(Instant::now()); + client.output.reliable(ServerMessage::RequestRemoteSessions); + } + (view.target.destination.clone(), rows.clone()) + }); + } + add_remote( + &mut remotes, + ListedSession { + route: SessionRoute::Direct(view.identity), + host: Some(view.target.destination.clone()), + summary: view.summary.clone(), + attached: 1, + }, + ); + } + + let mut loading_hosts = BTreeSet::new(); + for (server, (host, rows)) in hosts { + if rows.is_empty() { + loading_hosts.insert(host); + continue; + } + for row in rows { + let identity = SessionIdentity { + server, + session: row.id, + }; + // Prefer a mounted tab or existing direct window whenever one exists. + remotes.entry(identity).or_insert_with(|| ListedSession { + host: Some(host.clone()), + route: SessionRoute::Remote(identity), + summary: row.summary, + attached: row.attached, + }); + } + } + let mut remotes: Vec<_> = remotes.into_values().collect(); + remotes.sort_by(|a, b| { + a.host + .cmp(&b.host) + .then_with(|| a.route.identity().session.cmp(&b.route.identity().session)) + }); + local.extend(remotes); + (local, loading_hosts.into_iter().collect()) + } + + fn open_peer_session( + &mut self, + identity: SessionIdentity, + workspace: Option, + open_window: &mut impl FnMut(Option, SessionTarget) -> Result<()>, + ) -> Result<()> { + let target = self + .sessions + .values() + .flat_map(|s| s.remotes.values()) + .find(|mount| { + mount + .connection + .as_ref() + .and_then(|c| c.remote_identity()) + .is_some_and(|id| id.server == identity.server) + }) + .map(|mount| &mount.target) + .or_else(|| { + self.clients + .values() + .filter_map(|c| c.remote_window.as_ref()) + .find(|view| view.identity.server == identity.server) + .map(|view| &view.target) + }) + .context("the SSH connection to this host has closed")? + .clone(); + let attach = SessionTarget::Remembered(identity); + if let Some(owner) = workspace { + let session = self + .sessions + .get_mut(&owner.session) + .filter(|s| s.identity == owner && s.is_live()) + .context("workspace has closed")?; + if let Some(tab) = session + .remotes + .values() + .find_map(|m| m.selection_tab(identity, session.active_tab)) + { + return session.focus_tab(tab); + } + session.open_remote_at(session.active_tab, target, attach) + } else { + open_window(Some(target), attach) + } + } + + fn open_listed_session( + &mut self, + route: SessionRoute, + open_window: &mut impl FnMut(Option, SessionTarget) -> Result<()>, + ) -> Result<()> { + let (owner, mount) = match route { + SessionRoute::Local(id) => (id, None), + SessionRoute::Mounted { + owner, + tab, + identity, + } => (owner, Some((tab, identity))), + SessionRoute::Remote(identity) => { + return self.open_peer_session(identity, None, open_window); + } + SessionRoute::Direct(identity) => { + let view = self + .clients + .values() + .filter_map(|client| client.remote_window.as_ref()) + .find(|view| view.identity == identity) + .context("SSH window has closed")?; + return open_window( + Some(view.target.clone()), + SessionTarget::Remembered(identity), + ); + } + }; + let session = self + .sessions + .get_mut(&owner.session) + .filter(|s| s.identity == owner && s.is_live()) + .context("session has ended")?; + if let Some((tab, identity)) = mount { + let tab = session + .remotes + .values() + .filter_map(|mount| mount.selection_tab(identity, tab)) + .min_by_key(|id| (*id != tab, *id)) + .context("SSH session is no longer mounted here")?; + session.focus_tab(tab)?; + } + open_window(None, SessionTarget::Remembered(owner)) + } + fn command( &mut self, id: u64, @@ -578,6 +800,81 @@ impl Server { .output .reliable(ServerMessage::Sessions(sessions)); } + ClientMessage::ListSessionDirectory | ClientMessage::ListHostSessionDirectory => { + let include_hosts = matches!(message, ClientMessage::ListHostSessionDirectory); + let (sessions, loading_hosts) = self.session_directory(include_hosts); + let response = if include_hosts { + ServerMessage::HostSessionDirectory { + sessions, + loading_hosts, + } + } else { + ServerMessage::SessionDirectory(sessions) + }; + self.clients[&id].output.reliable(response); + } + ClientMessage::RemoteWindowSessions(mut sessions) => { + let view = client + .remote_window + .as_mut() + .context("register the SSH window first")?; + for row in &mut sessions { + ensure!( + row.id != 0 + && (1..=256).contains(&row.summary.tabs) + && row.summary.panes <= row.summary.tabs * MAX_PANES, + "invalid SSH session summary" + ); + row.summary.title = + clean_title(std::mem::take(&mut row.summary.title)).unwrap_or_default(); + } + view.host_sessions = Some(sessions); + client.output.reliable(ServerMessage::Pong); + } + ClientMessage::OpenPeerSession { + identity, + workspace, + } => { + self.open_peer_session(identity, workspace, open_window)?; + self.clients[&id].output.reliable(ServerMessage::Pong); + } + ClientMessage::OpenListedSession(route) => { + self.open_listed_session(route, open_window)?; + self.clients[&id].output.reliable(ServerMessage::Pong); + } + ClientMessage::RegisterRemoteWindow { + target, + identity, + summary, + } => { + ensure!( + client.session.is_none(), + "register the SSH window on its own connection" + ); + crate::client::validate_destination(&target.destination)?; + ensure!( + identity.session != 0 + && summary.tabs > 0 + && summary.tabs <= 256 + && summary.panes <= summary.tabs * MAX_PANES, + "invalid SSH session summary" + ); + let previous = client + .remote_window + .take() + .filter(|view| view.identity == identity); + client.remote_window = Some(RegisteredRemoteWindow { + last_query: previous.as_ref().and_then(|view| view.last_query), + host_sessions: previous.and_then(|view| view.host_sessions), + target, + identity, + summary: SessionSummary { + title: clean_title(summary.title).unwrap_or_default(), + ..summary + }, + }); + client.output.reliable(ServerMessage::Pong); + } ClientMessage::OpenRemoteTab { session, pane, @@ -922,6 +1219,12 @@ impl SessionState { | ClientMessage::Connect(_) | ClientMessage::Ping | ClientMessage::ListSessions + | ClientMessage::ListSessionDirectory + | ClientMessage::RegisterRemoteWindow { .. } + | ClientMessage::OpenListedSession(_) + | ClientMessage::ListHostSessionDirectory + | ClientMessage::RemoteWindowSessions(_) + | ClientMessage::OpenPeerSession { .. } | ClientMessage::OpenWindow { .. } | ClientMessage::OpenRemoteWindow { .. } | ClientMessage::OpenWindowForRemoteTab { .. } @@ -1516,6 +1819,248 @@ mod tests { }) } + #[test] + fn directory_lists_detached_sessions_and_live_remote_window_leases() { + let (launched, launches) = mpsc::channel(); + let server = TestServer::start_with_launcher(move |target, session| { + launched.send((target, session)).unwrap(); + Ok(()) + }); + let directory = || { + let mut query = server.client(); + send(&mut query, ClientMessage::ListSessionDirectory); + let ServerMessage::SessionDirectory(rows) = protocol::read_message(&mut query).unwrap() + else { + panic!("expected session directory"); + }; + rows + }; + let mut local = server.client(); + send( + &mut local, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); + let frame = snapshot(&mut local, |_| true); + let local_route = SessionRoute::Local(frame.lineage[0]); + assert_eq!(directory()[0].attached, 1); + drop(local); + + let identity = SessionIdentity { + server: [17; 16], + session: frame.lineage[0].session, + }; + let register = |stream: &mut UnixStream, title: &str| { + send( + stream, + ClientMessage::RegisterRemoteWindow { + target: RemoteWindow { + destination: "user@work".into(), + ssh: SshOptions { + executable: Some("/opt/psyterm".into()), + ..Default::default() + }, + }, + identity, + summary: SessionSummary { + title: title.into(), + tabs: 2, + panes: 3, + }, + }, + ); + assert!(matches!( + protocol::read_message(stream).unwrap(), + ServerMessage::Pong + )); + }; + let mut lease = server.client(); + register(&mut lease, "first title"); + register(&mut lease, "current title"); + let deadline = Instant::now() + Duration::from_secs(5); + let rows = loop { + let rows = directory(); + if rows[0].attached == 0 { + break rows; + } + assert!(Instant::now() < deadline, "local client did not detach"); + thread::sleep(Duration::from_millis(2)); + }; + assert_eq!(rows.len(), 2); + assert_eq!((rows[0].route, rows[0].attached), (local_route, 0)); + assert_eq!( + rows[0].summary, + SessionSummary::from_tabs(&frame.tabs, frame.active_tab) + ); + let direct = &rows[1]; + assert_eq!(direct.route, SessionRoute::Direct(identity)); + assert_eq!(direct.host.as_deref(), Some("user@work")); + assert_eq!( + ( + &*direct.summary.title, + direct.summary.tabs, + direct.summary.panes + ), + ("current title", 2, 3) + ); + let mut mirror = server.client(); + register(&mut mirror, "current title"); + assert_eq!(directory()[1].attached, 2); + + let open = |route| { + crate::launcher::control(&server.socket, ClientMessage::OpenListedSession(route)) + }; + open(direct.route).unwrap(); + let (Some(target), SessionTarget::Remembered(selected)) = launches.recv().unwrap() else { + panic!("expected an identity-checked SSH attach"); + }; + assert_eq!(selected, identity); + assert_eq!(target.ssh.executable.as_deref(), Some("/opt/psyterm")); + assert!(open(SessionRoute::Local(identity)).is_err()); + + drop((mirror, lease)); + let deadline = Instant::now() + Duration::from_secs(5); + while directory().len() > 1 { + assert!(Instant::now() < deadline, "closed SSH window still listed"); + thread::sleep(Duration::from_millis(2)); + } + assert!(open(direct.route).is_err()); + open(local_route).unwrap(); + assert!( + matches!(launches.recv().unwrap(), (None, SessionTarget::Remembered(id)) if id == frame.lineage[0]) + ); + } + + #[test] + fn direct_window_exposes_sibling_sessions_only_while_its_host_is_connected() { + let (tx, launches) = mpsc::channel(); + let server = TestServer::start_with_launcher(move |target, session| { + tx.send((target.unwrap(), session)).unwrap(); + Ok(()) + }); + let directory = || { + let mut query = server.client(); + send(&mut query, ClientMessage::ListHostSessionDirectory); + match protocol::read_message(&mut query).unwrap() { + ServerMessage::HostSessionDirectory { + sessions, + loading_hosts, + } => (sessions, loading_hosts), + other => panic!("expected host session directory, got {other:?}"), + } + }; + let mut lease = server.client(); + let mounted = SessionIdentity { + server: [17; 16], + session: 2, + }; + let peer = SessionIdentity { + session: 5, + ..mounted + }; + let summary = SessionSummary { + title: "current".into(), + tabs: 1, + panes: 1, + }; + let publish = |lease: &mut UnixStream, message| { + send(lease, message); + assert!(matches!( + protocol::read_message(lease).unwrap(), + ServerMessage::Pong + )); + }; + publish( + &mut lease, + ClientMessage::RegisterRemoteWindow { + target: RemoteWindow { + destination: "user@work".into(), + ssh: SshOptions { + executable: Some("/custom/psyterm".into()), + agent_socket: Some("/host/agent".into()), + }, + }, + identity: mounted, + summary: summary.clone(), + }, + ); + // Old publishers must not receive new messages they cannot decode. + assert!(directory().1.is_empty()); + publish(&mut lease, ClientMessage::RemoteWindowSessions(vec![])); + let (rows, waiting) = directory(); + assert_eq!(rows.len(), 1); + assert_eq!(waiting, ["user@work"]); + assert!(matches!( + protocol::read_message(&mut lease).unwrap(), + ServerMessage::RequestRemoteSessions + )); + let current = RemoteSessionInfo { + id: mounted.session, + summary, + attached: 1, + }; + let sibling = RemoteSessionInfo { + id: peer.session, + summary: SessionSummary { + title: "old build shell".into(), + tabs: 3, + panes: 7, + }, + attached: 0, + }; + publish( + &mut lease, + ClientMessage::RemoteWindowSessions(vec![sibling.clone(), current.clone()]), + ); + let (rows, waiting) = directory(); + assert!(waiting.is_empty()); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].route, SessionRoute::Direct(mounted)); + assert_eq!( + rows[1], + ListedSession { + route: SessionRoute::Remote(peer), + host: Some("user@work".into()), + summary: sibling.summary, + attached: 0 + } + ); + let mut legacy = server.client(); + send(&mut legacy, ClientMessage::ListSessionDirectory); + assert!( + matches!(protocol::read_message(&mut legacy).unwrap(), ServerMessage::SessionDirectory(rows) if rows.len() == 1) + ); + let open = || { + crate::launcher::control( + &server.socket, + ClientMessage::OpenPeerSession { + identity: peer, + workspace: None, + }, + ) + }; + open().unwrap(); + let (target, selection) = launches.recv().unwrap(); + assert_eq!(target.destination, "user@work"); + assert_eq!(target.ssh.executable.as_deref(), Some("/custom/psyterm")); + assert_eq!( + target.ssh.agent_socket.as_deref(), + Some(Path::new("/host/agent")) + ); + assert!(matches!(selection, SessionTarget::Remembered(id) if id == peer)); + publish( + &mut lease, + ClientMessage::RemoteWindowSessions(vec![current]), + ); + assert_eq!(directory().0.len(), 1); + drop(lease); + let deadline = Instant::now() + Duration::from_secs(5); + while !directory().0.is_empty() { + assert!(Instant::now() < deadline, "closed SSH window still listed"); + thread::sleep(Duration::from_millis(2)); + } + assert!(open().is_err()); + } + #[test] fn direct_remote_detach_can_be_looked_up_without_a_window() { let server = TestServer::start(); diff --git a/src/server/remote.rs b/src/server/remote.rs index 9275054..e48c8a2 100644 --- a/src/server/remote.rs +++ b/src/server/remote.rs @@ -14,15 +14,16 @@ pub(super) enum RemoteEvent { } pub(super) struct RemoteSession { - target: RemoteWindow, + pub(super) target: RemoteWindow, anchor: TabId, slot: TabId, cancelled: Arc, - connection: Option, + pub(super) connection: Option, // Remote IDs map to stable IDs allocated from the parent session's pool. tabs: HashMap, panes: HashMap, latest: Option>, + attaching: Option, requested_tab: Option, clipboard: VecDeque<(PaneId, Weak)>, } @@ -52,6 +53,43 @@ impl RemoteSession { (self.latest.is_none() && self.slot == local) || original(&self.tabs, local).is_some() } + pub(super) fn listed_session( + &self, + owner: SessionIdentity, + attached: usize, + ) -> Option { + 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 { + 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 @@ -278,28 +316,47 @@ impl SessionState { target: SessionTarget, ssh: SshOptions, ) -> Result<()> { - crate::client::validate_destination(&destination)?; 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 (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 window_target = RemoteWindow { - destination, - ssh: ssh.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 || { @@ -334,7 +391,7 @@ impl SessionState { } } })?; - self.insert_remote_slot(index, group, window_target, cancelled); + self.insert_remote_slot(index, group, window_target, cancelled, attaching); Ok(()) } @@ -344,8 +401,16 @@ impl SessionState { group: u64, target: RemoteWindow, cancelled: Arc, + attaching: Option, ) { 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 { @@ -373,6 +438,7 @@ impl SessionState { tabs: HashMap::new(), panes: HashMap::new(), latest: None, + attaching, requested_tab: None, clipboard: VecDeque::new(), }, @@ -624,6 +690,7 @@ mod tests { ssh: SshOptions::default(), }, Arc::new(AtomicBool::new(false)), + None, ); group } @@ -638,6 +705,77 @@ mod tests { ) } + #[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); @@ -786,9 +924,7 @@ mod tests { .err() .expect("refuse a recycled session ID"); assert!( - error - .to_string() - .contains("remembered remote session has ended"), + error.to_string().contains("remembered session has ended"), "{error:#}" ); } diff --git a/src/terminal.rs b/src/terminal.rs index 87e6259..2885aeb 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -1,9 +1,11 @@ //! Display-only workspace and panes. All terminal and multiplexer state is remote. +mod session_picker; + use crate::{ chrome, client::{Client, Updates}, colors, - commands::{self, CommandAction}, + commands::{self, CommandAction, SessionDirectory}, cursor::CursorAnimator, fonts::{self, TerminalFont}, input, @@ -44,6 +46,9 @@ pub struct Workspace { error: Option, focus: FocusHandle, palette: Option>, + session_directory: SessionDirectory, + session_refresh: Option>, + disconnected: bool, tab_rename: Option, outgoing: HashMap>, outgoing_snapshot: Option>, @@ -131,6 +136,8 @@ impl Workspace { fn close_palette(&mut self, window: &mut Window, cx: &mut Context) { self.palette = None; + self.session_refresh = None; + self.session_directory = SessionDirectory::Loading; self.restore_focus(window, cx); cx.notify(); } @@ -149,7 +156,7 @@ impl Workspace { cx.notify(); }); } - let items = commands::root_items(self.snapshot.as_deref(), self.client.remote().is_some()); + let items = self.palette_items(); let owner = cx.weak_entity(); self.palette = Some(cx.new(|cx| { CommandPalette::new( @@ -166,6 +173,7 @@ impl Workspace { cx, ) })); + self.refresh_session_directory(cx); cx.notify(); } @@ -244,6 +252,10 @@ impl Workspace { self.open_palette(window, cx); None } + SwitchSession(route) => { + self.switch_session(route, window, cx); + None + } NewWindow => { self.open_window(cx); None @@ -384,6 +396,7 @@ impl Workspace { { cx.write_to_clipboard(ClipboardItem::new_string(text)); } + view.disconnected |= update.disconnected; if let Some(error) = update.error { view.error = Some(error); } @@ -500,10 +513,7 @@ impl Workspace { view.snapshot = Some(snapshot); if let Some(palette) = &view.palette { if metadata_changed { - let items = commands::root_items( - view.snapshot.as_deref(), - view.client.remote().is_some(), - ); + let items = view.palette_items(); palette .update(cx, |palette, cx| palette.set_items(items, cx)); } @@ -531,6 +541,9 @@ impl Workspace { error: None, focus, palette: None, + session_directory: SessionDirectory::Loading, + session_refresh: None, + disconnected: false, tab_rename: None, outgoing: HashMap::new(), outgoing_snapshot: None, diff --git a/src/terminal/session_picker.rs b/src/terminal/session_picker.rs new file mode 100644 index 0000000..9cad874 --- /dev/null +++ b/src/terminal/session_picker.rs @@ -0,0 +1,147 @@ +use super::*; +use crate::{commands::PaletteItem, protocol::SessionRoute}; + +impl Workspace { + pub(super) fn palette_items(&self) -> Vec { + commands::root_items( + self.snapshot.as_deref(), + self.client.remote().is_some(), + &self.session_directory, + ) + } + + pub(super) fn refresh_session_directory(&mut self, cx: &mut Context) { + let client = self.client.clone(); + self.session_refresh = Some(cx.spawn(async move |view, cx| { + let interval = Duration::from_secs(2); + let mut pending_delay = Duration::from_millis(150); + loop { + let client = client.clone(); + let result = cx + .background_executor() + .spawn(async move { client.session_directory() }) + .await; + let delay = if result + .as_ref() + .is_ok_and(|page| !page.loading_hosts.is_empty()) + { + let delay = pending_delay; + pending_delay = (pending_delay * 2).min(interval); + delay + } else { + pending_delay = Duration::from_millis(150); + interval + }; + let directory = match result { + Ok(sessions) => SessionDirectory::Ready(sessions), + Err(error) => { + SessionDirectory::Unavailable(format!("Could not list sessions: {error:#}")) + } + }; + if view + .update(cx, |view, cx| { + if view.session_directory != directory { + view.session_directory = directory; + if let Some(palette) = &view.palette { + let items = view.palette_items(); + palette.update(cx, |palette, cx| palette.set_items(items, cx)); + } + } + }) + .is_err() + { + break; + } + cx.background_executor().timer(delay).await; + } + })); + } + + fn shows_session(&self, route: SessionRoute) -> bool { + if self.disconnected { + return false; + } + let Some(snapshot) = &self.snapshot else { + return false; + }; + let root = snapshot.lineage.first(); + if self.client.remote().is_some() { + return !matches!(route, SessionRoute::Local(_)) && root == Some(&route.identity()); + } + match route { + SessionRoute::Local(id) => root == Some(&id), + SessionRoute::Mounted { owner, tab, .. } => { + root == Some(&owner) && snapshot.tabs.iter().any(|t| t.id == tab) + } + SessionRoute::Direct(_) | SessionRoute::Remote(_) => false, + } + } + + fn activate_session( + &mut self, + route: SessionRoute, + window: &mut Window, + cx: &mut Context, + ) { + if let SessionRoute::Mounted { owner, tab, .. } = route + && self.client.remote().is_none() + && self + .snapshot + .as_ref() + .is_some_and(|s| s.lineage.first() == Some(&owner) && s.active_tab != tab) + { + self.execute(CommandAction::FocusTab(tab), window, cx); + } + if self.palette.is_some() { + self.close_palette(window, cx); + } + window.activate_window(); + } + + pub(super) fn switch_session( + &mut self, + route: SessionRoute, + window: &mut Window, + cx: &mut Context, + ) { + if self.shows_session(route) { + self.activate_session(route, window, cx); + return; + } + // The macOS host can raise an existing window without opening another view or SSH transport. + for peer in cx + .windows() + .iter() + .filter(|peer| **peer != window.window_handle()) + .filter_map(|peer| peer.downcast::()) + { + if peer.read(cx).is_ok_and(|view| view.shows_session(route)) + && peer + .update(cx, |view, window, cx| { + view.activate_session(route, window, cx) + }) + .is_ok() + { + return; + } + } + let workspace = self + .snapshot + .as_ref() + .filter(|_| self.client.remote().is_none() && !self.disconnected) + .and_then(|frame| frame.lineage.first().copied()); + let client = self.client.clone(); + let attach = cx + .background_executor() + .spawn(async move { client.open_listed_session(route, workspace) }); + cx.spawn(async move |view, cx| { + if let Err(error) = attach.await { + let _ = view.update(cx, |view, cx| { + view.error = Some(format!("Could not open session: {error:#}")); + cx.notify(); + }); + } + }) + .detach(); + } +}