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
Fix remote file browsing and empty states
RoversXb9ce28df11b0
diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rsindex f4135e0d..bcd35b9c 100644--- a/wezterm-gui/src/termwindow/remote_files.rs+++ b/wezterm-gui/src/termwindow/remote_files.rs@@ -76,6 +76,60 @@ impl RemotePath {}}+/// Whether `requested` needs the remote home resolved before it can be used.+/// Absolute roots do not: asking the server to canonicalize `.` first is both+/// pointless and a needless failure point, since a server that cannot answer+/// that request would break a project whose path was fully specified.+fn requested_root_needs_home(requested: &str) -> bool {+ requested == "~" || requested.starts_with("~/")+}++/// Validate a stored project path for use as a browse root. Kept separate from+/// [`RemotePath::from_server_absolute`] so the diagnostics distinguish "the+/// server answered with something odd" from "this project's stored path cannot+/// be browsed", and so traversal components never reach the server.+fn remote_root_from_absolute(requested: &str) -> Result<RemotePath, String> {+ if !requested.starts_with('/') {+ return Err(format!(+ "Unsupported remote project path {requested:?}: expected an absolute path or ~"+ ));+ }+ if requested.split('/').any(|component| component == "..") {+ return Err(format!(+ "Unsupported remote project path {requested:?}: `..` is not allowed"+ ));+ }+ RemotePath::from_server_absolute(requested)+}++/// Flatten an error and everything it wraps into one line. libssh and ssh2+/// failures surface through `SftpChannelError` as the near-useless+/// "Library-specific error", with the real reason one or more levels down.+fn error_chain(err: &(dyn std::error::Error + 'static)) -> String {+ let mut parts = vec![err.to_string()];+ let mut source = err.source();+ while let Some(inner) = source {+ parts.push(inner.to_string());+ source = inner.source();+ }+ parts.join(": ")+}++/// The deepest, most specific message in the chain — the part worth putting in+/// front of the user when the full chain is too long for a sidebar.+fn error_summary(err: &(dyn std::error::Error + 'static)) -> String {+ let mut deepest = err.to_string();+ let mut source = err.source();+ while let Some(inner) = source {+ let text = inner.to_string();+ if !text.is_empty() {+ deepest = text;+ }+ source = inner.source();+ }+ deepest+}+fn resolve_requested_root(home: RemotePath, requested: &str) -> Result<RemotePath, String> {if requested == "~" {return Ok(home);@@ -168,12 +222,36 @@ impl RemoteFileBackend for SftpRemoteFileBackend {fn resolve_root(&self, requested: String) -> RemoteFuture<RemotePath> {let sftp = self.sftp.clone();Box::pin(async move {- let home = sftp- .canonicalize(".")- .await- .map_err(|err| format!("Unable to resolve remote home: {err}"))?;- let home = RemotePath::from_server_absolute(home.as_str())?;- resolve_requested_root(home, &requested)+ if !requested_root_needs_home(&requested) {+ // Already absolute (or invalid): no server round-trip needed.+ return remote_root_from_absolute(&requested);+ }++ // SFTP has no concept of `~`; the home directory is whatever the+ // server canonicalizes the session's starting directory to. `.` is+ // the usual spelling, but not every server answers it, so fall back+ // to the empty path before giving up.+ let mut failures = Vec::new();+ for probe in [".", ""] {+ match sftp.canonicalize(probe.to_string()).await {+ Ok(home) => {+ return resolve_requested_root(+ RemotePath::from_server_absolute(home.as_str())?,+ &requested,+ )+ }+ Err(err) => {+ log::warn!(+ "remote files: sftp canonicalize({probe:?}) failed: {}",+ error_chain(&err)+ );+ failures.push(error_summary(&err));+ }+ }+ }+ let detail = failures.last().cloned().unwrap_or_default();+ log::error!("remote files: unable to resolve remote home: {failures:?}");+ Err(format!("Can't read the remote home directory: {detail}"))})}@@ -665,10 +743,15 @@ pub(crate) fn update_remote_connection_idle_timeout(minutes: u32) {pub(crate) fn invalidate_remote_connection_if_dead(key: &str, message: &str) -> bool {let lower = message.to_ascii_lowercase();+ // Matches both the wrapper text (`SftpChannelError`) and the innermost+ // cause, because a concise user-facing message carries only the latter.+ // "closed channel" covers async-channel's own wording on both ends:+ // "sending into a closed channel" and "receiving from an empty and closed+ // channel" — the previous "sending on a closed" never matched either.let dead = lower.contains("session is dead")|| lower.contains("channel is closed")|| lower.contains("channel closed")- || lower.contains("sending on a closed")+ || lower.contains("closed channel")|| lower.contains("no connection has been set up")|| lower.contains("connection, but we lost it")|| lower.contains("failed to send request")@@ -1118,6 +1201,175 @@ mod tests {use super::*;use std::sync::atomic::{AtomicUsize, Ordering};+ /// Records how many times the remote home was asked for, so a test can+ /// prove an absolute root never pays for that round-trip.+ #[derive(Default)]+ struct HomeProbeCounter {+ calls: AtomicUsize,+ home: Option<&'static str>,+ }++ impl HomeProbeCounter {+ /// Mirrors `SftpRemoteFileBackend::resolve_root` without a server: the+ /// closure stands in for `sftp.canonicalize`.+ fn resolve(&self, requested: &str) -> Result<RemotePath, String> {+ if !requested_root_needs_home(requested) {+ return remote_root_from_absolute(requested);+ }+ self.calls.fetch_add(1, Ordering::SeqCst);+ let home = self+ .home+ .ok_or_else(|| "Can't read the remote home directory: denied".to_string())?;+ resolve_requested_root(RemotePath::from_server_absolute(home)?, requested)+ }+ }++ fn with_home() -> HomeProbeCounter {+ HomeProbeCounter {+ calls: AtomicUsize::new(0),+ home: Some("/home/ada"),+ }+ }++ #[test]+ fn absolute_root_never_resolves_the_remote_home() {+ // The bug this pins: `resolve_root` used to canonicalize `.` first, so a+ // project with a fully specified path still broke on any server that+ // could not answer that request.+ let probe = with_home();+ assert_eq!(probe.resolve("/srv/app").unwrap().as_str(), "/srv/app");+ assert_eq!(probe.calls.load(Ordering::SeqCst), 0);++ // Even with no home available at all, an absolute root still works.+ let no_home = HomeProbeCounter::default();+ assert_eq!(no_home.resolve("/srv/app").unwrap().as_str(), "/srv/app");+ assert_eq!(no_home.calls.load(Ordering::SeqCst), 0);+ }++ #[test]+ fn tilde_resolves_to_the_remote_home() {+ let probe = with_home();+ assert_eq!(probe.resolve("~").unwrap().as_str(), "/home/ada");+ assert_eq!(probe.calls.load(Ordering::SeqCst), 1);+ }++ #[test]+ fn tilde_child_joins_beneath_the_home() {+ let probe = with_home();+ assert_eq!(+ probe.resolve("~/code/thinkterm").unwrap().as_str(),+ "/home/ada/code/thinkterm"+ );+ // Redundant separators and `.` segments collapse rather than escaping.+ assert_eq!(+ probe.resolve("~/code//./thinkterm").unwrap().as_str(),+ "/home/ada/code/thinkterm"+ );+ }++ #[test]+ fn traversal_is_rejected_on_both_paths() {+ let probe = with_home();+ // `~/..` goes through join_name, which refuses `..`.+ assert!(probe.resolve("~/../etc").is_err());+ // An absolute root is checked before it can ever reach the server.+ let err = probe.resolve("/srv/../etc").unwrap_err();+ assert!(err.contains(".."), "{err}");+ }++ #[test]+ fn relative_roots_are_rejected_with_a_clear_message() {+ let probe = with_home();+ for bad in ["relative/path", "", "C:/windows"] {+ let err = probe.resolve(bad).unwrap_err();+ assert!(+ err.contains("absolute path or ~"),+ "{bad:?} produced {err:?}"+ );+ }+ // The failure is decided locally; no home lookup was attempted.+ assert_eq!(probe.calls.load(Ordering::SeqCst), 0);+ }++ #[test]+ fn remote_paths_stay_slash_only() {+ // Guards the Windows client: joining must never introduce a `\`, and a+ // backslash is an ordinary character in a POSIX name.+ let root = RemotePath::from_server_absolute("/srv").unwrap();+ let child = root.join_name("a b").unwrap();+ assert_eq!(child.as_str(), "/srv/a b");+ assert_eq!(root.join_name("we\\ird").unwrap().as_str(), "/srv/we\\ird");+ assert!(root.join_name("nested/name").is_err());+ assert!(root.join_name("..").is_err());+ // A trailing slash from the server is normalized away, but root stays "/".+ assert_eq!(+ RemotePath::from_server_absolute("/srv/app/")+ .unwrap()+ .as_str(),+ "/srv/app"+ );+ assert_eq!(RemotePath::from_server_absolute("/").unwrap().as_str(), "/");+ }++ #[test]+ fn a_dead_transport_is_detected_from_the_concise_message_too() {+ // `resolve_root` hands the UI only the innermost cause, so invalidation+ // must recognise the transport failure from that alone — otherwise+ // Retry keeps handing back the same dead cached connection.+ for message in [+ "sending into a closed channel",+ "receiving from an empty and closed channel",+ "Failed to send request: sending into a closed channel",+ "session is dead",+ "Broken pipe",+ ] {+ assert!(+ invalidate_remote_connection_if_dead("unused-key", message),+ "{message:?} should invalidate"+ );+ }+ // A server-side refusal is not a dead connection: keep the session.+ for message in ["Permission denied", "No such file or directory"] {+ assert!(+ !invalidate_remote_connection_if_dead("unused-key", message),+ "{message:?} should not invalidate"+ );+ }+ }++ #[test]+ fn error_chain_keeps_the_specific_cause() {+ // "Library-specific error" alone is what made the UI message useless.+ #[derive(Debug)]+ struct Inner;+ impl std::fmt::Display for Inner {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Permission denied")+ }+ }+ impl std::error::Error for Inner {}++ #[derive(Debug)]+ struct Outer(Inner);+ impl std::fmt::Display for Outer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Library-specific error")+ }+ }+ impl std::error::Error for Outer {+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {+ Some(&self.0)+ }+ }++ let err = Outer(Inner);+ assert_eq!(+ error_chain(&err),+ "Library-specific error: Permission denied"+ );+ assert_eq!(error_summary(&err), "Permission denied");+ }+fn target(source: &str) -> RemoteFilesTarget {RemoteFilesTarget {project_id: "project".to_string(),diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex fcdb3a05..ac9813fd 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -72,6 +72,12 @@ const RIGHT_SIDEBAR_CLOSE_BUTTON_X_ADJUST: usize = 8;const RIGHT_SIDEBAR_CLOSE_BUTTON_Y_ADJUST: usize = 16;const RIGHT_SIDEBAR_MODE_HEIGHT: usize = 72;const RIGHT_SIDEBAR_EMPTY_HEIGHT: usize = 88;+/// Empty-state geometry for the remote Files panel, in design pixels.+const REMOTE_EMPTY_ICON_SIZE: usize = 40;+const REMOTE_EMPTY_ICON_GAP: usize = 18;+const REMOTE_EMPTY_DETAIL_GAP: usize = 6;+const REMOTE_EMPTY_BUTTON_GAP: usize = 22;+const REMOTE_EMPTY_BUTTON_HEIGHT: usize = 44;const SNIPPET_TOOLBAR_HEIGHT: usize = 58;const SNIPPET_SEARCH_HEIGHT: usize = 58;const SNIPPET_CARD_HEIGHT: usize = 116;@@ -8506,7 +8512,6 @@ impl crate::TermWindow {content_top,content_width,content_bottom,- icon_size,);}@@ -8544,75 +8549,65 @@ impl crate::TermWindow {content_top: usize,content_width: usize,content_bottom: usize,- icon_size: usize,) -> anyhow::Result<()> {let phase = self.right_sidebar_remote_files.phase.clone();+ // Which host the panel is talking about; shown under the title so the+ // user knows what they are about to connect to.+ let target_label = self+ .right_sidebar_remote_files+ .target+ .as_ref()+ .map(|target| target.project_name.clone());match phase {- RemoteFilesPhase::Disconnected => {- self.paint_files_message(- layers,- ui_font,- ui_metrics,- chrome,- muted_fg,- content_x,- content_top,- content_width,- content_bottom,- icon_size,- "Connect to browse this remote project",- )?;- self.paint_remote_files_connect_button(- layers,- ui_font,- ui_metrics,- chrome,- foreground,- content_x,- content_top + self.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT + 12),- content_width,- "Connect to Remote Files",- )- }- RemoteFilesPhase::Connecting => self.paint_files_message(+ RemoteFilesPhase::Disconnected => self.paint_remote_files_empty_state(layers,ui_font,ui_metrics,chrome,- muted_fg,content_x,content_top,content_width,content_bottom,- icon_size,- "Connecting to Remote Files...",+ // A neutral state, not a fault: CircleAlert here reads as+ // "something broke" the first time the panel is opened.+ SvgIcon::Server,+ false,+ "Not connected",+ target_label.as_deref(),+ Some(("Connect", true)),+ ),+ RemoteFilesPhase::Connecting => self.paint_remote_files_empty_state(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ content_x,+ content_top,+ content_width,+ content_bottom,+ SvgIcon::LoaderCircle,+ // Spinning also drives the repaint schedule, so the panel keeps+ // animating instead of freezing for the length of the connect.+ true,+ "Connecting…",+ target_label.as_deref(),+ Some(("Connecting…", false)),+ ),+ RemoteFilesPhase::Failed(message) => self.paint_remote_files_empty_state(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ content_x,+ content_top,+ content_width,+ content_bottom,+ SvgIcon::CircleAlert,+ false,+ "Connection failed",+ Some(message.as_str()),+ Some(("Retry", true)),),- RemoteFilesPhase::Failed(message) => {- self.paint_files_message(- layers,- ui_font,- ui_metrics,- chrome,- muted_fg,- content_x,- content_top,- content_width,- content_bottom,- icon_size,- &message,- )?;- self.paint_remote_files_connect_button(- layers,- ui_font,- ui_metrics,- chrome,- foreground,- content_x,- content_top + self.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT + 12),- content_width,- "Retry",- )- }RemoteFilesPhase::Connected => self.paint_remote_files_tree(layers,ui_font,@@ -8628,42 +8623,173 @@ impl crate::TermWindow {}}+ /// Centred icon / title / detail / action block for the remote Files panel+ /// when there is no tree to show.+ ///+ /// Deliberately not `paint_files_message`: that draws a bordered card meant+ /// for transient status ("Indexing files…") pinned to the top of the panel.+ /// Stacking it above a same-coloured button produced two identical-looking+ /// boxes where only the lower one was clickable, and its icon slot squeezed+ /// the text until it ellipsized mid-sentence.#[allow(clippy::too_many_arguments)]+ fn paint_remote_files_empty_state(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ icon: SvgIcon,+ spinning: bool,+ title: &str,+ detail: Option<&str>,+ action: Option<(&str, bool)>,+ ) -> anyhow::Result<()> {+ let line_h = ui_metrics.cell_size.height as usize;+ let icon_size = self.ui_px(REMOTE_EMPTY_ICON_SIZE);+ let mut block_h = icon_size + self.ui_px(REMOTE_EMPTY_ICON_GAP) + line_h;+ if detail.is_some() {+ block_h += self.ui_px(REMOTE_EMPTY_DETAIL_GAP) + line_h;+ }+ if action.is_some() {+ block_h += self.ui_px(REMOTE_EMPTY_BUTTON_GAP) + self.ui_px(REMOTE_EMPTY_BUTTON_HEIGHT);+ }++ // Centre in the panel, but never above the top edge when it is short.+ let available = content_bottom.saturating_sub(content_top);+ let mut y = content_top + available.saturating_sub(block_h) / 2;++ let icon_x = content_x + content_width.saturating_sub(icon_size) / 2;+ if spinning {+ self.paint_spinning_ui_icon(+ layers,+ 1,+ icon,+ icon_x,+ y,+ icon_size,+ chrome.secondary_text,+ )?;+ } else {+ self.paint_sidebar_icon(layers, icon, icon_x, y, icon_size, chrome.secondary_text)?;+ }+ y += icon_size + self.ui_px(REMOTE_EMPTY_ICON_GAP);++ self.paint_remote_files_centered_text(+ layers,+ ui_font,+ ui_metrics,+ title,+ content_x,+ y,+ content_width,+ chrome.text,+ )?;+ y += line_h;++ if let Some(detail) = detail {+ y += self.ui_px(REMOTE_EMPTY_DETAIL_GAP);+ self.paint_remote_files_centered_text(+ layers,+ ui_font,+ ui_metrics,+ detail,+ content_x,+ y,+ content_width,+ chrome.muted_text,+ )?;+ y += line_h;+ }++ if let Some((label, enabled)) = action {+ y += self.ui_px(REMOTE_EMPTY_BUTTON_GAP);+ self.paint_remote_files_connect_button(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ content_x,+ y,+ content_width,+ label,+ enabled,+ )?;+ }+ Ok(())+ }++ /// Horizontally centre a single line, falling back to the full width (and+ /// therefore ellipsizing) only when the text cannot fit.+ #[allow(clippy::too_many_arguments)]+ fn paint_remote_files_centered_text(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ text: &str,+ content_x: usize,+ y: usize,+ content_width: usize,+ color: LinearRgba,+ ) -> anyhow::Result<()> {+ let text_w = self+ .sidebar_text_width(ui_font, text)+ .unwrap_or(content_width as f32)+ .ceil() as usize;+ let width = text_w.min(content_width);+ let x = content_x + content_width.saturating_sub(width) / 2;+ self.paint_sidebar_text(layers, ui_font, ui_metrics, text, x, y, width, color)+ }++ #[allow(clippy::too_many_arguments)]+ /// The single call to action in an otherwise empty panel, so it is styled+ /// as a primary button (accent fill) rather than reusing the neutral+ /// `sidebar_button_bg` that the surrounding message cards use — otherwise+ /// the only clickable thing on screen looks exactly like the text above it.fn paint_remote_files_connect_button(&mut self,layers: &mut TripleLayerQuadAllocator,ui_font: &Rc<LoadedFont>,ui_metrics: RenderMetrics,chrome: UiPalette,- foreground: LinearRgba,x: usize,y: usize,width: usize,label: &str,+ enabled: bool,) -> anyhow::Result<()> {- let height = self.ui_px(44);- let hovered = self.is_pointer_over_ui_rect(x, y, width, height);+ let height = self.ui_px(REMOTE_EMPTY_BUTTON_HEIGHT);+ let hovered = enabled && self.is_pointer_over_ui_rect(x, y, width, height);+ let (fill, text_color) = if !enabled {+ (chrome.sidebar_button_bg, chrome.muted_text)+ } else if hovered {+ (chrome.selected_bg.mul_alpha(0.85), chrome.selected_text)+ } else {+ (chrome.selected_bg, chrome.selected_text)+ };self.fill_rounded_rectangle_with_border(layers,1,euclid::rect(x as f32, y as f32, width as f32, height as f32),- if hovered {- chrome.control_hover_bg- } else {- chrome.sidebar_button_bg- },- chrome.control_border,+ fill,+ if enabled { fill } else { chrome.control_border },self.ui_f32(SIDEBAR_ROW_RADIUS) + 4.0,CAPSULE_BORDER_WIDTH,).context("remote Files connect button")?;- self.ui_items.push(UIItem {- x,- y,- width,- height,- item_type: UIItemType::RightSidebarRemoteFileConnect,- });+ if enabled {+ self.ui_items.push(UIItem {+ x,+ y,+ width,+ height,+ item_type: UIItemType::RightSidebarRemoteFileConnect,+ });+ }let label_width = self.sidebar_text_width(ui_font, label).unwrap_or(width as f32)@@ -8677,7 +8803,7 @@ impl crate::TermWindow {text_x,y + height.saturating_sub(ui_metrics.cell_size.height as usize) / 2,width.saturating_sub(text_x.saturating_sub(x)),- foreground,+ text_color,)}@@ -8706,12 +8832,13 @@ impl crate::TermWindow {.target.as_ref().map(|target| target.project_name.as_str())- .unwrap_or("Remote Files");+ .unwrap_or("Remote Files")+ .to_string();self.paint_sidebar_text(layers,ui_font,ui_metrics,- label,+ &label,content_x,content_top+ self@@ -8735,12 +8862,14 @@ impl crate::TermWindow {let mut tree_top =content_top + self.ui_px(FILE_FILTER_HEIGHT) + self.ui_px(FILE_TREE_TOP_GAP);- if let Some(message) = self.right_sidebar_remote_files.error_message.clone() {+ let error_y = tree_top;+ let error_message = self.right_sidebar_remote_files.error_message.clone();+ if let Some(message) = error_message.as_deref() {self.paint_sidebar_text(layers,ui_font,ui_metrics,- &message,+ message,content_x,tree_top,content_width,@@ -8814,6 +8943,70 @@ impl crate::TermWindow {row_metrics,)?;}+ if max_scroll > 0.0 && scroll > 0.0 {+ // Rows retain their true origin so a partly scrolled first row has+ // the correct visible height and hit target. Mask the portion above+ // the viewport, then restore the fixed header content on top, just+ // like the local file tree does below.+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ content_top,+ content_width,+ tree_top.saturating_sub(content_top),+ )?;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &label,+ content_x,+ content_top+ + self+ .ui_px(FILE_FILTER_HEIGHT)+ .saturating_sub(ui_metrics.cell_size.height as usize)+ / 2,+ label_width,+ foreground,+ )?;+ self.paint_files_preview_header_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ refresh_x,+ refresh_y,+ refresh_size,+ SvgIcon::RotateCcw,+ UIItemType::RightSidebarRemoteFileRefresh,+ )?;+ if let Some(message) = error_message.as_deref() {+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ message,+ content_x,+ error_y,+ content_width,+ muted_fg,+ )?;+ }+ let fade_top = tree_top.saturating_sub(self.ui_px(FILE_TREE_TOP_GAP));+ let fade_height = self+ .ui_px(FILE_TREE_TOP_GAP)+ .saturating_add(self.ui_px(FILE_SCROLL_FADE_HEIGHT))+ .min(viewport_bottom.saturating_sub(fade_top));+ self.paint_right_sidebar_file_top_fade(+ layers,+ chrome,+ content_x,+ fade_top,+ content_width,+ fade_height,+ )?;+ }if footer_height > 0 {self.paint_sidebar_text(layers,