From 0f272d52986b653452dd70448ec909ed08f7e32d Mon Sep 17 00:00:00 2001 From: James Magahern Date: Tue, 17 Nov 2026 18:12:22 -0800 Subject: [PATCH] Share the macOS window host, resume sessions, and group Linux windows --- README.md | 28 ++- assets/dev.buzzert.psyterm.desktop | 9 + src/launcher.rs | 51 +++- src/launcher/macos.rs | 381 +++++++++++++++++++++++++++++ src/macos_app.rs | 74 ++++++ src/main.rs | 145 ++++++----- src/protocol.rs | 2 + src/server.rs | 48 +++- src/terminal.rs | 12 + 9 files changed, 666 insertions(+), 84 deletions(-) create mode 100644 assets/dev.buzzert.psyterm.desktop create mode 100644 src/launcher/macos.rs create mode 100644 src/macos_app.rs diff --git a/README.md b/README.md index 6896c61..cb9b9ce 100644 --- a/README.md +++ b/README.md @@ -35,10 +35,16 @@ codesign --force --sign - target/release/bundle/osx/psyTerm.app 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. 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. +You can copy `psyTerm.app` to Applications. All macOS windows share one Dock +icon. Closing a window detaches its session. Cmd+Q detaches every window and +keeps their shells, tabs, and scrollback in the daemon. Reopening the app from +Finder, the Dock, or `open` resumes the most recently detached local session, +including its SSH tabs. If all live sessions are attached, the app joins the +most recently used one. If none exist, it creates a session. + +Press Cmd+N or run `psyterm` from a shell to start an independent session +in another window of the running app. +The bundle’s `Contents/MacOS/psyterm` executable accepts the same CLI commands. ### Linux @@ -80,6 +86,18 @@ The default command starts or reuses a local server, asks its zygote to fork a GUI, and returns. Each invocation starts an independent session unless you pass `--attach`. +All Wayland windows use the app ID `dev.buzzert.psyterm`. Install the matching +desktop entry and icon with the release binary so the desktop can group windows +under the psyTerm launcher. + +```sh +sudo install -Dm755 target/release/psyterm /usr/local/bin/psyterm +sudo install -Dm644 assets/dev.buzzert.psyterm.desktop \ + /usr/local/share/applications/dev.buzzert.psyterm.desktop +sudo install -Dm644 assets/psyTerm.svg \ + /usr/local/share/icons/hicolor/scalable/apps/dev.buzzert.psyterm.svg +``` + ### Shells and sessions Each new session starts with one tab and one shell. A pane opened above or @@ -122,7 +140,7 @@ Finish any running work first, since shutdown ends its sessions, then launch | `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 --attach` | Reopen the last remote session you detached | | `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 --gui` | Open a window in the shared macOS app or run a Linux GUI in the current process | | `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 | diff --git a/assets/dev.buzzert.psyterm.desktop b/assets/dev.buzzert.psyterm.desktop new file mode 100644 index 0000000..b6b9637 --- /dev/null +++ b/assets/dev.buzzert.psyterm.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Type=Application +Name=psyTerm +Comment=Terminal emulator and multiplexer +Exec=psyterm +Icon=dev.buzzert.psyterm +Terminal=false +Categories=System;TerminalEmulator; +StartupWMClass=dev.buzzert.psyterm diff --git a/src/launcher.rs b/src/launcher.rs index d82fcff..16f008b 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -1,5 +1,7 @@ //! Local daemon startup, private sockets and process roles. +#[cfg(target_os = "macos")] +pub(crate) mod macos; #[cfg(target_os = "linux")] pub(crate) mod zygote; @@ -40,18 +42,48 @@ pub fn default_socket() -> Result { Ok(root.join("server.sock")) } -/// Start exactly one daemon. The daemon has its own lifetime lock; this lock is -/// held only while racing launchers agree on which process starts it. +/// Start exactly one daemon even when several launchers arrive together. pub fn ensure_server(socket: &Path) -> Result<()> { ensure_socket_parent(socket)?; if probe_server(socket)? { return Ok(()); } + let _lock = lock_startup(socket)?; + ensure_server_locked(socket) +} + +/// A macOS app launch attaches just like --attach, creating the first session +/// only if the daemon has no live ones. Hold the startup lock through Connect +/// so two simultaneous opens cannot both decide to create that first session. +#[cfg(target_os = "macos")] +pub(crate) fn connect_app_window( + socket: &Path, + cwd: Option, +) -> Result<(crate::client::Client, crate::client::Updates)> { + ensure_socket_parent(socket)?; + let _lock = lock_startup(socket)?; + ensure_server_locked(socket)?; + let connect = |target| { + crate::client::Client::connect(socket, None, target, protocol::SshOptions::default()) + }; + match connect(protocol::SessionTarget::Attach(None)) { + Err(error) if error.to_string() == protocol::NO_SESSIONS_TO_ATTACH => { + connect(protocol::SessionTarget::New { cwd }) + } + result => result, + } +} + +fn lock_startup(socket: &Path) -> Result { let startup_lock = private_file(&suffixed(socket, ".startup.lock"))?; // SAFETY: flock operates on our live file descriptor and has no pointers. if unsafe { libc::flock(startup_lock.as_raw_fd(), libc::LOCK_EX) } != 0 { return Err(io::Error::last_os_error()).context("lock server startup"); } + Ok(startup_lock) +} + +fn ensure_server_locked(socket: &Path) -> Result<()> { if probe_server(socket)? { return Ok(()); } @@ -223,20 +255,29 @@ fn role_command(executable: &Path, role: &str, socket: &Path, log_path: &Path) - Ok(command) } -// AppKit needs a fresh process for a server-requested window on macOS. +// The daemon may also receive a window request before a GUI has started. #[cfg(target_os = "macos")] pub fn open_window( socket: &Path, remote: Option, session: protocol::SessionTarget, ) -> Result<()> { + let request = macos::WindowRequest { + remote, + session, + resume: false, + }; + if macos::enqueue_if_running(socket, &request)? { + return Ok(()); + } + let mut command = role_command( &executable_path()?, "--gui", socket, &suffixed(socket, ".gui.log"), )?; - match session { + match request.session { protocol::SessionTarget::New { cwd: Some(cwd) } => { command.arg("--cwd").arg(cwd); } @@ -251,7 +292,7 @@ pub fn open_window( // SSH options, daemon identity checks, and connection errors are retained. protocol::SessionTarget::Remembered(_) => bail!("reattach through the invoking client"), } - if let Some(remote) = remote { + if let Some(remote) = request.remote { command.arg("--remote").arg(remote.destination); command .env_remove("PSYTERM_REMOTE_BIN") diff --git a/src/launcher/macos.rs b/src/launcher/macos.rs new file mode 100644 index 0000000..fba3d82 --- /dev/null +++ b/src/launcher/macos.rs @@ -0,0 +1,381 @@ +//! Route windows for all local daemon sockets to a single AppKit event loop. +use std::{ + fs::{self, File}, + io, + os::{ + fd::AsRawFd, + unix::{ + fs::{FileTypeExt, MetadataExt, PermissionsExt}, + net::{UnixListener, UnixStream}, + }, + }, + path::{Path, PathBuf}, + thread, + time::{Duration, Instant}, +}; + +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; + +use super::REQUEST_TIMEOUT; +use crate::{ + client::{Client, Updates}, + protocol::{self, RemoteWindow, SessionTarget}, +}; + +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct WindowRequest { + pub remote: Option, + pub session: SessionTarget, + pub resume: bool, +} + +impl WindowRequest { + pub fn connect(self, socket: &Path) -> Result<(Client, Updates)> { + if self.resume { + let SessionTarget::New { cwd } = self.session else { + bail!("expected an app launch without a session ID"); + }; + return super::connect_app_window(socket, cwd); + } + if self.remote.is_none() && matches!(self.session, SessionTarget::Attach(_)) { + super::require_server(socket)?; + } else { + super::ensure_server(socket)?; + } + match self.remote { + Some(remote) => { + Client::connect(socket, Some(&remote.destination), self.session, remote.ssh) + } + None => Client::connect(socket, None, self.session, Default::default()), + } + } +} + +#[derive(Serialize, Deserialize)] +struct OpenWindow { + socket: PathBuf, + request: WindowRequest, + wait_for_window: bool, +} + +pub(crate) struct PendingWindow { + pub socket: PathBuf, + pub request: WindowRequest, + pub reply: WindowReply, +} + +pub(crate) struct WindowReply(Option); + +impl WindowReply { + pub fn finish(self, result: Result<()>) { + if let Some(mut stream) = self.0 { + let response = result.map_err(|error| format!("{error:#}")); + if let Err(error) = protocol::write_message(&mut stream, &response) { + log::warn!("Reply to window launcher failed: {error:#}"); + } + } else if let Err(error) = result { + log::warn!("Open requested window failed: {error:#}"); + } + } +} + +/// The winner holds the lock while establishing its first terminal session. +/// Publish the listener only after that succeeds, so a failed first launch +/// leaves concurrent callers free to take over without losing their requests. +pub(crate) struct ElectedHost { + path: PathBuf, + lock: File, +} + +impl ElectedHost { + pub fn listen(self) -> Result { + bind_host(&self.path, self.lock) + } +} + +pub(crate) struct WindowHost { + pub windows: async_channel::Receiver, + path: PathBuf, + // Released by Drop or by the OS on process exit. + _owner: File, +} + +impl Drop for WindowHost { + fn drop(&mut self) { + self.windows.close(); + // Wake accept() when the last window closes, then release the address. + let _ = UnixStream::connect(&self.path); + let _ = fs::remove_file(&self.path); + } +} + +fn host_path() -> Result { + Ok(super::default_socket()?.with_file_name("gui.sock")) +} + +/// Become the primary GUI or forward the request and return its window-open result. +pub(crate) fn route(socket: &Path, request: &WindowRequest) -> Result> { + route_at(&host_path()?, socket, request) +} + +fn route_at(path: &Path, socket: &Path, request: &WindowRequest) -> Result> { + let lock = super::private_file(&super::suffixed(path, ".lock"))?; + let deadline = Instant::now() + Duration::from_secs(60); + loop { + // SAFETY: flock uses our open file descriptor and takes no pointers. + if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + return Ok(Some(ElectedHost { + path: path.to_owned(), + lock, + })); + } + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::WouldBlock { + return Err(error).context("elect the macOS window host"); + } + if let Some(stream) = connect_host(path)? { + forward(stream, socket, request, true)?; + return Ok(None); + } + // The owner has been elected but may not yet have bound its socket. + ensure!( + Instant::now() < deadline, + "window host did not finish starting" + ); + thread::sleep(Duration::from_millis(10)); + } +} + +/// The daemon calls this from the terminal actor. It must return before the +/// window connects back to that actor for its session. +pub(super) fn enqueue_if_running(socket: &Path, request: &WindowRequest) -> Result { + if let Some(stream) = connect_host(&host_path()?)? { + forward(stream, socket, request, false)?; + Ok(true) + } else { + Ok(false) + } +} + +fn connect_host(path: &Path) -> Result> { + match UnixStream::connect(path) { + Ok(stream) => Ok(Some(stream)), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused + ) => + { + Ok(None) + } + Err(error) => { + Err(error).with_context(|| format!("connect to window host at {}", path.display())) + } + } +} + +fn forward( + mut stream: UnixStream, + socket: &Path, + request: &WindowRequest, + wait_for_window: bool, +) -> Result<()> { + super::verify_peer(&stream)?; + stream.set_write_timeout(Some(REQUEST_TIMEOUT))?; + protocol::write_message( + &mut stream, + &OpenWindow { + socket: std::path::absolute(socket)?, + request: request.clone(), + wait_for_window, + }, + )?; + // The daemon waits only for queue acceptance. CLI callers also wait for + // SSH/session establishment and native window creation. + let timeout = if wait_for_window { + Duration::from_secs(60) + } else { + REQUEST_TIMEOUT + }; + stream.set_read_timeout(Some(timeout))?; + let response: Result<(), String> = protocol::read_message(&mut stream)?; + response.map_err(anyhow::Error::msg) +} + +fn bind_host(path: &Path, lock: File) -> Result { + if let Ok(metadata) = fs::symlink_metadata(path) { + ensure!( + metadata.file_type().is_socket() && metadata.uid() == super::uid(), + "refusing to replace a non-socket or unowned window host address" + ); + ensure!( + connect_host(path)?.is_none(), + "window host address is already in use" + ); + fs::remove_file(path)?; + } + let listener = UnixListener::bind(path).context("bind macOS window host socket")?; + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + let (sender, windows) = async_channel::unbounded(); + thread::Builder::new() + .name("psyterm-window-listener".into()) + .spawn(move || { + for stream in listener.incoming() { + if sender.is_closed() { + break; + } + let result = stream + .context("accept window request") + .and_then(|stream| receive_window(stream, &sender)); + if let Err(error) = result { + log::warn!("Receive window request failed: {error:#}"); + } + } + })?; + Ok(WindowHost { + windows, + path: path.to_owned(), + _owner: lock, + }) +} + +fn receive_window( + mut stream: UnixStream, + sender: &async_channel::Sender, +) -> Result<()> { + super::verify_peer(&stream)?; + stream.set_read_timeout(Some(REQUEST_TIMEOUT))?; + stream.set_write_timeout(Some(REQUEST_TIMEOUT))?; + let open: OpenWindow = protocol::read_message(&mut stream)?; + let pending = PendingWindow { + socket: open.socket, + request: open.request, + reply: WindowReply(if open.wait_for_window { + Some(stream.try_clone()?) + } else { + None + }), + }; + let accepted = sender + .send_blocking(pending) + .map_err(|_| anyhow::anyhow!("window host has closed")); + if !open.wait_for_window || accepted.is_err() { + WindowReply(Some(stream)).finish(accepted); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Barrier; + + fn next_window(host: &WindowHost) -> PendingWindow { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if let Ok(pending) = host.windows.try_recv() { + return pending; + } + assert!( + Instant::now() < deadline, + "forwarded request did not arrive" + ); + thread::sleep(Duration::from_millis(5)); + } + } + + #[test] + fn simultaneous_launches_share_one_host_and_forward_the_callers_session() { + let root = super::super::tests::test_dir(); + let path = root.join("gui.sock"); + // A first launch with an invalid attach must not accept other callers. + let missing = root.join("missing.sock"); + let invalid = WindowRequest { + remote: None, + session: SessionTarget::Attach(Some(99)), + resume: false, + }; + let failed = route_at(&path, &missing, &invalid).unwrap().unwrap(); + assert!(invalid.connect(&missing).is_err()); + assert!(connect_host(&path).unwrap().is_none()); + drop(failed); + + // Simulate a crash: the OS drops the listener/lock, but leaves the name. + drop(UnixListener::bind(&path).unwrap()); + let barrier = Barrier::new(2); + let launch = |id| { + let socket = root.join(format!("daemon-{id}")); + let request = WindowRequest { + remote: Some(RemoteWindow { + destination: format!("host-{id}"), + ssh: protocol::SshOptions { + executable: Some(format!("psyterm-{id}")), + agent_socket: Some(root.join(format!("agent-{id}"))), + }, + }), + session: SessionTarget::Attach(Some(id)), + resume: false, + }; + barrier.wait(); + match route_at(&path, &socket, &request) { + Ok(Some(elected)) => { + let host = elected.listen().unwrap(); + let pending = next_window(&host); + let other = 3 - id; + assert_eq!(pending.socket, root.join(format!("daemon-{other}"))); + assert!( + matches!(pending.request.session, SessionTarget::Attach(Some(id)) if id == other) + ); + let remote = pending.request.remote.unwrap(); + assert_eq!(remote.destination, format!("host-{other}")); + assert_eq!(remote.ssh.executable, Some(format!("psyterm-{other}"))); + assert_eq!( + remote.ssh.agent_socket, + Some(root.join(format!("agent-{other}"))) + ); + pending + .reply + .finish(Err(anyhow::anyhow!("unknown session"))); + true + } + Err(error) => { + assert_eq!(error.to_string(), "unknown session"); + false + } + Ok(None) => panic!("expected the opening error to reach the caller"), + } + }; + thread::scope(|scope| { + let other = scope.spawn(|| launch(1)); + assert_ne!(launch(2), other.join().unwrap()); + }); + assert!(!path.exists()); + + // A later launch elects another host. A daemon request can then be + // dispatched while the server actor is still handling New Window. + let socket = root.join("server.sock"); + let request = WindowRequest { + remote: None, + session: SessionTarget::New { cwd: None }, + resume: false, + }; + let host = route_at(&path, &socket, &request) + .unwrap() + .unwrap() + .listen() + .unwrap(); + forward( + connect_host(&path).unwrap().unwrap(), + &socket, + &request, + false, + ) + .unwrap(); + let pending = next_window(&host); + assert_eq!(pending.socket, socket); + assert!(pending.reply.0.is_none()); + drop(host); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/src/macos_app.rs b/src/macos_app.rs new file mode 100644 index 0000000..000e686 --- /dev/null +++ b/src/macos_app.rs @@ -0,0 +1,74 @@ +//! All AppKit windows share one event loop. Other launchers submit window requests +//! before initializing GPUI, so they never register a second Dock application. +use std::path::Path; + +use anyhow::Result; +use gpui::{App, Application, KeyBinding, Menu, MenuItem}; + +use crate::launcher::macos::{PendingWindow, WindowRequest, route}; +use crate::{NewWindow, Quit, open_workspace, quit_on_last_window}; + +pub fn run(socket: &Path, request: WindowRequest) -> Result<()> { + let Some(elected) = route(socket, &request)? else { + return Ok(()); + }; + // The first CLI invocation can report connection errors before AppKit starts. + let (client, updates) = request.connect(socket)?; + let host = elected.listen()?; + let windows = host.windows.clone(); + Application::new().run(move |cx| { + install_menus(cx); + quit_on_last_window(cx); + if let Err(error) = open_workspace(client, updates, cx) { + log::error!("{error:#}"); + cx.quit(); + return; + } + cx.spawn(async move |cx| { + while let Ok(PendingWindow { + socket, + request, + reply, + }) = windows.recv().await + { + // A slow SSH connection must leave the other windows interactive + // and allow later window requests to proceed independently. + let connection = cx + .background_executor() + .spawn(async move { request.connect(&socket) }); + cx.spawn(async move |cx| { + let result = connection.await.and_then(|(client, updates)| { + cx.update(|cx| open_workspace(client, updates, cx))? + }); + reply.finish(result); + }) + .detach(); + } + }) + .detach(); + }); + Ok(()) +} + +fn install_menus(cx: &mut App) { + cx.on_action(|_: &Quit, cx| cx.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)], + }, + // AppKit populates its Window menu with the process's open windows. + Menu { + name: "Window".into(), + items: vec![], + }, + ]); +} diff --git a/src/main.rs b/src/main.rs index 94f522e..75f192c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,8 @@ mod fonts; mod input; mod label; mod launcher; +#[cfg(target_os = "macos")] +mod macos_app; mod palette; mod pane_name; mod protocol; @@ -70,7 +72,7 @@ fn main() -> Result<()> { } "--help" | "-h" => { println!( - "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 --remote --attach Reopen the last detached remote session\n psyterm --remote HOST --attach [ID] Join an existing session on HOST\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" + "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 --remote --attach Reopen the last detached remote session\n psyterm --remote HOST --attach [ID] Join an existing session on HOST\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 Open a GUI window directly\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(()); } @@ -87,14 +89,24 @@ fn main() -> Result<()> { bail!("--remote needs an SSH destination, or --attach to reopen a detached remote session"); } #[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 app_launch = { + // Finder, Dock, and open(1) launch the bundle through launchd. A shell + // can also invoke the bundled executable directly as a normal CLI. + let from_launchd = unsafe { libc::getppid() } == 1; + if from_launchd + && matches!(role, "launch" | "gui") + && std::env::current_dir()? == std::path::Path::new("/") + && let Some(home) = std::env::home_dir() + { + std::env::set_current_dir(home)?; + } + from_launchd + && role == "launch" + && remote.is_none() + && attach.is_none() + && cwd.is_none() + && std::env::current_exe()?.ends_with("Contents/MacOS/psyterm") + }; let origin = if role == "launch" && remote.is_some() { session::PaneContext::from_env()? } else { @@ -181,12 +193,17 @@ fn main() -> Result<()> { } #[cfg(target_os = "linux")] "zygote" => launcher::zygote::run_zygote(&socket), - // 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()) => - { + #[cfg(target_os = "macos")] + "gui" | "launch" => macos_app::run( + &socket, + launcher::macos::WindowRequest { + remote: remote.map(|destination| protocol::RemoteWindow { destination, ssh }), + session, + resume: app_launch, + }, + ), + #[cfg(target_os = "linux")] + "gui" | "launch" if role == "gui" || (remote.is_some() && attach.is_some()) => { if remote.is_none() && attach.is_some() { launcher::require_server(&socket)?; } else { @@ -244,7 +261,7 @@ fn list_sessions(socket: &std::path::Path) -> Result<()> { Ok(()) } -/// Initialize GPUI on the main thread of the GUI process. +#[cfg(target_os = "linux")] pub(crate) fn run_gui( socket: PathBuf, remote: Option, @@ -252,63 +269,45 @@ pub(crate) fn run_gui( ssh: protocol::SshOptions, ) -> Result<()> { let (client, updates) = client::Client::connect(&socket, remote.as_deref(), session, ssh)?; - Application::new().run(move |cx: &mut App| { - // Each GUI process owns one window. Remember a direct SSH session - // on every graceful close, including the native close button and Quit. - if client.remote().is_some() { - let direct = client.clone(); - cx.on_app_quit(move |_| { - // Finish the local launcher request before AppKit exits. - if let Err(error) = direct.remember_remote_detach() { - log::warn!("Could not remember detached SSH session: {error:#}"); - } - std::future::ready(()) - }) - .detach(); - } - #[cfg(target_os = "macos")] - { - cx.on_action(|_: &Quit, cx| cx.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() { - cx.quit(); - } - }) - .detach(); - let bounds = Bounds::centered(None, size(px(1000.), px(680.)), cx); - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(bounds)), - titlebar: Some(TitlebarOptions { - title: Some("psyTerm".into()), - appears_transparent: cfg!(target_os = "macos"), - // GPUI positions the top-left of the 14-point close button. - traffic_light_position: cfg!(target_os = "macos") - .then(|| point(px(12.), px((chrome::HEADER_HEIGHT - 14.) / 2.))), - }), - window_decorations: Some(WindowDecorations::Client), - app_id: Some("dev.buzzert.psyterm".into()), - ..Default::default() - }, - move |window, cx| cx.new(|cx| terminal::Workspace::new(client, updates, window, cx)), - ) - .expect("could not open psyTerm window"); - cx.activate(true); + Application::new().run(move |cx| { + quit_on_last_window(cx); + open_workspace(client, updates, cx).expect("could not open psyTerm window"); }); Ok(()) } + +fn quit_on_last_window(cx: &App) { + cx.on_window_closed(|cx| { + if cx.windows().is_empty() { + cx.quit(); + } + }) + .detach(); +} + +fn open_workspace(client: client::Client, updates: client::Updates, cx: &mut App) -> Result<()> { + // Use GPUI's native window offset for subsequent windows. + let window_bounds = cx + .windows() + .is_empty() + .then(|| WindowBounds::Windowed(Bounds::centered(None, size(px(1000.), px(680.)), cx))); + cx.open_window( + WindowOptions { + window_bounds, + titlebar: Some(TitlebarOptions { + title: Some("psyTerm".into()), + appears_transparent: cfg!(target_os = "macos"), + // GPUI positions the top-left of the 14-point close button. + traffic_light_position: cfg!(target_os = "macos") + .then(|| point(px(12.), px((chrome::HEADER_HEIGHT - 14.) / 2.))), + }), + window_decorations: Some(WindowDecorations::Client), + app_id: Some("dev.buzzert.psyterm".into()), + ..Default::default() + }, + move |window, cx| cx.new(|cx| terminal::Workspace::new(client, updates, window, cx)), + ) + .context("open psyTerm window")?; + cx.activate(true); + Ok(()) +} diff --git a/src/protocol.rs b/src/protocol.rs index 0f02e32..7fa3772 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -11,6 +11,8 @@ use bincode::Options; use serde::{Deserialize, Serialize, de::DeserializeOwned}; pub const VERSION: u32 = 6; +// Version 6 reports an empty attach selection as a ServerMessage::Error string. +pub const NO_SESSIONS_TO_ATTACH: &str = "no sessions to attach to"; pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024; pub type PaneId = u64; pub type TabId = u64; diff --git a/src/server.rs b/src/server.rs index 3218f19..5772c1b 100644 --- a/src/server.rs +++ b/src/server.rs @@ -495,7 +495,7 @@ impl Server { (detached, session.last_used, session.id) }) .map(|session| session.id) - .context("no sessions to attach to") + .context(NO_SESSIONS_TO_ATTACH) } fn command( @@ -1539,6 +1539,52 @@ mod tests { } } + #[cfg(target_os = "macos")] + #[test] + fn app_launch_creates_one_initial_session_and_resumes_it_after_quit() { + let server = TestServer::start(); + let directory = server.socket.parent().unwrap().canonicalize().unwrap(); + let launch = |cwd| crate::launcher::connect_app_window(&server.socket, cwd).unwrap(); + let start = std::sync::Barrier::new(2); + let launch_together = || { + start.wait(); + launch(Some(directory.to_str().unwrap().to_owned())) + }; + let (first, second) = thread::scope(|scope| { + let peer = scope.spawn(launch_together); + (launch_together(), peer.join().unwrap()) + }); + + let list = || { + let response = + crate::launcher::control(&server.socket, ClientMessage::ListSessions).unwrap(); + let ServerMessage::Sessions(sessions) = response else { + panic!("expected session list") + }; + sessions + }; + let sessions = list(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].attached, 2); + let initial = first.1.recv_blocking().unwrap().snapshot.unwrap(); + assert_eq!(Path::new(&initial.panes[0].cwd), directory); + drop((first, second)); + let deadline = Instant::now() + Duration::from_secs(5); + while list()[0].attached != 0 { + assert!(Instant::now() < deadline, "app windows did not detach"); + thread::sleep(Duration::from_millis(2)); + } + + // This cwd would reject a new shell, so success requires resuming the live session. + let (_client, updates) = + launch(Some(directory.join("missing").to_str().unwrap().to_owned())); + let resumed = updates.recv_blocking().unwrap().snapshot.unwrap(); + assert_eq!(resumed.lineage, initial.lineage); + assert_eq!(resumed.active_tab, initial.active_tab); + assert_eq!(resumed.panes[0].id, initial.panes[0].id); + assert_eq!(list().len(), 1); + } + #[test] fn new_sessions_isolate_live_shells_and_attach_selects_only_existing_work() { let server = TestServer::start(); diff --git a/src/terminal.rs b/src/terminal.rs index a4127c2..e6f0b21 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -51,6 +51,18 @@ pub struct Workspace { transition_frame_pending: bool, _updates: Task<()>, } + +impl Drop for Workspace { + fn drop(&mut self) { + // GPUI drops each window's root on close, including during app shutdown. + if self.client.remote().is_some() + && let Err(error) = self.client.remember_remote_detach() + { + log::warn!("Could not remember detached SSH session: {error:#}"); + } + } +} + impl Workspace { fn begin_tab_rename(&mut self, window: &mut Window, cx: &mut Context) { let Some(tab) = self