diff --git a/README.md b/README.md index 73897de..6e1b707 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@ A terminal and multiplexer for macOS and Linux (Wayland), built with [GPUI 0.2.2 and [alacritty_terminal 0.26.0](https://docs.rs/alacritty_terminal/0.26.0/). A separate server owns terminal emulation, shells, tabs, panes, and scrollback. GUI processes display its snapshots and send input commands. Closing a window -detaches it; the shells keep running for the next local or remote connection. +detaches it. Run `psyterm --attach` to return to the running shells, or +`psyterm` to start a fresh session. ## Build and run @@ -35,8 +36,8 @@ open target/release/bundle/osx/psyTerm.app ``` You can copy `psyTerm.app` to Applications. The bundle and CLI both open a GUI -in the launching process and connect to the same local server. Use `open -n` -with the app path for another window. The bundle's +in the launching process. Press Cmd+N for another window with its own session, +or run `open -n` with the app path. The bundle's `Contents/MacOS/psyterm` executable also accepts the CLI commands below. ### Linux @@ -76,12 +77,19 @@ cargo build --locked --release ``` The default command starts or reuses a local server, asks its zygote to fork a -GUI, and returns. Running it again opens another view of the same workspace. +GUI, and returns. Each invocation starts an independent session unless you pass +`--attach`. ### Shells and sessions -The first attachment to an empty server creates a shell in the server's startup -directory. Shells inherit the server's environment and receive +Each new session starts with one tab and one shell. Windows opened with the +New Window shortcut start a fresh session in the focused pane’s directory on +the same host. 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 +selects the most recently used attached session. + +Shells inherit the server's environment and receive `TERM=xterm-256color` and `COLORTERM=truecolor`. The server uses `$SHELL` when set. On macOS it starts a login shell and falls back to the shell in your account settings. On Linux the fallback is `/bin/sh`. @@ -93,8 +101,9 @@ its zygote for new GUI windows, preserving existing windows and shells. Changes to server logic or the protocol still require restarting the server; `--shutdown` also ends its shell sessions. -This build uses protocol version 4. An older server must be restarted before -attaching; `psyterm --shutdown` can stop servers using versions 1–3. +This build uses protocol version 6. Both ends of an SSH connection need this protocol. +An older server must be restarted before attaching. `psyterm --shutdown` +can stop servers using versions 1–5. Finish any running work first, since shutdown ends its sessions, then launch `psyterm` again to start the updated server. @@ -102,10 +111,12 @@ Finish any running work first, since shutdown ends its sessions, then launch | Command | Behavior | | --- | --- | -| `psyterm` | Open a local window attached to the server | -| `psyterm --remote user@host` | Open a local GUI connected to the remote server over SSH | +| `psyterm` | Open a new local session in a new window | +| `psyterm --attach [ID]` | Open a window on an existing session | +| `psyterm --remote user@host` | Start a fresh SSH session in an adjacent tab when run from a local psyTerm pane, or a new window when run elsewhere | +| `psyterm --remote user@host --attach [ID]` | Reattach to an existing session on the SSH host | | `psyterm --gui` | Run the GUI in the current process | -| `psyterm --list` | Inspect tabs and panes in the running local server | +| `psyterm --list` | Show local sessions, attached window counts, tabs, and panes | | `psyterm --shutdown` | Stop the local server and end its sessions | | `psyterm --server` | Run the terminal server in the foreground | | `psyterm --socket PATH` | Select a separate local server socket; combine with other options | @@ -125,25 +136,33 @@ UID using `getpeereid` on macOS and `SO_PEERCRED` on Linux. The server logs to `server.sock.log` beside the socket. The Linux zygote logs to `server.sock.zygote.log`. -SSH uses `BatchMode=yes`: configure key/agent authentication and known-host trust -before connecting. The remote host needs a compatible `psyterm` executable in -its noninteractive SSH `PATH`. Override that executable with -`PSYTERM_REMOTE_BIN`; this direct-launch example uses the current environment: +From a local psyTerm shell, run `psyterm --remote me@workstation` to open a tab +immediately to the right of the invoking tab. The command returns to the local +shell while SSH connects. Run it again for an independent remote session, or +add `--attach ID` to open an existing one. Use `ssh me@workstation psyterm --list` +to find remote session IDs. Closing the window and reattaching to the local +session restores its mixed tab bar. The **+** button creates a local tab in +this workspace. Splitting a remote pane creates another shell on its SSH host. + +SSH uses `BatchMode=yes`. Configure key or agent authentication and trust the +host key before connecting. The remote host needs a compatible `psyterm` +executable on its noninteractive SSH `PATH`. To use a different path, set +`PSYTERM_REMOTE_BIN` in the invoking shell. ```sh -PSYTERM_REMOTE_BIN=/home/me/bin/psyterm \ - cargo run --locked -- --gui --remote me@workstation +PSYTERM_REMOTE_BIN=/home/me/bin/psyterm psyterm --remote me@workstation ``` SSH starts `psyterm --bridge` on the remote host, which starts or reuses that -host's server. stdout carries only framed protocol bytes. No TCP listener or -separate network authentication service is exposed. To end remote sessions, +host's server. SSH carries input and terminal updates over its standard streams. +To end remote sessions, run `psyterm --shutdown` on the remote host, for example through SSH. ## Controls | Action | macOS | Linux | | --- | --- | --- | +| Open a new window and session | Cmd+N | Ctrl+Shift+N | | Increase terminal text size | Cmd+Plus or Cmd+= | Ctrl+Plus or Ctrl+= | | Decrease terminal text size | Cmd+Minus | Ctrl+Minus | | Open or dismiss the command palette | Cmd+Shift+P | Ctrl+Shift+P | @@ -216,11 +235,11 @@ When a shell exits, its pane closes automatically. An empty tab closes too, and focus moves to an adjacent remaining pane or tab when needed. After the last shell exits, the window stays open with `+` available to start another tab. -Clients share the server's active tab, focused pane, selection, and scrollback -position. The most recent GUI resize sets each pane's grid size. These are -shared views of one workspace, not independent per-client layouts. Tabs and -panes survive GUI disconnects but are stored in daemon memory, not persisted -across server shutdown or machine restart. +Each session has its own tabs, panes, focus, and scrollback. Windows attached +to the same session share those and the underlying PTY grid. Each window keeps +its own text size, and the focused window sets the grid dimensions. Tabs and +panes survive GUI disconnects and stay in server memory until the shells exit +or the server stops. ## Appearance @@ -336,6 +355,6 @@ navigation bindings, stack insertion in both directions, collapsed-pane focus, exit cleanup, and stack reattachment. A second client's focus changes preserve palette input. These checks cover Linux Wayland. -Current limits include no arbitrary split trees or floating panes, shared per-server +Current limits include no arbitrary split trees or floating panes, shared per-session viewport state, no disk-restored sessions, no configuration files, no application mouse reporting, no Kitty keyboard protocol, no OSC 52 clipboard access, and no clickable links. diff --git a/scripts/check-wayland-idle.py b/scripts/check-wayland-idle.py index 876f220..66ca4a4 100755 --- a/scripts/check-wayland-idle.py +++ b/scripts/check-wayland-idle.py @@ -15,6 +15,8 @@ import subprocess import tempfile import time +PROTOCOL_VERSION = 6 + parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", type=Path, default=Path("target/debug/psyterm")) args = parser.parse_args() @@ -70,13 +72,16 @@ def write_frame(stream, payload): stream.sendall(struct.pack(" before, "updated terminal paint without compositor input", timeout=2) assert gui.poll() is None, "GUI exited during redraw" diff --git a/src/bindings.rs b/src/bindings.rs index 7001b8f..1414897 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -14,6 +14,9 @@ pub fn action_for_key(key: &Keystroke) -> Option { }; if modifiers == window_modifiers { match name.as_str() { + "n" if modifiers.shift == cfg!(not(target_os = "macos")) => { + return Some(CommandAction::NewWindow); + } // GPUI may fold Shift into the symbol. On XKB the keypad keys // have separate "add" and "subtract" names. "+" | "=" | "add" => return Some(CommandAction::IncreaseFontSize), @@ -148,9 +151,16 @@ mod tests { } #[test] - fn text_size_shortcuts_use_platform_conventions() { + fn new_window_and_text_size_shortcuts_use_platform_conventions() { use CommandAction::*; + let new_window = if cfg!(target_os = "macos") { + "cmd-n" + } else { + "ctrl-shift-n" + }; + assert!(matches!(action(new_window), Some(NewWindow))); + assert!(action("ctrl-n").is_none()); for key in [ "secondary-+", "secondary-=", diff --git a/src/client.rs b/src/client.rs index 74ee6dc..2d6e550 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,15 +1,20 @@ //! Display-only client transport. No terminal parser, PTY, or shell lives here. -use crate::protocol::{self, ClientMessage, ServerMessage, Snapshot}; +use crate::protocol::{self, ClientMessage, ServerMessage, SessionTarget, Snapshot, SshOptions}; use anyhow::{Context, Result, bail}; use std::{ - collections::VecDeque, - io::{Read, Write}, + collections::{HashSet, VecDeque}, + io::{self, Read, Write}, net::Shutdown, - os::unix::net::UnixStream, - path::Path, - process::{Child, Command, Stdio}, - sync::{Arc, Mutex, mpsc}, + os::{fd::OwnedFd, unix::net::UnixStream}, + path::{Path, PathBuf}, + process::{Child, ChildStderr, Command, Stdio}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + mpsc, + }, thread, + time::{Duration, Instant}, }; #[derive(Default)] @@ -17,6 +22,7 @@ pub struct Update { pub snapshot: Option>, pub clipboard: VecDeque, pub error: Option, + pub disconnected: bool, } pub struct Updates { @@ -24,6 +30,11 @@ pub struct Updates { pending: Arc>, } impl Updates { + pub fn recv_blocking(&self) -> Option { + self.signal.recv_blocking().ok()?; + Some(std::mem::take(&mut *self.pending.lock().unwrap())) + } + pub async fn recv(&self) -> Option { self.signal.recv().await.ok()?; Some(std::mem::take(&mut *self.pending.lock().unwrap())) @@ -33,6 +44,8 @@ impl Updates { #[derive(Clone)] pub struct Client(Arc); struct Connection { + launcher_socket: PathBuf, + remote: Option, commands: mpsc::Sender, socket: Option, ssh: Mutex>, @@ -50,17 +63,86 @@ impl Drop for Connection { } } +impl SshOptions { + pub fn from_env() -> Self { + Self { + executable: std::env::var("PSYTERM_REMOTE_BIN").ok(), + agent_socket: std::env::var_os("SSH_AUTH_SOCK").map(PathBuf::from), + } + } +} + +pub fn validate_destination(destination: &str) -> Result<()> { + if destination.is_empty() + || destination.len() > 1024 + || destination.starts_with('-') + || destination + .chars() + .any(|c| c.is_control() || c.is_whitespace()) + { + bail!("invalid SSH destination"); + } + Ok(()) +} + impl Client { - pub fn connect(socket: &Path, remote: Option<&str>) -> Result<(Self, Updates)> { - let (reader, writer, socket, ssh): (Box, Box, _, _) = + pub fn connect( + launcher_socket: &Path, + remote: Option<&str>, + session: SessionTarget, + ) -> Result<(Self, Updates)> { + Self::connect_with( + launcher_socket, + remote, + session, + SshOptions::from_env(), + None, + ) + } + + pub fn connect_remote( + launcher_socket: &Path, + destination: &str, + session: SessionTarget, + ssh: SshOptions, + cancelled: Arc, + ) -> Result<(Self, Updates)> { + Self::connect_with( + launcher_socket, + Some(destination), + session, + ssh, + Some(cancelled), + ) + } + + fn connect_with( + launcher_socket: &Path, + remote: Option<&str>, + session: SessionTarget, + options: SshOptions, + cancelled: Option>, + ) -> Result<(Self, Updates)> { + let (mut reader, mut writer, socket, mut ssh): (_, Box, _, _) = if let Some(remote) = remote { - if remote.is_empty() || remote.starts_with('-') || remote.contains(['\n', '\r']) { - bail!("invalid SSH destination"); + validate_destination(remote)?; + let executable = options.executable.as_deref().unwrap_or("psyterm"); + let attach = if matches!(session, SessionTarget::Attach(_)) { + " --attach" + } else { + "" + }; + let remote_command = format!("exec {} --bridge{attach}", shell_quote(executable)); + let mut ssh_command = Command::new("ssh"); + if let Some(socket) = options.agent_socket { + ssh_command.env("SSH_AUTH_SOCK", socket); + } else { + ssh_command.env_remove("SSH_AUTH_SOCK"); } - let executable = - std::env::var("PSYTERM_REMOTE_BIN").unwrap_or_else(|_| "psyterm".into()); - let remote_command = format!("exec {} --bridge", shell_quote(&executable)); - let mut child = Command::new("ssh") + // A socketpair allows a bounded, cancellable greeting even when the + // SSH connection succeeds but the remote bridge stalls. + let (reader, stdout) = UnixStream::pair()?; + let mut child = ssh_command .args([ "-T", "-o", @@ -72,31 +154,52 @@ impl Client { &remote_command, ]) .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) + .stdout(Stdio::from(OwnedFd::from(stdout))) + .stderr(Stdio::piped()) .spawn() .context("start SSH terminal transport")?; - let reader = Box::new(child.stdout.take().unwrap()) as Box; let writer = Box::new(child.stdin.take().unwrap()) as Box; (reader, writer, None, Some(child)) } else { - let stream = UnixStream::connect(socket).context("connect to psyTerm server")?; + let stream = + UnixStream::connect(launcher_socket).context("connect to psyTerm server")?; crate::launcher::verify_peer(&stream)?; ( - Box::new(stream.try_clone()?) as Box, + stream.try_clone()?, Box::new(stream.try_clone()?) as Box, Some(stream), None, ) }; + let stderr = ssh.as_mut().and_then(|child| child.stderr.take()); let (commands, receive) = mpsc::channel(); let (signal, notifications) = async_channel::bounded(1); let pending = Arc::new(Mutex::new(Update::default())); let connection = Self(Arc::new(Connection { + launcher_socket: launcher_socket.to_owned(), + remote: remote.map(str::to_owned), commands, socket, ssh: Mutex::new(ssh), })); + let diagnostic = stderr.map(ssh_diagnostics).transpose()?; + reader.set_read_timeout(Some(Duration::from_millis(150)))?; + let mut greeting = GreetingReader { + reader: &mut reader, + deadline: Instant::now() + Duration::from_secs(if remote.is_some() { 30 } else { 5 }), + cancelled: cancelled.as_deref(), + }; + if let Err(error) = greet(&mut greeting, &mut writer, session) { + drop(connection); + if let Some(detail) = diagnostic + .and_then(|rx| rx.recv_timeout(Duration::from_millis(150)).ok()) + .filter(|s| !s.is_empty()) + { + bail!("{error:#}: {detail}"); + } + return Err(error); + } + reader.set_read_timeout(None)?; let errors = pending.clone(); let notify = signal.clone(); thread::Builder::new() @@ -116,24 +219,13 @@ impl Client { .name("psyterm-client-reader".into()) .spawn(move || { let mut reader = reader; - let mut greeted = false; loop { let message = protocol::read_message::(&mut reader); let mut update = incoming.lock().unwrap(); match message { - Ok(ServerMessage::Hello { version, .. }) - if version == protocol::VERSION => - { - greeted = true - } - Ok(ServerMessage::Hello { .. }) => { - update.error = - Some("Server protocol version differs from this GUI".into()); - let _ = signal.try_send(()); - break; - } - Ok(ServerMessage::Snapshot(snapshot)) if greeted => { + Ok(ServerMessage::Snapshot(snapshot)) => { if let Err(error) = validate_snapshot(&snapshot) { + update.disconnected = true; update.error = Some(error.to_string()); let _ = signal.try_send(()); break; @@ -141,13 +233,14 @@ impl Client { // A slow window never accumulates a queue of obsolete frames. update.snapshot = Some(Arc::new(snapshot)); } - Ok(ServerMessage::Clipboard(text)) if greeted => { + Ok(ServerMessage::Clipboard(text)) => { if update.clipboard.len() < 16 { update.clipboard.push_back(text); } } Ok(ServerMessage::Error(error)) => update.error = Some(error), Ok(ServerMessage::Closing) => { + update.disconnected = true; update.error = Some("Server stopped. Shell sessions have ended.".into()); let _ = signal.try_send(()); @@ -155,9 +248,11 @@ impl Client { } Ok(ServerMessage::Pong) => {} Ok(_) => { - update.error = Some("Server sent data before its handshake".into()); + update.error = + Some("Unexpected server response after session handshake".into()); } Err(error) => { + update.disconnected = true; update.error = Some(format!( "Disconnected — sessions remain on the server. {error:#}" )); @@ -169,10 +264,6 @@ impl Client { let _ = signal.try_send(()); } })?; - connection.send(ClientMessage::Hello { - version: protocol::VERSION, - })?; - connection.send(ClientMessage::Attach)?; Ok(( connection, Updates { @@ -182,6 +273,22 @@ impl Client { )) } + pub fn remote(&self) -> Option<&str> { + self.0.remote.as_deref() + } + + /// Launch through the local daemon even when this terminal connects over SSH. + pub fn open_window(&self, remote: Option, cwd: Option) -> Result<()> { + crate::launcher::control( + &self.0.launcher_socket, + ClientMessage::OpenWindow { + target: remote, + session: SessionTarget::New { cwd }, + }, + )?; + Ok(()) + } + pub fn send(&self, message: ClientMessage) -> Result<()> { self.0 .commands @@ -199,17 +306,150 @@ impl Client { } } +/// Drain SSH stderr throughout the connection. Keep a bounded tail to explain +/// startup failures in the invoking window as well as in the daemon log. +fn ssh_diagnostics(mut stderr: ChildStderr) -> io::Result> { + let (tx, rx) = mpsc::channel(); + thread::Builder::new() + .name("psyterm-ssh-stderr".into()) + .spawn(move || { + let mut tail = Vec::new(); + let mut buf = [0; 1024]; + while let Ok(n) = stderr.read(&mut buf) { + if n == 0 { + break; + } + let _ = io::stderr().write_all(&buf[..n]); + tail.extend_from_slice(&buf[..n]); + tail.drain(..tail.len().saturating_sub(1024)); + } + let detail = String::from_utf8_lossy(&tail); + let _ = tx.send( + detail + .trim() + .lines() + .next_back() + .unwrap_or_default() + .to_owned(), + ); + })?; + Ok(rx) +} + +struct GreetingReader<'a> { + reader: &'a mut UnixStream, + deadline: Instant, + cancelled: Option<&'a AtomicBool>, +} + +impl GreetingReader<'_> { + fn check(&self) -> io::Result<()> { + if self + .cancelled + .is_some_and(|flag| flag.load(Ordering::Acquire)) + { + return Err(io::Error::new( + io::ErrorKind::ConnectionAborted, + "connection cancelled", + )); + } + if Instant::now() >= self.deadline { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "timed out waiting for the psyTerm server", + )); + } + Ok(()) + } +} + +impl Read for GreetingReader<'_> { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + loop { + self.check()?; + match self.reader.read(buffer) { + Err(e) + if matches!( + e.kind(), + io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock + ) => {} + result => return result, + } + } + } +} + +fn greet( + reader: &mut GreetingReader<'_>, + writer: &mut impl Write, + session: SessionTarget, +) -> Result<()> { + reader.check()?; + protocol::write_message( + writer, + &ClientMessage::Hello { + version: protocol::VERSION, + }, + )?; + match protocol::read_message::(reader)? { + ServerMessage::Hello { version, .. } if version == protocol::VERSION => {} + ServerMessage::Error(error) => bail!("{error}"), + _ => bail!("server protocol differs from this client"), + } + reader.check()?; + protocol::write_message(writer, &ClientMessage::Connect(session))?; + match protocol::read_message::(reader)? { + ServerMessage::Connected { .. } => Ok(()), + ServerMessage::Error(error) => bail!("{error}"), + _ => bail!("server did not acknowledge the session"), + } +} + fn shell_quote(value: &str) -> String { format!("'{}'", value.replace('\'', "'\\''")) } fn validate_snapshot(snapshot: &Snapshot) -> Result<()> { - if snapshot.tabs.len() > 256 || snapshot.panes.len() > 64 { + if snapshot.tabs.len() > 256 || snapshot.lineage.len() > 256 || snapshot.panes.len() > 64 { bail!("Server layout exceeds client limits"); } + let mut tab_ids = HashSet::new(); + let mut pane_ids = HashSet::new(); + let mut expanded = HashSet::new(); + for tab in &snapshot.tabs { + if !tab_ids.insert(tab.id) { + bail!("Server sent a duplicate tab ID"); + } + if tab.is_connecting() { + continue; + } + let ordered = tab.stacks.iter().flat_map(|s| s.panes.iter().map(|p| p.id)); + if tab.panes.is_empty() + || tab.panes.len() > 64 + || !tab.panes.iter().all(|id| pane_ids.insert(*id)) + || ordered.ne(tab.panes.iter().copied()) + || !tab.stacks.iter().any(|s| s.active_pane == tab.active_pane) + { + bail!("Server sent an invalid tab layout"); + } + for stack in &tab.stacks { + if !stack.panes.iter().any(|p| p.id == stack.active_pane) { + bail!("Server sent an invalid pane stack"); + } + if tab.id == snapshot.active_tab { + expanded.insert(stack.active_pane); + } + } + } + if !(tab_ids.contains(&snapshot.active_tab) || (tab_ids.is_empty() && snapshot.active_tab == 0)) + { + bail!("Server sent an invalid active tab"); + } + for pane in &snapshot.panes { let count = usize::from(pane.columns) * usize::from(pane.lines); - if pane.columns < 2 + if !expanded.remove(&pane.id) + || pane.columns < 2 || pane.lines == 0 || count > 1_000_000 || pane.cells.len() != count @@ -223,8 +463,12 @@ fn validate_snapshot(snapshot: &Snapshot) -> Result<()> { } /// SSH starts this command on the remote host. Only framed protocol bytes use stdout. -pub fn bridge(socket: &Path) -> Result<()> { - crate::launcher::ensure_server(socket)?; +pub fn bridge(socket: &Path, attach: bool) -> Result<()> { + if attach { + crate::launcher::require_server(socket)?; + } else { + crate::launcher::ensure_server(socket)?; + } let stream = UnixStream::connect(socket)?; let mut output = stream.try_clone()?; let copy_input = thread::spawn(move || { @@ -282,6 +526,40 @@ mod tests { assert_eq!(output.bytes, b"binary-without-newlines"); assert!(output.flushes > 0); } + #[test] + fn stalled_bridge_can_be_cancelled_during_a_partial_greeting() { + let (mut socket, mut peer) = UnixStream::pair().unwrap(); + socket + .set_read_timeout(Some(Duration::from_millis(15))) + .unwrap(); + let cancelled = AtomicBool::new(false); + thread::scope(|threads| { + let (ready, start) = mpsc::channel(); + let (done, wait) = mpsc::channel::<()>(); + let flag = &cancelled; + threads.spawn(move || { + peer.write_all(&[8, 0]).unwrap(); + start.recv().unwrap(); + flag.store(true, Ordering::Release); + // Keep the peer open until the reader notices cancellation. + let _ = wait.recv(); + }); + let mut greeting = GreetingReader { + reader: &mut socket, + deadline: Instant::now() + Duration::from_secs(5), + cancelled: Some(&cancelled), + }; + let mut header = [0; 4]; + greeting.read_exact(&mut header[..2]).unwrap(); + ready.send(()).unwrap(); + assert_eq!( + greeting.read_exact(&mut header[2..]).unwrap_err().kind(), + io::ErrorKind::ConnectionAborted + ); + drop(done); + }); + } + #[test] fn remote_binary_paths_are_shell_quoted() { assert_eq!(shell_quote("/tmp/a'b; x"), "'/tmp/a'\\''b; x'"); diff --git a/src/commands.rs b/src/commands.rs index 8a56279..e965997 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -7,6 +7,7 @@ use crate::protocol::{ScrollKind, Snapshot}; #[derive(Clone, Debug)] pub enum CommandAction { TogglePalette, + NewWindow, NewTab, IncreaseFontSize, DecreaseFontSize, @@ -112,6 +113,13 @@ pub fn root_items(snapshot: Option<&Snapshot>) -> Vec { shortcut("Cmd+T", "Ctrl+Shift+T"), NewTab, ), + PaletteItem::action( + "new-window", + "New window", + "create independent terminal session", + shortcut("Cmd+N", "Ctrl+Shift+N"), + NewWindow, + ), PaletteItem::action( "split-pane", "Split pane right", diff --git a/src/launcher.rs b/src/launcher.rs index 17fc74d..1254f0f 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -105,6 +105,13 @@ pub fn control(socket: &Path, command: ClientMessage) -> Result { result } +pub fn require_server(socket: &Path) -> Result<()> { + if !probe_server(socket)? { + bail!("no sessions to attach to at {}", socket.display()); + } + Ok(()) +} + fn probe_server(socket: &Path) -> Result { match UnixStream::connect(socket) { Ok(stream) => { @@ -163,7 +170,9 @@ fn control_stream_version( loop { let message: ServerMessage = protocol::read_message(&mut stream)?; match message { - ServerMessage::Pong | ServerMessage::Closing => return Ok(message), + ServerMessage::Pong | ServerMessage::Closing | ServerMessage::Sessions(_) => { + return Ok(message); + } ServerMessage::Error(error) => bail!("{error}"), _ => {} } @@ -215,13 +224,29 @@ fn role_command(executable: &Path, role: &str, socket: &Path, log_path: &Path) - // AppKit needs a fresh process for a server-requested window on macOS. #[cfg(target_os = "macos")] -pub fn open_window(socket: &Path, remote: Option) -> Result<()> { +pub fn open_window( + socket: &Path, + remote: Option, + session: protocol::SessionTarget, +) -> Result<()> { let mut command = role_command( &executable_path()?, "--gui", socket, &suffixed(socket, ".gui.log"), )?; + match session { + protocol::SessionTarget::New { cwd: Some(cwd) } => { + command.arg("--cwd").arg(cwd); + } + protocol::SessionTarget::New { .. } => {} + protocol::SessionTarget::Attach(id) => { + command.arg("--attach"); + if let Some(id) = id { + command.arg(id.to_string()); + } + } + } if let Some(host) = remote { command.arg("--remote").arg(host); } diff --git a/src/launcher/zygote.rs b/src/launcher/zygote.rs index 4bcad75..e3b4fc0 100644 --- a/src/launcher/zygote.rs +++ b/src/launcher/zygote.rs @@ -75,7 +75,11 @@ impl Zygote { } } - pub fn open_window(&mut self, remote: Option) -> Result<()> { + pub fn open_window( + &mut self, + remote: Option, + session: protocol::SessionTarget, + ) -> Result<()> { let executable = executable_path()?; let identity = ExecutableIdentity::read(&executable)?; let helper_exited = self.child.try_wait()?.is_some(); @@ -89,6 +93,7 @@ impl Zygote { match self.request(&LaunchRequest::Launch { server_socket: self.server_socket.clone(), remote, + session, })? { LaunchResponse::Launched { pid } => { log::info!("Forked psyTerm GUI {pid} from zygote {}", self.child.id()); @@ -164,6 +169,7 @@ enum LaunchRequest { Launch { server_socket: PathBuf, remote: Option, + session: protocol::SessionTarget, }, Shutdown, } @@ -222,6 +228,7 @@ pub fn run_zygote(socket: &Path) -> Result<()> { LaunchRequest::Launch { server_socket, remote, + session, } => { if let Err(error) = ensure_single_threaded() { protocol::write_message( @@ -251,7 +258,7 @@ pub fn run_zygote(socket: &Path) -> Result<()> { drop(stream); drop(listener); let result = set_child_reaping(false) - .and_then(|()| crate::run_gui(server_socket, remote)); + .and_then(|()| crate::run_gui(server_socket, remote, session)); let code = if let Err(error) = result { log::error!("GUI startup failed: {error:#}"); 1 diff --git a/src/main.rs b/src/main.rs index c321984..239615c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,24 +19,33 @@ mod transition; use anyhow::{Result, bail}; use gpui::{prelude::*, *}; +use protocol::{SessionId, SessionTarget}; use std::path::PathBuf; #[cfg(target_os = "macos")] -gpui::actions!(psyterm, [Quit]); +gpui::actions!(psyterm, [Quit, NewWindow]); fn main() -> Result<()> { env_logger::init(); // AppKit runs in the process that LaunchServices opens. Linux uses a prefork helper. - let mut role = if cfg!(target_os = "macos") { - "gui" - } else { - "launch" - }; + let mut role = "launch"; let mut socket = None; let mut remote = None; - let mut args = std::env::args().skip(1); + let mut cwd = None; + let mut attach: Option> = None; + let mut args = std::env::args().skip(1).peekable(); while let Some(arg) = args.next() { match arg.as_str() { + "--attach" => { + let id = args + .next_if(|arg| !arg.starts_with('-')) + .map(|id| id.parse::()) + .transpose() + .map_err(|_| { + anyhow::anyhow!("--attach expects a numeric session ID from --list") + })?; + attach = Some(id); + } "--server" => role = "server", #[cfg(target_os = "linux")] "--zygote" => role = "zygote", @@ -44,6 +53,12 @@ fn main() -> Result<()> { "--bridge" => role = "bridge", "--shutdown" => role = "shutdown", "--list" => role = "list", + "--cwd" => { + cwd = Some( + args.next() + .ok_or_else(|| anyhow::anyhow!("--cwd needs a directory"))?, + ); + } "--socket" => { socket = Some(PathBuf::from( args.next() @@ -52,63 +67,116 @@ fn main() -> Result<()> { } "--remote" => { remote = Some( - args.next() + args.next_if(|arg| !arg.starts_with('-')) .ok_or_else(|| anyhow::anyhow!("--remote needs an SSH destination"))?, ) } "--help" | "-h" => { println!( - "psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a local terminal window\n psyterm --remote user@host Connect a local GUI to a server over SSH\n psyterm --list List server-owned tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Run the GUI in the current process\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n" + "psyTerm — server-owned terminals with a GPUI front end\n\n psyterm Open a new session in a new window\n psyterm --attach [ID] Join an existing session (prefer the latest detached session)\n psyterm --remote user@host Open an SSH session (an adjacent tab when run inside psyTerm)\n psyterm --list List local sessions, tabs and panes\n psyterm --shutdown Stop the local server and its shell sessions\n psyterm --socket PATH Use a separate local server\n psyterm --gui Run the GUI in the current process\n psyterm --server Run the server in the foreground\n psyterm --bridge Binary stdin/stdout transport used by SSH\n\nClosing a window detaches; tabs and shells keep running.\nSSH requires key/agent authentication and psyterm in the remote PATH.\nPSYTERM_REMOTE_BIN overrides the remote executable path.\n" ); return Ok(()); } _ => bail!("unknown argument: {arg}; see --help"), } } + if attach.is_some() && !matches!(role, "gui" | "launch" | "bridge") { + bail!("--attach applies to a window or an SSH bridge"); + } + #[cfg(target_os = "macos")] + if matches!(role, "launch" | "gui") + && unsafe { libc::getppid() } == 1 + && std::env::current_dir()? == std::path::Path::new("/") + && let Some(home) = std::env::home_dir() + { + // Finder launches the bundled process from the filesystem root. + std::env::set_current_dir(home)?; + } + let session = if let Some(id) = attach { + SessionTarget::Attach(id) + } else { + SessionTarget::New { + cwd: if cwd.is_some() { + cwd + } else if remote.is_none() && matches!(role, "gui" | "launch") { + std::env::current_dir()?.into_os_string().into_string().ok() + } else { + None + }, + } + }; + if role == "launch" + && let Some(destination) = &remote + && let Some(origin) = session::PaneContext::from_env()? + { + if let Some(explicit) = &socket + && explicit.canonicalize()? != origin.socket.canonicalize()? + { + bail!("--socket points outside the invoking psyTerm pane"); + } + launcher::control( + &origin.socket, + protocol::ClientMessage::OpenRemoteTab { + session: origin.session, + pane: origin.pane, + destination: destination.clone(), + target: session, + ssh: protocol::SshOptions::from_env(), + }, + )?; + return Ok(()); + } + let socket = socket.map(Ok).unwrap_or_else(launcher::default_socket)?; match role { #[cfg(target_os = "macos")] - "server" => server::run(&socket, |remote| launcher::open_window(&socket, remote)), + "server" => server::run(&socket, |remote, session| { + launcher::open_window(&socket, remote, session) + }), #[cfg(target_os = "linux")] "server" => { let zygote_socket = socket.clone(); let mut zygote: Option = None; - server::run(&socket, move |remote| { + server::run(&socket, move |remote, session| { if zygote.is_none() { zygote = Some(launcher::zygote::Zygote::start(&zygote_socket)?); } - zygote.as_mut().unwrap().open_window(remote) + zygote.as_mut().unwrap().open_window(remote, session) }) } #[cfg(target_os = "linux")] "zygote" => launcher::zygote::run_zygote(&socket), - "gui" => { - #[cfg(target_os = "macos")] - { - // LaunchServices starts Finder-launched apps in / with launchd as parent. - // Give that first shell a useful directory while preserving CLI launch paths. - // SAFETY: getppid has no preconditions. - if unsafe { libc::getppid() } == 1 - && std::env::current_dir()? == std::path::Path::new("/") - && let Some(home) = std::env::home_dir() - { - std::env::set_current_dir(home)?; - } + // Check remote attach synchronously so a failed SSH/session lookup reaches the CLI. + "gui" | "launch" + if cfg!(target_os = "macos") + || role == "gui" + || (remote.is_some() && attach.is_some()) => + { + if remote.is_none() && attach.is_some() { + launcher::require_server(&socket)?; + } else { + launcher::ensure_server(&socket)?; } - launcher::ensure_server(&socket)?; - run_gui(socket, remote) + run_gui(socket, remote, session) } - "bridge" => client::bridge(&socket), + "bridge" => client::bridge(&socket, attach.is_some()), "shutdown" => { launcher::control(&socket, protocol::ClientMessage::Shutdown)?; Ok(()) } "list" => list_sessions(&socket), _ => { - launcher::ensure_server(&socket)?; + if attach.is_some() { + launcher::require_server(&socket)?; + } else { + launcher::ensure_server(&socket)?; + } launcher::control( &socket, - protocol::ClientMessage::OpenWindow { target: remote }, + protocol::ClientMessage::OpenWindow { + target: remote, + session, + }, )?; Ok(()) } @@ -116,44 +184,34 @@ fn main() -> Result<()> { } fn list_sessions(socket: &std::path::Path) -> Result<()> { - let mut stream = std::os::unix::net::UnixStream::connect(socket)?; - launcher::verify_peer(&stream)?; - stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?; - protocol::write_message( - &mut stream, - &protocol::ClientMessage::Hello { - version: protocol::VERSION, - }, - )?; - let hello: protocol::ServerMessage = protocol::read_message(&mut stream)?; - println!("{hello:?}"); - protocol::write_message(&mut stream, &protocol::ClientMessage::List)?; - loop { - match protocol::read_message(&mut stream)? { - protocol::ServerMessage::Snapshot(snapshot) => { - for tab in snapshot.tabs { - println!("tab {} {} panes {:?}", tab.id, tab.title, tab.panes); - for (index, stack) in tab.stacks.iter().enumerate() { - println!( - " stack {} expanded {} panes {:?}", - index + 1, - stack.active_pane, - stack.panes.iter().map(|pane| pane.id).collect::>() - ); - } - } - break; + let response = launcher::control(socket, protocol::ClientMessage::ListSessions)?; + let protocol::ServerMessage::Sessions(sessions) = response else { + bail!("expected session list"); + }; + for session in sessions { + println!("session {} ({} attached)", session.id, session.attached); + for tab in session.tabs { + println!("tab {} {} panes {:?}", tab.id, tab.title, tab.panes); + for (index, stack) in tab.stacks.iter().enumerate() { + println!( + " stack {} expanded {} panes {:?}", + index + 1, + stack.active_pane, + stack.panes.iter().map(|pane| pane.id).collect::>() + ); } - protocol::ServerMessage::Error(error) => bail!("{error}"), - _ => {} } } Ok(()) } /// Initialize GPUI on the main thread of the GUI process. -pub(crate) fn run_gui(socket: PathBuf, remote: Option) -> Result<()> { - let (client, updates) = client::Client::connect(&socket, remote.as_deref())?; +pub(crate) fn run_gui( + socket: PathBuf, + remote: Option, + session: SessionTarget, +) -> Result<()> { + let (client, updates) = client::Client::connect(&socket, remote.as_deref(), session)?; let connection: SharedString = remote .map(|host| format!("SSH · {host}")) .unwrap_or_else(|| "Local".into()) @@ -162,11 +220,20 @@ pub(crate) fn run_gui(socket: PathBuf, remote: Option) -> Result<()> { #[cfg(target_os = "macos")] { cx.on_action(|_: &Quit, cx| cx.quit()); - cx.bind_keys([KeyBinding::new("cmd-q", Quit, None)]); - cx.set_menus(vec![Menu { - name: "psyTerm".into(), - items: vec![MenuItem::action("Quit psyTerm", Quit)], - }]); + cx.bind_keys([ + KeyBinding::new("cmd-q", Quit, None), + KeyBinding::new("cmd-n", NewWindow, None), + ]); + cx.set_menus(vec![ + Menu { + name: "psyTerm".into(), + items: vec![MenuItem::action("Quit psyTerm", Quit)], + }, + Menu { + name: "File".into(), + items: vec![MenuItem::action("New Window", NewWindow)], + }, + ]); } cx.on_window_closed(|cx| { if cx.windows().is_empty() { diff --git a/src/protocol.rs b/src/protocol.rs index c3b74a6..677620e 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -10,10 +10,37 @@ use anyhow::{Context, Result, bail}; use bincode::Options; use serde::{Deserialize, Serialize, de::DeserializeOwned}; -pub const VERSION: u32 = 4; +pub const VERSION: u32 = 6; pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024; pub type PaneId = u64; pub type TabId = u64; +pub type SessionId = u64; + +#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)] +pub struct SessionIdentity { + pub server: [u8; 16], + pub session: SessionId, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum SessionTarget { + New { cwd: Option }, + Attach(Option), +} + +/// SSH settings inherited from the shell that requested a remote tab. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct SshOptions { + pub executable: Option, + pub agent_socket: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SessionInfo { + pub id: SessionId, + pub attached: usize, + pub tabs: Vec, +} #[derive(Debug, Clone, Serialize, Deserialize)] // Keep variants append-only: the shutdown command can retire an older server. @@ -21,7 +48,7 @@ pub enum ClientMessage { Hello { version: u32, }, - Attach, + Connect(SessionTarget), Input { pane: PaneId, bytes: Vec, @@ -62,11 +89,12 @@ pub enum ClientMessage { }, OpenWindow { target: Option, + session: SessionTarget, }, Detach, Shutdown, Ping, - /// Read current layout without attaching or creating a shell. + /// Inspect the layout of the session this client has joined. List, /// A blank/absent name returns to program-title/CWD naming. RenamePane { @@ -101,6 +129,17 @@ pub enum ClientMessage { tab: TabId, name: Option, }, + ListSessions, + OpenRemoteTab { + session: SessionIdentity, + pane: PaneId, + destination: String, + target: SessionTarget, + ssh: SshOptions, + }, + ClosePendingTab { + tab: TabId, + }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -164,10 +203,14 @@ pub enum ServerMessage { Error(String), Pong, Closing, + Connected { session: SessionId }, + Sessions(Vec), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Snapshot { + /// This session and the other sessions contributing tabs to its layout. + pub lineage: Vec, pub revision: u64, pub tabs: Vec, pub active_tab: TabId, @@ -175,9 +218,17 @@ pub struct Snapshot { pub panes: Vec, } +impl Snapshot { + pub fn active_tab(&self) -> Option<&TabInfo> { + self.tabs.iter().find(|tab| tab.id == self.active_tab) + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TabInfo { pub id: TabId, + /// SSH destination for a tab mounted from another host. + pub remote: Option, /// Effective display name: manual override, then the selected pane's name. pub title: String, pub manual_title: Option, @@ -188,6 +239,15 @@ pub struct TabInfo { pub stacks: Vec, } +impl TabInfo { + pub fn is_connecting(&self) -> bool { + self.remote.is_some() + && self.panes.is_empty() + && self.stacks.is_empty() + && self.active_pane == 0 + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StackInfo { pub panes: Vec, diff --git a/src/server.rs b/src/server.rs index 60844b5..b67ecb7 100644 --- a/src/server.rs +++ b/src/server.rs @@ -2,9 +2,12 @@ //! //! A single actor serializes layout and terminal commands. PTY workers parse //! bytes independently; per-client writers keep only the newest unsent grid. +mod remote; + use std::{ - collections::{HashMap, VecDeque}, + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, fs::{self, File, OpenOptions}, + io::Read, os::{ fd::AsRawFd, unix::{ @@ -106,7 +109,7 @@ fn flatten_panes(tab: &mut TabInfo) { struct Client { authenticated: bool, - attached: bool, + session: Option, output: Arc, writer: JoinHandle<()>, } @@ -115,7 +118,8 @@ enum Action { Connected(u64, UnixStream), Command(u64, ClientMessage), Disconnected(u64), - Terminal(PaneId, Event), + Terminal(SessionId, PaneId, Event), + Remote(SessionId, u64, remote::RemoteEvent, mpsc::Sender<()>), } #[derive(Default)] @@ -176,13 +180,16 @@ impl Outbox { } /// Run the headless server. The caller handles platform-specific window launches. -pub fn run(socket: &Path, open_window: impl FnMut(Option) -> Result<()>) -> Result<()> { +pub fn run( + socket: &Path, + open_window: impl FnMut(Option, SessionTarget) -> Result<()>, +) -> Result<()> { run_with_shell(socket, open_window, None) } fn run_with_shell( socket: &Path, - mut open_window: impl FnMut(Option) -> Result<()>, + mut open_window: impl FnMut(Option, SessionTarget) -> Result<()>, shell: Option, ) -> Result<()> { let (_socket_guard, listener) = bind_socket(socket)?; @@ -221,16 +228,16 @@ fn run_with_shell( })?; // The listener is woken explicitly on shutdown; the accept thread exits once // the actor channel receiver is dropped. + let mut identity = [0; 16]; + File::open("/dev/urandom")?.read_exact(&mut identity)?; let mut actor = Server { + identity, + socket: std::path::absolute(socket)?, shell, - panes: HashMap::new(), - tabs: Vec::new(), - active_tab: 0, - next_id: 1, clients: HashMap::new(), + sessions: BTreeMap::new(), + next_session: 1, sender, - revision: 0, - dirty: false, last_frame: Instant::now() - FRAME_INTERVAL, last_cwd_refresh: Instant::now(), }; @@ -244,7 +251,7 @@ fn run_with_shell( let _ = client.writer.join(); } // Drop sessions while the daemon is alive so their PTYs/children are reaped. - actor.panes.clear(); + actor.sessions.clear(); let _ = UnixStream::connect(socket); let _ = accept.join(); result @@ -279,34 +286,48 @@ fn read_client(id: u64, mut stream: UnixStream, sender: mpsc::SyncSender } struct Server { + identity: [u8; 16], + socket: PathBuf, + shell: Option, + sessions: BTreeMap, + next_session: SessionId, + clients: HashMap, + sender: mpsc::SyncSender, + last_frame: Instant, + last_cwd_refresh: Instant, +} + +struct SessionState { + identity: SessionIdentity, + socket: PathBuf, + remotes: HashMap, + id: SessionId, + last_used: Instant, shell: Option, panes: HashMap, tabs: Vec, active_tab: TabId, next_id: u64, - clients: HashMap, sender: mpsc::SyncSender, revision: u64, dirty: bool, - last_frame: Instant, - last_cwd_refresh: Instant, } impl Server { fn run( &mut self, receiver: &mpsc::Receiver, - open_window: &mut impl FnMut(Option) -> Result<()>, + open_window: &mut impl FnMut(Option, SessionTarget) -> Result<()>, ) -> Result<()> { loop { let until_cwd = CWD_REFRESH_INTERVAL.saturating_sub(self.last_cwd_refresh.elapsed()); - let timeout = if self.dirty { + let timeout = if self.sessions.values().any(|session| session.dirty) { Some( FRAME_INTERVAL .saturating_sub(self.last_frame.elapsed()) .min(until_cwd), ) - } else if !self.panes.is_empty() { + } else if !self.sessions.is_empty() { Some(until_cwd) } else { None @@ -331,7 +352,18 @@ impl Server { } } Action::Disconnected(id) => self.remove_client(id), - Action::Terminal(pane, event) => self.terminal_event(pane, event), + Action::Terminal(session_id, pane, event) => { + if let Some(session) = self.sessions.get_mut(&session_id) { + session.terminal_event(pane, event); + if !session.is_live() { + self.remove_empty_session(session_id); + } + } + } + Action::Remote(id, remote, event, processed) => { + self.remote_event(id, remote, event); + let _ = processed.send(()); + } Action::Command(id, command) => { if matches!(command, ClientMessage::Shutdown) && self @@ -352,12 +384,29 @@ impl Server { } } if self.last_cwd_refresh.elapsed() >= CWD_REFRESH_INTERVAL { - self.refresh_directories(); + for session in self.sessions.values_mut() { + session.refresh_directories(); + } self.last_cwd_refresh = Instant::now(); } - if self.dirty && self.last_frame.elapsed() >= FRAME_INTERVAL { - self.publish(); - self.dirty = false; + if self.last_frame.elapsed() >= FRAME_INTERVAL + && self.sessions.values().any(|s| s.dirty) + { + for session in self.sessions.values_mut().filter(|session| session.dirty) { + let id = session.id; + let mut subscribers = self + .clients + .values() + .filter(|client| client.session == Some(id)) + .peekable(); + if subscribers.peek().is_some() { + let snapshot = Arc::new(session.snapshot()); + for client in subscribers { + client.output.snapshot(snapshot.clone()); + } + } + session.dirty = false; + } self.last_frame = Instant::now(); } } @@ -388,7 +437,7 @@ impl Server { id, Client { authenticated: false, - attached: false, + session: None, output, writer, }, @@ -399,15 +448,58 @@ impl Server { fn remove_client(&mut self, id: u64) { if let Some(client) = self.clients.remove(&id) { client.output.close(); + if let Some(id) = client.session { + if let Some(session) = self.sessions.get_mut(&id) { + session.last_used = Instant::now(); + } + self.remove_empty_session(id); + } } - // Deliberately retain every tab, pane, grid and child process. + } + + fn remove_empty_session(&mut self, id: SessionId) { + if self + .sessions + .get(&id) + .is_some_and(|session| !session.is_live()) + && !self + .clients + .values() + .any(|client| client.session == Some(id)) + { + self.sessions.remove(&id); + } + } + + fn attach_target(&self, requested: Option) -> Result { + if let Some(id) = requested { + ensure!( + self.sessions + .get(&id) + .is_some_and(|session| session.is_live()), + "no such session: {id}" + ); + return Ok(id); + } + self.sessions + .values() + .filter(|session| session.is_live()) + .max_by_key(|session| { + let detached = !self + .clients + .values() + .any(|client| client.session == Some(session.id)); + (detached, session.last_used, session.id) + }) + .map(|session| session.id) + .context("no sessions to attach to") } fn command( &mut self, id: u64, message: ClientMessage, - open_window: &mut impl FnMut(Option) -> Result<()>, + open_window: &mut impl FnMut(Option, SessionTarget) -> Result<()>, ) -> Result<()> { let Some(client) = self.clients.get_mut(&id) else { return Ok(()); @@ -427,28 +519,130 @@ impl Server { } ensure!(client.authenticated, "protocol handshake is required"); match message { - ClientMessage::Attach => { - client.attached = true; - if self.tabs.is_empty() { - self.new_tab(None)?; - } - // New attachment receives an authoritative snapshot immediately. - self.publish(); - self.last_frame = Instant::now(); - self.dirty = false; + ClientMessage::Connect(target) => { + ensure!(client.session.is_none(), "client already has a session"); + let session_id = match target { + SessionTarget::Attach(id) => self.attach_target(id)?, + SessionTarget::New { cwd } => { + let id = self.next_session; + self.next_session += 1; + let mut state = SessionState::new( + SessionIdentity { + server: self.identity, + session: id, + }, + self.socket.clone(), + self.shell.clone(), + self.sender.clone(), + ); + state.new_tab(cwd)?; + self.sessions.insert(id, state); + id + } + }; + let session = self.sessions.get_mut(&session_id).unwrap(); + session.last_used = Instant::now(); + let client = self.clients.get_mut(&id).unwrap(); + client.session = Some(session_id); + client.output.reliable(ServerMessage::Connected { + session: session_id, + }); + client.output.snapshot(Arc::new(session.snapshot())); } ClientMessage::Ping => client.output.reliable(ServerMessage::Pong), - ClientMessage::List => { - let snapshot = self.snapshot(); + ClientMessage::ListSessions => { + let sessions = self + .sessions + .values_mut() + .filter(|session| session.is_live()) + .map(|session| { + session.update_titles(); + SessionInfo { + id: session.id, + attached: self + .clients + .values() + .filter(|client| client.session == Some(session.id)) + .count(), + tabs: session.tabs.clone(), + } + }) + .collect(); self.clients[&id] .output - .reliable(ServerMessage::Snapshot(snapshot)); + .reliable(ServerMessage::Sessions(sessions)); } - ClientMessage::OpenWindow { target } => { - open_window(target)?; + ClientMessage::OpenRemoteTab { + session, + pane, + destination, + target, + ssh, + } => { + let state = self + .sessions + .get_mut(&session.session) + .filter(|state| state.identity == session) + .context("originating psyTerm session has ended")?; + state.open_remote(pane, destination, target, ssh)?; + client.output.reliable(ServerMessage::Pong); + } + ClientMessage::OpenWindow { + target, + mut session, + } => { + if target.is_none() + && let SessionTarget::Attach(requested) = session + { + session = SessionTarget::Attach(Some(self.attach_target(requested)?)); + } + open_window(target, session)?; self.clients[&id].output.reliable(ServerMessage::Pong); } ClientMessage::Detach => self.remove_client(id), + message => { + let session = self + .sessions + .get_mut(&client.session.context("join a session first")?) + .context("session has ended")?; + session.last_used = Instant::now(); + session.command(message, &client.output)?; + } + } + Ok(()) + } +} + +impl SessionState { + fn new( + identity: SessionIdentity, + socket: PathBuf, + shell: Option, + sender: mpsc::SyncSender, + ) -> Self { + Self { + id: identity.session, + identity, + socket, + remotes: HashMap::new(), + last_used: Instant::now(), + shell, + panes: HashMap::new(), + tabs: Vec::new(), + active_tab: 0, + next_id: 1, + sender, + revision: 0, + dirty: false, + } + } + + fn command(&mut self, message: ClientMessage, output: &Arc) -> Result<()> { + let Some(message) = self.route_command(message, output)? else { + return Ok(()); + }; + match message { + ClientMessage::List => output.reliable(ServerMessage::Snapshot(self.snapshot())), ClientMessage::Input { pane, bytes } => { ensure!(bytes.len() <= 1024 * 1024, "input exceeds one MiB"); let pane = self.pane_mut(pane)?; @@ -564,17 +758,13 @@ impl Server { self.dirty = true; } ClientMessage::Copy { pane } => { + // A copy always has exactly one reply, even when a pane exits + // before its request arrives. SSH mirrors preserve that order. let text = self - .pane_mut(pane)? - .session - .term - .lock() - .selection_to_string(); - if let Some(text) = text { - self.clients[&id] - .output - .reliable(ServerMessage::Clipboard(text)); - } + .panes + .get(&pane) + .and_then(|pane| pane.session.term.lock().selection_to_string()); + output.reliable(ServerMessage::Clipboard(text.unwrap_or_default())); } ClientMessage::NewTab { cwd } => { self.new_tab(cwd)?; @@ -632,13 +822,14 @@ impl Server { ClientMessage::CycleTab { forward } => self.cycle_tab(forward), ClientMessage::CyclePane { forward } => self.cycle_pane(forward)?, ClientMessage::FocusTab { tab } => { - ensure!(self.tabs.iter().any(|entry| entry.id == tab), "unknown tab"); - self.active_tab = tab; - self.dirty = true; + self.focus_tab(tab)?; } ClientMessage::FocusPane { pane } => { self.focus_pane(pane)?; } + ClientMessage::ClosePendingTab { tab } => { + self.cancel_pending_tab(tab)?; + } ClientMessage::ClosePane { pane } => { ensure!(self.remove_pane(pane), "unknown pane"); } @@ -656,7 +847,14 @@ impl Server { self.refresh_directories(); self.dirty = true; } - ClientMessage::Hello { .. } | ClientMessage::Shutdown => unreachable!(), + ClientMessage::Hello { .. } + | ClientMessage::Shutdown + | ClientMessage::Connect(_) + | ClientMessage::Ping + | ClientMessage::ListSessions + | ClientMessage::OpenWindow { .. } + | ClientMessage::OpenRemoteTab { .. } + | ClientMessage::Detach => anyhow::bail!("expected a session command"), } Ok(()) } @@ -691,6 +889,11 @@ impl Server { fn focus_pane(&mut self, pane: PaneId) -> Result<()> { let (tab_index, stack_index, _) = self.pane_position(pane)?; + let id = self.tabs[tab_index].id; + self.focus_tab(id)?; + if let Some((remote, original)) = self.remote_pane(pane) { + remote.send(ClientMessage::FocusPane { pane: original })?; + } let tab = &mut self.tabs[tab_index]; tab.stacks[stack_index].active_pane = pane; tab.active_pane = pane; @@ -724,14 +927,16 @@ impl Server { } else { (index + count - 1) % count }; - self.active_tab = self.tabs[next].id; - self.dirty = true; + let _ = self.focus_tab(self.tabs[next].id); } fn cycle_pane(&mut self, forward: bool) -> Result<()> { let Some(tab) = self.tabs.iter().find(|tab| tab.id == self.active_tab) else { return Ok(()); }; + if tab.stacks.is_empty() { + return Ok(()); + } let index = tab .stacks .iter() @@ -751,6 +956,12 @@ impl Server { return Ok(()); }; let pane = self.tabs[tab_index].active_pane; + if self.tabs[tab_index].stacks.is_empty() { + if matches!(direction, Direction::Left | Direction::Right) { + self.cycle_tab(direction == Direction::Right); + } + return Ok(()); + } match direction { Direction::Up => self.focus_stack_pane(pane, VerticalDirection::Up), Direction::Down => self.focus_stack_pane(pane, VerticalDirection::Down), @@ -815,6 +1026,9 @@ impl Server { // No terminal lock is held here. On Event::Exit the I/O thread has // drained output and will finish, so joining Session cleanup is safe. drop(removed); + if self.active_tab != 0 { + let _ = self.focus_tab(self.active_tab); + } true } @@ -848,13 +1062,18 @@ impl Server { .and_then(|path| fs::canonicalize(path).ok()) .or_else(|| std::env::current_dir().ok()) .unwrap_or_else(|| PathBuf::from("/")); - let (session, events) = if let Some(shell) = &self.shell { - Session::with_shell_and_directory(shell.clone(), directory)? - } else { - Session::in_directory(directory)? - }; let id = self.next_id; self.next_id += 1; + let context = crate::session::PaneContext { + socket: self.socket.clone(), + session: self.identity, + pane: id, + }; + let (session, events) = if let Some(shell) = &self.shell { + Session::with_shell_and_directory(shell.clone(), directory, Some(&context))? + } else { + Session::in_directory(directory, &context)? + }; let cwd = session .working_directory() .unwrap_or(initial_directory) @@ -871,11 +1090,15 @@ impl Server { }, ); let sender = self.sender.clone(); + let session_id = self.id; thread::Builder::new() .name(format!("psyterm-events-{id}")) .spawn(move || { while let Ok(event) = events.recv_blocking() { - if sender.send(Action::Terminal(id, event)).is_err() { + if sender + .send(Action::Terminal(session_id, id, event)) + .is_err() + { break; } } @@ -884,6 +1107,7 @@ impl Server { } fn new_tab(&mut self, cwd: Option) -> Result<()> { + ensure!(self.tabs.len() < 256, "a window supports at most 256 tabs"); let pane = self.new_pane(cwd)?; let id = self.next_id; self.next_id += 1; @@ -891,6 +1115,7 @@ impl Server { id, title: "Shell".into(), manual_title: None, + remote: None, panes: vec![pane], active_pane: pane, stacks: vec![single_pane_stack(pane)], @@ -946,9 +1171,11 @@ impl Server { self.dirty = true; } - fn snapshot(&mut self) -> Snapshot { - self.revision += 1; + fn update_titles(&mut self) { for tab in &mut self.tabs { + if tab.remote.is_some() { + continue; + } tab.title = tab .manual_title .clone() @@ -962,6 +1189,24 @@ impl Server { } } } + } + + fn snapshot(&mut self) -> Snapshot { + self.update_titles(); + self.revision += 1; + if let Some(remote) = self + .remotes + .values() + .find(|remote| remote.owns_tab(self.active_tab)) + { + return Snapshot { + revision: self.revision, + lineage: self.lineage(), + tabs: self.tabs.clone(), + active_tab: self.active_tab, + panes: remote.visible_panes(self.active_tab), + }; + } let visible = self .tabs .iter() @@ -1022,22 +1267,13 @@ impl Server { }) .collect(); Snapshot { + lineage: self.lineage(), revision: self.revision, tabs: self.tabs.clone(), active_tab: self.active_tab, panes, } } - - fn publish(&mut self) { - if !self.clients.values().any(|client| client.attached) { - return; - } - let snapshot = Arc::new(self.snapshot()); - for client in self.clients.values().filter(|client| client.attached) { - client.output.snapshot(snapshot.clone()); - } - } } struct SocketGuard { @@ -1098,12 +1334,12 @@ mod tests { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_TEST: AtomicU64 = AtomicU64::new(1); - struct TestServer { - socket: PathBuf, + pub(super) struct TestServer { + pub(super) socket: PathBuf, thread: Option>>, } impl TestServer { - fn start() -> Self { + pub(super) fn start() -> Self { let directory = std::env::temp_dir().join(format!( "pt-s-{:x}-{:x}", std::process::id(), @@ -1116,7 +1352,7 @@ mod tests { let thread = thread::spawn(move || { run_with_shell( &address, - |_| Ok(()), + |_, _| Ok(()), Some(Shell::new("/bin/sh".into(), Vec::new())), ) }); @@ -1188,11 +1424,110 @@ mod tests { }) } + #[test] + fn new_sessions_isolate_live_shells_and_attach_selects_only_existing_work() { + let server = TestServer::start(); + let mut control = server.client(); + send( + &mut control, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); + assert!( + matches!(protocol::read_message::(&mut control).unwrap(), + ServerMessage::Error(message) if message.contains("no sessions")) + ); + + fn join(server: &TestServer, target: SessionTarget) -> (UnixStream, SessionId, Snapshot) { + let mut client = server.client(); + send(&mut client, ClientMessage::Connect(target)); + let ServerMessage::Connected { session } = + protocol::read_message::(&mut client).unwrap() + else { + panic!("session handshake failed"); + }; + let snapshot = snapshot(&mut client, |s| !s.tabs.is_empty()); + (client, session, snapshot) + } + let (mut first, first_id, a) = join(&server, SessionTarget::New { cwd: None }); + input(&mut first, a.panes[0].id, "printf 'FIRST_%s\n' SESSION\n"); + snapshot(&mut first, |s| contains(s, "FIRST_SESSION")); + send(&mut first, ClientMessage::NewTab { cwd: None }); + snapshot(&mut first, |s| s.tabs.len() == 2); + let (mut second, second_id, b) = join(&server, SessionTarget::New { cwd: None }); + assert_ne!(first_id, second_id); + assert_eq!(b.tabs.len(), 1); + assert!(!contains(&b, "FIRST_SESSION")); + input(&mut second, b.panes[0].id, "printf 'SECOND_%s\n' SESSION\n"); + snapshot(&mut second, |s| contains(s, "SECOND_SESSION")); + + let list = |control: &mut UnixStream| { + send(control, ClientMessage::ListSessions); + match protocol::read_message::(control).unwrap() { + ServerMessage::Sessions(list) => list, + msg => panic!("unexpected list response {msg:?}"), + } + }; + let listed = list(&mut control); + assert_eq!( + listed + .iter() + .map(|s| (s.id, s.tabs.len(), s.attached)) + .collect::>(), + [(first_id, 2, 1), (second_id, 1, 1)] + ); + + let (mut mirror, recent_id, _) = join(&server, SessionTarget::Attach(None)); + assert_eq!(recent_id, second_id); + send(&mut first, ClientMessage::Detach); + // EOF confirms the server applied the detach before selecting again. + while protocol::read_message::(&mut first).is_ok() {} + let (mut resumed, resumed_id, snapshot) = join(&server, SessionTarget::Attach(None)); + assert_eq!((resumed_id, snapshot.tabs.len()), (first_id, 2)); + send(&mut resumed, ClientMessage::FocusTab { tab: a.active_tab }); + let restored = list_after_commands(&mut resumed); + assert!(contains(&restored, "FIRST_SESSION")); + assert!(!contains(&restored, "SECOND_SESSION")); + let (_, named_id, named) = join(&server, SessionTarget::Attach(Some(second_id))); + assert_eq!(named_id, second_id); + assert!(contains(&named, "SECOND_SESSION")); + send( + &mut control, + ClientMessage::Connect(SessionTarget::Attach(Some(999))), + ); + assert!( + matches!(protocol::read_message::(&mut control).unwrap(), + ServerMessage::Error(message) if message.contains("no such session")) + ); + + send( + &mut mirror, + ClientMessage::ClosePane { + pane: b.panes[0].id, + }, + ); + list_after_commands(&mut mirror); + assert_eq!( + list(&mut control).iter().map(|s| s.id).collect::>(), + [first_id] + ); + send( + &mut control, + ClientMessage::Connect(SessionTarget::Attach(Some(second_id))), + ); + assert!( + matches!(protocol::read_message::(&mut control).unwrap(), + ServerMessage::Error(message) if message.contains("no such session")) + ); + } + #[test] fn detached_client_keeps_shell_and_grid_and_server_owns_layout() { let server = TestServer::start(); let mut first = server.client(); - send(&mut first, ClientMessage::Attach); + send( + &mut first, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let initial = snapshot(&mut first, |snapshot| snapshot.panes.len() == 1); let pane = initial.panes[0].id; let tab = initial.active_tab; @@ -1210,7 +1545,10 @@ mod tests { drop(first); let mut second = server.client(); - send(&mut second, ClientMessage::Attach); + send( + &mut second, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); let reattached = snapshot(&mut second, |snapshot| contains(snapshot, "READY_STATE")); assert_eq!(reattached.active_tab, tab); assert_eq!(reattached.panes[0].id, pane); @@ -1291,16 +1629,25 @@ mod tests { protocol::read_message::(&mut client).unwrap(), ServerMessage::Pong )); - send(&mut client, ClientMessage::OpenWindow { target: None }); + send( + &mut client, + ClientMessage::OpenWindow { + target: None, + session: SessionTarget::New { cwd: None }, + }, + ); assert!(matches!( protocol::read_message::(&mut client).unwrap(), ServerMessage::Pong )); - send(&mut client, ClientMessage::List); - let empty = snapshot(&mut client, |_| true); - assert!(empty.tabs.is_empty()); - assert!(empty.panes.is_empty()); - send(&mut client, ClientMessage::Attach); + send(&mut client, ClientMessage::ListSessions); + assert!( + matches!(protocol::read_message::(&mut client).unwrap(), ServerMessage::Sessions(sessions) if sessions.is_empty()) + ); + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let state = snapshot(&mut client, |snapshot| !snapshot.panes.is_empty()); send( &mut client, @@ -1343,35 +1690,33 @@ mod tests { } fn list_after_commands(client: &mut UnixStream) -> Snapshot { - // A round trip separates older queued snapshots from this inspection. + // The reliable List reply precedes Pong. Previous unsolicited snapshots + // already in flight are superseded by the explicit inspection. + send(client, ClientMessage::List); send(client, ClientMessage::Ping); + let mut inspected = None; loop { - match protocol::read_message::(client).unwrap() { - ServerMessage::Pong => break, + match protocol::read_message(client).unwrap() { + ServerMessage::Snapshot(snapshot) => inspected = Some(snapshot), + ServerMessage::Pong => return inspected.unwrap(), ServerMessage::Error(error) => panic!("server error: {error}"), _ => {} } } - send(client, ClientMessage::List); - snapshot(client, |_| true) } #[test] fn collapsed_output_rearms_wakeups_without_publishing_unchanged_grids() { let (sender, receiver) = mpsc::sync_channel(1024); - let mut actor = Server { - shell: Some(Shell::new("/bin/sh".into(), Vec::new())), - panes: HashMap::new(), - tabs: Vec::new(), - active_tab: 0, - next_id: 1, - clients: HashMap::new(), + let mut actor = SessionState::new( + SessionIdentity { + server: [1; 16], + session: 1, + }, + PathBuf::from("/tmp/psyterm-test-unused"), + Some(Shell::new("/bin/sh".into(), Vec::new())), sender, - revision: 0, - dirty: false, - last_frame: Instant::now(), - last_cwd_refresh: Instant::now(), - }; + ); actor.new_tab(None).unwrap(); let hidden = actor.tabs[0].active_pane; let visible = actor.new_pane(None).unwrap(); @@ -1386,7 +1731,7 @@ mod tests { // Drive actual PTY/parser events directly so absence of a publish is // tested through its dirty flag, without timing-dependent socket gaps. - let output = |actor: &mut Server, suffix: &str, expect_dirty: bool| { + let output = |actor: &mut SessionState, suffix: &str, expect_dirty: bool| { actor.panes[&hidden] .session .write(format!("printf 'HIDDEN_%s\\n' '{suffix}'\n").into_bytes()); @@ -1396,7 +1741,7 @@ mod tests { let event = receiver .recv_timeout(deadline.saturating_duration_since(Instant::now())) .unwrap(); - if let Action::Terminal(id, event) = event { + if let Action::Terminal(_, id, event) = event { let target_wakeup = id == hidden && matches!(event, Event::Wakeup); actor.dirty = false; actor.terminal_event(id, event); @@ -1431,7 +1776,10 @@ mod tests { fn stacks_insert_in_both_directions_and_only_expand_one_grid() { let server = TestServer::start(); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let first = initial.panes[0].id; input( @@ -1520,14 +1868,14 @@ mod tests { #[test] fn relative_commands_preserve_bursts_without_intermediate_snapshots() { let server = TestServer::start(); - // A control client does not attach, so the only snapshots are the - // explicit List responses after each complete command burst. let mut client = server.client(); - let inspect = |client: &mut UnixStream| { - send(client, ClientMessage::List); - snapshot(client, |_| true) - }; - for _ in 0..3 { + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); + snapshot(&mut client, |s| s.tabs.len() == 1); + let inspect = list_after_commands; + for _ in 0..2 { send(&mut client, ClientMessage::NewTab { cwd: None }); } let initial = inspect(&mut client); @@ -1613,7 +1961,10 @@ mod tests { fn horizontal_navigation_moves_between_columns_and_then_tabs() { let server = TestServer::start(); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let first = initial.panes[0].id; let first_tab = initial.active_tab; @@ -1693,7 +2044,10 @@ mod tests { fn stack_state_and_collapsed_shells_survive_clients_and_exit_cleanly() { let server = TestServer::start(); let mut first_client = server.client(); - send(&mut first_client, ClientMessage::Attach); + send( + &mut first_client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let initial = snapshot(&mut first_client, |s| s.panes.len() == 1); let top = initial.panes[0].id; send( @@ -1717,7 +2071,10 @@ mod tests { let three = snapshot(&mut first_client, |s| active_tab(s).panes.len() == 3); let bottom = active_tab(&three).active_pane; let mut other_client = server.client(); - send(&mut other_client, ClientMessage::Attach); + send( + &mut other_client, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); let mirrored = snapshot(&mut other_client, |s| active_tab(s).panes.len() == 3); assert_eq!(active_tab(&mirrored).panes, [top, middle, bottom]); send(&mut other_client, ClientMessage::FocusPane { pane: middle }); @@ -1728,7 +2085,10 @@ mod tests { drop(first_client); drop(other_client); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); let reattached = snapshot(&mut client, |s| active_tab(s).panes.len() == 3); assert_eq!(reattached.active_tab, initial.active_tab); assert_eq!(active_tab(&reattached).stacks[0].active_pane, middle); @@ -1764,7 +2124,10 @@ mod tests { fn natural_shell_exit_removes_panes_and_empty_tabs_without_stealing_focus() { let server = TestServer::start(); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let original = initial.panes[0].id; let original_tab = initial.active_tab; @@ -1818,7 +2181,10 @@ mod tests { fn exiting_active_tab_selects_the_adjacent_surviving_tab() { let server = TestServer::start(); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); snapshot(&mut client, |s| s.tabs.len() == 1); send(&mut client, ClientMessage::NewTab { cwd: None }); let middle = snapshot(&mut client, |s| s.tabs.len() == 2); @@ -1846,11 +2212,10 @@ mod tests { let mut client = server.client(); send( &mut client, - ClientMessage::NewTab { + ClientMessage::Connect(SessionTarget::New { cwd: Some(first_dir.to_string_lossy().into_owned()), - }, + }), ); - send(&mut client, ClientMessage::Attach); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let pane = initial.panes[0].id; assert_eq!(initial.panes[0].title, first_dir.to_string_lossy()); @@ -1879,7 +2244,10 @@ mod tests { send(&mut client, ClientMessage::Detach); drop(client); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); let reattached = snapshot(&mut client, |s| !s.panes.is_empty()); assert_eq!(reattached.panes[0].manual_title.as_deref(), Some("My work")); assert_eq!(reattached.panes[0].title, "My work"); @@ -1932,7 +2300,10 @@ mod tests { fn manual_tab_names_override_selected_panes_and_survive_clients_and_exit() { let server = TestServer::start(); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::New { cwd: None }), + ); let initial = snapshot(&mut client, |s| s.panes.len() == 1); let tab = initial.active_tab; let first = initial.panes[0].id; @@ -1988,6 +2359,11 @@ mod tests { // An independent client can rename an inactive tab without stealing // focus. All attached views receive the server's name immediately. let mut other = server.client(); + send( + &mut other, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); + snapshot(&mut other, |s| s.tabs.len() == 2); send( &mut other, ClientMessage::RenameTab { @@ -2004,7 +2380,10 @@ mod tests { send(&mut client, ClientMessage::Detach); drop(client); let mut client = server.client(); - send(&mut client, ClientMessage::Attach); + send( + &mut client, + ClientMessage::Connect(SessionTarget::Attach(None)), + ); let reattached = snapshot(&mut client, |s| s.tabs.len() == 2); let saved = reattached .tabs @@ -2078,9 +2457,10 @@ mod tests { #[test] fn slow_client_retains_only_latest_snapshot() { - let output = Outbox::default(); + let output = Arc::new(Outbox::default()); for revision in 1..=1000 { output.snapshot(Arc::new(Snapshot { + lineage: Vec::new(), revision, tabs: Vec::new(), active_tab: 0, diff --git a/src/server/remote.rs b/src/server/remote.rs new file mode 100644 index 0000000..9df6c47 --- /dev/null +++ b/src/server/remote.rs @@ -0,0 +1,743 @@ +//! 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), +} + +pub(super) struct RemoteSession { + destination: String, + anchor: TabId, + slot: TabId, + cancelled: Arc, + connection: Option, + // Remote IDs map to stable IDs allocated from the parent session's pool. + tabs: HashMap, + panes: HashMap, + latest: Option>, + requested_tab: Option, + clipboard: VecDeque<(PaneId, Weak)>, +} + +impl Drop for RemoteSession { + fn drop(&mut self) { + self.cancelled.store(true, Ordering::Release); + self.cancel_copies(); + } +} + +fn original(ids: &HashMap, local: u64) -> Option { + ids.iter() + .find_map(|(&remote, &id)| (id == local).then_some(remote)) +} + +fn mapped(ids: &mut HashMap, remote: u64, next: &mut u64) -> u64 { + *ids.entry(remote).or_insert_with(|| { + let id = *next; + *next += 1; + id + }) +} + +impl RemoteSession { + pub(super) fn owns_tab(&self, local: TabId) -> bool { + (self.latest.is_none() && self.slot == local) || original(&self.tabs, local).is_some() + } + + pub(super) fn send(&self, command: ClientMessage) -> Result<()> { + self.connection + .as_ref() + .context("SSH session is connecting")? + .send(command) + } + + // Keep one copy in flight on this connection. An attached session can + // contain multiple SSH hosts whose clipboard replies arrive out of order. + fn copy(&mut self, pane: PaneId, output: &Arc) -> Result<()> { + if self.clipboard.len() >= 16 { + output.reliable(ServerMessage::Clipboard(String::new())); + anyhow::bail!("too many pending clipboard requests"); + } + self.clipboard.push_back((pane, Arc::downgrade(output))); + if self.clipboard.len() == 1 { + self.send_next_copy()?; + } + Ok(()) + } + + fn finish_copy(&mut self, text: String) -> Result<()> { + if let Some((_, output)) = self.clipboard.pop_front() + && let Some(output) = output.upgrade() + { + output.reliable(ServerMessage::Clipboard(text)); + } + self.send_next_copy() + } + + fn send_next_copy(&mut self) -> Result<()> { + if let Some(&(pane, _)) = self.clipboard.front() + && let Err(error) = self.send(ClientMessage::Copy { pane }) + { + self.cancel_copies(); + return Err(error); + } + Ok(()) + } + + fn cancel_copies(&mut self) { + for (_, output) in self.clipboard.drain(..) { + if let Some(output) = output.upgrade() { + output.reliable(ServerMessage::Clipboard(String::new())); + } + } + } + + pub(super) fn visible_panes(&self, local: TabId) -> Vec { + self.latest + .as_ref() + .filter(|s| self.tabs.get(&s.active_tab) == Some(&local)) + .map(|s| { + s.panes + .iter() + .filter_map(|pane| { + let mut copy = pane.clone(); + copy.id = *self.panes.get(&pane.id)?; + Some(copy) + }) + .collect() + }) + .unwrap_or_default() + } + + /// Reconcile a whole remote session, including other tabs that may already + /// exist when explicitly attaching. Only the active remote tab has grids. + fn apply( + &mut self, + snapshot: Arc, + tabs: &mut Vec, + active: &mut TabId, + next: &mut u64, + ) -> Result { + let first = self.latest.is_none(); + let selected = self.owns_tab(*active); + if self.latest.as_ref().is_some_and(|old| { + old.tabs == snapshot.tabs + && old.active_tab == snapshot.active_tab + && old.lineage == snapshot.lineage + }) { + if self.requested_tab == Some(snapshot.active_tab) { + self.requested_tab = None; + } + self.latest = Some(snapshot); + return Ok(selected); + } + let index = tabs + .iter() + .position(|tab| self.owns_tab(tab.id)) + .context("SSH tab has closed")?; + let previous_count = if first { 1 } else { self.tabs.len() }; + ensure!( + tabs.len() - previous_count + snapshot.tabs.len() <= 256, + "a window supports at most 256 tabs" + ); + let mut new_tab_ids = self.tabs.clone(); + let mut new_pane_ids = self.panes.clone(); + new_tab_ids.retain(|id, _| snapshot.tabs.iter().any(|tab| tab.id == *id)); + new_pane_ids.retain(|id, _| snapshot.tabs.iter().any(|tab| tab.panes.contains(id))); + if first && !snapshot.tabs.is_empty() { + new_tab_ids.insert(snapshot.active_tab, self.slot); + } + let mut mapped_tabs = snapshot.tabs.clone(); + for tab in &mut mapped_tabs { + tab.id = mapped(&mut new_tab_ids, tab.id, next); + if tab.remote.is_none() { + tab.remote = Some(self.destination.clone()); + } + for pane in &mut tab.panes { + *pane = mapped(&mut new_pane_ids, *pane, next); + } + if tab.panes.is_empty() { + continue; // Nested SSH connection still establishing its first shell. + } + tab.active_pane = *new_pane_ids + .get(&tab.active_pane) + .context("invalid active SSH pane")?; + for stack in &mut tab.stacks { + stack.active_pane = *new_pane_ids + .get(&stack.active_pane) + .context("invalid SSH stack")?; + for pane in &mut stack.panes { + pane.id = *new_pane_ids.get(&pane.id).context("invalid SSH pane")?; + } + } + } + let remote_active = if snapshot.tabs.is_empty() { + 0 + } else { + *new_tab_ids + .get(&snapshot.active_tab) + .context("invalid active SSH tab")? + }; + self.tabs = new_tab_ids; + self.panes = new_pane_ids; + let changed = tabs[index..index + previous_count] != mapped_tabs; + if changed { + tabs.splice(index..index + previous_count, mapped_tabs); + } + if !snapshot.tabs.is_empty() { + // Ignore intermediate focus acknowledgements when a user cycles + // tabs several times before an SSH round trip finishes. + if self + .requested_tab + .is_some_and(|id| id == snapshot.active_tab || !self.tabs.contains_key(&id)) + { + self.requested_tab = None; + } + if selected && self.requested_tab.is_none() { + *active = remote_active; + } + } else if selected { + *active = tabs + .get(index.min(tabs.len().saturating_sub(1))) + .map_or(0, |tab| tab.id); + } + let ancestry_changed = self + .latest + .as_ref() + .is_none_or(|old| old.lineage != snapshot.lineage); + self.latest = Some(snapshot); + Ok(changed || selected || first || ancestry_changed) + } +} + +impl SessionState { + /// Propagate identities through nested SSH connections. This also catches + /// a user attaching a localhost SSH tab to its own parent session. + pub(super) fn lineage(&self) -> Vec { + let descendants = self + .remotes + .values() + .filter_map(|remote| remote.latest.as_ref()) + .flat_map(|snapshot| snapshot.lineage.iter().copied()) + .collect::>(); + 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::>() + .len(); + ensure!(count < 256, "too many nested SSH sessions"); + Ok(()) + } + pub(super) fn is_live(&self) -> bool { + !self.tabs.is_empty() || !self.remotes.is_empty() + } + + pub(super) fn open_remote( + &mut self, + pane: PaneId, + destination: String, + target: SessionTarget, + ssh: SshOptions, + ) -> Result<()> { + crate::client::validate_destination(&destination)?; + ensure!( + self.panes.contains_key(&pane), + "originating shell has ended" + ); + ensure!( + self.remotes.len() < MAX_PANES && self.tabs.len() < 256, + "too many SSH sessions or tabs" + ); + let (index, _, _) = self.pane_position(pane)?; + let group = self.next_id; + self.next_id += 1; + let socket = self.socket.clone(); + let session = self.id; + let sender = self.sender.clone(); + let dest = destination.clone(); + let cancelled = Arc::new(AtomicBool::new(false)); + let worker_cancelled = cancelled.clone(); + thread::Builder::new() + .name("psyterm-remote-tab".into()) + .spawn(move || { + // Permit one outstanding actor update per connection. The + // transport coalesces newer grids while the actor is busy. + let notify = |event| { + let (ack, processed) = mpsc::channel(); + sender + .send(Action::Remote(session, group, event, ack)) + .is_ok() + && processed.recv().is_ok() + }; + match Transport::connect_remote(&socket, &dest, target, ssh, worker_cancelled) { + Ok((client, updates)) => { + // Ownership of the transport moves to the server actor so + // dropping a mirror also tears down its SSH child/reader. + if !notify(RemoteEvent::Connected(client)) { + return; + } + while let Some(update) = updates.recv_blocking() { + let closed = update.disconnected; + if !notify(RemoteEvent::Updated(update)) || closed { + return; + } + } + notify(RemoteEvent::Ended(None)); + } + Err(error) => { + notify(RemoteEvent::Ended(Some(format!( + "Could not connect to {dest}: {error:#}" + )))); + } + } + })?; + self.insert_remote_slot(index, group, destination, cancelled); + Ok(()) + } + + fn insert_remote_slot( + &mut self, + index: usize, + group: u64, + destination: String, + cancelled: Arc, + ) { + let anchor = self.tabs[index].id; + self.tabs.insert( + index + 1, + TabInfo { + id: group, + title: "Connecting…".into(), + remote: Some(destination.clone()), + manual_title: None, + panes: Vec::new(), + active_pane: 0, + stacks: Vec::new(), + }, + ); + if self.active_tab == anchor { + self.active_tab = group; + } + self.dirty = true; + self.remotes.insert( + group, + RemoteSession { + destination, + anchor, + slot: group, + cancelled, + connection: None, + tabs: HashMap::new(), + panes: HashMap::new(), + latest: None, + requested_tab: None, + clipboard: VecDeque::new(), + }, + ); + } + + pub(super) fn cancel_pending_tab(&mut self, tab: TabId) -> Result<()> { + if self + .remotes + .get(&tab) + .is_some_and(|remote| remote.latest.is_none()) + { + self.remove_remote(tab); + return Ok(()); + } + if let Some((remote, id)) = self + .remotes + .values() + .find_map(|remote| original(&remote.tabs, tab).map(|id| (remote, id))) + { + return remote.send(ClientMessage::ClosePendingTab { tab: id }); + } + anyhow::bail!("SSH tab is no longer connecting") + } + + fn remove_remote(&mut self, group: u64) { + let Some(remote) = self.remotes.remove(&group) else { + return; + }; + let index = self + .tabs + .iter() + .position(|tab| remote.owns_tab(tab.id)) + .unwrap_or(0); + self.tabs.retain(|tab| !remote.owns_tab(tab.id)); + if remote.owns_tab(self.active_tab) { + self.active_tab = self + .tabs + .iter() + .find(|tab| remote.latest.is_none() && tab.id == remote.anchor) + .or_else(|| self.tabs.get(index.min(self.tabs.len().saturating_sub(1)))) + .map_or(0, |tab| tab.id); + } + if self.active_tab != 0 { + let _ = self.focus_tab(self.active_tab); + } + self.dirty = true; + } + + pub(super) fn focus_tab(&mut self, tab: TabId) -> Result<()> { + ensure!(self.tabs.iter().any(|entry| entry.id == tab), "unknown tab"); + if let Some((remote, original)) = self + .remotes + .values_mut() + .find_map(|remote| original(&remote.tabs, tab).map(|id| (remote, id))) + && (remote.requested_tab.is_some() + || remote + .latest + .as_ref() + .is_none_or(|s| s.active_tab != original)) + { + remote.send(ClientMessage::FocusTab { tab: original })?; + remote.requested_tab = Some(original); + } + self.active_tab = tab; + self.dirty = true; + Ok(()) + } + + pub(super) fn remote_pane(&mut self, pane: PaneId) -> Option<(&mut RemoteSession, PaneId)> { + self.remotes + .values_mut() + .find_map(|remote| original(&remote.panes, pane).map(|id| (remote, id))) + } + + /// Absolute pane actions use the pane's owner even if an older frame is + /// being acted on. Relative navigation is resolved in the mixed tab order. + pub(super) fn route_command( + &mut self, + mut command: ClientMessage, + output: &Arc, + ) -> Result> { + use ClientMessage::*; + let remote = match &mut command { + RenameTab { tab, .. } => self.remotes.values_mut().find_map(|remote| { + *tab = original(&remote.tabs, *tab)?; + Some(remote) + }), + NewStackPane { pane, .. } => { + let Some(local) = (*pane).or_else(|| { + self.tabs + .iter() + .find(|t| t.id == self.active_tab) + .map(|t| t.active_pane) + }) else { + return Ok(Some(command)); + }; + self.remote_pane(local).map(|(remote, original)| { + *pane = Some(original); + remote + }) + } + Input { pane, .. } + | Resize { pane, .. } + | Selection { pane, .. } + | Copy { pane } + | Scroll { pane, .. } + | Split { pane, .. } + | ClosePane { pane } + | RenamePane { pane, .. } => self.remote_pane(*pane).map(|(remote, original)| { + *pane = original; + remote + }), + _ => None, + }; + let Some(remote) = remote else { + return Ok(Some(command)); + }; + if let Copy { pane } = command { + remote.copy(pane, output)?; + } else { + remote.send(command)?; + } + Ok(None) + } +} + +impl Server { + pub(super) fn remote_event(&mut self, session: SessionId, group: u64, event: RemoteEvent) { + let Some(state) = self.sessions.get_mut(&session) else { + return; + }; + if let RemoteEvent::Updated(update) = &event + && let Some(snapshot) = &update.snapshot + && let Err(reason) = state.check_lineage(group, &snapshot.lineage) + { + self.remote_event(session, group, RemoteEvent::Ended(Some(reason.to_string()))); + return; + } + let Some(remote) = state.remotes.get_mut(&group) else { + return; + }; + let (closed, error) = match event { + RemoteEvent::Connected(client) => { + remote.connection = Some(client); + return; + } + RemoteEvent::Ended(error) => (true, error), + RemoteEvent::Updated(update) => { + for text in update.clipboard { + if let Err(error) = remote.finish_copy(text) { + log::warn!("SSH clipboard: {error}"); + } + } + let mut closed = update.disconnected; + let mut error = update + .error + .map(|error| format!("{}: {error}", remote.destination)); + if let Some(snapshot) = update.snapshot { + closed |= snapshot.tabs.is_empty(); + match remote.apply( + snapshot, + &mut state.tabs, + &mut state.active_tab, + &mut state.next_id, + ) { + Ok(changed) => state.dirty |= changed, + Err(reason) => { + closed = true; + error = Some(format!( + "Invalid layout from {}: {reason}", + remote.destination + )); + } + } + } + (closed, error) + } + }; + if closed { + state.remove_remote(group); + self.remove_empty_session(session); + } + if let Some(error) = error { + for client in self + .clients + .values() + .filter(|client| client.session == Some(session)) + { + client.output.reliable(ServerMessage::Error(error.clone())); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session(server: u8) -> SessionState { + let (sender, _) = mpsc::sync_channel(64); + SessionState::new( + SessionIdentity { + server: [server; 16], + session: 1, + }, + PathBuf::from("/tmp/psyterm-unused-test-socket"), + Some(Shell::new("/bin/sh".into(), vec![])), + sender, + ) + } + + fn reserve(local: &mut SessionState, anchor: usize) -> TabId { + let group = local.next_id; + local.next_id += 1; + local.insert_remote_slot( + anchor, + group, + "user@work".into(), + Arc::new(AtomicBool::new(false)), + ); + group + } + + fn apply(local: &mut SessionState, group: u64, snapshot: Snapshot) -> Result { + local.check_lineage(group, &snapshot.lineage)?; + local.remotes.get_mut(&group).unwrap().apply( + Arc::new(snapshot), + &mut local.tabs, + &mut local.active_tab, + &mut local.next_id, + ) + } + + #[test] + fn remote_ids_remain_stable_and_do_not_collide_with_local_tabs_or_other_mirrors() { + let mut local = session(1); + let mut remote = session(2); + local.new_tab(None).unwrap(); + local.new_tab(None).unwrap(); + let left = local.tabs[0].clone(); + let right = local.tabs[1].clone(); + local.focus_tab(left.id).unwrap(); + let group = reserve(&mut local, 0); + assert_eq!(local.active_tab, group); + assert!(local.snapshot().panes.is_empty()); + remote.new_tab(None).unwrap(); + remote.new_tab(None).unwrap(); + // The peers allocated exactly the same tab/pane IDs. + assert_eq!(remote.tabs[0].id, left.id); + apply(&mut local, group, remote.snapshot()).unwrap(); + assert_eq!(local.tabs[0].id, left.id); + assert_eq!(local.tabs[2].id, group); + assert_eq!(local.tabs[3].id, right.id); + assert_eq!(local.active_tab, group); + assert!( + local.tabs[1..3] + .iter() + .all(|t| t.remote.as_deref() == Some("user@work")) + ); + let remote_pane = local.tabs[2].active_pane; + assert_eq!(local.snapshot().panes[0].id, remote_pane); + assert_ne!(remote_pane, right.active_pane); + let first_remote = local.tabs[1].id; + local.focus_tab(left.id).unwrap(); + let second = reserve(&mut local, 0); + apply(&mut local, second, remote.snapshot()).unwrap(); + assert_eq!( + local + .tabs + .iter() + .map(|t| t.id) + .collect::>() + .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::>(), + [left.id, right.id] + ); + assert_eq!(local.active_tab, right.id); + } + + #[test] + fn copies_from_different_views_are_serialized_and_disconnect_completes_waiters() { + let upstream = super::super::tests::TestServer::start(); + let (client, updates) = + Transport::connect(&upstream.socket, None, SessionTarget::New { cwd: None }).unwrap(); + let (frames, receive) = mpsc::channel(); + thread::spawn(move || { + while let Some(update) = updates.recv_blocking() { + if frames.send(update).is_err() { + break; + } + } + }); + let mut local = session(1); + local.new_tab(None).unwrap(); + let group = reserve(&mut local, 0); + let remote = local.remotes.get_mut(&group).unwrap(); + remote.connection = Some(client); + let first = Arc::new(Outbox::default()); + let second = Arc::new(Outbox::default()); + remote.copy(1, &first).unwrap(); + remote.copy(1, &second).unwrap(); + + // An ordered rename acts as a fence after the copy commands on the + // upstream wire. Only one copy should have reached that server. + remote + .send(ClientMessage::RenameTab { + tab: 2, + name: Some("fence".into()), + }) + .unwrap(); + let mut replies = Vec::new(); + loop { + let update = receive.recv_timeout(Duration::from_secs(5)).unwrap(); + replies.extend(update.clipboard); + if update + .snapshot + .is_some_and(|snapshot| snapshot.tabs[0].title == "fence") + { + break; + } + } + assert_eq!(replies, [""]); + remote + .finish_copy("text for the first window".into()) + .unwrap(); + assert!( + matches!(first.next(), Some(ServerMessage::Clipboard(text)) if text == "text for the first window") + ); + let mut remote_replied = false; + while !remote_replied { + let update = receive.recv_timeout(Duration::from_secs(5)).unwrap(); + remote_replied = !update.clipboard.is_empty(); + } + // An SSH disconnect while the second result is in flight must never + // direct the first window's clipboard into the second window. + local.remove_remote(group); + assert!(matches!(second.next(), Some(ServerMessage::Clipboard(text)) if text.is_empty())); + } + + #[test] + fn failed_cancelled_and_recursive_attachments_preserve_the_origin() { + let mut local = session(7); + local.new_tab(None).unwrap(); + let anchor = local.active_tab; + let group = reserve(&mut local, 0); + let cancelled = local.remotes[&group].cancelled.clone(); + let own_snapshot = local.snapshot(); + assert!( + apply(&mut local, group, own_snapshot) + .unwrap_err() + .to_string() + .contains("inside itself") + ); + local.cancel_pending_tab(group).unwrap(); + assert!(cancelled.load(Ordering::Acquire)); + assert_eq!(local.active_tab, anchor); + assert_eq!(local.tabs.len(), 1); + + let mut upstream = session(8); + upstream.new_tab(None).unwrap(); + let group = reserve(&mut local, 0); + apply(&mut local, group, upstream.snapshot()).unwrap(); + assert_eq!(local.lineage(), [local.identity, upstream.identity]); + let mut cyclic = upstream.snapshot(); + cyclic.lineage.push(local.identity); + assert!(apply(&mut local, group, cyclic).is_err()); + let before = local.tabs.clone(); + let mut broken = upstream.snapshot(); + broken.tabs[0].active_pane = u64::MAX; + assert!(apply(&mut local, group, broken).is_err()); + assert_eq!(local.tabs, before); + local.remove_remote(group); + assert_eq!(local.lineage(), [local.identity]); + assert_eq!(local.active_tab, anchor); + } +} diff --git a/src/session.rs b/src/session.rs index be022d1..e11f094 100644 --- a/src/session.rs +++ b/src/session.rs @@ -8,7 +8,9 @@ mod macos; #[cfg(target_os = "macos")] use macos::MacProcess; +use crate::protocol::{PaneId, SessionIdentity}; use std::collections::HashMap; +use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread::{self, JoinHandle}; @@ -19,7 +21,7 @@ use alacritty_terminal::grid::Dimensions; use alacritty_terminal::sync::FairMutex; use alacritty_terminal::term::{Config, Term}; use alacritty_terminal::tty::{self, Options, Shell}; -use anyhow::{Context, Result}; +use anyhow::{Context, Result, ensure}; #[derive(Clone)] pub struct EventProxy { @@ -67,6 +69,77 @@ impl Dimensions for GridSize { } } +/// The route inherited by a shell and its children, scoped to the spawning daemon. +pub(crate) struct PaneContext { + pub socket: PathBuf, + pub session: SessionIdentity, + pub pane: PaneId, +} + +impl PaneContext { + const ENV: &str = "PSYTERM_PANE"; + + fn encode(&self) -> Result { + let socket = self + .socket + .to_str() + .context("psyTerm socket must have a UTF-8 path")?; + Ok(format!( + "{:032x}:{}:{}:{}", + u128::from_be_bytes(self.session.server), + self.session.session, + self.pane, + socket + )) + } + + pub(crate) fn from_env() -> Result> { + std::env::var_os(Self::ENV) + .map(|value| Self::decode(value.to_str().context("expected UTF-8")?)) + .transpose() + .context("invalid PSYTERM_PANE") + } + + fn decode(value: &str) -> Result { + let mut parts = value.splitn(4, ':'); + let server = + u128::from_str_radix(parts.next().context("missing server ID")?, 16)?.to_be_bytes(); + let session = parts.next().context("missing session ID")?.parse()?; + let pane = parts.next().context("missing pane ID")?.parse()?; + let socket = PathBuf::from(parts.next().context("missing socket path")?); + ensure!(socket.is_absolute(), "expected an absolute socket path"); + Ok(Self { + socket, + session: SessionIdentity { server, session }, + pane, + }) + } +} + +/// Allow a shell opened from Finder or a development build to invoke the CLI +/// by name. Shell startup files still run normally and can customize this PATH. +fn shell_path_with_cli() -> Option { + use std::os::unix::fs::PermissionsExt; + + let executable = std::env::current_exe().ok()?; + let directory = executable.parent()?; + if executable.file_name()? != "psyterm" { + return None; + } + let path = std::env::var_os("PATH").unwrap_or_else(|| "/usr/bin:/bin".into()); + let mut entries: Vec<_> = std::env::split_paths(&path).collect(); + let resolved = entries.iter().map(|dir| dir.join("psyterm")).find(|file| { + file.metadata() + .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0) + }); + if resolved.and_then(|file| file.canonicalize().ok()) == executable.canonicalize().ok() { + return None; + } + entries.retain(|entry| entry != directory); + entries.insert(0, directory.to_owned()); + std::env::join_paths(entries).ok()?.into_string().ok() +} + pub struct Session { pub term: Arc>>, sender: EventLoopSender, @@ -85,24 +158,26 @@ pub struct Session { impl Session { pub fn in_directory( - directory: Option, + directory: Option, + context: &PaneContext, ) -> Result<(Self, async_channel::Receiver)> { let program = std::env::var("SHELL").ok().filter(|s| !s.is_empty()); #[cfg(target_os = "macos")] let shell = macos::login_shell(program); #[cfg(not(target_os = "macos"))] let shell = Shell::new(program.unwrap_or_else(|| "/bin/sh".into()), Vec::new()); - Self::with_shell_and_directory(shell, directory) + Self::with_shell_and_directory(shell, directory, Some(context)) } #[cfg(test)] fn with_shell(shell: Shell) -> Result<(Self, async_channel::Receiver)> { - Self::with_shell_and_directory(shell, None) + Self::with_shell_and_directory(shell, None, None) } pub(crate) fn with_shell_and_directory( shell: Shell, - working_directory: Option, + working_directory: Option, + context: Option<&PaneContext>, ) -> Result<(Self, async_channel::Receiver)> { let size = WindowSize { num_cols: 80, @@ -118,15 +193,22 @@ impl Session { &GridSize(size), proxy.clone(), ))); + let mut env = HashMap::from([ + ("TERM".into(), "xterm-256color".into()), + ("COLORTERM".into(), "truecolor".into()), + ]); + if let Some(context) = context { + env.insert(PaneContext::ENV.into(), context.encode()?); + if let Some(path) = shell_path_with_cli() { + env.insert("PATH".into(), path); + } + } let options = Options { shell: Some(shell), // None preserves the directory from which the application launched. working_directory, drain_on_exit: true, - env: HashMap::from([ - ("TERM".into(), "xterm-256color".into()), - ("COLORTERM".into(), "truecolor".into()), - ]), + env, }; let pty = tty::new(&options, size, 0).context("Could not start the shell PTY")?; #[cfg(target_os = "linux")] @@ -530,11 +612,20 @@ mod tests { #[test] fn real_pty_transports_input_resize_environment_and_exit() { // Reading first lets the test resize before the child examines its TTY. - let script = "read value; printf '\\033[2J\\033[H%s %s %s ' \"$value\" \"$TERM\" \"$COLORTERM\"; stty size"; - let (mut session, events) = Session::with_shell(Shell::new( - "/bin/sh".into(), - vec!["-c".into(), script.into()], - )) + let script = r#"read value; printf '\033[2J\033[H%s %s %s ' "$value" "$TERM" "$COLORTERM"; stty size; printf '%s' "$PSYTERM_PANE""#; + let context = PaneContext { + socket: PathBuf::from("/tmp/pty:example/socket"), + session: SessionIdentity { + server: [23; 16], + session: 11, + }, + pane: 23, + }; + let (mut session, events) = Session::with_shell_and_directory( + Shell::new("/bin/sh".into(), vec!["-c".into(), script.into()]), + None, + Some(&context), + ) .expect("start real PTY"); session.resize(100, 30, 9, 18); session.write(b"PTY_OK\n".to_vec()); @@ -562,6 +653,13 @@ mod tests { first_line.contains("PTY_OK xterm-256color truecolor 30 100"), "{first_line:?}" ); + let env_line: String = (0..term.columns()) + .map(|column| term.grid()[Point::new(Line(1), Column(column))].c) + .collect(); + let inherited = PaneContext::decode(env_line.trim_end()).unwrap(); + assert_eq!(inherited.session, context.session); + assert_eq!(inherited.pane, context.pane); + assert_eq!(inherited.socket, context.socket); assert_eq!((term.columns(), term.screen_lines()), (100, 30)); } } diff --git a/src/terminal.rs b/src/terminal.rs index c8cb52b..7aa9d67 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -54,12 +54,12 @@ pub struct Workspace { } impl Workspace { fn begin_tab_rename(&mut self, window: &mut Window, cx: &mut Context) { - let Some(tab) = self.snapshot.as_ref().and_then(|snapshot| { - snapshot - .tabs - .iter() - .find(|tab| tab.id == snapshot.active_tab) - }) else { + let Some(tab) = self + .snapshot + .as_deref() + .and_then(Snapshot::active_tab) + .filter(|tab| !tab.is_connecting()) + else { return; }; let id = tab.id; @@ -166,6 +166,7 @@ impl Workspace { if !matches!( action, CommandAction::TogglePalette + | CommandAction::NewWindow | CommandAction::IncreaseFontSize | CommandAction::DecreaseFontSize ) && (self.palette.is_some() @@ -180,6 +181,30 @@ impl Workspace { cx.stop_propagation(); } + fn open_window(&self, cx: &mut Context) { + let client = self.client.clone(); + let cwd = self + .focused_pane() + .map(|pane| pane.read(cx).data().cwd.clone()); + let active_tab = self.snapshot.as_deref().and_then(Snapshot::active_tab); + let remote = client + .remote() + .or_else(|| active_tab?.remote.as_deref()) + .map(str::to_owned); + let launch = cx + .background_executor() + .spawn(async move { client.open_window(remote, cwd) }); + cx.spawn(async move |view, cx| { + if let Err(error) = launch.await { + let _ = view.update(cx, |view, cx| { + view.error = Some(format!("Could not open a new window: {error:#}")); + cx.notify(); + }); + } + }) + .detach(); + } + fn execute(&mut self, action: CommandAction, window: &mut Window, cx: &mut Context) { use CommandAction::*; let pane = self.focused_pane(); @@ -189,6 +214,10 @@ impl Workspace { self.open_palette(window, cx); None } + NewWindow => { + self.open_window(cx); + None + } IncreaseFontSize | DecreaseFontSize => { let delta = if matches!(action, IncreaseFontSize) { 1. @@ -225,7 +254,13 @@ impl Workspace { Direction::Down }, }), - ClosePane => pane_id.map(|pane| ClientMessage::ClosePane { pane }), + ClosePane => pane_id + .map(|pane| ClientMessage::ClosePane { pane }) + .or_else(|| { + let tab = self.snapshot.as_deref()?.active_tab()?; + tab.is_connecting() + .then_some(ClientMessage::ClosePendingTab { tab: tab.id }) + }), ResetPaneName => pane_id.map(|pane| ClientMessage::RenamePane { pane, name: None }), ResetTabName => self .snapshot @@ -307,7 +342,8 @@ impl Workspace { if cx .update(|window, cx| { view.update(cx, |view, cx| { - for text in update.clipboard { + for text in update.clipboard.into_iter().filter(|text| !text.is_empty()) + { cx.write_to_clipboard(ClipboardItem::new_string(text)); } if let Some(error) = update.error { @@ -535,12 +571,18 @@ impl Render for Workspace { if let Some(snapshot) = &self.snapshot { incoming = pane_scene(snapshot, &self.panes, incoming_offset, Some(&self.client)); if snapshot.panes.is_empty() { - incoming = incoming.child( - div() - .p_4() - .text_color(rgb(chrome::MUTED)) - .child("No sessions. Use + to open a terminal."), - ); + let status = match snapshot.active_tab() { + Some(tab) if tab.is_connecting() => tab + .remote + .as_ref() + .map(|host| format!("Connecting to {host}…")), + Some(_) => None, // The selected tab's grid is still in transit. + None => Some("No sessions. Use + to open a terminal.".to_owned()), + }; + if let Some(status) = status { + incoming = + incoming.child(div().p_4().text_color(rgb(chrome::MUTED)).child(status)); + } } } else { incoming = incoming.child( @@ -561,15 +603,34 @@ impl Render for Workspace { .bg(rgb(chrome::APP_BACKGROUND)) .child(header) .child(body); + #[cfg(target_os = "macos")] + { + root = root.on_action(cx.listener(|view, _: &crate::NewWindow, _, cx| { + view.open_window(cx); + })); + } if let Some(error) = &self.error { root = root.child( div() + .flex() + .items_center() .px_3() .py_1() .text_size(px(12.)) .text_color(rgb(chrome::TEXT)) .bg(rgb(chrome::BORDER)) - .child(error.clone()), + .child(div().flex_1().min_w_0().child(error.clone())) + .child( + div() + .id("dismiss-error") + .px_2() + .cursor_pointer() + .child("Dismiss") + .on_click(cx.listener(|view, _, _, cx| { + view.error = None; + cx.notify(); + })), + ), ); } if let Some(palette) = &self.palette { diff --git a/src/transition.rs b/src/transition.rs index eebf6b5..6a6d991 100644 --- a/src/transition.rs +++ b/src/transition.rs @@ -115,6 +115,7 @@ mod tests { fn stack(ids: &[u64], active: u64) -> crate::protocol::TabInfo { crate::protocol::TabInfo { id: 1, + remote: None, title: String::new(), manual_title: None, panes: ids.to_vec(),