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.
This commit is contained in:
James Magahern
2026-11-17 19:36:19 -08:00
parent 2fa33e5e8c
commit 804ab007ee
11 changed files with 1869 additions and 85 deletions
+265 -23
View File
@@ -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<RemoteDirectory>,
}
#[derive(Default)]
struct RemoteDirectory {
sessions: Vec<RemoteSessionInfo>,
requested_at: Option<Instant>,
pending: bool,
}
impl RemoteDirectory {
fn refresh(&mut self, commands: &mpsc::Sender<ClientMessage>) {
// 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<SessionInfo>) {
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<Vec<RemoteSessionInfo>>,
}
/// 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<Mutex<RemoteWindowListing>>,
notify: UnixStream,
}
impl RemoteListing {
fn start(
socket: PathBuf,
target: RemoteWindow,
frame: &Snapshot,
commands: mpsc::Sender<ClientMessage>,
) -> Result<Self> {
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<RemoteWindow>,
@@ -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<RemoteSessionInfo> {
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::SessionDirectoryPage> {
crate::launcher::session_directory(&self.connection.launcher_socket)
}
pub fn open_listed_session(
&self,
route: SessionRoute,
workspace: Option<SessionIdentity>,
) -> 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<Update>,
signal: async_channel::Sender<()>,
remote_session: Option<&RemoteSession>,
mut listing: Option<RemoteListing>,
) {
loop {
let message = protocol::read_message::<ServerMessage>(&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::<ServerMessage>(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);
}