A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Introduce content views and remote-thread UI
RoversX2a63963be031
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rsindex 56870558..bf17548a 100644--- a/config/src/keyassignment.rs+++ b/config/src/keyassignment.rs@@ -585,6 +585,8 @@ pub enum KeyAssignment {CreateWorkspaceThread(String),ToggleWorkspaceThreadsCollapsed(String),RemoveProject(String),+ ConnectWorkspaceThread(String),+ DisconnectWorkspaceThread(String),ToggleWorkspaceThreadPinned(String),DeleteWorkspaceThread(String),MarkWorkspaceThreadUnread(String),diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex f27d9a8a..00ef3247 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -2,7 +2,7 @@ use crate::client::{ClientId, ClientInfo};use crate::pane::{CachePolicy, Pane, PaneId};use crate::ssh_agent::AgentProxy;use crate::tab::{SplitRequest, Tab, TabId};-use crate::window::{Window, WindowId};+use crate::window::{Window, WindowId, WindowUiSurfaceId};use anyhow::{anyhow, Context, Error};use config::keyassignment::SpawnTabDomain;use config::{configuration, ExitBehavior, GuiPosition};@@ -29,7 +29,9 @@ use std::time::{Duration, Instant};use termwiz::escape::csi::{DecPrivateMode, DecPrivateModeCode, Device, Mode};use termwiz::escape::{Action, CSI};use thiserror::*;-use wezterm_term::{Clipboard, ClipboardSelection, DownloadHandler, TerminalSize};+use wezterm_term::{+ Clipboard, ClipboardSelection, DownloadHandler, TerminalConfiguration, TerminalSize,+};#[cfg(windows)]use winapi::um::winsock2::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};@@ -373,6 +375,11 @@ pub struct MuxWindowBuilder {notified: bool,}+struct ExistingWindowSpawnContext {+ size: TerminalSize,+ term_config: Option<Arc<dyn TerminalConfiguration>>,+}+impl MuxWindowBuilder {fn notify(&mut self) {if self.notified {@@ -1005,6 +1012,41 @@ impl Mux {Ok(())}+ pub fn register_window_ui_surface(+ &self,+ window_id: WindowId,+ surface_id: WindowUiSurfaceId,+ ) -> bool {+ let changed = {+ let mut windows = self.windows.write();+ let Some(window) = windows.get_mut(&window_id) else {+ return false;+ };+ window.add_ui_surface(surface_id)+ };++ if changed {+ self.notify(MuxNotification::WindowInvalidated(window_id));+ }+ changed+ }++ pub fn unregister_window_ui_surface(&self, window_id: WindowId, surface_id: &str) -> bool {+ let changed = {+ let mut windows = self.windows.write();+ let Some(window) = windows.get_mut(&window_id) else {+ return false;+ };+ window.remove_ui_surface(surface_id)+ };++ if changed {+ self.notify(MuxNotification::WindowInvalidated(window_id));+ self.prune_dead_windows();+ }+ changed+ }+pub fn window_containing_tab(&self, tab_id: TabId) -> Option<WindowId> {for w in self.windows.read().values() {for t in w.iter() {@@ -1018,6 +1060,11 @@ impl Mux {pub fn is_empty(&self) -> bool {self.panes.read().is_empty()+ && self+ .windows+ .read()+ .values()+ .all(|window| window.ui_surface_count() == 0)}pub fn is_workspace_empty(&self, workspace: &str) -> bool {@@ -1409,27 +1456,13 @@ impl Mux {.context("resolve_spawn_tab_domain")?;let window_builder;- let term_config;- let (window_id, size) = if let Some(window_id) = window_id {- let window = self- .get_window_mut(window_id)- .ok_or_else(|| anyhow!("window_id {} not found on this server", window_id))?;- let tab = window- .get_active()- .ok_or_else(|| anyhow!("window {} has no tabs", window_id))?;- let pane = tab- .get_active_pane()- .ok_or_else(|| anyhow!("active tab in window {} has no panes", window_id))?;- term_config = pane.get_config();-- let size = tab.get_size();-- (window_id, size)+ let (window_id, size, term_config) = if let Some(window_id) = window_id {+ let context = self.existing_window_spawn_context(window_id, size)?;+ (window_id, context.size, context.term_config)} else {- term_config = None;window_builder = self.new_empty_window(Some(workspace_for_new_window), window_position);- (*window_builder, size)+ (*window_builder, size, None)};if domain.state() == DomainState::Detached {@@ -1486,6 +1519,26 @@ impl Mux {Ok((tab, pane, window_id))}++ fn existing_window_spawn_context(+ &self,+ window_id: WindowId,+ requested_size: TerminalSize,+ ) -> anyhow::Result<ExistingWindowSpawnContext> {+ let window = self+ .get_window_mut(window_id)+ .ok_or_else(|| anyhow!("window_id {} not found on this server", window_id))?;+ let Some(tab) = window.get_active() else {+ return Ok(ExistingWindowSpawnContext {+ size: requested_size,+ term_config: None,+ });+ };+ let size = tab.get_size();+ let term_config = tab.get_active_pane().and_then(|pane| pane.get_config());++ Ok(ExistingWindowSpawnContext { size, term_config })+ }}pub struct IdentityHolder {@@ -1553,3 +1606,54 @@ impl wezterm_term::DownloadHandler for MuxDownloader {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn window_ui_surfaces_are_distinct_prune_anchors() {+ let mux = Mux::new(None);+ let window = Window::new(Some("test-workspace".to_string()), None);+ let window_id = window.window_id();+ mux.windows.write().insert(window_id, window);++ assert!(mux.is_empty());+ assert!(mux.register_window_ui_surface(window_id, "remote-thread:a".to_string()));+ assert!(mux.register_window_ui_surface(window_id, "ssh-hosts".to_string()));+ assert!(!mux.register_window_ui_surface(window_id, "ssh-hosts".to_string()));+ assert!(!mux.is_empty());++ mux.prune_dead_windows();+ assert!(mux.get_window(window_id).is_some());++ assert!(mux.unregister_window_ui_surface(window_id, "remote-thread:a"));+ assert!(mux.get_window(window_id).is_some());++ assert!(mux.unregister_window_ui_surface(window_id, "ssh-hosts"));+ assert!(mux.get_window(window_id).is_none());+ assert!(mux.is_empty());+ }++ #[test]+ fn existing_window_spawn_context_allows_empty_window() {+ let mux = Mux::new(None);+ let window = Window::new(Some("test-workspace".to_string()), None);+ let window_id = window.window_id();+ mux.windows.write().insert(window_id, window);++ let requested_size = TerminalSize {+ rows: 33,+ cols: 111,+ pixel_width: 999,+ pixel_height: 777,+ dpi: 144,+ };+ let context = mux+ .existing_window_spawn_context(window_id, requested_size)+ .unwrap();++ assert_eq!(context.size, requested_size);+ assert!(context.term_config.is_none());+ }+}diff --git a/mux/src/ssh.rs b/mux/src/ssh.rsindex 8455891a..c5b0fb6e 100644--- a/mux/src/ssh.rs+++ b/mux/src/ssh.rs@@ -177,6 +177,19 @@ fn format_host_verification_for_terminal(failed: HostVerificationFailed) -> Vec</// pane, we play some tricks with wrapped versions of the pty, child/// and the reader and writer instances so that we can inject the/// interactive setup. The bulk of that is driven by `connect_ssh_session`.+/// Coarse lifecycle of the SSH connection backing a [`RemoteSshDomain`], so the+/// GUI can show a "Connecting…" state and detect unreachable hosts instead of+/// staring at a blank pane. `Authenticating` means the TCP connect + handshake+/// succeeded and we are talking to the SSH daemon (any interactive prompts now+/// render in the real pane).+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum SshConnectionStatus {+ Connecting,+ Authenticating,+ Connected,+ Failed(String),+}+pub struct RemoteSshDomain {session: Mutex<Option<Session>>,dom: SshDomain,@@ -184,6 +197,8 @@ pub struct RemoteSshDomain {name: String,/// Optional stored password used to auto-answer the first password prompt.password: Option<String>,+ /// Shared, updated by the connection thread so the GUI can poll progress.+ connection_status: Arc<Mutex<SshConnectionStatus>>,}pub fn ssh_domain_to_ssh_config(ssh_dom: &SshDomain) -> anyhow::Result<ConfigMap> {@@ -263,9 +278,20 @@ impl RemoteSshDomain {session: Mutex::new(None),dom: dom.clone(),password,+ connection_status: Arc::new(Mutex::new(SshConnectionStatus::Connecting)),})}+ /// Current connection lifecycle status; the GUI polls this while a+ /// "Connecting…" view is shown.+ pub fn connection_status(&self) -> SshConnectionStatus {+ self.connection_status.lock().unwrap().clone()+ }++ fn set_connection_status(&self, status: SshConnectionStatus) {+ *self.connection_status.lock().unwrap() = status;+ }+/// Run a one-shot, read-only `cat /etc/os-release` over the already/// established session and return the parsed distro `ID` (e.g. "ubuntu")./// Returns `None` on any error (no session, command failure, etc).@@ -290,6 +316,12 @@ impl RemoteSshDomain {ssh_domain_to_ssh_config(&self.dom)}+ fn prepare_connection_attempt(&self) -> anyhow::Result<ConfigMap> {+ let ssh_config = self.ssh_config().context("obtain ssh config")?;+ self.set_connection_status(SshConnectionStatus::Connecting);+ Ok(ssh_config)+ }+fn build_command(&self,pane_id: PaneId,@@ -377,9 +409,17 @@ impl RemoteSshDomain {size: TerminalSize,password: Option<String>,) -> anyhow::Result<StartNewSessionResult> {- let (session, events) = Session::connect(self.ssh_config().context("obtain ssh config")?)- .context("connect to ssh server")?;+ let (session, events) = match Session::connect(self.prepare_connection_attempt()?)+ .context("connect to ssh server")+ {+ Ok(result) => result,+ Err(err) => {+ self.set_connection_status(SshConnectionStatus::Failed(format!("{:#}", err)));+ return Err(err);+ }+ };self.session.lock().unwrap().replace(session.clone());+ let status = Arc::clone(&self.connection_status);// We get to establish the session!//@@ -434,6 +474,7 @@ impl RemoteSshDomain {// to perform the blocking (from its perspective) terminal// UI to carry out any authentication.let mut stdout_write = BufWriter::new(stdout_write);+ let thread_status = Arc::clone(&status);std::thread::spawn(move || {if let Err(err) = connect_ssh_session(session,@@ -448,7 +489,9 @@ impl RemoteSshDomain {command_line,env,password,+ Arc::clone(&thread_status),) {+ *thread_status.lock().unwrap() = SshConnectionStatus::Failed(format!("{:#}", err));let _ = write!(stdout_write, "{:#}", err);log::error!("Failed to connect ssh: {:#}", err);}@@ -479,7 +522,11 @@ fn connect_ssh_session(command_line: Option<String>,env: HashMap<String, String>,mut password: Option<String>,+ status: Arc<Mutex<SshConnectionStatus>>,) -> anyhow::Result<()> {+ let set_status = |next: SshConnectionStatus| {+ *status.lock().unwrap() = next;+ };struct StdoutShim<'a> {size: Arc<Mutex<TerminalSize>>,stdout: &'a mut BufWriter<FileDescriptor>,@@ -647,6 +694,8 @@ fn connect_ssh_session(}}SessionEvent::HostVerify(verify) => {+ // Handshake succeeded; we're now interacting with the daemon.+ set_status(SshConnectionStatus::Authenticating);shim.output_line(&verify.message)?;let mut editor = LineEditor::new(&mut shim);let mut host = PasswordPromptHost::default();@@ -663,6 +712,7 @@ fn connect_ssh_session(smol::block_on(verify.answer(ok)).context("send verify response")?;}SessionEvent::Authenticate(auth) => {+ set_status(SshConnectionStatus::Authenticating);if !auth.username.is_empty() {shim.output_line(&format!("Authentication for {}", auth.username))?;}@@ -700,13 +750,16 @@ fn connect_ssh_session(smol::block_on(auth.answer(answers))?;}SessionEvent::Error(err) => {+ set_status(SshConnectionStatus::Failed(err.clone()));shim.output_line(&format!("Error: {}", err))?;}SessionEvent::HostVerificationFailed(failed) => {+ set_status(SshConnectionStatus::Failed(failed.to_string()));let message = format_host_verification_for_terminal(failed);shim.render(&message)?;}SessionEvent::Authenticated => {+ set_status(SshConnectionStatus::Connected);// Our session has been authenticated: we can now// set up the real pty for the panematch smol::block_on(session.request_pty(@@ -792,6 +845,8 @@ impl Domain for RemoteSshDomain {let child = Box::new(concrete_child);let writer = Box::new(pty.take_writer().context("take writer from pty")?);+ // Reusing a session that was already authenticated.+ self.set_connection_status(SshConnectionStatus::Connected);StartNewSessionResult { pty, child, writer }}Err(err) => {@@ -1208,3 +1263,23 @@ impl std::io::Read for PtyReader {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn prepare_connection_attempt_resets_failed_status() {+ let dom = SshDomain {+ name: "test-ssh".to_string(),+ remote_address: "example.invalid:22".to_string(),+ ..SshDomain::default()+ };+ let domain = RemoteSshDomain::with_ssh_domain(&dom).unwrap();++ domain.set_connection_status(SshConnectionStatus::Failed("old failure".to_string()));+ domain.prepare_connection_attempt().unwrap();++ assert_eq!(domain.connection_status(), SshConnectionStatus::Connecting);+ }+}diff --git a/mux/src/window.rs b/mux/src/window.rsindex a086e3a3..54a4a3a0 100644--- a/mux/src/window.rs+++ b/mux/src/window.rs@@ -1,14 +1,17 @@use crate::pane::CloseReason;use crate::{Mux, MuxNotification, Tab, TabId};use config::GuiPosition;+use std::collections::BTreeSet;use std::sync::Arc;static WIN_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);pub type WindowId = usize;+pub type WindowUiSurfaceId = String;pub struct Window {id: WindowId,tabs: Vec<Arc<Tab>>,+ ui_surfaces: BTreeSet<WindowUiSurfaceId>,active: usize,last_active: Option<TabId>,workspace: String,@@ -21,6 +24,7 @@ impl Window {Self {id: WIN_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed),tabs: vec![],+ ui_surfaces: BTreeSet::new(),active: 0,last_active: None,title: String::new(),@@ -89,7 +93,19 @@ impl Window {}pub fn is_empty(&self) -> bool {- self.tabs.is_empty()+ self.tabs.is_empty() && self.ui_surfaces.is_empty()+ }++ pub fn ui_surface_count(&self) -> usize {+ self.ui_surfaces.len()+ }++ pub fn add_ui_surface(&mut self, surface_id: WindowUiSurfaceId) -> bool {+ self.ui_surfaces.insert(surface_id)+ }++ pub fn remove_ui_surface(&mut self, surface_id: &str) -> bool {+ self.ui_surfaces.remove(surface_id)}pub fn len(&self) -> usize {@@ -266,3 +282,27 @@ impl Window {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ui_surfaces_keep_empty_window_alive_individually() {+ let mut window = Window::new(Some("test-workspace".to_string()), None);+ assert!(window.is_empty());++ assert!(window.add_ui_surface("remote-thread:a".to_string()));+ assert!(window.add_ui_surface("ssh-hosts".to_string()));+ assert!(!window.add_ui_surface("ssh-hosts".to_string()));+ assert_eq!(window.ui_surface_count(), 2);+ assert!(!window.is_empty());++ assert!(window.remove_ui_surface("remote-thread:a"));+ assert_eq!(window.ui_surface_count(), 1);+ assert!(!window.is_empty());++ assert!(window.remove_ui_surface("ssh-hosts"));+ assert!(window.is_empty());+ }+}diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rsindex cf74a21c..a0e151c8 100644--- a/wezterm-gui/src/commands.rs+++ b/wezterm-gui/src/commands.rs@@ -928,6 +928,22 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Commmenubar: &[],icon: Some("md_delete"),},+ ConnectWorkspaceThread(_) => CommandDef {+ brief: "Connect Thread".into(),+ doc: "Connects or reconnects the ThinkTerm remote thread".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: None,+ },+ DisconnectWorkspaceThread(_) => CommandDef {+ brief: "Disconnect Thread".into(),+ doc: "Disconnects the remote session while keeping the ThinkTerm thread".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: None,+ },ToggleWorkspaceThreadPinned(_) => CommandDef {brief: "Pin Thread".into(),doc: "Toggles the pinned state for the ThinkTerm thread".into(),diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex 20ebf66b..5afc928b 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -314,6 +314,7 @@ impl GuiFrontEnd {term_config,None,None,+ None,)}diff --git a/wezterm-gui/src/spawn.rs b/wezterm-gui/src/spawn.rsindex edf87532..03553284 100644--- a/wezterm-gui/src/spawn.rs+++ b/wezterm-gui/src/spawn.rs@@ -11,6 +11,8 @@ use std::sync::Arc;use wezterm_term::TerminalSize;use window::WindowOps;+pub type SpawnSuccessAction = Box<dyn FnOnce(&mut crate::termwindow::TermWindow) + Send + Sync>;+#[derive(Copy, Debug, Clone, Eq, PartialEq)]pub enum SpawnWhere {NewWindow,@@ -27,16 +29,22 @@ pub fn spawn_command_impl(term_config: Arc<TermConfig>,completion_window: Option<::window::Window>,layout_mutation_reason: Option<&'static str>,+ success_action: Option<SpawnSuccessAction>,) {let spawn = spawn.clone();promise::spawn::spawn(async move {match spawn_command_internal(spawn, spawn_where, size, src_window_id, term_config).await {Ok(()) => {- if let (Some(window), Some(reason)) = (completion_window, layout_mutation_reason) {+ if let Some(window) = completion_window {window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(move |tw| {- tw.persist_workspace_layout_after_mutation(reason);+ if let Some(action) = success_action {+ action(tw);+ }+ if let Some(reason) = layout_mutation_reason {+ tw.persist_workspace_layout_after_mutation(reason);+ }},)));}diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rsindex 46e8de52..71cbeda4 100644--- a/wezterm-gui/src/ssh_hosts.rs+++ b/wezterm-gui/src/ssh_hosts.rs@@ -318,15 +318,6 @@ pub fn ssh_domain_name(spec: &SshHostSpec) -> String {format!("ssh:{}", endpoint(spec))}-/// Default workspace a connection lands in: `ssh:<endpoint>`, unless the host-/// overrides it.-pub fn default_workspace_name(spec: &SshHostSpec) -> String {- spec.default_workspace- .clone()- .filter(|name| !name.trim().is_empty())- .unwrap_or_else(|| format!("ssh:{}", endpoint(spec)))-}-/// Translate a stored host spec into a `config::SshDomain`.pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {let mut ssh_option = HashMap::new();@@ -338,6 +329,11 @@ pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {ssh_option.insert("identityfile".to_string(), identity.clone());}}+ // Default connect timeout so an unreachable host fails fast instead of+ // hanging on the OS default TCP timeout. Users can override via ssh_options.+ ssh_option+ .entry("connecttimeout".to_string())+ .or_insert_with(|| "10".to_string());let remote_address = match spec.port {Some(port) => format!("{}:{port}", spec.host),@@ -583,4 +579,43 @@ Host prod *.internal.unwrap().ends_with("/.ssh/prod"));}++ fn spec_with_options(ssh_options: HashMap<String, String>) -> SshHostSpec {+ SshHostSpec {+ label: "t".to_string(),+ host: "example.com".to_string(),+ port: None,+ username: None,+ identity_file: None,+ password: None,+ ssh_options,+ multiplexing: false,+ default_workspace: None,+ detect_os: false,+ detected_distro: None,+ }+ }++ #[test]+ fn build_ssh_domain_injects_default_connect_timeout() {+ let dom = build_ssh_domain(&spec_with_options(HashMap::new()));+ assert_eq!(+ dom.ssh_option.get("connecttimeout").map(String::as_str),+ Some("10"),+ "an unreachable host should fail fast via a default connect timeout"+ );+ }++ #[test]+ fn build_ssh_domain_preserves_user_connect_timeout() {+ let mut options = HashMap::new();+ // User-provided key with mixed case; build_ssh_domain lowercases it.+ options.insert("ConnectTimeout".to_string(), "3".to_string());+ let dom = build_ssh_domain(&spec_with_options(options));+ assert_eq!(+ dom.ssh_option.get("connecttimeout").map(String::as_str),+ Some("3"),+ "an explicit connecttimeout override must win over the default"+ );+ }}diff --git a/wezterm-gui/src/tabbar.rs b/wezterm-gui/src/tabbar.rsindex 18f44e34..4c7e22fd 100644--- a/wezterm-gui/src/tabbar.rs+++ b/wezterm-gui/src/tabbar.rs@@ -1,3 +1,4 @@+use crate::termwindow::content_view::ContentViewId;use crate::termwindow::ui::status_icon::UiStatusKind;use crate::termwindow::ui::terminal_title_for_display;use crate::termwindow::{PaneInformation, TabInformation, UIItem, UIItemType};@@ -34,7 +35,9 @@ pub enum TabBarItem {NewTabButton,WindowButton(IntegratedTitleButton),/// Synthetic tab for a ThinkTerm content view (e.g. SSH hosts).- ContentView,+ ContentView {+ id: ContentViewId,+ },}#[derive(Clone, Debug, PartialEq)]diff --git a/wezterm-gui/src/termwindow/content_view.rs b/wezterm-gui/src/termwindow/content_view.rsindex c7e1d6ad..231cc728 100644--- a/wezterm-gui/src/termwindow/content_view.rs+++ b/wezterm-gui/src/termwindow/content_view.rs@@ -1,8 +1,7 @@//! Reusable "content view" framework: a GPU-drawn panel that occupies the-//! terminal content area and behaves like a synthetic tab (switch / close /-//! preserve state). The SSH hosts manager is the first implementer; other-//! native panels can plug in by implementing [`ContentView`] and calling-//! `TermWindow::open_content_view`.+//! terminal content area. Some views behave like synthetic tabs (switch /+//! close / preserve state), while thread-owned views can stay driven by the+//! workspace sidebar instead.use crate::quad::TripleLayerQuadAllocator;use crate::termwindow::TermWindow;@@ -14,6 +13,18 @@ use wezterm_font::LoadedFont;use wezterm_term::{KeyCode, KeyModifiers};use window::{MouseEventKind as WMEK, RectF};+pub(crate) type ContentViewId = u64;++/// Progress of an SSH connection that a content view kicked off, pushed by the+/// owning `TermWindow` while it polls the remote domain. Only the remote-thread+/// view consumes it; `Authenticating`/`Connected` are not pushed because at that+/// point the view is closed and the real terminal is revealed instead.+#[derive(Clone, Debug)]+pub(crate) enum RemoteConnectPhase {+ Connecting,+ Failed { message: String },+}+/// What `TermWindow` should do after a content view handled an input event.pub(crate) enum ContentViewResponse {/// Event not consumed by the view.@@ -30,6 +41,32 @@ pub(crate) trait ContentView {/// Title shown on the synthetic tab.fn title(&self) -> String;+ /// Whether this view should appear in the window's top tab bar.+ fn show_in_tab_bar(&self) -> bool {+ true+ }++ /// Stable key used to activate an existing tab instead of opening a duplicate.+ fn tab_key(&self) -> Option<String> {+ None+ }++ /// Space id that owns this synthetic tab. `None` means the view is global+ /// and remains visible while switching Spaces.+ fn space_id(&self) -> Option<&str> {+ None+ }++ /// Called when a deduplicated or background synthetic tab is explicitly+ /// brought back to the foreground by user action.+ fn on_reactivated(&mut self) -> ContentViewResponse {+ ContentViewResponse::Ignored+ }++ /// Push SSH connection progress into a view that initiated a connection.+ /// Default is a no-op; only the remote-thread view reacts.+ fn on_remote_connect_phase(&mut self, _phase: RemoteConnectPhase) {}+/// Whether the view currently wants the cursor-blink animation running/// (true only while a text field is focused, to avoid needless repaints).fn wants_cursor_blink(&self) -> bool {diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rsindex 9ea0a37c..b98a9a06 100644--- a/wezterm-gui/src/termwindow/keyevent.rs+++ b/wezterm-gui/src/termwindow/keyevent.rs@@ -493,7 +493,9 @@ impl super::TermWindow {self.content_view_copy();return true;}- let resp = self.content_view.as_mut().map(|v| v.on_key(term_key, mods));+ let resp = self+ .active_content_view_mut()+ .map(|v| v.on_key(term_key, mods));match resp {Some(crate::termwindow::content_view::ContentViewResponse::Ignored)| None => {}@@ -505,7 +507,7 @@ impl super::TermWindow {}// IME / composed text (e.g. CJK input) arrives here.Key::Composed(text) => {- let resp = self.content_view.as_mut().map(|v| v.on_paste(&text));+ let resp = self.active_content_view_mut().map(|v| v.on_paste(&text));if let Some(resp) = resp {self.handle_content_response(resp);}@@ -722,7 +724,31 @@ impl super::TermWindow {stage.finish(pane.is_some());let pane = match pane {Some(pane) => pane,- None => return,+ None => {+ if self.content_view_foreground() && key.key_is_down {+ match self.win_key_code_to_termwiz_key_code(&key.key) {+ Key::Code(term_key) => {+ let mods = key.modifiers.remove_positional_mods();+ let resp = self+ .active_content_view_mut()+ .map(|view| view.on_key(term_key, mods));+ if let Some(resp) = resp {+ self.handle_content_response(resp);+ }+ }+ Key::Composed(text) => {+ let resp = self+ .active_content_view_mut()+ .map(|view| view.on_paste(&text));+ if let Some(resp) = resp {+ self.handle_content_response(resp);+ }+ }+ Key::None => {}+ }+ }+ return;+ }};// First, try to match raw physical key@@ -884,7 +910,31 @@ impl super::TermWindow {stage.finish(pane.is_some());let pane = match pane {Some(pane) => pane,- None => return,+ None => {+ if self.content_view_foreground() && window_key.key_is_down {+ match self.win_key_code_to_termwiz_key_code(&window_key.key) {+ Key::Code(term_key) => {+ let mods = window_key.modifiers.remove_positional_mods();+ let resp = self+ .active_content_view_mut()+ .map(|view| view.on_key(term_key, mods));+ if let Some(resp) = resp {+ self.handle_content_response(resp);+ }+ }+ Key::Composed(text) => {+ let resp = self+ .active_content_view_mut()+ .map(|view| view.on_paste(&text));+ if let Some(resp) = resp {+ self.handle_content_response(resp);+ }+ }+ Key::None => {}+ }+ }+ return;+ }};// The leader key is a kind of modal modifier key.diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex dd7e2978..c4dfdcaa 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -18,6 +18,7 @@ use crate::tabbar::{TabBarItem, TabBarState};use crate::termwindow::background::{load_background_image, reload_background_image, LoadedBackgroundLayer,};+use crate::termwindow::content_view::{ContentView, ContentViewId};use crate::termwindow::keyevent::{KeyTableArgs, KeyTableState};use crate::termwindow::modal::Modal;use crate::termwindow::render::paint::AllowImage;@@ -56,7 +57,7 @@ use mux_lua::MuxPane;use smol::channel::Sender;use smol::Timer;use std::cell::{RefCell, RefMut};-use std::collections::{HashMap, LinkedList};+use std::collections::{HashMap, HashSet, LinkedList};use std::ops::Add;use std::path::PathBuf;use std::rc::Rc;@@ -93,6 +94,7 @@ pub mod onboarding;pub mod palette;pub mod paneselect;mod prevcursor;+pub mod remote_thread_view;pub mod render;pub mod resize;mod selection;@@ -141,6 +143,30 @@ pub(crate) fn theme_aligned_tab_bar_colors_from_palette(palette: &ColorPalette)inactive_tab_edge_hover: Some(rgba(background)),}}++struct ContentViewTab {+ id: ContentViewId,+ key: Option<String>,+ space_id: Option<String>,+ view: Box<dyn ContentView>,+}++/// An in-flight SSH connection started from a `RemoteThreadView`. The view stays+/// foreground as the "Connecting…" UI while we poll the background SSH domain;+/// on success we adopt the materialized workspace, on failure we kill it.+pub(crate) struct RemoteConnectState {+ pub generation: u64,+ pub thread_id: String,+ pub workspace_name: String,+ pub domain_name: String,+ pub started: std::time::Instant,+ /// Startup-created mux window that should be cleaned up only if the remote+ /// workspace is successfully adopted.+ pub orphan_candidate_window_id: Option<MuxWindowId>,+ /// `(domain_name, host_id)` to run OS detection on once connected.+ pub detect_os: Option<(String, String)>,+}+use crate::spawn::SpawnWhere;use prevcursor::PrevCursorPos;@@ -260,7 +286,7 @@ pub enum UIItemType {BelowScrollThumb,Split(PositionedSplit),/// Close button on the synthetic content-view tab.- ContentViewClose,+ ContentViewClose(ContentViewId),}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -765,15 +791,20 @@ pub struct TermWindow {context_menu: Option<ui::context_menu::ContextMenuState>,context_menu_suppressed_release: Option<MousePress>,dragging: Option<(UIItem, MouseEvent)>,- /// When `Some`, a content view (e.g. SSH hosts) is available as a synthetic- /// tab. `content_view_active` is whether it is the foreground content (vs a- /// terminal tab being shown).- content_view: Option<Box<dyn crate::termwindow::content_view::ContentView>>,- content_view_active: bool,+ /// Content views (e.g. SSH hosts) shown as synthetic tabs.+ content_views: Vec<ContentViewTab>,+ active_content_view_id: Option<ContentViewId>,+ content_view_response_tab_id: Option<ContentViewId>,+ next_content_view_id: ContentViewId,+ registered_content_view_surfaces: HashMap<ContentViewId, MuxWindowId>,+ /// Tracks SSH connections kicked off by `RemoteThreadView`s.+ remote_connects: HashMap<ContentViewId, RemoteConnectState>,+ next_remote_connect_generation: u64,space_owner_id: u64,active_space_id: String,workspace_layout_structure_fingerprint: Option<u64>,workspace_sidebar_width: usize,+ workspace_sidebar_pending_thread_selection: Option<String>,workspace_sidebar_collapsed: bool,workspace_sidebar_scroll_offset: f32,workspace_sidebar_scrollbar_visible_until: Option<Instant>,@@ -1269,12 +1300,18 @@ impl TermWindow {context_menu: None,context_menu_suppressed_release: None,dragging: None,- content_view: None,- content_view_active: false,+ content_views: vec![],+ active_content_view_id: None,+ content_view_response_tab_id: None,+ next_content_view_id: 1,+ registered_content_view_surfaces: HashMap::new(),+ remote_connects: HashMap::new(),+ next_remote_connect_generation: 1,space_owner_id,active_space_id,workspace_layout_structure_fingerprint,workspace_sidebar_width,+ workspace_sidebar_pending_thread_selection: None,workspace_sidebar_collapsed: !native_settings.onboarding.show_left_sidebar_by_default,workspace_sidebar_scroll_offset: 0.0,workspace_sidebar_scrollbar_visible_until: None,@@ -1957,6 +1994,7 @@ impl TermWindow {front_end().rebind_known_window(window, mux_window_id);}+ self.sync_content_view_surfaces_with_mux();self.clear_all_overlays();self.current_highlight.take();self.apply_workspace_thread_font_scales();@@ -2244,11 +2282,14 @@ impl TermWindow {return;}self.snapshot_active_workspace_thread_layout();+ self.workspace_sidebar_pending_thread_selection = None;if !crate::workspace_threads::switch_window_space(self.space_owner_id, &space_id) {window.invalidate();return;}+ self.set_content_view_active(false);self.active_space_id = space_id.clone();+ self.sync_content_view_surfaces_with_mux();self.workspace_sidebar_scroll_offset = 0.0;if let Some(thread_id) = crate::workspace_threads::ensure_active_thread_for_space(&space_id){@@ -2264,6 +2305,7 @@ impl TermWindow {let deleted_active_space = self.active_space_id == space_id;if deleted_active_space {self.active_space_id = deleted.fallback_space_id.clone();+ self.sync_content_view_surfaces_with_mux();self.workspace_sidebar_scroll_offset = 0.0;if let Some(window) = window {if let Some(thread_id) =@@ -2573,30 +2615,234 @@ impl TermWindow {/// True when a content view is the foreground content (occupying the/// content area instead of terminal panes).pub(crate) fn content_view_foreground(&self) -> bool {- self.content_view.is_some() && self.content_view_active+ self.active_content_view_index().is_some()}- pub(crate) fn open_content_view(- &mut self,- view: Box<dyn crate::termwindow::content_view::ContentView>,- ) {- self.content_view = Some(view);- self.content_view_active = true;+ fn content_view_visible_in_active_space(&self, tab: &ContentViewTab) -> bool {+ match tab.space_id.as_deref() {+ Some(space_id) => space_id == self.active_space_id,+ None => true,+ }+ }++ fn content_view_shown_in_tab_bar(&self, tab: &ContentViewTab) -> bool {+ self.content_view_visible_in_active_space(tab) && tab.view.show_in_tab_bar()+ }++ fn active_content_view_shown_in_tab_bar(&self) -> bool {+ self.active_content_view_id.is_some_and(|active_id| {+ self.content_views+ .iter()+ .any(|tab| tab.id == active_id && self.content_view_shown_in_tab_bar(tab))+ })+ }++ fn content_view_surface_id(id: ContentViewId) -> String {+ format!("thinkterm-content-view:{id}")+ }++ fn sync_content_view_surfaces_with_mux(&mut self) {+ let mux = Mux::get();+ let mux_window_id = self.mux_window_id;+ let foreground_ids = self+ .active_content_view_id+ .filter(|active_id| {+ self.content_views.iter().any(|tab| {+ tab.id == *active_id && self.content_view_visible_in_active_space(tab)+ })+ })+ .into_iter()+ .collect::<HashSet<_>>();++ let registered = self+ .registered_content_view_surfaces+ .iter()+ .map(|(id, window_id)| (*id, *window_id))+ .collect::<Vec<_>>();+ for (id, window_id) in registered {+ if window_id != mux_window_id || !foreground_ids.contains(&id) {+ mux.unregister_window_ui_surface(window_id, &Self::content_view_surface_id(id));+ self.registered_content_view_surfaces.remove(&id);+ }+ }++ for id in foreground_ids {+ if self.registered_content_view_surfaces.get(&id).copied() == Some(mux_window_id) {+ continue;+ }++ if mux.register_window_ui_surface(mux_window_id, Self::content_view_surface_id(id)) {+ self.registered_content_view_surfaces+ .insert(id, mux_window_id);+ }+ }+ }++ fn active_content_view_index(&self) -> Option<usize> {+ let active_id = self.active_content_view_id?;+ self.content_views+ .iter()+ .position(|tab| tab.id == active_id && self.content_view_visible_in_active_space(tab))+ }++ pub(crate) fn active_content_view(&self) -> Option<&dyn ContentView> {+ self.active_content_view_index()+ .map(|idx| self.content_views[idx].view.as_ref())+ }++ pub(crate) fn active_content_view_mut(&mut self) -> Option<&mut dyn ContentView> {+ let idx = self.active_content_view_index()?;+ Some(self.content_views[idx].view.as_mut())+ }++ fn content_view_mut_by_id(&mut self, id: ContentViewId) -> Option<&mut dyn ContentView> {+ let idx = self.content_views.iter().position(|tab| tab.id == id)?;+ Some(self.content_views[idx].view.as_mut())+ }++ fn content_view_id_for_key(&self, key: &str) -> Option<ContentViewId> {+ self.content_views+ .iter()+ .find(|tab| {+ tab.key.as_deref() == Some(key) && self.content_view_visible_in_active_space(tab)+ })+ .map(|tab| tab.id)+ }++ fn active_content_view_key_is(&self, key: &str) -> bool {+ self.active_content_view_id+ .and_then(|id| self.content_views.iter().find(|tab| tab.id == id))+ .and_then(|tab| tab.key.as_deref())+ == Some(key)+ }++ pub(crate) fn active_content_view_is_remote_thread(&self) -> bool {+ self.active_content_view()+ .and_then(|view| view.tab_key())+ .is_some_and(|key| {+ key.starts_with(+ crate::termwindow::remote_thread_view::REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX,+ )+ })+ }++ pub(crate) fn content_view_count(&self) -> usize {+ self.content_views+ .iter()+ .filter(|tab| self.content_view_shown_in_tab_bar(tab))+ .count()+ }++ fn content_view_pending_thread_selection(&self, id: ContentViewId) -> Option<String> {+ self.content_views+ .iter()+ .find(|tab| tab.id == id)+ .and_then(|tab| tab.key.as_deref())+ .and_then(|key| {+ key.strip_prefix(+ crate::termwindow::remote_thread_view::REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX,+ )+ })+ .map(ToString::to_string)+ }++ fn sync_workspace_sidebar_pending_thread_selection(&mut self) {+ self.workspace_sidebar_pending_thread_selection = self+ .active_content_view_id+ .and_then(|id| self.content_view_pending_thread_selection(id));+ }++ fn set_active_content_view_id(&mut self, id: Option<ContentViewId>) {+ let was_foreground = self.content_view_foreground();+ self.active_content_view_id = id.filter(|id| {+ self.content_views+ .iter()+ .any(|tab| tab.id == *id && self.content_view_visible_in_active_space(tab))+ });+ self.sync_content_view_surfaces_with_mux();+ self.sync_workspace_sidebar_pending_thread_selection();+ if was_foreground && !self.content_view_foreground() {+ self.resize_mux_tabs_to_current_terminal_size();+ }self.invalidate_window();}+ fn reactivate_content_view_by_id(&mut self, id: ContentViewId) {+ let response = self+ .content_view_mut_by_id(id)+ .map(|view| view.on_reactivated())+ .unwrap_or(crate::termwindow::content_view::ContentViewResponse::Ignored);+ self.handle_content_response_for(id, response);+ }++ pub(crate) fn open_content_view(&mut self, view: Box<dyn ContentView>) -> ContentViewId {+ let key = view.tab_key();+ let space_id = view.space_id().map(ToString::to_string);+ if let Some(existing_id) = key+ .as_deref()+ .and_then(|key| self.content_view_id_for_key(key))+ {+ self.set_active_content_view_id(Some(existing_id));+ // A reactivation response may close the tab; callers only use this+ // as an activation request and do not rely on the returned id+ // remaining open.+ self.reactivate_content_view_by_id(existing_id);+ return existing_id;+ }++ let id = self.next_content_view_id;+ self.next_content_view_id = self.next_content_view_id.saturating_add(1).max(1);+ self.content_views.push(ContentViewTab {+ id,+ key,+ space_id,+ view,+ });+ self.set_active_content_view_id(Some(id));+ id+ }+pub(crate) fn close_content_view(&mut self) {- self.content_view = None;- self.content_view_active = false;- self.invalidate_window();+ if let Some(id) = self+ .content_view_response_tab_id+ .or(self.active_content_view_id)+ {+ self.close_content_view_by_id(id);+ }}- pub(crate) fn request_close_content_view(&mut self) {- let response = match self.content_view.as_mut() {- Some(view) => view.on_close_requested(),- None => crate::termwindow::content_view::ContentViewResponse::Ignored,+ pub(crate) fn close_content_view_by_id(&mut self, id: ContentViewId) {+ let was_foreground = self.active_content_view_id == Some(id);+ let Some(idx) = self.content_views.iter().position(|tab| tab.id == id) else {+ return;};- self.handle_content_response(response);+ self.content_views.remove(idx);++ if was_foreground {+ self.active_content_view_id = self+ .content_views+ .iter()+ .take(idx)+ .rev()+ .chain(self.content_views.iter().skip(idx))+ .find(|tab| self.content_view_visible_in_active_space(tab))+ .map(|tab| tab.id);+ }+ self.sync_content_view_surfaces_with_mux();+ self.sync_workspace_sidebar_pending_thread_selection();++ if was_foreground && !self.content_view_foreground() {+ self.resize_mux_tabs_to_current_terminal_size();+ }+ self.invalidate_window();+ }++ pub(crate) fn request_close_content_view_by_id(&mut self, id: ContentViewId) {+ let response = self+ .content_view_mut_by_id(id)+ .map(|view| view.on_close_requested())+ .unwrap_or(crate::termwindow::content_view::ContentViewResponse::Ignored);+ self.handle_content_response_for(id, response);}pub(crate) fn show_onboarding(&mut self) {@@ -2617,6 +2863,9 @@ impl TermWindow {}pub(crate) fn pick_content_view_folder(&mut self) {+ let Some(view_id) = self.active_content_view_id else {+ return;+ };let Some(window) = self.window.as_ref().cloned() else {return;};@@ -2625,27 +2874,55 @@ impl TermWindow {if let Some(path) = path {notify_window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {let response = term_window- .content_view- .as_mut()+ .content_view_mut_by_id(view_id).map(|view| view.on_folder_picked(path)).unwrap_or(crate::termwindow::content_view::ContentViewResponse::Ignored);- term_window.handle_content_response(response);+ term_window.handle_content_response_for(view_id, response);})));}}));}pub(crate) fn set_content_view_active(&mut self, active: bool) {- if self.content_view.is_some() {- self.content_view_active = active;- self.invalidate_window();+ if active {+ let id = self+ .active_content_view_id+ .filter(|id| {+ self.content_views+ .iter()+ .any(|tab| tab.id == *id && self.content_view_visible_in_active_space(tab))+ })+ .or_else(|| {+ self.content_views+ .iter()+ .rev()+ .find(|tab| self.content_view_visible_in_active_space(tab))+ .map(|tab| tab.id)+ });+ self.set_active_content_view_id(id);+ } else {+ self.set_active_content_view_id(None);+ }+ }++ pub(crate) fn activate_content_view(&mut self, id: ContentViewId) {+ if self+ .content_views+ .iter()+ .any(|tab| tab.id == id && self.content_view_visible_in_active_space(tab))+ {+ self.set_active_content_view_id(Some(id));+ self.reactivate_content_view_by_id(id);}}/// Toggle the SSH hosts content view (sidebar button / OpenSshHosts).pub(crate) fn toggle_ssh_hosts_view(&mut self) {- if self.content_view.is_some() {+ let key = crate::termwindow::ssh_hosts_view::SSH_HOSTS_CONTENT_VIEW_KEY;+ if self.active_content_view_key_is(key) {self.close_content_view();+ } else if let Some(id) = self.content_view_id_for_key(key) {+ self.activate_content_view(id);} else {self.open_content_view(Box::new(crate::termwindow::ssh_hosts_view::SshHostsView::new(),@@ -2661,7 +2938,7 @@ impl TermWindow {/// Copy the active content view's focused text to the clipboard (⌘C).pub(crate) fn content_view_copy(&mut self) {- if let Some(text) = self.content_view.as_ref().and_then(|v| v.copy_text()) {+ if let Some(text) = self.active_content_view().and_then(|v| v.copy_text()) {if !text.is_empty() {self.copy_to_clipboard(config::keyassignment::ClipboardCopyDestination::Clipboard,@@ -2673,7 +2950,7 @@ impl TermWindow {/// Cut the active content view's selected text to the clipboard (⌘X).pub(crate) fn content_view_cut(&mut self) {- if let Some(text) = self.content_view.as_mut().and_then(|v| v.cut_text()) {+ if let Some(text) = self.active_content_view_mut().and_then(|v| v.cut_text()) {if !text.is_empty() {self.copy_to_clipboard(config::keyassignment::ClipboardCopyDestination::Clipboard,@@ -2685,6 +2962,9 @@ impl TermWindow {}fn content_view_paste_from(&mut self, clipboard: ClipboardPasteSource) {+ let Some(view_id) = self.active_content_view_id else {+ return;+ };let Some(window) = self.window.as_ref().map(|w| w.clone()) else {return;};@@ -2696,9 +2976,11 @@ impl TermWindow {promise::spawn::spawn(async move {if let Ok(clip) = future.await {window.notify(TermWindowNotif::Apply(Box::new(move |myself| {- let resp = myself.content_view.as_mut().map(|v| v.on_paste(&clip));+ let resp = myself+ .content_view_mut_by_id(view_id)+ .map(|v| v.on_paste(&clip));if let Some(resp) = resp {- myself.handle_content_response(resp);+ myself.handle_content_response_for(view_id, resp);}})));}@@ -2716,17 +2998,30 @@ impl TermWindow {pub(crate) fn handle_content_response(&mut self,response: crate::termwindow::content_view::ContentViewResponse,+ ) {+ let Some(id) = self.active_content_view_id else {+ return;+ };+ self.handle_content_response_for(id, response);+ }++ pub(crate) fn handle_content_response_for(+ &mut self,+ id: ContentViewId,+ response: crate::termwindow::content_view::ContentViewResponse,) {use crate::termwindow::content_view::ContentViewResponse;match response {ContentViewResponse::Ignored => return,ContentViewResponse::Redraw => {}ContentViewResponse::Close => {- self.content_view = None;- self.content_view_active = false;+ self.close_content_view_by_id(id);+ return;}ContentViewResponse::Run(func) => {+ let previous_response_tab_id = self.content_view_response_tab_id.replace(id);func(self);+ self.content_view_response_tab_id = previous_response_tab_id;}}self.invalidate_window();@@ -3709,7 +4004,7 @@ impl TermWindow {if self.content_view_foreground() {match assignment {CopyTo(destination) => {- if let Some(text) = self.content_view.as_ref().and_then(|v| v.copy_text()) {+ if let Some(text) = self.active_content_view().and_then(|v| v.copy_text()) {if !text.is_empty() {self.copy_to_clipboard(*destination, text);}@@ -3940,9 +4235,8 @@ impl TermWindow {}}CreateWorkspaceThread(project_id) => {- let thread_id = crate::workspace_threads::create_thread(project_id, None);if let Some(window) = window.as_ref() {- self.activate_workspace_thread(thread_id, window);+ self.create_workspace_thread(project_id, window);}}ToggleWorkspaceThreadsCollapsed(project_id) => {@@ -3971,6 +4265,17 @@ impl TermWindow {}}}+ ConnectWorkspaceThread(thread_id) => {+ if let Some(window) = window.as_ref() {+ self.connect_remote_thread(thread_id.clone(), window);+ }+ }+ DisconnectWorkspaceThread(thread_id) => {+ self.disconnect_workspace_thread(+ thread_id,+ window.as_ref().map(|w| w as &dyn WindowOps),+ );+ }ToggleWorkspaceThreadPinned(thread_id) => {crate::workspace_threads::toggle_thread_pinned(thread_id);if let Some(window) = window.as_ref() {@@ -3978,23 +4283,7 @@ impl TermWindow {}}DeleteWorkspaceThread(thread_id) => {- if let Some(deleted) = crate::workspace_threads::delete_thread(thread_id) {- if deleted.was_active {- if let (Some(next_thread_id), Some(window)) =- (deleted.next_thread_id, window.as_ref())- {- self.activate_workspace_thread(next_thread_id, window);- }- } else if let Some(workspace) = deleted.materialized_workspace_name {- let mux = Mux::get();- for window_id in mux.iter_windows_in_workspace(&workspace) {- mux.kill_window(window_id);- }- }- if let Some(window) = window.as_ref() {- window.invalidate();- }- }+ self.end_workspace_thread(thread_id, window.as_ref().map(|w| w as &dyn WindowOps));}MarkWorkspaceThreadUnread(thread_id) => {crate::workspace_threads::mark_thread_unread(thread_id);diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 4627040d..00a81e13 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1,5 +1,6 @@use crate::frontend::front_end;use crate::tabbar::TabBarItem;+use crate::termwindow::content_view::ContentViewId;use crate::termwindow::ui::pane_nav_bar_height_for_metrics;use crate::termwindow::ui::platform_chrome::WindowTabChromeParams;use crate::termwindow::ui::tokens::{@@ -21,7 +22,7 @@ use config::keyassignment::{};use config::{MouseEventAltScreen, TermConfig};use mux::pane::{Pane, WithPaneLines};-use mux::ssh::RemoteSshDomain;+use mux::ssh::{RemoteSshDomain, SshConnectionStatus};use mux::tab::{PositionedPane, SplitDirection};use mux::window::WindowId as MuxWindowId;use mux::Mux;@@ -39,6 +40,10 @@ use wezterm_term::{ClickPosition, LastMouseClick, StableRowIndex};const TAB_WHEEL_SURFACE_LOCK_MS: u64 = 700;const TAB_WHEEL_DIRECTION_LOCK_MS: u64 = 140;+/// Overall ceiling on the "Connecting…" phase, as a backstop for the case where+/// the TCP connect succeeds but the SSH banner/handshake then stalls (the+/// per-connect `connecttimeout` only bounds the TCP connect itself).+const REMOTE_CONNECT_OVERALL_TIMEOUT_SECS: u64 = 20;impl super::TermWindow {pub(crate) fn collapsed_pane_min_cells(&self) -> usize {@@ -181,7 +186,12 @@ impl super::TermWindow {let Some(window) = mux.get_window(self.mux_window_id) else {return 0.0;};- let tab_count = window.len();+ let window_tab_count = if self.active_content_view_is_remote_thread() {+ 0+ } else {+ window.len()+ };+ let tab_count = window_tab_count + self.content_view_count();if tab_count <= 1 {return 0.0;}@@ -628,7 +638,7 @@ impl super::TermWindow {| UIItemType::BelowScrollThumb| UIItemType::ScrollThumb| UIItemType::Split(_)- | UIItemType::ContentViewClose => {}+ | UIItemType::ContentViewClose(_) => {}}}@@ -677,7 +687,7 @@ impl super::TermWindow {| UIItemType::BelowScrollThumb| UIItemType::ScrollThumb| UIItemType::Split(_)- | UIItemType::ContentViewClose => {}+ | UIItemType::ContentViewClose(_) => {}}}@@ -745,10 +755,7 @@ impl super::TermWindow {pub fn mouse_event_impl(&mut self, event: MouseEvent, context: &dyn WindowOps) {log::trace!("{:?}", event);- let pane = match self.get_active_pane_or_overlay() {- Some(pane) => pane,- None => return,- };+ let pane = self.get_active_pane_or_overlay();self.current_mouse_event.replace(event.clone());@@ -756,8 +763,25 @@ impl super::TermWindow {return;}- if self.mouse_event_context_menu(&event, &pane, context) {- return;+ if let Some(pane) = pane.as_ref() {+ if self.mouse_event_context_menu(&event, pane, context) {+ return;+ }+ } else if matches!(+ self.current_mouse_capture,+ Some(MouseCapture::TerminalPane(_))+ ) {+ self.current_mouse_capture = None;+ }++ if pane.is_none()+ && matches!(+ self.current_mouse_capture,+ None | Some(MouseCapture::TerminalPane(_))+ )+ && !self.content_view_foreground()+ {+ self.current_mouse_capture = None;}if self.mouse_wheel_right_sidebar(&event, context) {@@ -796,7 +820,8 @@ impl super::TermWindow {.sub((padding_left + border.left.get() as f32) as isize).max(0) as f32)/ self.render_metrics.cell_size.width as f32;- let x = if !pane.is_mouse_grabbed() {+ let pane_mouse_grabbed = pane.as_ref().is_some_and(|pane| pane.is_mouse_grabbed());+ let x = if !pane_mouse_grabbed {// Round the x coordinate so that we're a bit more forgiving of// the horizontal position when selecting cellsx.round()@@ -947,15 +972,18 @@ impl super::TermWindow {if capture_mouse {self.current_mouse_capture = Some(MouseCapture::UI);}- self.mouse_event_ui_item(item, pane, y, event, context);+ if let Some(pane) = pane.clone() {+ self.mouse_event_ui_item(item, pane, y, event, context);+ } else {+ self.mouse_event_ui_item_without_pane(item, event, context);+ }} else if self.content_view_foreground() {// The content view owns the content area; route by pixel coords.context.set_cursor(Some(MouseCursor::Arrow));let px = event.coords.x as f32;let py = event.coords.y as f32;let resp = self- .content_view- .as_mut()+ .active_content_view_mut().map(|v| v.on_mouse(px, py, event.kind));if let Some(resp) = resp {self.handle_content_response(resp);@@ -964,6 +992,14 @@ impl super::TermWindow {self.current_mouse_capture,None | Some(MouseCapture::TerminalPane(_))) {+ let Some(pane) = pane else {+ context.set_cursor(Some(MouseCursor::Arrow));+ context.invalidate();+ if prior_ui_item != ui_item {+ self.update_title_post_status();+ }+ return;+ };if event.kind == WMEK::Press(MousePress::Left) && self.right_sidebar_has_text_focus() {self.right_sidebar_snippet_focus = None;context.invalidate();@@ -1230,6 +1266,16 @@ impl super::TermWindow {) {self.last_ui_item.replace(item.clone());match item.item_type {+ UIItemType::TabBar(TabBarItem::NewTabButton { .. })+ if self.active_content_view_is_remote_thread() =>+ {+ self.mouse_event_disabled_new_tab_button(context);+ }+ UIItemType::TabBar(TabBarItem::NewTabButton { .. })+ if self.content_view_foreground() =>+ {+ self.mouse_event_local_new_tab_button(event, context);+ }UIItemType::TabBar(item) => {self.mouse_event_tab_bar(item, event, context);}@@ -1340,10 +1386,10 @@ impl super::TermWindow {self.toggle_ssh_hosts_view();}}- UIItemType::ContentViewClose => {+ UIItemType::ContentViewClose(id) => {context.set_cursor(Some(MouseCursor::Hand));if event.kind == WMEK::Press(MousePress::Left) {- self.request_close_content_view();+ self.request_close_content_view_by_id(id);}}UIItemType::WorkspaceSidebarViewOptions => {@@ -1361,6 +1407,141 @@ impl super::TermWindow {}}+ fn mouse_event_ui_item_without_pane(+ &mut self,+ item: UIItem,+ event: MouseEvent,+ context: &dyn WindowOps,+ ) {+ self.last_ui_item.replace(item.clone());+ match item.item_type {+ UIItemType::TabBar(TabBarItem::NewTabButton { .. })+ if self.active_content_view_is_remote_thread() =>+ {+ self.mouse_event_disabled_new_tab_button(context);+ }+ UIItemType::TabBar(TabBarItem::NewTabButton { .. }) => {+ self.mouse_event_local_new_tab_button(event, context);+ }+ UIItemType::TabBar(item) => {+ self.mouse_event_tab_bar(item, event, context);+ }+ UIItemType::CloseTab(idx) => {+ self.mouse_event_close_tab(idx, event, context);+ }+ UIItemType::ProjectNew => {+ self.mouse_event_project_new(event, context);+ }+ UIItemType::SpaceMenu => {+ self.mouse_event_space_menu(item, event, context);+ }+ UIItemType::ProjectToggleThreads(project_id) => {+ self.mouse_event_project_toggle_threads(project_id, event, context);+ }+ UIItemType::Project(project_id) => {+ self.mouse_event_project(project_id, event, context);+ }+ UIItemType::WorkspaceThread(thread_id) => {+ self.mouse_event_workspace_thread(thread_id, event, context);+ }+ UIItemType::WorkspaceThreadPin(thread_id) => {+ self.mouse_event_workspace_thread_pin(thread_id, event, context);+ }+ UIItemType::WorkspaceThreadDelete(thread_id) => {+ self.mouse_event_workspace_thread_delete(thread_id, event, context);+ }+ UIItemType::WorkspaceThreadNew(project_id) => {+ self.mouse_event_workspace_thread_new(project_id, event, context);+ }+ UIItemType::WorkspaceSidebarToggle => {+ self.mouse_event_workspace_sidebar_toggle(event, context);+ }+ UIItemType::WorkspaceSidebarHeaderBlank => {+ self.mouse_event_workspace_sidebar_header_blank(event, context);+ }+ UIItemType::WorkspaceSidebarBackground => {+ context.set_cursor(Some(MouseCursor::Arrow));+ }+ UIItemType::WorkspaceSidebarScrollTrack => {+ self.mouse_event_workspace_sidebar_scroll_track(item, event, context);+ }+ UIItemType::WorkspaceSidebarScrollThumb => {+ self.mouse_event_workspace_sidebar_scroll_thumb(item, event, context);+ }+ UIItemType::WorkspaceSidebarResize => {+ self.mouse_event_workspace_sidebar_resize(item, event, context);+ }+ UIItemType::WorkspaceSidebarSettings => {+ self.mouse_event_workspace_sidebar_settings(event, context);+ }+ UIItemType::WorkspaceSidebarSshHosts => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.toggle_ssh_hosts_view();+ }+ }+ UIItemType::WorkspaceSidebarViewOptions => {+ self.mouse_event_workspace_sidebar_view_options(item, event, context);+ }+ UIItemType::WorkspaceSidebarNotifications => {+ context.set_cursor(Some(MouseCursor::Hand));+ }+ UIItemType::RightSidebarToggle => {+ self.mouse_event_right_sidebar_toggle(event, context);+ }+ UIItemType::RightSidebarMode(mode) => {+ self.mouse_event_right_sidebar_mode(mode, event, context);+ }+ UIItemType::RightSidebarBackground => {+ context.set_cursor(Some(MouseCursor::Arrow));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.right_sidebar_snippet_focus = None;+ context.invalidate();+ }+ }+ UIItemType::RightSidebarResize => {+ self.mouse_event_right_sidebar_resize(item, event, context);+ }+ UIItemType::RightSidebarSnippetScrollTrack => {+ self.mouse_event_right_sidebar_snippet_scroll_track(item, event, context);+ }+ UIItemType::RightSidebarSnippetScrollThumb => {+ self.mouse_event_right_sidebar_snippet_scroll_thumb(item, event, context);+ }+ UIItemType::RightSidebarSnippetNew+ | UIItemType::RightSidebarSnippetBack+ | UIItemType::RightSidebarSnippetSave+ | UIItemType::RightSidebarSnippetSearch+ | UIItemType::RightSidebarSnippetTitle+ | UIItemType::RightSidebarSnippetBody+ | UIItemType::RightSidebarSnippetEdit(_)+ | UIItemType::RightSidebarSnippetPaste(_)+ | UIItemType::RightSidebarSnippetRun(_)+ | UIItemType::RightSidebarSnippetDelete(_) => {+ self.mouse_event_right_sidebar_snippet(item.item_type.clone(), event, context);+ }+ UIItemType::ContentViewClose(id) => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.request_close_content_view_by_id(id);+ }+ }+ UIItemType::ContextMenuBackdrop => {+ context.set_cursor(Some(MouseCursor::Arrow));+ }+ UIItemType::ContextMenuItem(_) => {+ context.set_cursor(Some(MouseCursor::Hand));+ }+ UIItemType::AboveScrollThumb+ | UIItemType::ScrollThumb+ | UIItemType::BelowScrollThumb+ | UIItemType::Split(_)+ | UIItemType::PaneNav { .. } => {+ context.set_cursor(Some(MouseCursor::Arrow));+ }+ }+ }+fn reflow_workspace_sidebar(&mut self, context: &dyn WindowOps) {if let Some(window) = self.window.as_ref().cloned() {let dimensions = self.dimensions;@@ -1384,7 +1565,7 @@ impl super::TermWindow {context: &dyn WindowOps,) {context.set_cursor(Some(MouseCursor::SizeLeftRight));- if event.kind == WMEK::Press(MousePress::Left) {+ if matches!(event.kind, WMEK::Press(MousePress::Left)) {self.dragging.replace((item, event));}}@@ -1616,8 +1797,7 @@ impl super::TermWindow {context: &dyn WindowOps,) {if let WMEK::Press(MousePress::Left) = event.kind {- let thread_id = crate::workspace_threads::create_thread(&project_id, None);- self.activate_workspace_thread(thread_id, context);+ self.create_workspace_thread(&project_id, context);}context.set_cursor(Some(MouseCursor::Arrow));}@@ -1705,7 +1885,9 @@ impl super::TermWindow {) {match event.kind {WMEK::Press(MousePress::Left) => {- self.activate_workspace_thread(thread_id, context);+ if !self.open_remote_workspace_thread_without_connecting(&thread_id, context) {+ self.activate_workspace_thread(thread_id, context);+ }}WMEK::Press(MousePress::Right) => {self.show_term_context_menu(@@ -1750,19 +1932,7 @@ impl super::TermWindow {) {match event.kind {WMEK::Press(MousePress::Left) => {- if let Some(deleted) = crate::workspace_threads::delete_thread(&thread_id) {- if deleted.was_active {- if let Some(next_thread_id) = deleted.next_thread_id {- self.activate_workspace_thread(next_thread_id, context);- }- } else if let Some(workspace) = deleted.materialized_workspace_name {- let mux = Mux::get();- for window_id in mux.iter_windows_in_workspace(&workspace) {- mux.kill_window(window_id);- }- }- context.invalidate();- }+ self.end_workspace_thread(&thread_id, Some(context));}WMEK::Press(MousePress::Right) => {self.show_term_context_menu(@@ -1776,6 +1946,121 @@ impl super::TermWindow {context.set_cursor(Some(MouseCursor::Arrow));}+ pub(crate) fn end_workspace_thread(+ &mut self,+ thread_id: &str,+ context: Option<&dyn WindowOps>,+ ) {+ match crate::workspace_threads::end_workspace_thread_record(thread_id) {+ crate::workspace_threads::EndWorkspaceThreadResult::DeletedThread(deleted) => {+ self.finish_deleted_workspace_thread(deleted, context);+ }+ crate::workspace_threads::EndWorkspaceThreadResult::RemovedProject(removed) => {+ self.finish_removed_project(removed, context);+ }+ crate::workspace_threads::EndWorkspaceThreadResult::Noop => {+ if let Some(context) = context {+ context.invalidate();+ }+ }+ }+ }++ pub(crate) fn disconnect_workspace_thread(+ &mut self,+ thread_id: &str,+ context: Option<&dyn WindowOps>,+ ) {+ let live_workspaces = Mux::get().iter_workspaces();+ let Some(disconnected) = crate::workspace_threads::disconnect_workspace_thread_record(+ thread_id,+ &live_workspaces,+ ) else {+ if let Some(context) = context {+ context.invalidate();+ }+ return;+ };++ let cleanup_workspaces = vec![disconnected.workspace_name];+ if disconnected.was_active {+ if let (Some(next_thread_id), Some(context)) = (disconnected.next_thread_id, context) {+ self.activate_workspace_thread_with_cleanup(+ next_thread_id,+ context,+ cleanup_workspaces,+ );+ return;+ }+ if context.is_none() {+ return;+ }+ }++ kill_workspace_windows(&cleanup_workspaces, None);++ if let Some(context) = context {+ context.invalidate();+ }+ }++ fn finish_deleted_workspace_thread(+ &mut self,+ deleted: crate::workspace_threads::DeletedWorkspaceThread,+ context: Option<&dyn WindowOps>,+ ) {+ let cleanup_workspaces = deleted+ .materialized_workspace_name+ .into_iter()+ .collect::<Vec<_>>();+ if deleted.was_active {+ if let (Some(next_thread_id), Some(context)) = (deleted.next_thread_id, context) {+ self.activate_workspace_thread_with_cleanup(+ next_thread_id,+ context,+ cleanup_workspaces,+ );+ return;+ }+ if context.is_none() {+ return;+ }+ }++ kill_workspace_windows(&cleanup_workspaces, None);++ if let Some(context) = context {+ context.invalidate();+ }+ }++ fn finish_removed_project(+ &mut self,+ removed: crate::workspace_threads::RemovedProject,+ context: Option<&dyn WindowOps>,+ ) {+ let cleanup_workspaces = removed.materialized_workspace_names;+ if removed.was_active {+ if let (Some(next_thread_id), Some(context)) = (removed.next_thread_id, context) {+ self.activate_workspace_thread_with_cleanup(+ next_thread_id,+ context,+ cleanup_workspaces,+ );+ return;+ }+ if context.is_none() {+ return;+ }+ }++ kill_workspace_windows(&cleanup_workspaces, None);++ if let Some(context) = context {+ context.invalidate();+ }+ }+fn project_context_menu_items(&self, project_id: &str) -> Vec<ContextMenuItem> {let project_id = project_id.to_string();let mut reveal_item = ContextMenuItem::item_with_icon(@@ -1934,10 +2219,92 @@ impl super::TermWindow {]}+ fn open_remote_workspace_thread_without_connecting(+ &mut self,+ thread_id: &str,+ context: &dyn WindowOps,+ ) -> bool {+ self.open_remote_workspace_thread_view(thread_id, context, false)+ }++ fn open_remote_workspace_thread_view(+ &mut self,+ thread_id: &str,+ context: &dyn WindowOps,+ force_disconnected: bool,+ ) -> bool {+ let live_workspaces = Mux::get().iter_workspaces();+ let Some(mut state) =+ crate::workspace_threads::thread_connection_state(thread_id, &live_workspaces)+ else {+ return false;+ };++ if !state.is_remote || (!force_disconnected && state.is_live) {+ if !state.is_remote {+ return false;+ }++ let key = format!(+ "{}{}",+ crate::termwindow::remote_thread_view::REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX,+ thread_id+ );+ if let Some(view_id) = self.content_view_id_for_key(&key) {+ self.snapshot_active_workspace_thread_layout();+ self.workspace_sidebar_pending_thread_selection = Some(thread_id.to_string());+ self.activate_content_view(view_id);+ context.invalidate();+ return true;+ }++ return false;+ }+ if force_disconnected {+ state.is_live = false;+ }++ self.snapshot_active_workspace_thread_layout();+ self.workspace_sidebar_pending_thread_selection = Some(thread_id.to_string());+ self.open_content_view(Box::new(+ crate::termwindow::remote_thread_view::RemoteThreadView::new(state),+ ));+ context.invalidate();+ true+ }+fn workspace_thread_context_menu_items(&self, thread_id: &str) -> Vec<ContextMenuItem> {let thread_id = thread_id.to_string();let is_pinned = crate::workspace_threads::thread_is_pinned(&thread_id);- vec![+ let live_workspaces = Mux::get().iter_workspaces();+ let connection =+ crate::workspace_threads::thread_connection_state(&thread_id, &live_workspaces);+ let mut items = vec![];++ if let Some(connection) = connection.as_ref() {+ let remote_host_exists = connection.is_remote+ && crate::ssh_hosts::host_spec(+ crate::workspace_threads::remote_host_id_for_project_id(&connection.project_id),+ )+ .is_some();+ if connection.is_remote && connection.is_live {+ items.push(ContextMenuItem::item_with_icon(+ "Disconnect Thread",+ "unlink",+ KeyAssignment::DisconnectWorkspaceThread(thread_id.clone()),+ ));+ items.push(ContextMenuItem::Separator);+ } else if connection.is_remote && remote_host_exists {+ items.push(ContextMenuItem::item_with_icon(+ "Connect Thread",+ "link",+ KeyAssignment::ConnectWorkspaceThread(thread_id.clone()),+ ));+ items.push(ContextMenuItem::Separator);+ }+ }++ items.extend([ContextMenuItem::item_with_icon(if is_pinned {"Unpin Thread"@@ -1962,11 +2329,58 @@ impl super::TermWindow {"envelope.badge",KeyAssignment::MarkWorkspaceThreadUnread(thread_id),),- ]+ ]);+ items}pub(crate) fn activate_workspace_thread(&mut self, thread_id: String, context: &dyn WindowOps) {- self.activate_workspace_thread_impl(thread_id, context, None);+ self.activate_workspace_thread_impl(thread_id, context, None, Vec::new());+ }++ fn activate_workspace_thread_with_cleanup(+ &mut self,+ thread_id: String,+ context: &dyn WindowOps,+ workspaces_to_kill_after_adopt: Vec<String>,+ ) {+ self.activate_workspace_thread_impl(+ thread_id,+ context,+ None,+ workspaces_to_kill_after_adopt,+ );+ }++ pub(crate) fn create_workspace_thread(&mut self, project_id: &str, context: &dyn WindowOps) {+ let thread_id = crate::workspace_threads::create_thread(project_id, None);+ if !self.open_remote_workspace_thread_without_connecting(&thread_id, context) {+ self.activate_workspace_thread(thread_id, context);+ }+ }++ pub(crate) fn open_ssh_host_thread_without_connecting(+ &mut self,+ host_id: String,+ context: &dyn WindowOps,+ ) -> bool {+ let Some(spec) = crate::ssh_hosts::host_spec(&host_id) else {+ context.invalidate();+ return false;+ };++ self.snapshot_active_workspace_thread_layout();+ let thread_id = crate::workspace_threads::create_disconnected_remote_host_thread(+ &self.active_space_id,+ &host_id,+ &spec.label,+ crate::ssh_hosts::host_project_path(&spec),+ spec.default_workspace.clone(),+ );+ if !self.open_remote_workspace_thread_without_connecting(&thread_id, context) {+ context.invalidate();+ return false;+ }+ true}pub(crate) fn activate_workspace_thread_for_new_window(@@ -1975,7 +2389,19 @@ impl super::TermWindow {context: &dyn WindowOps,startup_window_id: MuxWindowId,) {- self.activate_workspace_thread_impl(thread_id, context, Some(startup_window_id));+ if self.open_remote_workspace_thread_without_connecting(&thread_id, context) {+ // Do not auto-connect remote threads while restoring a new window.+ // Remote hosts may be unavailable or expensive to wake; let the+ // disconnected view make the connection an explicit user action.+ return;+ }++ self.activate_workspace_thread_impl(+ thread_id,+ context,+ Some(startup_window_id),+ Vec::new(),+ );}fn activate_workspace_thread_impl(@@ -1983,8 +2409,18 @@ impl super::TermWindow {thread_id: String,context: &dyn WindowOps,orphan_candidate_window_id: Option<MuxWindowId>,+ workspaces_to_kill_after_adopt: Vec<String>,) {+ if crate::workspace_threads::thread_space_id(&thread_id).as_deref()+ != Some(self.active_space_id.as_str())+ {+ context.invalidate();+ return;+ }+self.snapshot_active_workspace_thread_layout();+ self.workspace_sidebar_pending_thread_selection = None;+ self.set_content_view_active(false);let mux = Mux::get();let live_workspaces = mux.iter_workspaces();@@ -2001,20 +2437,36 @@ impl super::TermWindow {// orphaned a startup mux window, tidy it up. cleanup_orphaned_mux_window// is a no-op when the window is still shown or has a thread binding.cleanup_orphaned_mux_window(orphan_candidate_window_id);+ kill_workspace_windows(&workspaces_to_kill_after_adopt, Some(&plan.workspace_name));context.invalidate();return;}let workspace_name = plan.workspace_name.clone();- let remote_spec = crate::ssh_hosts::host_spec(- crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id),- );+ let remote_host_id =+ crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id).to_string();+ let remote_spec = crate::ssh_hosts::host_spec(&remote_host_id);+ if remote_spec.is_none() && crate::workspace_threads::project_is_remote(&plan.project_id) {+ log::warn!(+ "refusing to connect remote thread {:?}: SSH host {:?} no longer exists",+ plan.thread_id,+ remote_host_id+ );+ context.invalidate();+ return;+ }+ let mut detect_remote_os = None;let (initial_cwd, default_domain) = if let Some(spec) = remote_spec.as_ref() {match crate::ssh_hosts::ensure_ssh_domain_registered(spec) {- Ok(domain_name) => (- None,- config::keyassignment::SpawnTabDomain::DomainName(domain_name),- ),+ Ok(domain_name) => {+ if spec.detect_os {+ detect_remote_os = Some((domain_name.clone(), remote_host_id));+ }+ (+ None,+ config::keyassignment::SpawnTabDomain::DomainName(domain_name),+ )+ }Err(err) => {log::error!("failed to register SSH domain for session {:?}: {err:#}",@@ -2046,6 +2498,8 @@ impl super::TermWindow {let reconcile_window = self.window.clone();let adopt_workspace = workspace_name.clone();+ let detect_window = self.window.clone();+ let cleanup_workspaces = workspaces_to_kill_after_adopt;promise::spawn::spawn(async move {let materialized = match crate::workspace_threads::materialize_thread(workspace_name,@@ -2068,93 +2522,229 @@ impl super::TermWindow {front_end().set_switching_workspaces(false);if materialized {cleanup_orphaned_mux_window(orphan_candidate_window_id);+ kill_workspace_windows(&cleanup_workspaces, Some(&adopt_workspace));}reconcile_workspace_layout_after_materialize(reconcile_window);++ if materialized {+ if let Some((detect_domain, detect_project)) = detect_remote_os {+ if let Some(domain) = Mux::get().get_domain_by_name(&detect_domain) {+ if let Some(ssh) = domain.as_ref().downcast_ref::<RemoteSshDomain>() {+ if let Some(distro) = ssh.detect_os_release().await {+ if crate::ssh_hosts::set_host_distro(&detect_project, &distro) {+ if let Some(win) = detect_window.as_ref() {+ win.invalidate();+ }+ }+ }+ }+ }+ }+ }}).detach();context.invalidate();}- /// Connect to a stored SSH host: ensure its mux domain is registered, then- /// create/restore a session in the target workspace (default `ssh:<host>`)- /// whose panes spawn into that SSH domain. Mirrors- /// [`Self::activate_workspace_thread`] but targets the SSH domain.- pub(crate) fn connect_ssh_host(+ fn failed_remote_thread_for_pane(+ &self,+ pane_id: mux::pane::PaneId,+ ) -> Option<(String, String)> {+ let mux = Mux::get();+ let pane = mux.get_pane(pane_id)?;+ let domain = mux.get_domain(pane.domain_id())?;+ let ssh = domain.as_ref().downcast_ref::<RemoteSshDomain>()?;+ let SshConnectionStatus::Failed(message) = ssh.connection_status() else {+ return None;+ };++ let workspace = self.current_mux_workspace()?;+ let thread_id =+ crate::workspace_threads::thread_id_for_workspace(&self.active_space_id, &workspace)?;+ let live_workspaces = mux.iter_workspaces();+ let state =+ crate::workspace_threads::thread_connection_state(&thread_id, &live_workspaces)?;+ state.is_remote.then_some((thread_id, message))+ }++ pub(crate) fn redirect_failed_remote_tab_spawn_to_thread_view(&mut self,- project_id: String,- target_workspace: Option<String>,- ) {- let window = self.window.clone();- let invalidate = |window: &_| {- if let Some(win) = window {- WindowOps::invalidate(win);+ pane_id: mux::pane::PaneId,+ ) -> bool {+ let Some((thread_id, message)) = self.failed_remote_thread_for_pane(pane_id) else {+ return false;+ };+ let Some(window) = self.window.clone() else {+ return false;+ };++ if self.open_remote_workspace_thread_view(&thread_id, &window, true) {+ let key = format!(+ "{}{}",+ crate::termwindow::remote_thread_view::REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX,+ thread_id+ );+ if let Some(view_id) = self.content_view_id_for_key(&key) {+ if let Some(view) = self.content_view_mut_by_id(view_id) {+ view.on_remote_connect_phase(+ crate::termwindow::content_view::RemoteConnectPhase::Failed { message },+ );+ }}+ } else {+ window.invalidate();+ }+ true+ }++ /// Single entry point for "connect this thread" (context menu, etc). For a+ /// disconnected remote thread it routes through the `RemoteThreadView`+ /// "Connecting…" UI; otherwise it activates the thread directly.+ pub(crate) fn connect_remote_thread(&mut self, thread_id: String, context: &dyn WindowOps) {+ let live_workspaces = Mux::get().iter_workspaces();+ let is_disconnected_remote =+ crate::workspace_threads::thread_connection_state(&thread_id, &live_workspaces)+ .map(|state| state.is_remote && !state.is_live)+ .unwrap_or(false);++ if is_disconnected_remote+ && self.open_remote_workspace_thread_without_connecting(&thread_id, context)+ {+ if self.begin_open_remote_thread_connection(thread_id.clone(), context, None) {+ return;+ }+ }++ self.activate_workspace_thread(thread_id, context);+ }++ fn begin_open_remote_thread_connection(+ &mut self,+ thread_id: String,+ context: &dyn WindowOps,+ orphan_candidate_window_id: Option<MuxWindowId>,+ ) -> bool {+ let key = format!(+ "{}{}",+ crate::termwindow::remote_thread_view::REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX,+ thread_id+ );+ let Some(view_id) = self.content_view_id_for_key(&key) else {+ return false;};- let Some(spec) = crate::ssh_hosts::host_spec(&project_id) else {- invalidate(&window);+ // Show the spinner immediately, then start the connection.+ if let Some(view) = self.content_view_mut_by_id(view_id) {+ view.on_remote_connect_phase(+ crate::termwindow::content_view::RemoteConnectPhase::Connecting,+ );+ }+ self.begin_remote_thread_connection_impl(+ thread_id,+ view_id,+ context,+ orphan_candidate_window_id,+ );+ true+ }++ /// Start connecting a remote thread while keeping its `RemoteThreadView`+ /// foreground as the "Connecting…" UI. The SSH workspace is materialized in+ /// the background (we do not switch this window's active workspace, so the+ /// additive reconcile leaves the new mux window alone); a poll loop adopts+ /// it once authenticated, or kills it on failure.+ pub(crate) fn begin_remote_thread_connection(+ &mut self,+ thread_id: String,+ view_id: ContentViewId,+ context: &dyn WindowOps,+ ) {+ self.begin_remote_thread_connection_impl(thread_id, view_id, context, None);+ }++ fn begin_remote_thread_connection_impl(+ &mut self,+ thread_id: String,+ view_id: ContentViewId,+ context: &dyn WindowOps,+ orphan_candidate_window_id: Option<MuxWindowId>,+ ) {+ let mux = Mux::get();+ let live_workspaces = mux.iter_workspaces();+ let Some(plan) =+ crate::workspace_threads::activation_plan_for_thread(&thread_id, &live_workspaces)+ else {+ self.fail_remote_connect(view_id, "This thread could not be activated.");+ return;+ };++ // Already live (or a local thread that needs no session): just reveal.+ if !plan.needs_materialize {+ self.remote_connects.remove(&view_id);+ let window = self.window.as_ref().cloned();+ self.close_content_view_by_id(view_id);+ if let Some(window) = window {+ self.activate_workspace_thread_impl(+ thread_id,+ &window,+ orphan_candidate_window_id,+ Vec::new(),+ );+ }+ return;+ }++ let remote_host_id =+ crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id).to_string();+ let Some(spec) = crate::ssh_hosts::host_spec(&remote_host_id) else {+ self.fail_remote_connect(view_id, "The saved SSH host no longer exists.");return;};let domain_name = match crate::ssh_hosts::ensure_ssh_domain_registered(&spec) {Ok(name) => name,Err(err) => {- log::error!(- "failed to register SSH domain for {:?}: {err:#}",- spec.label- );+ self.fail_remote_connect(view_id, &format!("{err:#}"));return;}};- let base_workspace_name = target_workspace- .filter(|name| !name.trim().is_empty())- .unwrap_or_else(|| crate::ssh_hosts::default_workspace_name(&spec));- let workspace_name = crate::workspace_threads::remote_workspace_name_for_space(- &self.active_space_id,- &project_id,- &base_workspace_name,- );-- let mux = Mux::get();- // Already live? Just switch this window to it rather than spawning a- // duplicate.- if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {- self.adopt_workspace_in_this_window(&workspace_name);- invalidate(&window);- return;- }self.snapshot_active_workspace_thread_layout();- let _ = crate::workspace_threads::create_remote_host_thread(- &self.active_space_id,- &project_id,- &spec.label,- crate::ssh_hosts::host_project_path(&spec),- &workspace_name,- );+ let workspace_name = plan.workspace_name.clone();+ let layout = crate::workspace_threads::thread_layout(&plan.thread_id);let size = self.config.initial_size(self.dimensions.dpi as u32,crate::cell_pixel_dims(&self.config, self.dimensions.dpi as f64).ok(),);let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =Arc::new(TermConfig::with_config(self.config.clone()));- // Suppress the additive reconcile while materializing; adopt the new- // mux window into THIS window afterwards (no duplicate, others intact).- front_end().set_switching_workspaces(true);- mux.set_active_workspace(&workspace_name);- let ws = workspace_name.clone();- let adopt_workspace = workspace_name.clone();- let detect_os = spec.detect_os;- let detect_domain = domain_name.clone();- let detect_project = project_id.clone();- let detect_window = window.clone();- let reconcile_window = window.clone();+ let generation = self.next_remote_connect_generation;+ self.next_remote_connect_generation =+ self.next_remote_connect_generation.saturating_add(1).max(1);+ if let Some(previous) = self.remote_connects.insert(+ view_id,+ super::RemoteConnectState {+ generation,+ thread_id,+ workspace_name: workspace_name.clone(),+ domain_name: domain_name.clone(),+ started: Instant::now(),+ orphan_candidate_window_id,+ detect_os: spec+ .detect_os+ .then(|| (domain_name.clone(), remote_host_id)),+ },+ ) {+ self.kill_remote_connect_workspace(&previous.workspace_name);+ }++ let materialize_workspace = workspace_name;promise::spawn::spawn(async move {if let Err(err) = crate::workspace_threads::materialize_thread(- ws,- None,+ materialize_workspace,+ layout,None,size,None,@@ -2163,14 +2753,100 @@ impl super::TermWindow {).await{- log::error!("failed to connect SSH session: {err:#}");+ log::error!("failed to materialize connecting SSH thread: {err:#}");}- adopt_workspace_into_window(&reconcile_window, &adopt_workspace);- front_end().set_switching_workspaces(false);- reconcile_workspace_layout_after_materialize(reconcile_window);+ })+ .detach();++ self.schedule_remote_connect_poll(view_id, generation);+ context.invalidate();+ }++ fn schedule_remote_connect_poll(&self, view_id: ContentViewId, generation: u64) {+ let Some(window) = self.window.clone() else {+ return;+ };+ promise::spawn::spawn(async move {+ smol::Timer::after(Duration::from_millis(200)).await;+ window.notify(TermWindowNotif::Apply(Box::new(move |tw| {+ tw.poll_remote_connect(view_id, generation);+ })));+ })+ .detach();+ }++ fn poll_remote_connect(&mut self, view_id: ContentViewId, generation: u64) {+ let Some(state) = self.remote_connects.get(&view_id) else {+ return;+ };+ if state.generation != generation {+ return; // superseded by a newer attempt or cancelled+ }+ let domain_name = state.domain_name.clone();+ let workspace_name = state.workspace_name.clone();+ let elapsed = state.started.elapsed();++ let status = Mux::get()+ .get_domain_by_name(&domain_name)+ .and_then(|domain| {+ domain+ .as_ref()+ .downcast_ref::<RemoteSshDomain>()+ .map(|ssh| ssh.connection_status())+ });++ match status {+ Some(SshConnectionStatus::Authenticating) | Some(SshConnectionStatus::Connected) => {+ self.reveal_remote_connect(view_id, generation);+ }+ Some(SshConnectionStatus::Failed(message)) => {+ self.kill_remote_connect_workspace(&workspace_name);+ self.fail_remote_connect(view_id, &message);+ }+ _ => {+ if elapsed >= Duration::from_secs(REMOTE_CONNECT_OVERALL_TIMEOUT_SECS) {+ self.kill_remote_connect_workspace(&workspace_name);+ self.fail_remote_connect(view_id, "Connection timed out.");+ return;+ }+ if let Some(view) = self.content_view_mut_by_id(view_id) {+ view.on_remote_connect_phase(+ crate::termwindow::content_view::RemoteConnectPhase::Connecting,+ );+ }+ self.schedule_remote_connect_poll(view_id, generation);+ self.invalidate_window();+ }+ }+ }++ fn reveal_remote_connect(&mut self, view_id: ContentViewId, generation: u64) {+ let Some(state) = self.remote_connects.remove(&view_id) else {+ return;+ };+ if state.generation != generation {+ self.remote_connects.insert(view_id, state);+ return;+ }+ let detect = state.detect_os;+ let orphan_candidate_window_id = state.orphan_candidate_window_id;+ let window = self.window.as_ref().cloned();+ let reveal_now = self.active_content_view_id == Some(view_id);+ self.close_content_view_by_id(view_id);+ if reveal_now {+ if let Some(window) = window.clone() {+ self.activate_workspace_thread_impl(+ state.thread_id,+ &window,+ orphan_candidate_window_id,+ Vec::new(),+ );+ }+ }- // Optional, user-controlled OS detection over the live session.- if detect_os {+ if let Some((detect_domain, detect_project)) = detect {+ let detect_window = window;+ promise::spawn::spawn(async move {if let Some(domain) = Mux::get().get_domain_by_name(&detect_domain) {if let Some(ssh) = domain.as_ref().downcast_ref::<RemoteSshDomain>() {if let Some(distro) = ssh.detect_os_release().await {@@ -2182,11 +2858,37 @@ impl super::TermWindow {}}}- }- })- .detach();+ })+ .detach();+ }+ }++ fn fail_remote_connect(&mut self, view_id: ContentViewId, message: &str) {+ self.remote_connects.remove(&view_id);+ if let Some(view) = self.content_view_mut_by_id(view_id) {+ view.on_remote_connect_phase(+ crate::termwindow::content_view::RemoteConnectPhase::Failed {+ message: message.to_string(),+ },+ );+ }+ self.invalidate_window();+ }- invalidate(&window);+ /// Cancel an in-flight connection started from `view_id` and tear down its+ /// background SSH workspace. The view has already reset itself to Idle.+ pub(crate) fn cancel_remote_thread_connection(&mut self, view_id: ContentViewId) {+ if let Some(state) = self.remote_connects.remove(&view_id) {+ self.kill_remote_connect_workspace(&state.workspace_name);+ }+ self.invalidate_window();+ }++ fn kill_remote_connect_workspace(&self, workspace_name: &str) {+ let mux = Mux::get();+ for window_id in mux.iter_windows_in_workspace(workspace_name) {+ mux.kill_window(window_id);+ }}fn pane_nav_tab_context_menu_items(&self, pane_id: mux::pane::PaneId) -> Vec<ContextMenuItem> {@@ -2379,6 +3081,10 @@ impl super::TermWindow {}fn spawn_pane_nav_tab(&mut self, pane_id: mux::pane::PaneId, pane_index: usize) {+ if self.redirect_failed_remote_tab_spawn_to_thread_view(pane_id) {+ return;+ }+let mux = Mux::get();let tab = match mux.get_active_tab_for_window(self.mux_window_id) {Some(tab) => tab,@@ -2439,6 +3145,23 @@ impl super::TermWindow {context.set_cursor(Some(MouseCursor::Arrow));}+ fn mouse_event_disabled_new_tab_button(&mut self, context: &dyn WindowOps) {+ context.set_cursor(Some(MouseCursor::Arrow));+ }++ fn mouse_event_local_new_tab_button(&mut self, event: MouseEvent, context: &dyn WindowOps) {+ if event.kind == WMEK::Press(MousePress::Left) {+ self.spawn_command(+ &SpawnCommand {+ domain: SpawnTabDomain::DomainName("local".to_string()),+ ..SpawnCommand::default()+ },+ crate::spawn::SpawnWhere::NewTab,+ );+ }+ context.set_cursor(Some(MouseCursor::Arrow));+ }+fn do_new_tab_button_click(&mut self, button: MousePress) {let pane = match self.get_active_pane_or_overlay() {Some(pane) => pane,@@ -2610,14 +3333,24 @@ impl super::TermWindow {event: MouseEvent,context: &dyn WindowOps,) {+ if self.active_content_view_is_remote_thread()+ && matches!(+ item,+ TabBarItem::Tab { .. } | TabBarItem::NewTabButton { .. }+ )+ {+ context.set_cursor(Some(MouseCursor::Arrow));+ return;+ }+match event.kind {WMEK::Press(MousePress::Left) => match item {TabBarItem::Tab { tab_idx, .. } => {self.set_content_view_active(false);self.activate_tab(tab_idx as isize).ok();}- TabBarItem::ContentView => {- self.set_content_view_active(true);+ TabBarItem::ContentView { id } => {+ self.activate_content_view(id);}TabBarItem::NewTabButton { .. } => {self.do_new_tab_button_click(MousePress::Left);@@ -2655,7 +3388,7 @@ impl super::TermWindow {TabBarItem::None| TabBarItem::LeftStatus| TabBarItem::RightStatus- | TabBarItem::ContentView+ | TabBarItem::ContentView { .. }| TabBarItem::WindowButton(_) => {}},WMEK::Press(MousePress::Right) => match item {@@ -2672,7 +3405,7 @@ impl super::TermWindow {TabBarItem::None| TabBarItem::LeftStatus| TabBarItem::RightStatus- | TabBarItem::ContentView+ | TabBarItem::ContentView { .. }| TabBarItem::WindowButton(_) => {}},WMEK::Move => match item {@@ -2691,7 +3424,7 @@ impl super::TermWindow {}TabBarItem::WindowButton(_)| TabBarItem::Tab { .. }- | TabBarItem::ContentView+ | TabBarItem::ContentView { .. }| TabBarItem::NewTabButton { .. } => {}},WMEK::HorzWheel(amount) => {@@ -3289,3 +4022,15 @@ fn cleanup_orphaned_mux_window(window_id: Option<MuxWindowId>) {log::trace!("clean up unbound startup mux window {window_id} in workspace {workspace:?}");mux.kill_window(window_id);}++fn kill_workspace_windows(workspaces: &[String], skip_workspace: Option<&str>) {+ let mux = Mux::get();+ for workspace in workspaces {+ if skip_workspace == Some(workspace.as_str()) {+ continue;+ }+ for window_id in mux.iter_windows_in_workspace(workspace) {+ mux.kill_window(window_id);+ }+ }+}diff --git a/wezterm-gui/src/termwindow/onboarding.rs b/wezterm-gui/src/termwindow/onboarding.rsindex f8110f03..39db8db8 100644--- a/wezterm-gui/src/termwindow/onboarding.rs+++ b/wezterm-gui/src/termwindow/onboarding.rs@@ -1885,6 +1885,14 @@ impl ContentView for OnboardingView {"ThinkTerm Setup".to_string()}+ fn tab_key(&self) -> Option<String> {+ Some(format!("onboarding:{}", self.initial_space_id))+ }++ fn space_id(&self) -> Option<&str> {+ Some(&self.initial_space_id)+ }+fn wants_cursor_blink(&self) -> bool {false}diff --git a/wezterm-gui/src/termwindow/remote_thread_view.rs b/wezterm-gui/src/termwindow/remote_thread_view.rsnew file mode 100644index 00000000..0d2e01f6--- /dev/null+++ b/wezterm-gui/src/termwindow/remote_thread_view.rs@@ -0,0 +1,700 @@+use crate::quad::TripleLayerQuadAllocator;+use crate::ssh_hosts;+use crate::termwindow::content_view::{ContentView, ContentViewResponse, RemoteConnectPhase};+use crate::termwindow::ui::icons::SvgIcon;+use crate::termwindow::TermWindow;+use crate::ui::{+ rect, ControlState, DrawContext, InteractionState, UiContext, UiPalette, WidgetKind,+};+use crate::workspace_threads::{self, ThreadConnectionState};+use mux::Mux;+use std::rc::Rc;+use std::time::{Duration, Instant};+use wezterm_font::LoadedFont;+use wezterm_term::{KeyCode, KeyModifiers};+use window::{MouseEventKind as WMEK, MousePress, RectF, WindowOps};++const SPINNER_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];++const CONTENT_MAX_W: f32 = 860.0;+const PAD: f32 = 48.0;+const CARD_RADIUS: f32 = 18.0;+const BUTTON_RADIUS: f32 = 14.0;+const BUTTON_MIN_H: f32 = 52.0;+const HERO_ICON_SIZE: f32 = 64.0;+pub(crate) const REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX: &str = "remote-thread:";++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum RemoteThreadAction {+ Connect,+ EndThread,+ Cancel,+ Retry,+}++/// Lifecycle of the view's own UI: disconnected (offer Connect), in-flight+/// connection (spinner + Cancel), or a failed attempt (error + Retry/Cancel).+enum ViewPhase {+ Idle,+ Connecting { started: Instant },+ Failed { message: String },+}++pub(crate) struct RemoteThreadView {+ state: ThreadConnectionState,+ endpoint: String,+ stale_message: Option<String>,+ phase: ViewPhase,+ widgets: UiContext<RemoteThreadAction>,+ interaction: InteractionState<RemoteThreadAction>,+}++struct RemoteThreadSnapshot {+ state: ThreadConnectionState,+ endpoint: String,+ stale_message: Option<String>,+}++impl RemoteThreadView {+ pub(crate) fn new(state: ThreadConnectionState) -> Self {+ let snapshot = remote_thread_snapshot(state);++ Self {+ state: snapshot.state,+ endpoint: snapshot.endpoint,+ stale_message: snapshot.stale_message,+ phase: ViewPhase::Idle,+ widgets: UiContext::default(),+ interaction: InteractionState::default(),+ }+ }++ fn display_title(&self) -> String {+ if self.state.project_name.trim().is_empty() {+ self.state.thread_name.clone()+ } else {+ format!("{} · {}", self.state.thread_name, self.state.project_name)+ }+ }++ fn apply_snapshot(&mut self, snapshot: RemoteThreadSnapshot) {+ self.state = snapshot.state;+ self.endpoint = snapshot.endpoint;+ self.stale_message = snapshot.stale_message;+ }++ fn paint_impl(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ area: RectF,+ palette: UiPalette,+ font: &Rc<LoadedFont>,+ title_font: &Rc<LoadedFont>,+ ) -> anyhow::Result<()> {+ self.widgets.clear();+ ctx.draw_rect(+ layers,+ 0,+ area.origin.x,+ area.origin.y,+ area.size.width,+ area.size.height,+ palette.window_bg,+ )?;++ let shell_w = (area.size.width - PAD * 2.0).min(CONTENT_MAX_W).max(0.0);+ let x = area.origin.x + ((area.size.width - shell_w) / 2.0).max(PAD);+ let mut y = area.origin.y + (area.size.height * 0.12).clamp(PAD, 112.0);+ let width = shell_w;+ let line_h = (ctx.metrics.cell_size.height as f32 + 8.0).max(34.0);++ let is_error =+ matches!(self.phase, ViewPhase::Failed { .. }) || self.stale_message.is_some();+ let hero_icon = if is_error {+ SvgIcon::CircleAlert+ } else {+ SvgIcon::Server+ };+ ctx.draw_rounded_frame(+ layers,+ 0,+ x,+ y + 4.0,+ HERO_ICON_SIZE,+ HERO_ICON_SIZE,+ palette.control_bg,+ palette.control_border,+ 20.0,+ )?;+ ctx.draw_svg_icon(+ layers,+ hero_icon,+ x + 18.0,+ y + 22.0,+ 28.0,+ if is_error {+ palette.secondary_text+ } else {+ palette.text+ },+ )?;+ let hero_text_x = x + HERO_ICON_SIZE + 22.0;+ let hero_text_w = (width - HERO_ICON_SIZE - 22.0).max(0.0);+ ctx.draw_text(+ layers,+ title_font,+ hero_text_x,+ y,+ &self.display_title(),+ palette.text,+ hero_text_w,+ )?;++ let status = match &self.phase {+ ViewPhase::Connecting { .. } => format!("Connecting to {}…", self.endpoint),+ ViewPhase::Failed { message } => message.clone(),+ ViewPhase::Idle => self+ .stale_message+ .clone()+ .unwrap_or_else(|| "This SSH thread is not connected.".to_string()),+ };+ ctx.draw_text(+ layers,+ font,+ hero_text_x,+ y + line_h + 16.0,+ &status,+ palette.muted_text,+ hero_text_w,+ )?;+ y += 112.0;++ let info_h = 214.0;+ self.paint_info_panel(ctx, layers, font, palette, x, y, width, info_h, line_h)?;+ y += info_h + 22.0;++ let note_h = line_h * 2.0 + 34.0;+ self.paint_status_panel(ctx, layers, font, palette, x, y, width, note_h, line_h)?;+ y += note_h + 28.0;++ let button_h = (line_h + 22.0).max(BUTTON_MIN_H);+ self.paint_phase_buttons(ctx, layers, font, palette, x, y, button_h)?;++ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_info_panel(+ &self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ palette: UiPalette,+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ line_h: f32,+ ) -> anyhow::Result<()> {+ ctx.draw_rounded_frame(+ layers,+ 0,+ x,+ y,+ width,+ height,+ palette.control_bg,+ palette.control_border,+ CARD_RADIUS,+ )?;+ let pad = 24.0;+ ctx.draw_text(+ layers,+ font,+ x + pad,+ y + 22.0,+ "Connection",+ palette.text,+ width - pad * 2.0,+ )?;+ let row_y = y + 70.0;+ let label_w = (width * 0.32).clamp(118.0, 168.0);+ let details = [+ ("Project", self.state.project_name.as_str()),+ ("Endpoint", self.endpoint.as_str()),+ ("Thread", self.state.thread_name.as_str()),+ ];+ for (idx, (label, value)) in details.iter().enumerate() {+ let y = row_y + idx as f32 * (line_h + 6.0);+ ctx.draw_text(layers, font, x + pad, y, label, palette.muted_text, label_w)?;+ ctx.draw_text(+ layers,+ font,+ x + pad + label_w,+ y,+ value,+ palette.text,+ width - pad * 2.0 - label_w,+ )?;+ }+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_status_panel(+ &self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ palette: UiPalette,+ x: f32,+ y: f32,+ width: f32,+ height: f32,+ line_h: f32,+ ) -> anyhow::Result<()> {+ ctx.draw_rounded_frame(+ layers,+ 0,+ x,+ y,+ width,+ height,+ palette.control_bg,+ palette.control_border,+ CARD_RADIUS,+ )?;+ let pad = 20.0;+ let text_w = width - pad * 2.0;+ let (line_one, line_two) = match &self.phase {+ ViewPhase::Connecting { started } => {+ let elapsed = started.elapsed();+ let frame =+ SPINNER_FRAMES[(elapsed.as_millis() / 120) as usize % SPINNER_FRAMES.len()];+ (+ format!("{frame} Connecting…"),+ format!("Elapsed {}s", elapsed.as_secs()),+ )+ }+ ViewPhase::Failed { .. } => (+ "The connection failed.".to_string(),+ "Retry, or cancel to dismiss.".to_string(),+ ),+ ViewPhase::Idle => (+ "Connect opens SSH.".to_string(),+ "Delete removes this thread.".to_string(),+ ),+ };+ ctx.draw_text(+ layers,+ font,+ x + pad,+ y + 16.0,+ &line_one,+ palette.text,+ text_w,+ )?;+ ctx.draw_text(+ layers,+ font,+ x + pad,+ y + 16.0 + line_h,+ &line_two,+ palette.muted_text,+ text_w,+ )?;+ Ok(())+ }++ fn paint_phase_buttons(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ palette: UiPalette,+ x: f32,+ y: f32,+ button_h: f32,+ ) -> anyhow::Result<()> {+ // (label, icon, action, primary, enabled)+ let buttons: Vec<(&str, SvgIcon, RemoteThreadAction, bool, bool)> = match &self.phase {+ ViewPhase::Idle => vec![+ (+ "Connect",+ SvgIcon::Link2,+ RemoteThreadAction::Connect,+ true,+ self.can_connect(),+ ),+ (+ "Delete Thread",+ SvgIcon::Trash2,+ RemoteThreadAction::EndThread,+ false,+ true,+ ),+ ],+ ViewPhase::Connecting { .. } => {+ vec![(+ "Cancel",+ SvgIcon::X,+ RemoteThreadAction::Cancel,+ false,+ true,+ )]+ }+ ViewPhase::Failed { .. } => vec![+ (+ "Retry",+ SvgIcon::RotateCcw,+ RemoteThreadAction::Retry,+ true,+ self.can_connect(),+ ),+ (+ "Cancel",+ SvgIcon::X,+ RemoteThreadAction::Cancel,+ false,+ true,+ ),+ ],+ };+ let mut bx = x;+ for (label, icon, action, primary, enabled) in buttons {+ let w = (ctx.measure_text_width(font, label) + 92.0).max(168.0);+ self.paint_action_button(+ ctx,+ layers,+ font,+ palette,+ rect(bx, y, w, button_h),+ label,+ icon,+ action,+ primary,+ enabled,+ )?;+ bx += w + 16.0;+ }+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_action_button(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ palette: UiPalette,+ area: RectF,+ label: &str,+ icon: SvgIcon,+ action: RemoteThreadAction,+ primary: bool,+ enabled: bool,+ ) -> anyhow::Result<()> {+ self.widgets.push(area, WidgetKind::Button, action);+ let state = self.button_state(action, primary, enabled);+ let (mut bg, mut border) = state.colors(palette);+ let mut text = palette.text;+ if primary && enabled {+ bg = if state == ControlState::Pressed {+ palette.selected_bg.mul_alpha(0.82)+ } else {+ palette.selected_bg+ };+ border = palette.selected_bg;+ text = palette.selected_text;+ } else if !enabled {+ bg = bg.mul_alpha(0.52);+ text = palette.muted_text;+ }+ ctx.draw_rounded_frame(+ layers,+ 0,+ area.origin.x,+ area.origin.y,+ area.size.width,+ area.size.height,+ bg,+ border,+ BUTTON_RADIUS,+ )?;+ let icon_size = 22.0;+ let icon_x = area.origin.x + 18.0;+ let icon_y = area.origin.y + (area.size.height - icon_size) / 2.0;+ ctx.draw_svg_icon(layers, icon, icon_x, icon_y, icon_size, text)?;+ let text_x = icon_x + icon_size + 12.0;+ ctx.draw_text(+ layers,+ font,+ text_x,+ Self::centered_text_y(ctx, area),+ label,+ text,+ area.size.width - (text_x - area.origin.x) - 16.0,+ )?;+ Ok(())+ }++ fn on_mouse_impl(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {+ let hit = self.widgets.hit_test(x, y).map(|target| target.action);+ match kind {+ WMEK::Move => {+ if self.interaction.hovered != hit {+ self.interaction.hovered = hit;+ ContentViewResponse::Redraw+ } else {+ ContentViewResponse::Ignored+ }+ }+ WMEK::Press(MousePress::Left) => {+ self.interaction.pressed = hit;+ ContentViewResponse::Redraw+ }+ WMEK::Release(MousePress::Left) => {+ let pressed = self.interaction.pressed.take();+ if let (Some(hit), Some(pressed)) = (hit, pressed) {+ if hit == pressed {+ return self.apply(hit);+ }+ }+ ContentViewResponse::Redraw+ }+ _ => ContentViewResponse::Ignored,+ }+ }++ fn apply(&mut self, action: RemoteThreadAction) -> ContentViewResponse {+ match action {+ RemoteThreadAction::Connect | RemoteThreadAction::Retry if self.can_connect() => {+ self.phase = ViewPhase::Connecting {+ started: Instant::now(),+ };+ begin_connect_response(self.state.thread_id.clone())+ }+ RemoteThreadAction::Connect | RemoteThreadAction::Retry => ContentViewResponse::Ignored,+ RemoteThreadAction::Cancel => {+ self.phase = ViewPhase::Idle;+ self.interaction = InteractionState::default();+ cancel_connect_response()+ }+ RemoteThreadAction::EndThread => end_thread_response(self.state.thread_id.clone()),+ }+ }++ fn button_state(+ &self,+ action: RemoteThreadAction,+ primary: bool,+ enabled: bool,+ ) -> ControlState {+ if !enabled {+ ControlState::Disabled+ } else if self.interaction.pressed == Some(action) {+ ControlState::Pressed+ } else if self.interaction.hovered == Some(action) {+ ControlState::Hovered+ } else if primary {+ ControlState::Active+ } else {+ ControlState::Normal+ }+ }++ fn can_connect(&self) -> bool {+ self.stale_message.is_none()+ }++ fn centered_text_y(ctx: &DrawContext, area: RectF) -> f32 {+ let cell_height = ctx.metrics.cell_size.height as f32;+ area.origin.y + ((area.size.height - cell_height) / 2.0).max(0.0)+ }+}++impl ContentView for RemoteThreadView {+ fn title(&self) -> String {+ self.display_title()+ }++ fn show_in_tab_bar(&self) -> bool {+ false+ }++ fn tab_key(&self) -> Option<String> {+ Some(format!(+ "{}{}",+ REMOTE_THREAD_CONTENT_VIEW_KEY_PREFIX, self.state.thread_id+ ))+ }++ fn space_id(&self) -> Option<&str> {+ Some(&self.state.space_id)+ }++ fn on_reactivated(&mut self) -> ContentViewResponse {+ // Don't disturb an in-flight or just-failed attempt when the tab is+ // re-focused; the connection poll on TermWindow owns those transitions.+ if matches!(+ self.phase,+ ViewPhase::Connecting { .. } | ViewPhase::Failed { .. }+ ) {+ return ContentViewResponse::Redraw;+ }++ let live_workspaces = Mux::get().iter_workspaces();+ let Some(state) =+ workspace_threads::thread_connection_state(&self.state.thread_id, &live_workspaces)+ else {+ self.stale_message = Some("This saved SSH thread no longer exists.".to_string());+ return ContentViewResponse::Redraw;+ };++ if state.is_live {+ return reveal_live_thread_response(state.thread_id);+ }++ self.apply_snapshot(remote_thread_snapshot(state));+ ContentViewResponse::Redraw+ }++ fn next_frame_time(&self) -> Option<Instant> {+ match self.phase {+ ViewPhase::Connecting { .. } => Some(Instant::now() + Duration::from_millis(120)),+ _ => None,+ }+ }++ fn on_remote_connect_phase(&mut self, phase: RemoteConnectPhase) {+ match phase {+ RemoteConnectPhase::Connecting => {+ if !matches!(self.phase, ViewPhase::Connecting { .. }) {+ self.phase = ViewPhase::Connecting {+ started: Instant::now(),+ };+ }+ }+ RemoteConnectPhase::Failed { message } => {+ self.interaction = InteractionState::default();+ self.phase = ViewPhase::Failed { message };+ }+ }+ }++ fn paint(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ area: RectF,+ palette: UiPalette,+ font: &Rc<LoadedFont>,+ title_font: &Rc<LoadedFont>,+ _section_font: &Rc<LoadedFont>,+ _cursor_on: bool,+ ) -> anyhow::Result<()> {+ self.paint_impl(ctx, layers, area, palette, font, title_font)+ }++ fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {+ self.on_mouse_impl(x, y, kind)+ }++ fn on_key(&mut self, key: KeyCode, _mods: KeyModifiers) -> ContentViewResponse {+ match key {+ KeyCode::Escape => self.on_close_requested(),+ _ => ContentViewResponse::Ignored,+ }+ }++ fn on_close_requested(&mut self) -> ContentViewResponse {+ match self.phase {+ ViewPhase::Connecting { .. } => cancel_and_close_response(),+ ViewPhase::Idle | ViewPhase::Failed { .. } => ContentViewResponse::Close,+ }+ }+}++fn remote_thread_snapshot(state: ThreadConnectionState) -> RemoteThreadSnapshot {+ let host_id = workspace_threads::remote_host_id_for_project_id(&state.project_id);+ let spec = ssh_hosts::host_spec(host_id);+ let endpoint = spec+ .as_ref()+ .map(format_endpoint)+ .unwrap_or_else(|| state.project_name.clone());+ let stale_message = if state.is_remote && spec.is_none() {+ Some("The saved SSH host for this thread no longer exists.".to_string())+ } else {+ None+ };++ RemoteThreadSnapshot {+ state,+ endpoint,+ stale_message,+ }+}++/// Already-live thread: close this view and switch to the running terminal.+fn reveal_live_thread_response(thread_id: String) -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ let window = tw.window.as_ref().cloned();+ tw.close_content_view();+ if let Some(window) = window {+ tw.activate_workspace_thread(thread_id, &window);+ }+ }))+}++/// Begin a connection while keeping this view foreground as the "Connecting…"+/// UI. `content_view_response_tab_id` is set to this view's id during dispatch.+fn begin_connect_response(thread_id: String) -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ let Some(view_id) = tw.content_view_response_tab_id else {+ return;+ };+ let Some(window) = tw.window.as_ref().cloned() else {+ return;+ };+ tw.begin_remote_thread_connection(thread_id, view_id, &window);+ }))+}++/// Abort an in-flight connection (kills the background SSH window) and return to+/// the disconnected view.+fn cancel_connect_response() -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ if let Some(view_id) = tw.content_view_response_tab_id {+ tw.cancel_remote_thread_connection(view_id);+ }+ }))+}++fn cancel_and_close_response() -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ if let Some(view_id) = tw.content_view_response_tab_id {+ tw.cancel_remote_thread_connection(view_id);+ tw.close_content_view_by_id(view_id);+ }+ }))+}++fn end_thread_response(thread_id: String) -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ tw.close_content_view();+ let window = tw.window.as_ref().cloned();+ tw.end_workspace_thread(&thread_id, window.as_ref().map(|w| w as &dyn WindowOps));+ }))+}++fn format_endpoint(spec: &ssh_hosts::SshHostSpec) -> String {+ let host = match spec.port {+ Some(port) if port != 22 => format!("{}:{port}", spec.host),+ _ => spec.host.clone(),+ };+ match &spec.username {+ Some(user) if !user.is_empty() => format!("{user}@{host}"),+ _ => host,+ }+}diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rsindex 2b28fe96..2590f47b 100644--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs@@ -147,62 +147,71 @@ impl crate::TermWindow {.and_then(|window| window.idx_by_id(tab_id))});- // When a content view is the foreground, no mux tab is "active".- let cv_present = self.content_view.is_some();- let cv_active = self.content_view_active;+ // Remote thread connection views are selected from the sidebar and must+ // not expose the underlying mux tabs here; clicking those stale tabs+ // would leave the remote thread UI and jump to the prior terminal.+ let active_content_view_id = self.active_content_view_id;+ let cv_active = self.active_content_view_shown_in_tab_bar();+ let show_mux_tabs = !self.active_content_view_is_remote_thread();let tab_step = tab_width + WINDOW_TAB_GAP;let mut tab_sequence_idx = 0usize;- for item in self.tab_bar.items() {- let TabBarItem::Tab { tab_idx, active } = item.item else {- continue;- };- let active = active && !cv_active;+ if show_mux_tabs {+ for item in self.tab_bar.items() {+ let TabBarItem::Tab { tab_idx, active } = item.item else {+ continue;+ };+ let active = active && !cv_active;- let virtual_left = tab_sequence_idx as f32 * tab_step as f32 - scroll_offset;- tab_sequence_idx += 1;+ let virtual_left = tab_sequence_idx as f32 * tab_step as f32 - scroll_offset;+ tab_sequence_idx += 1;- let tab_left = viewport_left as f32 + virtual_left;- let tab_right = tab_left + tab_width as f32;- if tab_right <= viewport_left as f32 || tab_left >= viewport_right as f32 {- continue;- }+ let tab_left = viewport_left as f32 + virtual_left;+ let tab_right = tab_left + tab_width as f32;+ if tab_right <= viewport_left as f32 || tab_left >= viewport_right as f32 {+ continue;+ }- let visible_left = tab_left.max(viewport_left as f32);- let visible_right = tab_right.min(viewport_right as f32);- let visible_width = (visible_right - visible_left).max(0.0);- if visible_width <= 1.0 {- continue;- }+ let visible_left = tab_left.max(viewport_left as f32);+ let visible_right = tab_right.min(viewport_right as f32);+ let visible_width = (visible_right - visible_left).max(0.0);+ if visible_width <= 1.0 {+ continue;+ }- self.paint_window_tab(- layers,- &mut ui_items,- item,- tab_idx,- active,- inline_rename_tab_idx == Some(tab_idx),- tab_left,- visible_left,- visible_width,- viewport_left,- viewport_right,- content_row_y,- content_row_height,- tab_width,- button_size,- icon_size,- &font,- metrics,- chrome,- background,- if active { foreground } else { muted_fg },- )?;+ self.paint_window_tab(+ layers,+ &mut ui_items,+ item,+ tab_idx,+ active,+ inline_rename_tab_idx == Some(tab_idx),+ tab_left,+ visible_left,+ visible_width,+ viewport_left,+ viewport_right,+ content_row_y,+ content_row_height,+ tab_width,+ button_size,+ icon_size,+ &font,+ metrics,+ chrome,+ background,+ if active { foreground } else { muted_fg },+ )?;+ }}- // Synthetic content-view tab (e.g. SSH Hosts), placed after the mux tabs.- if cv_present {+ // Synthetic content-view tabs (e.g. SSH Hosts), placed after the mux tabs.+ for content_tab in &self.content_views {+ if !self.content_view_shown_in_tab_bar(content_tab) {+ continue;+ }let virtual_left = tab_sequence_idx as f32 * tab_step as f32 - scroll_offset;+ tab_sequence_idx += 1;let tab_left = viewport_left as f32 + virtual_left;let tab_right = tab_left + tab_width as f32;if tab_right > viewport_left as f32 && tab_left < viewport_right as f32 {@@ -210,16 +219,13 @@ impl crate::TermWindow {let visible_right = tab_right.min(viewport_right as f32);let visible_width = (visible_right - visible_left).max(0.0);if visible_width > 1.0 {- let title = self- .content_view- .as_ref()- .map(|v| v.title())- .unwrap_or_default();+ let active = active_content_view_id == Some(content_tab.id);self.paint_content_view_tab(layers,&mut ui_items,- &title,- cv_active,+ content_tab.id,+ &content_tab.view.title(),+ active,tab_left,visible_left,visible_width,@@ -234,7 +240,7 @@ impl crate::TermWindow {metrics,chrome,background,- if cv_active { foreground } else { muted_fg },+ if active { foreground } else { muted_fg },)?;}}@@ -803,6 +809,7 @@ impl crate::TermWindow {&self,layers: &mut TripleLayerQuadAllocator,ui_items: &mut Vec<UIItem>,+ id: crate::termwindow::content_view::ContentViewId,title: &str,active: bool,tab_left: f32,@@ -860,7 +867,7 @@ impl crate::TermWindow {y: row_y,width: visible_width.max(0.0) as usize,height: row_height,- item_type: UIItemType::TabBar(TabBarItem::ContentView),+ item_type: UIItemType::TabBar(TabBarItem::ContentView { id }),});let tab_left = tab_left.max(0.0) as usize;@@ -891,7 +898,7 @@ impl crate::TermWindow {y: close_y,width: button_size,height: button_size,- item_type: UIItemType::ContentViewClose,+ item_type: UIItemType::ContentViewClose(id),});self.paint_fancy_tab_icon(layers,diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex b3234390..a540aee0 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -229,12 +229,11 @@ impl crate::TermWindow {(dimensions.pixel_height as f32 - top - border.bottom.get() as f32 - bottom_tab_h).max(0.0);let area = euclid::rect(left, top, width, height);+ let active_content_view_idx = self.active_content_view_index();// Cursor blink: only animate when the view wants it (focused input).- let wants_blink = self- .content_view- .as_ref()- .map(|v| v.wants_cursor_blink())+ let wants_blink = active_content_view_idx+ .map(|idx| self.content_views[idx].view.wants_cursor_blink()).unwrap_or(false);let blink_ms = (self.config.cursor_blink_rate as u64).max(100);let cursor_on = if wants_blink {@@ -252,7 +251,8 @@ impl crate::TermWindow {let gl_state = self.render_state.as_ref().unwrap();let ctx = DrawContext::new(gl_state, dimensions, &render_metrics);- let next_frame = if let Some(view) = self.content_view.as_mut() {+ let next_frame = if let Some(idx) = active_content_view_idx {+ let view = self.content_views[idx].view.as_mut();view.paint(&ctx,layers,diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex 9005c450..8288061e 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -313,6 +313,10 @@ impl super::TermWindow {}pub fn sync_pane_font_sizes(&self) {+ if self.content_view_foreground() {+ return;+ }+for pos in self.get_panes_to_render() {if let Err(err) = self.sync_positioned_pane_font_size(&pos) {log::error!(@@ -324,6 +328,17 @@ impl super::TermWindow {}}+ pub(crate) fn resize_mux_tabs_to_current_terminal_size(&mut self) {+ let mux = Mux::get();+ if let Some(window) = mux.get_window(self.mux_window_id) {+ for tab in window.iter() {+ tab.resize(self.terminal_size);+ }+ }+ self.reapply_collapsed_panes_for_window();+ self.sync_pane_font_sizes();+ }+pub fn resize(&mut self,dimensions: Dimensions,@@ -490,14 +505,11 @@ impl super::TermWindow {let terminal_size_changed = self.terminal_size != size;self.terminal_size = size;if terminal_size_changed {- let mux = Mux::get();- if let Some(window) = mux.get_window(self.mux_window_id) {- for tab in window.iter() {- tab.resize(size);- }+ if self.content_view_foreground() {+ log::trace!("content view foreground; deferring mux tab resize");+ } else {+ self.resize_mux_tabs_to_current_terminal_size();}- self.reapply_collapsed_panes_for_window();- self.sync_pane_font_sizes();} else {log::trace!("terminal size unchanged; skipping mux tab resize");}diff --git a/wezterm-gui/src/termwindow/spawn.rs b/wezterm-gui/src/termwindow/spawn.rsindex 2089c854..34947085 100644--- a/wezterm-gui/src/termwindow/spawn.rs+++ b/wezterm-gui/src/termwindow/spawn.rs@@ -4,7 +4,28 @@ use config::TermConfig;use std::sync::Arc;impl super::TermWindow {- pub fn spawn_command(&self, spawn: &SpawnCommand, spawn_where: SpawnWhere) {+ pub fn spawn_command(&mut self, spawn: &SpawnCommand, spawn_where: SpawnWhere) {+ if matches!(spawn_where, SpawnWhere::NewTab | SpawnWhere::NewTabAt(_))+ && self.active_content_view_is_remote_thread()+ {+ return;+ }++ if matches!(spawn_where, SpawnWhere::NewTab | SpawnWhere::NewTabAt(_))+ && spawn.domain == SpawnTabDomain::CurrentPaneDomain+ {+ if let Some(pane_id) = self.get_active_pane_or_overlay().map(|pane| pane.pane_id()) {+ if self.redirect_failed_remote_tab_spawn_to_thread_view(pane_id) {+ return;+ }+ }+ }++ let deactivate_content_view_after_spawn = matches!(+ spawn_where,+ SpawnWhere::NewTab | SpawnWhere::NewTabAt(_) | SpawnWhere::SplitPane(_)+ ) && self.content_view_foreground();+let size = if spawn_where == SpawnWhere::NewWindow {self.config.initial_size(self.dimensions.dpi as u32,@@ -28,6 +49,11 @@ impl super::TermWindow {term_config,self.window.clone(),layout_mutation_reason,+ deactivate_content_view_after_spawn.then(|| {+ Box::new(|term_window: &mut crate::termwindow::TermWindow| {+ term_window.set_content_view_active(false);+ }) as crate::spawn::SpawnSuccessAction+ }),)}diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rsindex 7e1a42b6..532921f0 100644--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs@@ -21,6 +21,8 @@ use wezterm_term::{KeyCode, KeyModifiers};use window::color::LinearRgba;use window::{MouseEventKind as WMEK, MousePress, RectF};+pub(crate) const SSH_HOSTS_CONTENT_VIEW_KEY: &str = "ssh-hosts";+const FIELD_NAME: usize = 0;const FIELD_HOST: usize = 1;const FIELD_PORT: usize = 2;@@ -409,7 +411,7 @@ impl SshHostsView {ContentViewResponse::Redraw}SshViewAction::SaveAndConnect => match self.persist_form() {- Some(id) => connect_response(id),+ Some(id) => open_thread_response(id),None => ContentViewResponse::Redraw,},SshViewAction::Cancel => {@@ -423,7 +425,7 @@ impl SshHostsView {}SshViewAction::ResizeLeftPane => ContentViewResponse::Redraw,SshViewAction::Connect(i) => match self.filtered.get(i) {- Some(entry) => connect_response(entry.id.clone()),+ Some(entry) => open_thread_response(entry.id.clone()),None => ContentViewResponse::Redraw,},}@@ -443,11 +445,11 @@ impl SshHostsView {(KeyCode::Enter, _) => {if in_form {match self.persist_form() {- Some(id) => connect_response(id),+ Some(id) => open_thread_response(id),None => ContentViewResponse::Redraw,}} else if let Some(entry) = self.filtered.get(self.selected) {- connect_response(entry.id.clone())+ open_thread_response(entry.id.clone())} else {ContentViewResponse::Redraw}@@ -1338,7 +1340,7 @@ impl SshHostsView {let btn_w = |label: &str| ctx.measure_text_width(font, label) + 36.0;let mut bx = x;for (label, action, primary) in [- ("Save & Connect", SshViewAction::SaveAndConnect, true),+ ("Save & Open", SshViewAction::SaveAndConnect, true),("Save", SshViewAction::Save, false),("Cancel", SshViewAction::Cancel, false),] {@@ -1369,11 +1371,15 @@ impl SshHostsView {}}-/// Close the view and connect to the given remote project on the main window.-fn connect_response(project_id: String) -> ContentViewResponse {+/// Close the view and open a disconnected remote thread on the main window.+fn open_thread_response(project_id: String) -> ContentViewResponse {ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {- tw.close_content_view();- tw.connect_ssh_host(project_id, None);+ let window = tw.window.as_ref().cloned();+ if let Some(window) = window {+ if tw.open_ssh_host_thread_without_connecting(project_id, &window) {+ tw.close_content_view();+ }+ }}))}@@ -1382,6 +1388,10 @@ impl ContentView for SshHostsView {"SSH Hosts".to_string()}+ fn tab_key(&self) -> Option<String> {+ Some(SSH_HOSTS_CONTENT_VIEW_KEY.to_string())+ }+fn wants_cursor_blink(&self) -> bool {// A text field is always focused while this view is open.truediff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rsindex 5b2607fc..85d205f3 100644--- a/wezterm-gui/src/termwindow/ui/sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs@@ -267,6 +267,17 @@ impl crate::TermWindow {}}+ fn is_workspace_sidebar_thread_selected(+ &self,+ session: &workspace_threads::WorkspaceThreadView,+ ) -> bool {+ if let Some(thread_id) = self.workspace_sidebar_pending_thread_selection.as_deref() {+ thread_id == session.id.as_str()+ } else {+ session.is_active+ }+ }+fn sidebar_thread_dot_color(&self,session: &workspace_threads::WorkspaceThreadView,@@ -1069,7 +1080,8 @@ impl crate::TermWindow {session_row_height,);let is_renaming_session = self.is_renaming_sidebar_thread(&session.id);- if session.is_active {+ let is_selected = self.is_workspace_sidebar_thread_selected(session);+ if is_selected {self.fill_rounded_rectangle_with_border(layers,0,@@ -1135,11 +1147,7 @@ impl crate::TermWindow {pinned_text_x,text_y,text_right.saturating_sub(pinned_text_x + SIDEBAR_INSET),- if session.is_active {- active_fg- } else {- foreground- },+ if is_selected { active_fg } else { foreground },)?;if is_hovered && !is_renaming_session {@@ -1426,7 +1434,8 @@ impl crate::TermWindow {row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;let hit_height = hit_bottom.saturating_sub(hit_y).max(1);- if row_is_visible && session.is_active {+ let is_selected = self.is_workspace_sidebar_thread_selected(session);+ if row_is_visible && is_selected {self.fill_rounded_rectangle_with_border(layers,0,@@ -1477,7 +1486,7 @@ impl crate::TermWindow {.saturating_sub(SIDEBAR_INSET)};let text_width = text_right.saturating_sub(session_text_x + SIDEBAR_INSET);- if is_hovered && !session.is_active && !is_renaming_session {+ if is_hovered && !is_selected && !is_renaming_session {self.fill_rounded_rectangle(layers,0,@@ -1510,11 +1519,7 @@ impl crate::TermWindow {session_text_x,text_y,text_width,- if session.is_active {- active_fg- } else {- foreground- },+ if is_selected { active_fg } else { foreground },)?;if is_hovered && !is_renaming_session {let pin_icon = if session.is_pinned {diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 9a307126..fed010da 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -70,6 +70,8 @@ pub struct WorkspaceThread {pub name: String,pub project_id: ProjectId,pub layout: Option<WorkspaceThreadLayoutSnapshot>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub planned_workspace_name: Option<String>,pub materialized_workspace_name: Option<String>,pub last_active_at: i64,#[serde(default)]@@ -160,6 +162,18 @@ pub struct ActivationPlan {pub needs_materialize: bool,}+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ThreadConnectionState {+ pub space_id: SpaceId,+ pub project_id: ProjectId,+ pub thread_id: WorkspaceThreadId,+ pub project_name: String,+ pub thread_name: String,+ pub workspace_name: String,+ pub is_remote: bool,+ pub is_live: bool,+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct DeletedWorkspaceThread {pub was_active: bool,@@ -174,6 +188,20 @@ pub struct RemovedProject {pub materialized_workspace_names: Vec<String>,}+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum EndWorkspaceThreadResult {+ DeletedThread(DeletedWorkspaceThread),+ RemovedProject(RemovedProject),+ Noop,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DisconnectedWorkspaceThread {+ pub was_active: bool,+ pub next_thread_id: Option<WorkspaceThreadId>,+ pub workspace_name: String,+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct DeletedSpace {pub materialized_workspace_names: Vec<String>,@@ -646,6 +674,11 @@ pub fn workspace_has_thread_binding(workspace: &str) -> bool {store.workspace_space_id(workspace).is_some()}+pub fn thread_id_for_workspace(space_id: &str, workspace: &str) -> Option<WorkspaceThreadId> {+ let store = THREAD_STORE.lock();+ store.thread_id_for_workspace(space_id, workspace)+}+/// A brand-new / empty Space has no project yet. Give it a stable default/// project rooted at the user's home directory. Previously this used the/// process launch cwd (`std::env::current_dir()`), which is arbitrary — `/`@@ -727,54 +760,22 @@ pub fn create_project_from_path(space_id: &str, path: &str) -> Result<WorkspaceTOk(thread_id)}-/// Create a new thread under a remote (SSH) project bound to `workspace_name`,-/// mark it active, and return its id. Remote host connection details live in-/// `ssh_hosts.json`; the project record here is layout/sidebar state only.-pub fn create_remote_host_thread(+pub fn create_disconnected_remote_host_thread(space_id: &str,host_id: &str,label: &str,path: PathBuf,- workspace_name: &str,+ workspace_override: Option<String>,) -> WorkspaceThreadId {let mut store = THREAD_STORE.lock();store.normalize_after_load();- let project_id = if store- .projects- .iter()- .any(|project| project.id == host_id && project.space_id == space_id)- {- host_id.to_string()- } else {- remote_project_id_for_space(space_id, host_id)- };- if let Some(project) = store.projects.iter_mut().find(|p| p.id == project_id) {- project.space_id = space_id.to_string();- project.name = label.to_string();- project.path = path.clone();- } else {- store.projects.push(Project {- id: project_id.clone(),- space_id: space_id.to_string(),- name: label.to_string(),- path,- threads: vec![],- active_thread_id: None,- threads_collapsed: false,- });- }-- let project = store- .projects- .iter_mut()- .find(|p| p.id == project_id)- .expect("remote project was just inserted");- let name = format!("Thread {}", project.threads.len() + 1);- let session = WorkspaceThread::new(project_id.clone(), name, Some(workspace_name.to_string()));- let thread_id = session.id.clone();- project.active_thread_id = Some(thread_id.clone());- project.threads.push(session);- store.set_active_project_for_space(space_id, project_id);+ let thread_id = store.create_disconnected_remote_host_thread(+ space_id,+ host_id,+ label,+ path,+ workspace_override,+ );persist_locked(&store);thread_id}@@ -789,6 +790,36 @@ pub fn activate_thread_record(plan}+pub fn activation_plan_for_thread(+ thread_id: &str,+ live_workspaces: &[String],+) -> Option<ActivationPlan> {+ let store = THREAD_STORE.lock();+ store.activation_plan_for_thread(thread_id, live_workspaces)+}++pub fn thread_connection_state(+ thread_id: &str,+ live_workspaces: &[String],+) -> Option<ThreadConnectionState> {+ let store = THREAD_STORE.lock();+ store.thread_connection_state(thread_id, live_workspaces)+}++pub fn thread_space_id(thread_id: &str) -> Option<SpaceId> {+ let store = THREAD_STORE.lock();+ store.thread_space_id(thread_id)+}++pub fn project_is_remote(project_id: &str) -> bool {+ let store = THREAD_STORE.lock();+ store+ .projects+ .iter()+ .find(|project| project.id == project_id)+ .is_some_and(is_remote_project)+}+pub fn refresh_thread_work_for_pane(pane_id: PaneId) -> bool {let mux = Mux::get();let Some((_domain_id, window_id, _tab_id)) = mux.resolve_pane_id(pane_id) else {@@ -1045,6 +1076,7 @@ pub fn mark_thread_unread(thread_id: &str) -> bool {changed}+#[allow(dead_code)]pub fn delete_thread(thread_id: &str) -> Option<DeletedWorkspaceThread> {let mut store = THREAD_STORE.lock();let deleted = store.delete_thread(thread_id);@@ -1054,6 +1086,28 @@ pub fn delete_thread(thread_id: &str) -> Option<DeletedWorkspaceThread> {deleted}+pub fn end_workspace_thread_record(thread_id: &str) -> EndWorkspaceThreadResult {+ let mut store = THREAD_STORE.lock();+ let result = store.end_workspace_thread_record(thread_id);+ if !matches!(result, EndWorkspaceThreadResult::Noop) {+ persist_locked(&store);+ }+ result+}++pub fn disconnect_workspace_thread_record(+ thread_id: &str,+ live_workspaces: &[String],+) -> Option<DisconnectedWorkspaceThread> {+ let mut store = THREAD_STORE.lock();+ let (disconnected, changed) =+ store.disconnect_workspace_thread_record(thread_id, live_workspaces);+ if changed {+ persist_locked(&store);+ }+ disconnected+}+pub fn toggle_project_threads_collapsed(project_id: &str) -> bool {let mut store = THREAD_STORE.lock();let changed = store.toggle_project_threads_collapsed(project_id);@@ -1192,6 +1246,7 @@ impl WorkspaceThreadStore {changed = true;}changed |= self.repair_cross_space_local_workspace_bindings();+ changed |= self.ensure_unique_thread_names();changed}@@ -1482,6 +1537,26 @@ impl WorkspaceThreadStore {})}+ fn thread_id_for_workspace(+ &self,+ space_id: &str,+ workspace: &str,+ ) -> Option<WorkspaceThreadId> {+ self.projects.iter().find_map(|project| {+ if project.space_id != space_id {+ return None;+ }+ project+ .threads+ .iter()+ .find(|session| {+ session.materialized_workspace_name.as_deref() == Some(workspace)+ || workspace_name_for_thread(&project.id, &session.id) == workspace+ })+ .map(|session| session.id.clone())+ })+ }+fn workspace_belongs_to_other_space(&self, space_id: &str, workspace: &str) -> bool {self.workspace_space_id(workspace).is_some_and(|owner_space_id| owner_space_id != space_id)@@ -1514,19 +1589,108 @@ impl WorkspaceThreadStore {changed}+ fn ensure_unique_thread_names(&mut self) -> bool {+ let mut changed = false;+ for project in &mut self.projects {+ let mut used = Vec::<String>::new();+ let mut next_index = project.threads.len().saturating_add(1).max(1);++ for session in &mut project.threads {+ let trimmed = session.name.trim();+ if !trimmed.is_empty() && !used.iter().any(|name| name == trimmed) {+ if session.name != trimmed {+ session.name = trimmed.to_string();+ changed = true;+ }+ used.push(session.name.clone());+ continue;+ }++ loop {+ let candidate = format!("Thread {next_index}");+ next_index += 1;+ if !used.iter().any(|name| name == &candidate) {+ session.name = candidate.clone();+ used.push(candidate);+ changed = true;+ break;+ }+ }+ }+ }+ changed+ }+fn create_thread(&mut self, project_id: &str, name: Option<String>) -> WorkspaceThreadId {let project = self.projects.iter_mut().find(|project| project.id == project_id).expect("project_id should exist before creating session");- let name = name.unwrap_or_else(|| format!("Thread {}", project.threads.len() + 1));+ let name = name+ .map(|name| unique_thread_name(project, None, name.trim()))+ .unwrap_or_else(|| next_thread_name(project));let session = WorkspaceThread::new(project.id.clone(), name, None);let id = session.id.clone();project.threads.push(session);id}+ fn create_disconnected_remote_host_thread(+ &mut self,+ space_id: &str,+ host_id: &str,+ label: &str,+ path: PathBuf,+ workspace_override: Option<String>,+ ) -> WorkspaceThreadId {+ let project_id = if self+ .projects+ .iter()+ .any(|project| project.id == host_id && project.space_id == space_id)+ {+ host_id.to_string()+ } else {+ remote_project_id_for_space(space_id, host_id)+ };++ if let Some(project) = self.projects.iter_mut().find(|p| p.id == project_id) {+ project.space_id = space_id.to_string();+ project.name = label.to_string();+ project.path = path.clone();+ } else {+ self.projects.push(Project {+ id: project_id.clone(),+ space_id: space_id.to_string(),+ name: label.to_string(),+ path,+ threads: vec![],+ active_thread_id: None,+ threads_collapsed: false,+ });+ }++ let project = self+ .projects+ .iter_mut()+ .find(|p| p.id == project_id)+ .expect("remote project was just inserted");+ let name = next_thread_name(project);+ let mut session = WorkspaceThread::new(project_id.clone(), name, None);+ if let Some(workspace) = workspace_override.as_deref().map(str::trim) {+ if !workspace.is_empty() {+ session.planned_workspace_name = Some(workspace_name_for_remote_default(+ &project_id,+ &session.id,+ workspace,+ ));+ }+ }+ let thread_id = session.id.clone();+ project.threads.push(session);+ thread_id+ }+fn create_project_from_path(&mut self, space_id: &str, path: PathBuf) -> WorkspaceThreadId {// New project ids include the stable Space id, but migration must never// recompute old project ids; existing Project.id values remain valid.@@ -1689,42 +1853,99 @@ impl WorkspaceThreadStore {thread_id: &str,live_workspaces: &[String],) -> Option<ActivationPlan> {- let project = self.projects.iter_mut().find(|project| {+ let plan = self.activation_plan_for_thread(thread_id, live_workspaces)?;+ let project = self+ .projects+ .iter_mut()+ .find(|project| project.id == plan.project_id)?;+ let session = project+ .threads+ .iter_mut()+ .find(|session| session.id == plan.thread_id)?;+ session.materialized_workspace_name = Some(plan.workspace_name.clone());+ session.last_active_at = now_ts();+ session.is_unread = false;+ session.work_finished_unseen = false;+ project.active_thread_id = Some(plan.thread_id.clone());+ let space_id = project.space_id.clone();+ let active_project_id = project.id.clone();+ let _ = project;+ self.set_active_project_for_space(&space_id, active_project_id);+ Some(plan)+ }++ fn activation_plan_for_thread(+ &self,+ thread_id: &str,+ live_workspaces: &[String],+ ) -> Option<ActivationPlan> {+ let project = self.projects.iter().find(|project| {project.threads.iter().any(|session| session.id == thread_id)})?;- let project_id = project.id.clone();let session = project.threads- .iter_mut()+ .iter().find(|session| session.id == thread_id)?;let workspace_name = session.materialized_workspace_name.clone()- .unwrap_or_else(|| workspace_name_for_thread(&project_id, &session.id));+ .or_else(|| session.planned_workspace_name.clone())+ .unwrap_or_else(|| workspace_name_for_thread(&project.id, &session.id));let needs_materialize = !live_workspaces.iter().any(|live| live == &workspace_name);- session.materialized_workspace_name = Some(workspace_name.clone());- session.last_active_at = now_ts();- session.is_unread = false;- session.work_finished_unseen = false;- let thread_id = session.id.clone();- project.active_thread_id = Some(thread_id.clone());- let space_id = project.space_id.clone();- let active_project_id = project.id.clone();- let project_path = project.path.clone();- let _ = project;- self.set_active_project_for_space(&space_id, active_project_id);Some(ActivationPlan {- project_id,- thread_id,+ project_id: project.id.clone(),+ thread_id: session.id.clone(),workspace_name,- project_path,+ project_path: project.path.clone(),needs_materialize,})}+ fn thread_connection_state(+ &self,+ thread_id: &str,+ live_workspaces: &[String],+ ) -> Option<ThreadConnectionState> {+ let project = self.projects.iter().find(|project| {+ project+ .threads+ .iter()+ .any(|session| session.id == thread_id)+ })?;+ let session = project+ .threads+ .iter()+ .find(|session| session.id == thread_id)?;+ let workspace_name = session+ .materialized_workspace_name+ .clone()+ .or_else(|| session.planned_workspace_name.clone())+ .unwrap_or_else(|| workspace_name_for_thread(&project.id, &session.id));+ Some(ThreadConnectionState {+ space_id: project.space_id.clone(),+ project_id: project.id.clone(),+ thread_id: session.id.clone(),+ project_name: project.name.clone(),+ thread_name: session.name.clone(),+ workspace_name: workspace_name.clone(),+ is_remote: is_remote_project(project),+ is_live: live_workspaces.iter().any(|live| live == &workspace_name),+ })+ }++ fn thread_space_id(&self, thread_id: &str) -> Option<SpaceId> {+ self.projects.iter().find_map(|project| {+ project+ .threads+ .iter()+ .any(|session| session.id == thread_id)+ .then(|| project.space_id.clone())+ })+ }+fn snapshot_active_space_thread_layout(&mut self,space_id: &str,@@ -1811,18 +2032,22 @@ impl WorkspaceThreadStore {}for project in &mut self.projects {- if let Some(session) = project+ let Some(index) = project.threads- .iter_mut()- .find(|session| session.id == thread_id)- {- if session.name == name {- return false;- }- session.name = name.to_string();- session.last_active_at = now_ts();- return true;+ .iter()+ .position(|session| session.id == thread_id)+ else {+ continue;+ };++ let unique_name = unique_thread_name(project, Some(thread_id), name);+ let session = &mut project.threads[index];+ if session.name == unique_name {+ return false;}+ session.name = unique_name;+ session.last_active_at = now_ts();+ return true;}false}@@ -1959,34 +2184,159 @@ impl WorkspaceThreadStore {None}- fn remove_project(&mut self, project_id: &str) -> Option<RemovedProject> {- let index = self- .projects- .iter()- .position(|project| project.id == project_id)?;- let space_id = self.projects[index].space_id.clone();- if self+ fn end_workspace_thread_record(&mut self, thread_id: &str) -> EndWorkspaceThreadResult {+ if let Some(deleted) = self.delete_thread(thread_id) {+ return EndWorkspaceThreadResult::DeletedThread(deleted);+ }++ let Some(project_index) = self.projects.iter().position(|project| {+ project+ .threads+ .iter()+ .any(|session| session.id == thread_id)+ }) else {+ return EndWorkspaceThreadResult::Noop;+ };++ if !is_remote_project(&self.projects[project_index]) {+ return EndWorkspaceThreadResult::Noop;+ }++ let project_id = self.projects[project_index].id.clone();+ let space_id = self.projects[project_index].space_id.clone();+ let project_count = self.projects.iter().filter(|project| project.space_id == space_id)- .count()- <= 1- {- return None;+ .count();++ if project_count <= 1 {+ let mut project = default_project_for_space(&space_id);+ let session = WorkspaceThread::new(project.id.clone(), "main".to_string(), None);+ project.active_thread_id = Some(session.id.clone());+ project.threads.push(session);+ self.projects.push(project);+ self.set_active_project_for_space(&space_id, project_id.clone());}- let removed = self.projects.remove(index);- let was_active = self.active_project_id_for_space(&space_id).as_deref() == Some(project_id);- let materialized_workspace_names = removed++ self.remove_project(&project_id)+ .map(EndWorkspaceThreadResult::RemovedProject)+ .unwrap_or(EndWorkspaceThreadResult::Noop)+ }++ fn disconnect_workspace_thread_record(+ &mut self,+ thread_id: &str,+ live_workspaces: &[String],+ ) -> (Option<DisconnectedWorkspaceThread>, bool) {+ let Some(project_index) = self.projects.iter().position(|project| {+ project+ .threads+ .iter()+ .any(|session| session.id == thread_id)+ }) else {+ return (None, false);+ };++ if !is_remote_project(&self.projects[project_index]) {+ return (None, false);+ }++ let project_id = self.projects[project_index].id.clone();+ let space_id = self.projects[project_index].space_id.clone();+ let workspace_name = self.projects[project_index].threads.iter()- .filter_map(|session| session.materialized_workspace_name.clone())- .collect::<Vec<_>>();+ .find(|session| session.id == thread_id)+ .and_then(|session| session.materialized_workspace_name.clone())+ .unwrap_or_else(|| workspace_name_for_thread(&project_id, thread_id));++ if !live_workspaces.iter().any(|live| live == &workspace_name) {+ return (None, false);+ }+ let was_active = self.active_project_id_for_space(&space_id).as_deref()+ == Some(project_id.as_str())+ && self.projects[project_index].active_thread_id.as_deref() == Some(thread_id);+ let mut changed = false;let next_thread_id = if was_active {- let Some(next_index) = self+ let default_project_id = default_project_for_space(&space_id).id;+ if self.projects.iter()- .enumerate()+ .all(|project| project.id != default_project_id || project.space_id != space_id)+ {+ let mut project = default_project_for_space(&space_id);+ let session = WorkspaceThread::new(project.id.clone(), "main".to_string(), None);+ let thread_id = session.id.clone();+ project.active_thread_id = Some(thread_id);+ project.threads.push(session);+ self.projects.push(project);+ changed = true;+ }++ let next_thread_id = {+ let project = self+ .projects+ .iter_mut()+ .find(|project| {+ project.id == default_project_id && project.space_id == space_id+ })+ .expect("default project should exist");+ project.active_thread_id.clone().unwrap_or_else(|| {+ let session =+ WorkspaceThread::new(project.id.clone(), "main".to_string(), None);+ let thread_id = session.id.clone();+ project.active_thread_id = Some(thread_id.clone());+ project.threads.push(session);+ changed = true;+ thread_id+ })+ };+ changed |= self.set_active_project_for_space(&space_id, default_project_id);+ Some(next_thread_id)+ } else {+ None+ };++ (+ Some(DisconnectedWorkspaceThread {+ was_active,+ next_thread_id,+ workspace_name,+ }),+ changed,+ )+ }++ fn remove_project(&mut self, project_id: &str) -> Option<RemovedProject> {+ let index = self+ .projects+ .iter()+ .position(|project| project.id == project_id)?;+ let space_id = self.projects[index].space_id.clone();+ if self+ .projects+ .iter()+ .filter(|project| project.space_id == space_id)+ .count()+ <= 1+ {+ return None;+ }+ let removed = self.projects.remove(index);+ let was_active = self.active_project_id_for_space(&space_id).as_deref() == Some(project_id);+ let materialized_workspace_names = removed+ .threads+ .iter()+ .filter_map(|session| session.materialized_workspace_name.clone())+ .collect::<Vec<_>>();++ let next_thread_id = if was_active {+ let Some(next_index) = self+ .projects+ .iter()+ .enumerate().filter(|(_, project)| project.space_id == space_id).map(|(idx, _)| idx).find(|idx| *idx >= index)@@ -2055,6 +2405,7 @@ impl WorkspaceThread {name,project_id,layout: None,+ planned_workspace_name: None,materialized_workspace_name: workspace,last_active_at: now_ts(),is_pinned: false,@@ -2075,6 +2426,7 @@ impl WorkspaceThread {name,project_id,layout: None,+ planned_workspace_name: None,materialized_workspace_name: workspace,last_active_at: now_ts(),is_pinned: false,@@ -2747,6 +3099,14 @@ fn workspace_name_for_thread(project_id: &str, thread_id: &str) -> String {format!("thinkterm:{project_id}:{thread_id}")}+fn workspace_name_for_remote_default(project_id: &str, thread_id: &str, workspace: &str) -> String {+ format!(+ "{}:{}",+ workspace_name_for_thread(project_id, thread_id),+ workspace+ )+}+pub fn remote_project_id_for_space(space_id: &str, host_id: &str) -> ProjectId {format!("{host_id}{REMOTE_PROJECT_SPACE_SEPARATOR}{space_id}")}@@ -2758,14 +3118,6 @@ pub fn remote_host_id_for_project_id(project_id: &str) -> &str {.unwrap_or(project_id)}-pub fn remote_workspace_name_for_space(- space_id: &str,- host_id: &str,- base_workspace: &str,-) -> String {- format!("thinkterm:ssh:{space_id}:{host_id}:{base_workspace}")-}-fn next_space_name(spaces: &[Space]) -> String {let mut index = spaces.len() + 1;loop {@@ -2777,6 +3129,47 @@ fn next_space_name(spaces: &[Space]) -> String {}}+fn thread_name_in_use(project: &Project, ignored_thread_id: Option<&str>, name: &str) -> bool {+ project+ .threads+ .iter()+ .any(|thread| ignored_thread_id != Some(thread.id.as_str()) && thread.name == name)+}++fn next_thread_name(project: &Project) -> String {+ let mut index = project.threads.len().saturating_add(1).max(1);+ loop {+ let name = format!("Thread {index}");+ if !thread_name_in_use(project, None, &name) {+ return name;+ }+ index += 1;+ }+}++fn unique_thread_name(+ project: &Project,+ ignored_thread_id: Option<&str>,+ requested: &str,+) -> String {+ let requested = requested.trim();+ if requested.is_empty() {+ return next_thread_name(project);+ }+ if !thread_name_in_use(project, ignored_thread_id, requested) {+ return requested.to_string();+ }++ let mut index = 2;+ loop {+ let name = format!("{requested} {index}");+ if !thread_name_in_use(project, ignored_thread_id, &name) {+ return name;+ }+ index += 1;+ }+}+fn new_id(prefix: &str) -> String {format!("{prefix}-{}-{:08x}",@@ -2822,6 +3215,73 @@ mod tests {}}+ #[test]+ fn normalize_makes_thread_names_unique_per_project() {+ let mut store = test_store();+ store.projects.push(test_project(+ "project-1",+ "Project",+ PathBuf::from("/tmp/project"),+ vec![+ WorkspaceThread::new("project-1".to_string(), "Thread 2".to_string(), None),+ WorkspaceThread::new("project-1".to_string(), "Thread 2".to_string(), None),+ WorkspaceThread::new("project-1".to_string(), "Thread 3".to_string(), None),+ ],+ ));++ assert!(store.normalize_after_load());+ let names = store.projects[0]+ .threads+ .iter()+ .map(|thread| thread.name.as_str())+ .collect::<Vec<_>>();+ assert_eq!(names, vec!["Thread 2", "Thread 4", "Thread 3"]);+ }++ #[test]+ fn create_thread_skips_existing_default_thread_names() {+ let mut store = test_store();+ store.projects.push(test_project(+ "project-1",+ "Project",+ PathBuf::from("/tmp/project"),+ vec![+ WorkspaceThread::new("project-1".to_string(), "Thread 1".to_string(), None),+ WorkspaceThread::new("project-1".to_string(), "Thread 3".to_string(), None),+ ],+ ));++ let thread_id = store.create_thread("project-1", None);+ let thread = store.projects[0]+ .threads+ .iter()+ .find(|thread| thread.id == thread_id)+ .expect("created thread");+ assert_eq!(thread.name, "Thread 4");+ }++ #[test]+ fn rename_thread_keeps_names_unique_in_project() {+ let mut store = test_store();+ let first = WorkspaceThread::new("project-1".to_string(), "Build".to_string(), None);+ let second = WorkspaceThread::new("project-1".to_string(), "Review".to_string(), None);+ let second_id = second.id.clone();+ store.projects.push(test_project(+ "project-1",+ "Project",+ PathBuf::from("/tmp/project"),+ vec![first, second],+ ));++ assert!(store.rename_thread(&second_id, "Build".to_string()));+ let renamed = store.projects[0]+ .threads+ .iter()+ .find(|thread| thread.id == second_id)+ .expect("renamed thread");+ assert_eq!(renamed.name, "Build 2");+ }+#[test]fn normalize_empty_space_without_active_project_is_stable() {let mut store = test_store();@@ -2965,6 +3425,40 @@ mod tests {);}+ #[test]+ fn thread_id_for_workspace_matches_materialized_or_expected_name() {+ let mut store = test_store();+ let space_id = store.create_space_record("Remote".to_string());+ let mut thread = WorkspaceThread::new("ssh-host".to_string(), "main".to_string(), None);+ let thread_id = thread.id.clone();+ let expected_workspace = workspace_name_for_thread("ssh-host", &thread_id);+ thread.materialized_workspace_name = Some("custom-remote".to_string());+ store.projects.push(test_project_in_space(+ &space_id,+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ vec![thread],+ ));++ assert_eq!(+ store+ .thread_id_for_workspace(&space_id, "custom-remote")+ .as_deref(),+ Some(thread_id.as_str())+ );+ assert_eq!(+ store+ .thread_id_for_workspace(&space_id, &expected_workspace)+ .as_deref(),+ Some(thread_id.as_str())+ );+ assert_eq!(+ store.thread_id_for_workspace("other-space", "custom-remote"),+ None+ );+ }+#[test]fn workspace_thread_store_round_trip() {let dir = tempdir().unwrap();@@ -3105,6 +3599,134 @@ mod tests {);}+ #[test]+ fn remote_thread_connection_state_does_not_select_or_materialize() {+ let space_id = default_space_id();+ let mut store = test_store();+ let thread = WorkspaceThread::new("ssh-host".to_string(), "main".to_string(), None);+ let thread_id = thread.id.clone();+ store.projects.push(Project {+ id: "ssh-host".to_string(),+ space_id: space_id.clone(),+ name: "Remote".to_string(),+ path: PathBuf::from("ssh://[email protected]"),+ threads: vec![thread],+ active_thread_id: None,+ threads_collapsed: false,+ });++ let state = store+ .thread_connection_state(&thread_id, &[])+ .expect("remote thread state");+ assert_eq!(state.space_id, space_id);+ assert!(state.is_remote);+ assert!(!state.is_live);+ assert_eq!(+ state.workspace_name,+ workspace_name_for_thread("ssh-host", &thread_id)+ );+ assert!(store.projects[0].active_thread_id.is_none());+ assert!(store.spaces[0].active_project_id.is_none());+ assert!(store.projects[0].threads[0]+ .materialized_workspace_name+ .is_none());+ assert_eq!(store.thread_space_id(&thread_id), Some(space_id));+ }++ #[test]+ fn activation_plan_for_thread_does_not_select_or_materialize() {+ let space_id = default_space_id();+ let mut store = test_store();+ let thread = WorkspaceThread::new("ssh-host".to_string(), "main".to_string(), None);+ let thread_id = thread.id.clone();+ store.projects.push(Project {+ id: "ssh-host".to_string(),+ space_id: space_id.clone(),+ name: "Remote".to_string(),+ path: PathBuf::from("ssh://[email protected]"),+ threads: vec![thread],+ active_thread_id: None,+ threads_collapsed: false,+ });++ let plan = store+ .activation_plan_for_thread(&thread_id, &[])+ .expect("activation plan");+ assert!(plan.needs_materialize);+ assert_eq!(+ plan.workspace_name,+ workspace_name_for_thread("ssh-host", &thread_id)+ );+ assert!(store.projects[0].active_thread_id.is_none());+ assert!(store.spaces[0].active_project_id.is_none());+ assert!(store.projects[0].threads[0]+ .materialized_workspace_name+ .is_none());+ assert_eq!(store.thread_to_restore_for_space(&space_id), (None, false));++ let plan = store.activate_thread_record(&thread_id, &[]).unwrap();+ assert!(plan.needs_materialize);+ assert_eq!(+ store.projects[0].active_thread_id.as_deref(),+ Some(thread_id.as_str())+ );+ assert_eq!(+ store.spaces[0].active_project_id.as_deref(),+ Some("ssh-host")+ );+ assert!(thread_has_restorable_workspace(+ &store.projects[0].threads[0]+ ));+ assert_eq!(+ store.thread_to_restore_for_space(&space_id),+ (Some(thread_id), false)+ );+ }++ #[test]+ fn disconnected_remote_host_thread_preserves_workspace_override() {+ let space_id = default_space_id();+ let mut store = test_store();+ let thread_id = store.create_disconnected_remote_host_thread(+ &space_id,+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ Some("custom-remote-workspace".to_string()),+ );++ let project = store+ .projects+ .iter()+ .find(|project| project.threads.iter().any(|thread| thread.id == thread_id))+ .expect("remote project");+ let thread = project+ .threads+ .iter()+ .find(|thread| thread.id == thread_id)+ .expect("remote thread");+ let expected_workspace =+ workspace_name_for_remote_default(&project.id, &thread_id, "custom-remote-workspace");+ assert_eq!(+ thread.planned_workspace_name.as_deref(),+ Some(expected_workspace.as_str())+ );+ assert!(thread.materialized_workspace_name.is_none());+ assert!(!thread_has_restorable_workspace(thread));++ let state = store+ .thread_connection_state(&thread_id, &["custom-remote-workspace".to_string()])+ .expect("remote thread state");+ assert_eq!(state.space_id, space_id);+ assert_eq!(state.workspace_name, expected_workspace);+ assert!(!state.is_live);++ let plan = store+ .activate_thread_record(&thread_id, &[])+ .expect("activation plan");+ assert_eq!(plan.workspace_name, expected_workspace);+ }+#[test]fn workspace_work_observation_transitions_to_finished_unseen() {let mut store = test_store();@@ -3666,6 +4288,236 @@ mod tests {assert!(store.remove_project("project-1").is_none());}+ #[test]+ fn end_workspace_thread_deletes_thread_when_project_has_fallback_thread() {+ let space_id = default_space_id();+ let mut store = test_store();+ let first = WorkspaceThread::new("project-1".to_string(), "main".to_string(), None);+ let second = WorkspaceThread::new("project-1".to_string(), "Thread 2".to_string(), None);+ let first_id = first.id.clone();+ let second_id = second.id.clone();+ let mut project = test_project(+ "project-1",+ "thinkterm",+ PathBuf::from("/tmp/thinkterm"),+ vec![first, second],+ );+ project.active_thread_id = Some(second_id.clone());+ store.projects.push(project);+ store.set_active_project_for_space(&space_id, "project-1".to_string());++ let result = store.end_workspace_thread_record(&second_id);+ let EndWorkspaceThreadResult::DeletedThread(deleted) = result else {+ panic!("expected deleted thread result");+ };+ assert!(deleted.was_active);+ assert_eq!(deleted.next_thread_id, Some(first_id.clone()));+ assert_eq!(store.projects[0].threads.len(), 1);+ assert_eq!(+ store.projects[0].active_thread_id.as_deref(),+ Some(first_id.as_str())+ );+ }++ #[test]+ fn end_workspace_thread_removes_remote_project_when_space_has_fallback_project() {+ let space_id = default_space_id();+ let mut store = test_store();+ let local = WorkspaceThread::new("project-local".to_string(), "main".to_string(), None);+ let local_id = local.id.clone();+ let mut local_project = test_project(+ "project-local",+ "Home",+ PathBuf::from("/tmp/home"),+ vec![local],+ );+ local_project.active_thread_id = Some(local_id.clone());+ store.projects.push(local_project);++ let remote = WorkspaceThread::new("ssh-host".to_string(), "Session 1".to_string(), None);+ let remote_id = remote.id.clone();+ let mut remote_project = test_project(+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ vec![remote],+ );+ remote_project.active_thread_id = Some(remote_id.clone());+ store.projects.push(remote_project);+ store.set_active_project_for_space(&space_id, "ssh-host".to_string());++ let result = store.end_workspace_thread_record(&remote_id);+ let EndWorkspaceThreadResult::RemovedProject(removed) = result else {+ panic!("expected removed project result");+ };+ assert!(removed.was_active);+ assert_eq!(removed.next_thread_id, Some(local_id.clone()));+ assert_eq!(store.projects.len(), 1);+ assert_eq!(store.projects[0].id, "project-local");+ assert_eq!(+ store.active_project_id_for_space(&space_id).as_deref(),+ Some("project-local")+ );+ }++ #[test]+ fn end_workspace_thread_seeds_default_project_before_removing_last_remote_project() {+ let space_id = default_space_id();+ let mut store = test_store();+ let remote = WorkspaceThread::new("ssh-host".to_string(), "Session 1".to_string(), None);+ let remote_id = remote.id.clone();+ let mut remote_project = test_project(+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ vec![remote],+ );+ remote_project.active_thread_id = Some(remote_id.clone());+ store.projects.push(remote_project);+ store.set_active_project_for_space(&space_id, "ssh-host".to_string());++ let result = store.end_workspace_thread_record(&remote_id);+ let EndWorkspaceThreadResult::RemovedProject(removed) = result else {+ panic!("expected removed project result");+ };+ assert!(removed.was_active);+ let next_thread_id = removed+ .next_thread_id+ .clone()+ .expect("new default thread id");+ assert_eq!(store.projects.len(), 1);+ assert_eq!(store.projects[0].name, "Home");+ assert_eq!(store.projects[0].threads.len(), 1);+ assert_eq!(store.projects[0].threads[0].name, "main");+ assert_eq!(store.projects[0].threads[0].id, next_thread_id);+ assert_eq!(store.projects[0].active_thread_id, Some(next_thread_id));+ assert_eq!(+ store.active_project_id_for_space(&space_id).as_deref(),+ Some(store.projects[0].id.as_str())+ );+ }++ #[test]+ fn end_workspace_thread_noops_for_last_local_thread() {+ let space_id = default_space_id();+ let mut store = test_store();+ let thread = WorkspaceThread::new("project-local".to_string(), "main".to_string(), None);+ let thread_id = thread.id.clone();+ let mut project = test_project(+ "project-local",+ "Home",+ PathBuf::from("/tmp/home"),+ vec![thread],+ );+ project.active_thread_id = Some(thread_id.clone());+ store.projects.push(project);+ store.set_active_project_for_space(&space_id, "project-local".to_string());++ assert_eq!(+ store.end_workspace_thread_record(&thread_id),+ EndWorkspaceThreadResult::Noop+ );+ assert_eq!(store.projects.len(), 1);+ assert_eq!(store.projects[0].threads.len(), 1);+ assert_eq!(+ store.active_project_id_for_space(&space_id).as_deref(),+ Some("project-local")+ );+ }++ #[test]+ fn disconnect_active_remote_thread_keeps_record_and_switches_to_default_project() {+ let space_id = default_space_id();+ let mut store = test_store();+ let remote = WorkspaceThread::new("ssh-host".to_string(), "Session 1".to_string(), None);+ let remote_id = remote.id.clone();+ let remote_workspace = workspace_name_for_thread("ssh-host", &remote_id);+ let mut remote_project = test_project(+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ vec![remote],+ );+ remote_project.active_thread_id = Some(remote_id.clone());+ store.projects.push(remote_project);+ store.set_active_project_for_space(&space_id, "ssh-host".to_string());++ let (disconnected, changed) =+ store.disconnect_workspace_thread_record(&remote_id, &[remote_workspace.clone()]);+ let disconnected = disconnected.expect("disconnected remote thread");+ assert!(changed);+ assert!(disconnected.was_active);+ assert_eq!(disconnected.workspace_name, remote_workspace);+ assert!(disconnected.next_thread_id.is_some());+ assert!(store.projects.iter().any(|project| project.id == "ssh-host"+ && project.threads.iter().any(|thread| thread.id == remote_id)));+ assert_eq!(+ store.active_project_id_for_space(&space_id).as_deref(),+ Some(store.projects[1].id.as_str())+ );+ }++ #[test]+ fn disconnect_inactive_remote_thread_keeps_active_project() {+ let space_id = default_space_id();+ let mut store = test_store();+ let local = WorkspaceThread::new("project-local".to_string(), "main".to_string(), None);+ let local_id = local.id.clone();+ let mut local_project = test_project(+ "project-local",+ "Home",+ PathBuf::from("/tmp/home"),+ vec![local],+ );+ local_project.active_thread_id = Some(local_id);+ store.projects.push(local_project);++ let remote = WorkspaceThread::new("ssh-host".to_string(), "Session 1".to_string(), None);+ let remote_id = remote.id.clone();+ let remote_workspace = workspace_name_for_thread("ssh-host", &remote_id);+ let mut remote_project = test_project(+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ vec![remote],+ );+ remote_project.active_thread_id = Some(remote_id.clone());+ store.projects.push(remote_project);+ store.set_active_project_for_space(&space_id, "project-local".to_string());++ let (disconnected, changed) =+ store.disconnect_workspace_thread_record(&remote_id, &[remote_workspace.clone()]);+ let disconnected = disconnected.expect("disconnected remote thread");+ assert!(!changed);+ assert!(!disconnected.was_active);+ assert_eq!(disconnected.next_thread_id, None);+ assert_eq!(disconnected.workspace_name, remote_workspace);+ assert_eq!(+ store.active_project_id_for_space(&space_id).as_deref(),+ Some("project-local")+ );+ }++ #[test]+ fn disconnect_non_live_remote_thread_noops() {+ let mut store = test_store();+ let remote = WorkspaceThread::new("ssh-host".to_string(), "Session 1".to_string(), None);+ let remote_id = remote.id.clone();+ let mut remote_project = test_project(+ "ssh-host",+ "Remote",+ PathBuf::from("ssh://[email protected]"),+ vec![remote],+ );+ remote_project.active_thread_id = Some(remote_id.clone());+ store.projects.push(remote_project);++ assert_eq!(+ store.disconnect_workspace_thread_record(&remote_id, &[]),+ (None, false)+ );+ }+#[test]fn project_reveal_path_requires_existing_local_directory() {let mut store = test_store();diff --git a/wezterm-ssh/src/pty.rs b/wezterm-ssh/src/pty.rsindex 258f2a82..b017275b 100644--- a/wezterm-ssh/src/pty.rs+++ b/wezterm-ssh/src/pty.rs@@ -1,12 +1,16 @@-use crate::session::{SessionRequest, SessionSender, SignalChannel};+use crate::session::{DeadSession, SessionRequest, SessionSender, SignalChannel};use crate::sessioninner::{ChannelId, ChannelInfo, DescriptorState};use crate::sessionwrap::SessionWrap;use filedescriptor::{socketpair, FileDescriptor};use portable_pty::{ExitStatus, PtySize};-use smol::channel::{bounded, Receiver, TryRecvError};+use smol::channel::{bounded, Receiver, TryRecvError, TrySendError};use std::collections::{HashMap, VecDeque};use std::io::{Read, Write};-use std::sync::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;++const RESIZE_RETRY_DELAY: Duration = Duration::from_millis(25);#[derive(Debug)]pub(crate) struct NewPty {@@ -29,6 +33,8 @@ pub struct SshPty {pub(crate) reader: FileDescriptor,pub(crate) writer: FileDescriptor,pub(crate) size: Mutex<PtySize>,+ pending_resize: Arc<Mutex<Option<PtySize>>>,+ resize_retry_scheduled: Arc<AtomicBool>,}impl std::io::Write for SshPty {@@ -41,20 +47,64 @@ impl std::io::Write for SshPty {}}+impl SshPty {+ fn schedule_resize_retry(&self, tx: SessionSender) {+ if self.resize_retry_scheduled.swap(true, Ordering::AcqRel) {+ return;+ }++ let pending_resize = Arc::clone(&self.pending_resize);+ let retry_scheduled = Arc::clone(&self.resize_retry_scheduled);+ let channel = self.channel;+ std::thread::spawn(move || loop {+ std::thread::sleep(RESIZE_RETRY_DELAY);+ let Some(size) = pending_resize.lock().unwrap().take() else {+ retry_scheduled.store(false, Ordering::Release);+ if pending_resize.lock().unwrap().is_none() {+ return;+ }+ if retry_scheduled.swap(true, Ordering::AcqRel) {+ return;+ }+ continue;+ };++ match try_send_resize(&tx, channel, size) {+ Ok(()) => {}+ Err(TrySendError::Full(_)) => {+ restore_pending_resize_if_missing(&pending_resize, size);+ }+ Err(TrySendError::Closed(_)) => {+ retry_scheduled.store(false, Ordering::Release);+ return;+ }+ }+ });+ }+}+impl portable_pty::MasterPty for SshPty {fn resize(&self, size: PtySize) -> anyhow::Result<()> {- self.tx- .as_ref()- .unwrap()- .try_send(SessionRequest::ResizePty(- ResizePty {- channel: self.channel,- size,- },- None,- ))?;-*self.size.lock().unwrap() = size;+ let Some(tx) = self.tx.as_ref() else {+ return Err(DeadSession.into());+ };+ match try_send_resize(tx, self.channel, size) {+ Ok(()) => {}+ Err(TrySendError::Full(_)) => {+ // Resize events are coalescable and can arrive in bursts during+ // live resizing or UI view transitions. Keep the latest size+ // and retry it so the remote PTY doesn't get stuck at stale+ // rows/cols when the burst stops.+ *self.pending_resize.lock().unwrap() = Some(size);+ self.schedule_resize_retry(tx.clone());+ log::debug!(+ "coalescing SSH resize for channel {} because the request queue is full",+ self.channel+ );+ }+ Err(TrySendError::Closed(_)) => return Err(DeadSession.into()),+ }Ok(())}@@ -89,6 +139,21 @@ impl portable_pty::MasterPty for SshPty {}}+fn try_send_resize(+ tx: &SessionSender,+ channel: ChannelId,+ size: PtySize,+) -> Result<(), TrySendError<SessionRequest>> {+ tx.try_send_request(SessionRequest::ResizePty(ResizePty { channel, size }, None))+}++fn restore_pending_resize_if_missing(pending_resize: &Mutex<Option<PtySize>>, size: PtySize) {+ let mut pending = pending_resize.lock().unwrap();+ if pending.is_none() {+ *pending = Some(size);+ }+}+#[derive(Debug)]pub struct SshChildProcess {pub(crate) channel: ChannelId,@@ -280,6 +345,8 @@ impl crate::sessioninner::SessionInner {reader: read_from_stdout,writer: write_to_stdin,size: Mutex::new(newpty.size),+ pending_resize: Arc::new(Mutex::new(None)),+ resize_retry_scheduled: Arc::new(AtomicBool::new(false)),};let (exit_tx, exit_rx) = bounded(1);@@ -326,3 +393,91 @@ impl crate::sessioninner::SessionInner {Ok(())}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session::{SessionRequest, SessionSender};+ use portable_pty::MasterPty;+ use smol::channel::bounded;+ use std::sync::Arc;+ use std::time::Duration;++ #[test]+ fn resize_retries_latest_request_when_session_queue_is_full() {+ let (tx, rx) = bounded(1);+ tx.try_send(SessionRequest::SessionDropped).unwrap();+ let (pipe_write, _pipe_read) = socketpair().unwrap();+ let (writer, reader) = socketpair().unwrap();+ let pty = SshPty {+ channel: 7,+ tx: Some(SessionSender {+ tx,+ pipe: Arc::new(Mutex::new(pipe_write)),+ }),+ reader,+ writer,+ size: Mutex::new(PtySize {+ rows: 24,+ cols: 80,+ pixel_width: 640,+ pixel_height: 480,+ }),+ pending_resize: Arc::new(Mutex::new(None)),+ resize_retry_scheduled: Arc::new(AtomicBool::new(false)),+ };++ let size = PtySize {+ rows: 40,+ cols: 120,+ pixel_width: 960,+ pixel_height: 800,+ };++ pty.resize(size).unwrap();+ assert_eq!(*pty.size.lock().unwrap(), size);++ assert!(matches!(+ rx.try_recv().unwrap(),+ SessionRequest::SessionDropped+ ));+ let mut retried = None;+ for _ in 0..40 {+ if let Ok(request) = rx.try_recv() {+ retried = Some(request);+ break;+ }+ std::thread::sleep(Duration::from_millis(10));+ }++ let Some(SessionRequest::ResizePty(resize, None)) = retried else {+ panic!("expected retried resize request");+ };+ assert_eq!(resize.channel, 7);+ assert_eq!(resize.size, size);+ }++ #[test]+ fn resize_retry_restore_preserves_newer_pending_request() {+ let old_size = PtySize {+ rows: 24,+ cols: 80,+ pixel_width: 640,+ pixel_height: 480,+ };+ let newer_size = PtySize {+ rows: 40,+ cols: 120,+ pixel_width: 960,+ pixel_height: 800,+ };++ let pending = Mutex::new(Some(newer_size));+ restore_pending_resize_if_missing(&pending, old_size);+ assert_eq!(*pending.lock().unwrap(), Some(newer_size));++ let pending = Mutex::new(None);+ restore_pending_resize_if_missing(&pending, old_size);+ assert_eq!(*pending.lock().unwrap(), Some(old_size));+ }+}diff --git a/wezterm-ssh/src/session.rs b/wezterm-ssh/src/session.rsindex 5eac13c7..e0ef5729 100644--- a/wezterm-ssh/src/session.rs+++ b/wezterm-ssh/src/session.rs@@ -40,6 +40,15 @@ impl SessionSender {Ok(())}+ pub(crate) fn try_send_request(+ &self,+ event: SessionRequest,+ ) -> Result<(), smol::channel::TrySendError<SessionRequest>> {+ self.tx.try_send(event)?;+ self.post_send();+ Ok(())+ }+pub async fn send(&self, event: SessionRequest) -> anyhow::Result<()> {self.tx.send(event).await?;self.post_send();diff --git a/wezterm-ssh/src/sessioninner.rs b/wezterm-ssh/src/sessioninner.rsindex b93cb976..f84b8518 100644--- a/wezterm-ssh/src/sessioninner.rs+++ b/wezterm-ssh/src/sessioninner.rs@@ -398,8 +398,31 @@ impl SessionInner {.with_context(|| format!("binding to {bind_addr:?}"))?;}- sock.connect(&addr.into())- .with_context(|| format!("Connecting to {hostname}:{port} ({addr:?})"))?;+ // Honor a connect timeout so that an unreachable host fails promptly+ // instead of blocking for the OS default (~75s on macOS, or indefinitely+ // for blackhole routes). `connect_timeout` leaves the socket in+ // non-blocking mode, so restore blocking afterwards for the handshake.+ match self+ .config+ .get("connecttimeout")+ .and_then(|value| value.parse::<u64>().ok())+ .filter(|seconds| *seconds > 0)+ .map(Duration::from_secs)+ {+ Some(timeout) => {+ sock.connect_timeout(&addr.into(), timeout)+ .with_context(|| {+ format!("Connecting to {hostname}:{port} ({addr:?}) within {timeout:?}")+ })?;+ sock.set_nonblocking(false).with_context(|| {+ format!("restoring blocking mode after connect to {hostname}:{port}")+ })?;+ }+ None => {+ sock.connect(&addr.into())+ .with_context(|| format!("Connecting to {hostname}:{port} ({addr:?})"))?;+ }+ }Ok((sock, None))}@@ -1135,6 +1158,12 @@ fn write_from_buf<W: Write>(w: &mut W, buf: &mut VecDeque<u8>) -> std::io::Resulfn read_into_buf<R: Read>(r: &mut R, buf: &mut VecDeque<u8>) -> std::io::Result<bool> {let current_len = buf.len();+ if current_len == buf.capacity() {+ // The channel buffer is full. Report no progress so the event loop+ // applies backpressure instead of reading an empty slice and treating+ // the resulting Ok(0) as EOF.+ return Ok(false);+ }buf.resize(buf.capacity(), 0);let target_buf = &mut buf.make_contiguous()[current_len..];match r.read(target_buf) {@@ -1186,3 +1215,51 @@ impl Drop for KillOnDropChild {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Cursor;++ struct CountingReader {+ calls: usize,+ }++ impl Read for CountingReader {+ fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {+ self.calls += 1;+ panic!("full buffers must not call read");+ }+ }++ #[test]+ fn read_into_full_buf_reports_backpressure_without_reading() {+ let mut buf = VecDeque::with_capacity(3);+ while buf.len() < buf.capacity() {+ buf.push_back(0);+ }+ let mut reader = CountingReader { calls: 0 };++ assert_eq!(read_into_buf(&mut reader, &mut buf).unwrap(), false);+ assert_eq!(reader.calls, 0);+ assert_eq!(buf.len(), buf.capacity());+ }++ #[test]+ fn read_into_non_full_buf_keeps_eof_semantics() {+ let mut buf = VecDeque::with_capacity(8);+ let mut reader = Cursor::new(Vec::<u8>::new());++ let err = read_into_buf(&mut reader, &mut buf).unwrap_err();+ assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);+ }++ #[test]+ fn read_into_non_full_buf_reports_progress() {+ let mut buf = VecDeque::with_capacity(8);+ let mut reader = Cursor::new(b"abc".to_vec());++ assert_eq!(read_into_buf(&mut reader, &mut buf).unwrap(), true);+ assert_eq!(buf.iter().copied().collect::<Vec<_>>(), b"abc");+ }+}