Skip to content

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.

Harden remote files and pane resize synchronization

RoversX0b512bf98390
diff --git a/Cargo.lock b/Cargo.lock
index 6b80aa6e..c3b7262f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7350,6 +7350,7 @@ dependencies = [
"openssl",
"ordered-float 4.6.0",
"parking_lot",
+ "percent-encoding",
"phf",
"phf_codegen 0.10.0",
"portable-pty",
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index 5a5e047f..6cd40970 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -949,7 +949,7 @@ impl Tab {
/// this algorithm biases towards adjusting the left/top nodes
/// first. For large resizes this tends to proportionally adjust
/// the relative sizes of the elements in a split.
- pub fn resize(&self, size: TerminalSize) {
+ pub fn resize(&self, size: TerminalSize) -> bool {
self.inner.lock().resize(size)
}
@@ -1788,10 +1788,10 @@ impl TabInner {
self.size
}
- fn resize(&mut self, size: TerminalSize) {
+ fn resize(&mut self, size: TerminalSize) -> bool {
if size.rows == 0 || size.cols == 0 {
// Ignore "impossible" resize requests
- return;
+ return false;
}
// No-op resizes must not emit TabResized: for mux client tabs the
@@ -1800,7 +1800,7 @@ impl TabInner {
// transient client/server size disagreement into an endless
// resize/resync storm that visibly flickers the window contents.
if size == self.size {
- return;
+ return false;
}
if let Some(zoomed) = &self.zoomed {
@@ -1826,6 +1826,15 @@ impl TabInner {
dpi: dims.dpi,
};
+ // The requested size can be smaller than the split tree's
+ // minimum. In that case it clamps back to the size we already
+ // hold; treat that as the same no-op as an exact request. Without
+ // this second check, a GUI recovery pass can emit TabResized on
+ // every frame even though no geometry can change.
+ if size == self.size {
+ return false;
+ }
+
// Update the split nodes with adjusted sizes
adjust_x_size(
self.pane.as_mut().unwrap(),
@@ -1847,6 +1856,7 @@ impl TabInner {
}
Mux::try_get().map(|mux| mux.notify(MuxNotification::TabResized(self.id)));
+ true
}
fn apply_pane_size(&mut self, pane_size: TerminalSize, cursor: &mut Cursor) {
@@ -3851,6 +3861,37 @@ mod test {
MuxTestGuard
}
+ #[test]
+ fn resize_clamped_to_the_split_minimum_becomes_a_noop() {
+ let _mux = install_mux();
+ let size = test_size();
+ let tab = Tab::new(&size);
+ tab.assign_pane(&FakePane::new(1, size));
+ let split_size = tab
+ .compute_split_size(0, SplitRequest::default())
+ .expect("initial tab can split");
+ tab.split_and_insert(
+ 0,
+ SplitRequest::default(),
+ FakePane::new(2, split_size.second),
+ )
+ .expect("split succeeds");
+
+ let tiny = TerminalSize {
+ rows: 1,
+ cols: 1,
+ pixel_width: 10,
+ pixel_height: 25,
+ dpi: 96,
+ };
+ assert!(tab.inner.lock().resize(tiny));
+ assert!(tab.get_size().cols > tiny.cols);
+ assert!(
+ !tab.inner.lock().resize(tiny),
+ "the same clamped result must not emit another TabResized"
+ );
+ }
+
#[test]
fn pane_stack_add_switch_and_remove() {
let _mux = install_mux();
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index a70b6493..865ffe87 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -32,6 +32,32 @@ use wezterm_term::{
TerminalConfiguration, TerminalSize,
};
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct ResizeDecision {
+ converge_local_surface: bool,
+ send_rpc: bool,
+}
+
+fn render_dimensions_match_size(dimensions: RenderableDimensions, size: TerminalSize) -> bool {
+ dimensions.cols == size.cols
+ && dimensions.viewport_rows == size.rows
+ && dimensions.pixel_width == size.pixel_width
+ && dimensions.pixel_height == size.pixel_height
+ && dimensions.dpi == size.dpi
+}
+
+fn decide_resize(
+ last_requested: Option<TerminalSize>,
+ dimensions: RenderableDimensions,
+ target: TerminalSize,
+) -> ResizeDecision {
+ let converge_local_surface = !render_dimensions_match_size(dimensions, target);
+ ResizeDecision {
+ converge_local_surface,
+ send_rpc: last_requested != Some(target) && converge_local_surface,
+ }
+}
+
pub struct ClientPane {
client: Arc<ClientInner>,
local_pane_id: PaneId,
@@ -450,40 +476,41 @@ impl Pane for ClientPane {
}
fn resize(&self, size: TerminalSize) -> anyhow::Result<()> {
- {
+ let (decision, prior_requested, advertised) = {
// Dedupe against the last size WE requested, not against the
// server-advertised dimensions: mid-split (or any server-side
// relayout) the advertised dims legitimately disagree with the
// GUI's still-stale layout for a moment, and re-asserting the
// stale size would revert the server's pane resize and bake a
// corrupt geometry into its split tree via
- // rebuild_splits_sizes_from_contained_panes. Only a real local
- // layout change may produce a new request.
+ // rebuild_splits_sizes_from_contained_panes.
let mut requested = self.requested_size.lock();
- if *requested == Some(size) {
- return Ok(());
- }
+ let prior_requested = *requested;
+ let render = self.renderable.lock();
+ let mut inner = render.inner.borrow_mut();
+ let advertised = inner.dimensions;
+ let decision = decide_resize(prior_requested, advertised, size);
requested.replace(size);
- }
- let render = self.renderable.lock();
- let mut inner = render.inner.borrow_mut();
-
- let cols = size.cols as usize;
- let rows = size.rows as usize;
- if inner.dimensions.cols != cols
- || inner.dimensions.viewport_rows != rows
- || inner.dimensions.pixel_width != size.pixel_width
- || inner.dimensions.pixel_height != size.pixel_height
- {
- inner.dimensions.cols = cols;
- inner.dimensions.viewport_rows = rows;
- inner.dimensions.pixel_width = size.pixel_width;
- inner.dimensions.pixel_height = size.pixel_height;
+ if decision.converge_local_surface {
+ inner.apply_local_resize(size);
+ }
+ if decision.send_rpc {
+ inner.update_last_send();
+ }
+ (decision, prior_requested, advertised)
+ };
- // Invalidate any cached rows on a resize
- inner.make_all_stale();
+ log::trace!(
+ "pane {} resize {:?}: requested={:?} advertised={:?} target={:?}",
+ self.local_pane_id,
+ decision,
+ prior_requested,
+ advertised,
+ size
+ );
+ if decision.send_rpc {
let client = Arc::clone(&self.client);
let remote_pane_id = self.remote_pane_id;
let remote_tab_id = self.remote_tab_id();
@@ -498,7 +525,6 @@ impl Pane for ClientPane {
.await
})
.detach();
- inner.update_last_send();
}
Ok(())
}
@@ -757,3 +783,83 @@ impl std::io::Write for PaneWriter {
Ok(())
}
}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ fn size(cols: usize, rows: usize, dpi: u32) -> TerminalSize {
+ TerminalSize {
+ rows,
+ cols,
+ pixel_width: cols * 10,
+ pixel_height: rows * 20,
+ dpi,
+ }
+ }
+
+ fn dimensions(size: TerminalSize) -> RenderableDimensions {
+ RenderableDimensions {
+ cols: size.cols,
+ viewport_rows: size.rows,
+ scrollback_rows: size.rows,
+ dpi: size.dpi,
+ pixel_width: size.pixel_width,
+ pixel_height: size.pixel_height,
+ ..RenderableDimensions::default()
+ }
+ }
+
+ #[test]
+ fn resize_decision_separates_local_convergence_from_rpc() {
+ let target = size(120, 40, 96);
+ let old = size(100, 30, 96);
+
+ assert_eq!(
+ decide_resize(Some(target), dimensions(target), target),
+ ResizeDecision {
+ converge_local_surface: false,
+ send_rpc: false,
+ }
+ );
+ assert_eq!(
+ decide_resize(Some(target), dimensions(old), target),
+ ResizeDecision {
+ converge_local_surface: true,
+ send_rpc: false,
+ },
+ "a delayed server surface must be repaired locally without repeating the RPC"
+ );
+ assert_eq!(
+ decide_resize(Some(old), dimensions(target), target),
+ ResizeDecision {
+ converge_local_surface: false,
+ send_rpc: false,
+ },
+ "a server that already reached the target needs no RPC"
+ );
+ assert_eq!(
+ decide_resize(Some(old), dimensions(old), target),
+ ResizeDecision {
+ converge_local_surface: true,
+ send_rpc: true,
+ },
+ "a genuine target change sends exactly one RPC"
+ );
+ }
+
+ #[test]
+ fn resize_decision_includes_dpi() {
+ let target = size(120, 40, 144);
+ let mut advertised = dimensions(target);
+ advertised.dpi = 96;
+
+ assert_eq!(
+ decide_resize(Some(target), advertised, target),
+ ResizeDecision {
+ converge_local_surface: true,
+ send_rpc: false,
+ }
+ );
+ }
+}
diff --git a/wezterm-client/src/pane/renderable.rs b/wezterm-client/src/pane/renderable.rs
index 6767552e..91a4744e 100644
--- a/wezterm-client/src/pane/renderable.rs
+++ b/wezterm-client/src/pane/renderable.rs
@@ -27,32 +27,70 @@ use wezterm_term::{KeyCode, KeyModifiers, Line, StableRowIndex};
const MAX_POLL_INTERVAL: Duration = Duration::from_secs(30);
const BASE_POLL_INTERVAL: Duration = Duration::from_millis(20);
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct FetchToken {
+ epoch: u64,
+ started_at: Instant,
+}
+
#[derive(Debug)]
enum LineEntry {
// Up to date wrt. server and has been rendered at least once
Line(Line),
// Currently being downloaded from the server
- Fetching(Instant),
+ Fetching(FetchToken),
// We have a version of the line locally and are treating it
// as needing rendering because we are also in the process of
// downloading a newer version from the server
- LineAndFetching(Line, Instant),
+ LineAndFetching(Line, FetchToken),
// We have a local copy but it is stale and will need to be
// fetched again
Stale(Line),
}
impl LineEntry {
- fn kind(&self) -> (&'static str, Option<Instant>) {
+ fn kind(&self) -> (&'static str, Option<FetchToken>) {
match self {
Self::Line(_) => ("Line", None),
- Self::Fetching(since) => ("Fetching", Some(*since)),
- Self::LineAndFetching(_, since) => ("LineAndFetching", Some(*since)),
+ Self::Fetching(token) => ("Fetching", Some(*token)),
+ Self::LineAndFetching(_, token) => ("LineAndFetching", Some(*token)),
Self::Stale(_) => ("Stale", None),
}
}
}
+fn invalidate_line_entries(lines: &mut LruCache<StableRowIndex, LineEntry>, preserve_lines: bool) {
+ if !preserve_lines {
+ lines.clear();
+ return;
+ }
+
+ let mut stale = LruCache::unbounded();
+ while let Some((stable_row, entry)) = lines.pop_lru() {
+ match entry {
+ LineEntry::Stale(line)
+ | LineEntry::Line(line)
+ | LineEntry::LineAndFetching(line, _) => {
+ stale.put(stable_row, LineEntry::Stale(line));
+ }
+ LineEntry::Fetching(_) => {}
+ }
+ }
+ *lines = stale;
+}
+
+fn render_geometry_changed(current: RenderableDimensions, next: RenderableDimensions) -> bool {
+ current.cols != next.cols
+ || current.viewport_rows != next.viewport_rows
+ || current.pixel_width != next.pixel_width
+ || current.pixel_height != next.pixel_height
+ || current.dpi != next.dpi
+}
+
+fn fetch_token_is_current(token: FetchToken, epoch: u64) -> bool {
+ token.epoch == epoch
+}
+
pub struct RenderableInner {
pub client: Arc<ClientInner>,
remote_pane_id: PaneId,
@@ -66,6 +104,7 @@ pub struct RenderableInner {
pub dimensions: RenderableDimensions,
lines: LruCache<StableRowIndex, LineEntry>,
+ line_cache_epoch: u64,
pub title: String,
pub working_dir: Option<Url>,
pub seqno: SequenceNo,
@@ -108,6 +147,7 @@ impl RenderableInner {
lines: LruCache::new(
NonZeroUsize::new(configuration().scrollback_lines.max(128)).unwrap(),
),
+ line_cache_epoch: 0,
title: title.to_string(),
working_dir: None,
fetch_limiter,
@@ -349,7 +389,13 @@ impl RenderableInner {
{
self.cursor_position = delta.cursor_position;
}
- self.dimensions = delta.dimensions;
+ if render_geometry_changed(self.dimensions, delta.dimensions) {
+ let preserve_lines = self.dimensions.cols == delta.dimensions.cols;
+ self.dimensions = delta.dimensions;
+ self.invalidate_line_cache(preserve_lines);
+ } else {
+ self.dimensions = delta.dimensions;
+ }
self.title = delta.title;
self.working_dir = delta.working_dir.map(Into::into);
log::trace!(
@@ -390,11 +436,12 @@ impl RenderableInner {
continue;
}
to_fetch.add(stable_row);
+ let token = self.fetch_token(now);
let entry = match prior {
- Some(LineEntry::Fetching(_)) | None => LineEntry::Fetching(now),
+ Some(LineEntry::Fetching(_)) | None => LineEntry::Fetching(token),
Some(LineEntry::LineAndFetching(old, ..))
| Some(LineEntry::Stale(old))
- | Some(LineEntry::Line(old)) => LineEntry::LineAndFetching(old, now),
+ | Some(LineEntry::Line(old)) => LineEntry::LineAndFetching(old, token),
};
log::trace!(
"row {} {:?} -> {:?} due to dirty and IN viewport",
@@ -407,7 +454,7 @@ impl RenderableInner {
}
if !to_fetch.is_empty() {
if self.fetch_limiter.non_blocking_admittance_check(1) {
- self.schedule_fetch_lines(to_fetch, now);
+ self.schedule_fetch_lines(to_fetch, self.fetch_token(now));
} else {
log::warn!(
"exceeded fetch throttle, drop {:?} and mark stale",
@@ -423,15 +470,43 @@ impl RenderableInner {
}
pub fn make_all_stale(&mut self) {
- let mut lines = LruCache::unbounded();
- while let Some((stable_row, entry)) = self.lines.pop_lru() {
- let entry = match entry {
- LineEntry::Stale(old) | LineEntry::Line(old) => LineEntry::Stale(old),
- entry => entry,
- };
- lines.put(stable_row, entry);
+ self.invalidate_line_cache(true);
+ }
+
+ fn fetch_token(&self, started_at: Instant) -> FetchToken {
+ FetchToken {
+ epoch: self.line_cache_epoch,
+ started_at,
}
- self.lines = lines;
+ }
+
+ fn invalidate_line_cache(&mut self, preserve_lines: bool) {
+ self.line_cache_epoch = self.line_cache_epoch.wrapping_add(1);
+ invalidate_line_entries(&mut self.lines, preserve_lines);
+ }
+
+ /// Converge the locally rendered surface to the geometry requested by the
+ /// GUI. This is deliberately separate from deciding whether a Resize RPC
+ /// is needed: a delayed server update can temporarily restore old
+ /// dimensions after the desired size was already requested.
+ pub(crate) fn apply_local_resize(&mut self, size: wezterm_term::TerminalSize) -> bool {
+ if self.dimensions.cols == size.cols
+ && self.dimensions.viewport_rows == size.rows
+ && self.dimensions.pixel_width == size.pixel_width
+ && self.dimensions.pixel_height == size.pixel_height
+ && self.dimensions.dpi == size.dpi
+ {
+ return false;
+ }
+
+ let preserve_lines = self.dimensions.cols == size.cols;
+ self.dimensions.cols = size.cols;
+ self.dimensions.viewport_rows = size.rows;
+ self.dimensions.pixel_width = size.pixel_width;
+ self.dimensions.pixel_height = size.pixel_height;
+ self.dimensions.dpi = size.dpi;
+ self.invalidate_line_cache(preserve_lines);
+ true
}
fn make_stale(&mut self, stable_row: StableRowIndex) {
@@ -450,11 +525,11 @@ impl RenderableInner {
stable_row: StableRowIndex,
mut line: Line,
config: &ConfigHandle,
- fetch_start: Option<Instant>,
+ fetch_token: Option<FetchToken>,
) {
line.scan_and_create_hyperlinks(&config.hyperlink_rules);
- let entry = if let Some(fetch_start) = fetch_start {
+ let entry = if let Some(fetch_token) = fetch_token {
// If we're completing a fetch, only replace entries that were
// set to fetching as part of our fetch. If they are now longer
// tagged that way, then someone came along after us and changed
@@ -462,7 +537,7 @@ impl RenderableInner {
match self.lines.pop(&stable_row) {
Some(LineEntry::LineAndFetching(_, then)) | Some(LineEntry::Fetching(then))
- if fetch_start == then =>
+ if fetch_token == then =>
{
log::trace!(
"row {} fetch done -> Line seq={} vs self.seq={}",
@@ -479,7 +554,7 @@ impl RenderableInner {
"row {} {:?} changed since fetch started at {:?}, so leave it be",
stable_row,
e.kind(),
- fetch_start
+ fetch_token
);
self.lines.put(stable_row, e);
return;
@@ -492,7 +567,11 @@ impl RenderableInner {
self.lines.put(stable_row, entry);
}
- fn schedule_fetch_lines(&mut self, to_fetch: RangeSet<StableRowIndex>, now: Instant) {
+ fn schedule_fetch_lines(
+ &mut self,
+ to_fetch: RangeSet<StableRowIndex>,
+ fetch_token: FetchToken,
+ ) {
if to_fetch.is_empty() || self.dead {
return;
}
@@ -502,7 +581,7 @@ impl RenderableInner {
"will fetch lines {:?} for remote tab id {} at {:?}",
to_fetch,
self.remote_pane_id,
- now,
+ fetch_token,
);
let client = Arc::clone(&self.client);
@@ -525,7 +604,7 @@ impl RenderableInner {
}
Err(err) => Err(err),
};
- Self::apply_lines(local_pane_id, result, to_fetch, now)
+ Self::apply_lines(local_pane_id, result, to_fetch, fetch_token)
})
.detach();
}
@@ -534,7 +613,7 @@ impl RenderableInner {
local_pane_id: PaneId,
result: anyhow::Result<Vec<(StableRowIndex, Line)>>,
to_fetch: RangeSet<StableRowIndex>,
- now: Instant,
+ fetch_token: FetchToken,
) -> anyhow::Result<()> {
let mux = Mux::get();
let pane = mux
@@ -544,13 +623,23 @@ impl RenderableInner {
let renderable = client_tab.renderable.lock();
let mut inner = renderable.inner.borrow_mut();
+ if !fetch_token_is_current(fetch_token, inner.line_cache_epoch) {
+ log::trace!(
+ "discarding line fetch for pane {} from epoch {} because current epoch is {}",
+ local_pane_id,
+ fetch_token.epoch,
+ inner.line_cache_epoch
+ );
+ return Ok(());
+ }
+
match result {
Ok(lines) => {
let config = configuration();
- log::trace!("fetch complete for {:?} at {:?}", to_fetch, now);
+ log::trace!("fetch complete for {:?} with {:?}", to_fetch, fetch_token);
for (stable_row, line) in lines.into_iter() {
- inner.put_line(stable_row, line, &config, Some(now));
+ inner.put_line(stable_row, line, &config, Some(fetch_token));
}
}
Err(err) => {
@@ -558,11 +647,13 @@ impl RenderableInner {
for r in to_fetch.iter() {
for stable_row in r.clone() {
let entry = match inner.lines.pop(&stable_row) {
- Some(LineEntry::Fetching(then)) if then == now => {
+ Some(LineEntry::Fetching(then)) if then == fetch_token => {
// leave it popped
continue;
}
- Some(LineEntry::LineAndFetching(line, then)) if then == now => {
+ Some(LineEntry::LineAndFetching(line, then))
+ if then == fetch_token =>
+ {
// revert to just a line
LineEntry::Line(line)
}
@@ -729,6 +820,7 @@ impl RenderableState {
let mut result = vec![];
let mut to_fetch = RangeSet::new();
let now = Instant::now();
+ let fetch_token = inner.fetch_token(now);
for idx in lines.clone() {
let entry = match inner.lines.pop(&idx) {
@@ -752,12 +844,12 @@ impl RenderableState {
Some(LineEntry::Stale(line)) => {
result.push(line.clone());
to_fetch.add(idx);
- LineEntry::LineAndFetching(line, now)
+ LineEntry::LineAndFetching(line, fetch_token)
}
None => {
result.push(Line::with_width(inner.dimensions.cols, SEQ_ZERO));
to_fetch.add(idx);
- LineEntry::Fetching(now)
+ LineEntry::Fetching(fetch_token)
}
};
@@ -794,7 +886,7 @@ impl RenderableState {
to_fetch
);
- inner.schedule_fetch_lines(to_fetch, now);
+ inner.schedule_fetch_lines(to_fetch, fetch_token);
(lines.start, result)
}
@@ -858,3 +950,83 @@ impl RenderableState {
self.inner.borrow().dimensions
}
}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ fn line(width: usize) -> Line {
+ Line::with_width(width, SEQ_ZERO)
+ }
+
+ fn dimensions(cols: usize, rows: usize, dpi: u32) -> RenderableDimensions {
+ RenderableDimensions {
+ cols,
+ viewport_rows: rows,
+ scrollback_rows: rows,
+ dpi,
+ pixel_width: cols * 10,
+ pixel_height: rows * 20,
+ ..RenderableDimensions::default()
+ }
+ }
+
+ #[test]
+ fn preserving_invalidation_cancels_fetches_and_keeps_stale_lines() {
+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());
+ let token = FetchToken {
+ epoch: 7,
+ started_at: Instant::now(),
+ };
+ lines.put(1, LineEntry::Line(line(80)));
+ lines.put(2, LineEntry::LineAndFetching(line(80), token));
+ lines.put(3, LineEntry::Fetching(token));
+
+ invalidate_line_entries(&mut lines, true);
+
+ assert!(matches!(lines.get(&1), Some(LineEntry::Stale(_))));
+ assert!(matches!(lines.get(&2), Some(LineEntry::Stale(_))));
+ assert!(
+ lines.get(&3).is_none(),
+ "an in-flight fetch without a line must be canceled"
+ );
+ }
+
+ #[test]
+ fn width_changing_invalidation_clears_every_cached_line() {
+ let mut lines = LruCache::new(NonZeroUsize::new(8).unwrap());
+ lines.put(1, LineEntry::Line(line(80)));
+ lines.put(2, LineEntry::Stale(line(80)));
+
+ invalidate_line_entries(&mut lines, false);
+
+ assert!(lines.is_empty());
+ }
+
+ #[test]
+ fn geometry_epoch_ignores_scrollback_motion_but_detects_render_size() {
+ let current = dimensions(80, 24, 96);
+ let mut scrollback_only = current;
+ scrollback_only.scrollback_rows += 1;
+ scrollback_only.physical_top += 1;
+ assert!(!render_geometry_changed(current, scrollback_only));
+
+ let mut new_width = current;
+ new_width.cols += 1;
+ assert!(render_geometry_changed(current, new_width));
+
+ let mut new_dpi = current;
+ new_dpi.dpi += 1;
+ assert!(render_geometry_changed(current, new_dpi));
+ }
+
+ #[test]
+ fn fetch_token_from_prior_epoch_is_not_current() {
+ let token = FetchToken {
+ epoch: 4,
+ started_at: Instant::now(),
+ };
+ assert!(fetch_token_is_current(token, 4));
+ assert!(!fetch_token_is_current(token, 5));
+ }
+}
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index 05cdfb98..ae696c21 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -103,6 +103,7 @@ unicode-linebreak = "0.1"
unicode-segmentation.workspace = true
unicode-width.workspace = true
uuid = { workspace = true, features = ["v4"] }
+percent-encoding.workspace = true
url-funcs.workspace = true
url.workspace = true
walkdir.workspace = true
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index e8e94ea5..3fdf35a1 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -295,6 +295,10 @@ pub(crate) struct NativeWorkspaceSettings {
/// puts downloads", which is what most people want and what keeps the
/// setting meaningful after moving between machines.
pub(crate) remote_download_directory: String,
+ /// Where files dropped onto a REMOTE terminal are uploaded, as a remote
+ /// path. Empty means [`DEFAULT_REMOTE_DROP_DESTINATION`]; the literal
+ /// `cwd` means the shell's current directory at drop time.
+ pub(crate) remote_drop_destination: String,
}
impl Default for NativeWorkspaceSettings {
@@ -302,6 +306,7 @@ impl Default for NativeWorkspaceSettings {
Self {
remote_sftp_idle_minutes: DEFAULT_REMOTE_SFTP_IDLE_MINUTES,
remote_download_directory: String::new(),
+ remote_drop_destination: String::new(),
}
}
}
@@ -372,6 +377,41 @@ pub(crate) fn set_remote_download_directory(path: Option<PathBuf>) -> anyhow::Re
save(&settings)
}
+/// Default landing folder for files dropped onto a remote terminal. Visible
+/// on purpose: an upload the user cannot `ls` into might as well not exist,
+/// and the branded name says where it came from.
+pub(crate) const DEFAULT_REMOTE_DROP_DESTINATION: &str = "~/ThinkTerm_Uploads";
+
+/// The literal setting value that means "the shell's current directory".
+pub(crate) const REMOTE_DROP_DESTINATION_CWD: &str = "cwd";
+
+/// The configured remote-drop destination, never empty. Not validated here:
+/// only the remote side can judge a remote path, and its refusal surfaces on
+/// the transfer row where the drop's outcome already lives.
+pub(crate) fn remote_drop_destination() -> String {
+ let configured = load().workspaces.remote_drop_destination;
+ let trimmed = configured.trim();
+ if trimmed.is_empty() {
+ DEFAULT_REMOTE_DROP_DESTINATION.to_string()
+ } else {
+ trimmed.to_string()
+ }
+}
+
+pub(crate) fn set_remote_drop_destination(value: &str) -> anyhow::Result<()> {
+ let mut settings = load();
+ let trimmed = value.trim();
+ // Storing the default as emptiness keeps the file clean and lets a future
+ // default change reach everyone who never made a choice.
+ settings.workspaces.remote_drop_destination =
+ if trimmed.is_empty() || trimmed == DEFAULT_REMOTE_DROP_DESTINATION {
+ String::new()
+ } else {
+ trimmed.to_string()
+ };
+ save(&settings)
+}
+
pub(crate) fn settings_path() -> PathBuf {
config::HOME_DIR
.join(".config")
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index d9cca345..6e8389ce 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -349,6 +349,7 @@ enum SettingsAction {
IncreaseRemoteSftpIdle,
ResetRemoteSftpIdle,
ChooseRemoteDownloadDirectory,
+ RemoteDropDestinationInput,
ResetRemoteDownloadDirectory,
OpenBottomQuotesJson,
ResetBottomQuotesJson,
@@ -768,6 +769,8 @@ struct SettingsUiState {
font_size_input: TextInputState,
font_family_input: TextInputState,
font_family_input_dirty: bool,
+ remote_drop_input: TextInputState,
+ remote_drop_input_dirty: bool,
interaction: InteractionState<SettingsAction>,
drag: Option<SettingsDrag>,
open_dropdown: Option<SettingsDropdown>,
@@ -797,6 +800,8 @@ impl SettingsUiState {
font_size_input: TextInputState::new(),
font_family_input: TextInputState::new(),
font_family_input_dirty: false,
+ remote_drop_input: TextInputState::new(),
+ remote_drop_input_dirty: false,
interaction: InteractionState::default(),
drag: None,
open_dropdown: None,
@@ -1350,6 +1355,8 @@ impl SettingsWindow {
.clone()
.unwrap_or_else(|| Self::effective_font_family(&config)),
);
+ ui.remote_drop_input
+ .set_text_end(crate::native_settings::remote_drop_destination());
let settings = Rc::new(RefCell::new(Self {
instance_id,
@@ -1610,7 +1617,11 @@ impl SettingsWindow {
self.ui.interaction.hovered = action;
self.ui.interaction.pressed = action;
match action {
- Some(SettingsAction::SearchInput | SettingsAction::FontFamilyInput) => {
+ Some(
+ SettingsAction::SearchInput
+ | SettingsAction::FontFamilyInput
+ | SettingsAction::RemoteDropDestinationInput,
+ ) => {
self.set_focused_input(action);
self.ui.open_dropdown = None;
}
@@ -1983,6 +1994,7 @@ impl SettingsWindow {
match action {
SettingsAction::SearchInput => Some(&self.ui.search),
SettingsAction::FontFamilyInput => Some(&self.ui.font_family_input),
+ SettingsAction::RemoteDropDestinationInput => Some(&self.ui.remote_drop_input),
_ => None,
}
}
@@ -2024,6 +2036,11 @@ impl SettingsWindow {
self.ui.font_family_input_dirty = true;
true
}
+ SettingsAction::RemoteDropDestinationInput => {
+ f(&mut self.ui.remote_drop_input);
+ self.ui.remote_drop_input_dirty = true;
+ true
+ }
_ => false,
}
}
@@ -2125,6 +2142,25 @@ impl SettingsWindow {
{
self.save_and_apply_native_terminal_settings();
}
+ if self.ui.interaction.focused == Some(SettingsAction::RemoteDropDestinationInput) {
+ self.commit_remote_drop_destination_from_ui();
+ }
+ }
+
+ fn commit_remote_drop_destination_from_ui(&mut self) {
+ if !self.ui.remote_drop_input_dirty {
+ return;
+ }
+ self.ui.remote_drop_input_dirty = false;
+ let value = self.ui.remote_drop_input.text().to_string();
+ if let Err(err) = crate::native_settings::set_remote_drop_destination(&value) {
+ log::error!("failed to save the remote drop destination: {err:#}");
+ }
+ // Re-read so the field shows what will actually happen — an emptied
+ // field snaps back to the default it now means.
+ self.ui
+ .remote_drop_input
+ .set_text_end(crate::native_settings::remote_drop_destination());
}
fn commit_native_terminal_inputs_from_ui(&mut self) -> bool {
@@ -3089,6 +3125,9 @@ impl SettingsWindow {
SettingsAction::FontFamilyInput => {
self.set_focused_input(Some(SettingsAction::FontFamilyInput));
}
+ SettingsAction::RemoteDropDestinationInput => {
+ self.set_focused_input(Some(SettingsAction::RemoteDropDestinationInput));
+ }
SettingsAction::ClearSearch => {
self.ui.search.clear();
self.ui.sidebar_scroll.reset();
@@ -3998,8 +4037,8 @@ impl SettingsWindow {
let ui_font = Rc::clone(&self.ui_font);
let scroll = self.ui.content_scroll.offset;
let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
- // Idle timeout, download folder, and the reset beside it.
- let row_count = 3;
+ // Idle timeout, download folder, its reset, and the drop destination.
+ let row_count = 4;
let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
let card_height = self.settings_card_height(row_count);
self.ui.content_scroll.set_extents(
@@ -4060,6 +4099,19 @@ impl SettingsWindow {
"Reset",
SettingsAction::ResetRemoteDownloadDirectory,
true,
+ )?;
+ let remote_drop_value = self.ui.remote_drop_input.text().to_string();
+ self.paint_text_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step * 3.0,
+ row_width,
+ "Remote Drop Destination",
+ "Where files dropped onto a remote terminal are uploaded. Use cwd for the shell's current directory.",
+ &remote_drop_value,
+ crate::native_settings::DEFAULT_REMOTE_DROP_DESTINATION,
+ SettingsAction::RemoteDropDestinationInput,
+ true,
)
}
diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs
index 301ae559..9b822e4e 100644
--- a/wezterm-gui/src/termwindow/keyevent.rs
+++ b/wezterm-gui/src/termwindow/keyevent.rs
@@ -191,7 +191,7 @@ enum OnlyKeyBindings {
impl super::TermWindow {
fn paste_text_into_inline_tab_rename(&mut self, text: &str) {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.insert(text);
+ rename.input.caret_insert(text, false);
self.update_title_impl();
if let Some(window) = self.window.as_ref() {
window.invalidate();
@@ -212,14 +212,13 @@ impl super::TermWindow {
return true;
}
- let mut shortcut_mods = window_key.modifiers;
- shortcut_mods.remove(Modifiers::SHIFT | Modifiers::LEFT_SHIFT | Modifiers::RIGHT_SHIFT);
- let super_only = shortcut_mods == Modifiers::SUPER;
- if super_only {
+ let edit = crate::ui::EditModifiers::from(window_key.modifiers);
+ let shift = edit.shift;
+ if edit.command {
match &window_key.key {
KeyCode::Char('a') | KeyCode::Char('A') => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.select_all();
+ rename.input.caret_select_all();
self.update_title_impl();
context.invalidate();
}
@@ -228,8 +227,9 @@ impl super::TermWindow {
KeyCode::Char('c') | KeyCode::Char('C') => {
if let Some(rename) = self.inline_tab_rename.as_ref() {
let text = rename
- .selected_text()
- .unwrap_or_else(|| rename.text.clone());
+ .input
+ .caret_selected_text()
+ .unwrap_or_else(|| rename.input.text().to_string());
context.set_clipboard(Clipboard::Clipboard, text);
}
return true;
@@ -237,14 +237,14 @@ impl super::TermWindow {
KeyCode::Char('x') | KeyCode::Char('X') => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
let text = rename
- .selected_text()
- .unwrap_or_else(|| rename.text.clone());
+ .input
+ .caret_selected_text()
+ .unwrap_or_else(|| rename.input.text().to_string());
context.set_clipboard(Clipboard::Clipboard, text);
- if rename.has_selection() {
- rename.delete_selection();
+ if rename.input.caret_selection_range().is_some() {
+ rename.input.caret_delete_selection();
} else {
- rename.text.clear();
- rename.cursor = 0;
+ rename.input.clear();
}
self.update_title_impl();
context.invalidate();
@@ -267,18 +267,63 @@ impl super::TermWindow {
}
return true;
}
+ KeyCode::LeftArrow if cfg!(target_os = "macos") => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.input.caret_move_home(shift);
+ }
+ self.update_title_impl();
+ context.invalidate();
+ return true;
+ }
+ KeyCode::RightArrow if cfg!(target_os = "macos") => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.input.caret_move_end(shift);
+ }
+ self.update_title_impl();
+ context.invalidate();
+ return true;
+ }
+ KeyCode::Char('\u{8}') if cfg!(target_os = "macos") => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.input.caret_delete_to_start();
+ }
+ self.update_title_impl();
+ context.invalidate();
+ return true;
+ }
_ => {}
}
}
- let text_mod_blockers = Modifiers::ALT
- | Modifiers::CTRL
- | Modifiers::SUPER
- | Modifiers::LEADER
- | Modifiers::LEFT_ALT
- | Modifiers::RIGHT_ALT
- | Modifiers::LEFT_CTRL
- | Modifiers::RIGHT_CTRL;
+ if edit.word {
+ match &window_key.key {
+ KeyCode::LeftArrow => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.input.caret_word_left(shift);
+ }
+ self.update_title_impl();
+ context.invalidate();
+ return true;
+ }
+ KeyCode::RightArrow => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.input.caret_word_right(shift);
+ }
+ self.update_title_impl();
+ context.invalidate();
+ return true;
+ }
+ KeyCode::Char('\u{8}') => {
+ if let Some(rename) = self.inline_tab_rename.as_mut() {
+ rename.input.caret_delete_word_back();
+ }
+ self.update_title_impl();
+ context.invalidate();
+ return true;
+ }
+ _ => {}
+ }
+ }
let mut dirty = false;
match &window_key.key {
@@ -294,51 +339,49 @@ impl super::TermWindow {
}
KeyCode::Char('\u{8}') => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.backspace();
+ rename.input.caret_backspace();
dirty = true;
}
}
KeyCode::Char('\u{7f}') => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.delete();
+ rename.input.caret_delete_forward();
dirty = true;
}
}
KeyCode::LeftArrow => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.move_left();
+ rename.input.caret_move_left(shift);
dirty = true;
}
}
KeyCode::RightArrow => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.move_right();
+ rename.input.caret_move_right(shift);
dirty = true;
}
}
KeyCode::Home => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.cursor = 0;
+ rename.input.caret_move_home(shift);
dirty = true;
}
}
KeyCode::End => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.cursor = rename.text.chars().count();
+ rename.input.caret_move_end(shift);
dirty = true;
}
}
- KeyCode::Char(c)
- if !window_key.modifiers.intersects(text_mod_blockers) && !c.is_control() =>
- {
+ KeyCode::Char(c) if edit.plain() && !c.is_control() => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.insert(&c.to_string());
+ rename.input.caret_insert(&c.to_string(), false);
dirty = true;
}
}
- KeyCode::Composed(text) if !window_key.modifiers.intersects(text_mod_blockers) => {
+ KeyCode::Composed(text) if edit.plain() => {
if let Some(rename) = self.inline_tab_rename.as_mut() {
- rename.insert(text);
+ rename.input.caret_insert(text, false);
dirty = true;
}
}
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 63b8f53c..20a4534b 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -98,6 +98,7 @@ pub mod paneselect;
mod prevcursor;
pub(crate) mod remote_files;
pub mod remote_thread_view;
+pub(crate) mod remote_walk;
pub mod render;
pub mod resize;
mod selection;
@@ -298,7 +299,45 @@ pub(crate) enum ContextMenuApplicationAction {
/// Sidebar view-options: show/hide threads with this work status.
ToggleWorkspaceStatusFilter(crate::workspace_threads::WorkspaceThreadWorkStatus),
/// Fetch a file from the remote Files panel into the Downloads folder.
- DownloadRemoteFile(remote_files::RemotePath),
+ DownloadRemoteFile {
+ path: remote_files::RemotePath,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// Fetch a whole remote directory. Carries the click position so a
+ /// "really download N items?" prompt can appear where the user is looking
+ /// — the walk is asynchronous, so the pointer has moved on by then.
+ DownloadRemoteFolder {
+ path: remote_files::RemotePath,
+ anchor: ::window::Point,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// Delete a remote file or folder, after a confirmation anchored likewise.
+ DeleteRemoteEntry {
+ path: remote_files::RemotePath,
+ anchor: ::window::Point,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// Begin an inline rename of a remote row.
+ RenameRemoteEntry {
+ path: remote_files::RemotePath,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// Create a fresh `untitled folder` under this remote directory.
+ NewRemoteFolder {
+ parent: remote_files::RemotePath,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// Run a finished transfer again from its recorded source. Carries the
+ /// menu's position so a retried folder download can re-raise its size
+ /// confirmation in place.
+ RetryRemoteTransfer {
+ id: u64,
+ anchor: ::window::Point,
+ },
+ /// Clear a finished transfer row away.
+ DismissRemoteTransfer(u64),
+ /// The user's answer to whatever [`PendingRemoteConfirm`] is waiting.
+ ResolveRemoteConfirm(bool),
/// Copy the remote preview's selected text, or the whole buffer.
CopyRemotePreviewSelection,
CopyRemotePreviewAll,
@@ -608,15 +647,48 @@ pub(crate) struct PendingLocalCopy {
pub directory: PathBuf,
/// Destination-relative paths that already exist.
pub conflicts: std::collections::HashSet<PathBuf>,
- /// Where the drop landed, so the prompt appears there rather than at some
- /// default corner — the walk is asynchronous, so the pointer has moved on
- /// by the time we can ask.
- pub anchor: ::window::Point,
/// What the walk left out, carried through so the finished row can say so
/// rather than reporting a clean success over silently omitted data.
pub note: Option<String>,
}
+/// A remote operation waiting on an explicit yes from the user before it is
+/// allowed to touch anything. One slot, not one per operation: only one
+/// confirmation menu can be on screen, and starting a new one supersedes (and
+/// cancels) whatever was still waiting.
+pub(crate) enum PendingRemoteConfirm {
+ /// A folder download whose walk finished large enough to ask about.
+ FolderDownload {
+ transfer_id: u64,
+ plan: remote_walk::RemoteWalkPlan,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// A folder delete: always confirmed, whatever its size — there is no
+ /// trash on the far side to undo it from.
+ FolderDelete {
+ transfer_id: u64,
+ remote: remote_files::RemotePath,
+ plan: remote_walk::RemoteWalkPlan,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// A single-file delete. No transfer row: it either happens or reports
+ /// through the panel's notice line.
+ FileDelete {
+ remote: remote_files::RemotePath,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+ /// A folder upload whose plan crossed the confirmation threshold.
+ FolderUpload {
+ transfer_id: u64,
+ directory: remote_files::RemotePath,
+ plan: transfer_walk::TransferPlan,
+ origin: remote_files::RemoteOperationOrigin,
+ /// Terminal drops paste the landed folder's remote path here once the
+ /// upload finishes; panel drops carry `None`.
+ paste_target: Option<(mux::pane::PaneId, remote_files::RemotePath)>,
+ },
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PaneDropZone {
Center,
@@ -799,40 +871,45 @@ enum InlineTabRenameTarget {
WorkspaceThread(String),
/// A file row in the right sidebar Files panel; commits via fs::rename.
File(PathBuf),
+ /// A row in the REMOTE Files panel; commits via an SFTP rename, so unlike
+ /// every other target the commit is asynchronous and reports its failure
+ /// through the panel's notice line rather than a log.
+ RemoteFile {
+ path: remote_files::RemotePath,
+ source_key: String,
+ },
}
#[derive(Clone, Debug)]
struct InlineTabRename {
target: InlineTabRenameTarget,
- text: String,
- cursor: usize,
- selection_anchor: Option<usize>,
+ input: TextInputState,
}
impl InlineTabRename {
fn new(target: InlineTabRenameTarget, text: String) -> Self {
- let cursor = text.chars().count();
- Self {
- target,
- text,
- cursor,
- selection_anchor: Some(0),
- }
+ let mut input = TextInputState::new();
+ input.set_text_end(text);
+ input.caret_select_all();
+ Self { target, input }
}
+ /// Legacy tab surfaces still paint their inline editor as title text. File
+ /// rows use the real shared text-input painter; keep this adapter for tabs
+ /// until those surfaces move to the same widget.
fn display_text(&self) -> String {
- if self.has_selection() {
- return if self.text.is_empty() {
+ if self.input.caret_selection_range().is_some() {
+ return if self.input.is_empty() {
"|".to_string()
} else {
- self.text.clone()
+ self.input.text().to_string()
};
}
let mut text = String::new();
let mut inserted_cursor = false;
- for (idx, ch) in self.text.chars().enumerate() {
- if idx == self.cursor {
+ for (idx, ch) in self.input.text().chars().enumerate() {
+ if idx == self.input.cursor {
text.push('|');
inserted_cursor = true;
}
@@ -843,111 +920,6 @@ impl InlineTabRename {
}
text
}
-
- fn len(&self) -> usize {
- self.text.chars().count()
- }
-
- fn byte_idx(&self, char_idx: usize) -> usize {
- self.text
- .char_indices()
- .nth(char_idx)
- .map(|(idx, _)| idx)
- .unwrap_or_else(|| self.text.len())
- }
-
- fn selection_range(&self) -> Option<(usize, usize)> {
- let anchor = self.selection_anchor?;
- if anchor == self.cursor {
- None
- } else if anchor < self.cursor {
- Some((anchor, self.cursor))
- } else {
- Some((self.cursor, anchor))
- }
- }
-
- fn has_selection(&self) -> bool {
- self.selection_range().is_some()
- }
-
- fn selected_text(&self) -> Option<String> {
- let (start, end) = self.selection_range()?;
- Some(
- self.text
- .chars()
- .skip(start)
- .take(end.saturating_sub(start))
- .collect(),
- )
- }
-
- fn select_all(&mut self) {
- self.selection_anchor = Some(0);
- self.cursor = self.len();
- }
-
- fn clear_selection(&mut self) {
- self.selection_anchor = None;
- }
-
- fn delete_selection(&mut self) -> bool {
- let Some((start, end)) = self.selection_range() else {
- return false;
- };
- let start_byte = self.byte_idx(start);
- let end_byte = self.byte_idx(end);
- self.text.replace_range(start_byte..end_byte, "");
- self.cursor = start;
- self.clear_selection();
- true
- }
-
- fn insert(&mut self, text: &str) {
- self.delete_selection();
- for ch in text.chars() {
- if matches!(ch, '\r' | '\n') {
- continue;
- }
- let byte_idx = self.byte_idx(self.cursor);
- self.text.insert(byte_idx, ch);
- self.cursor += 1;
- }
- }
-
- fn backspace(&mut self) {
- if self.delete_selection() {
- return;
- }
- if self.cursor == 0 {
- return;
- }
- let remove_idx = self.cursor - 1;
- let byte_idx = self.byte_idx(remove_idx);
- self.text.remove(byte_idx);
- self.cursor = remove_idx;
- }
-
- fn delete(&mut self) {
- if self.delete_selection() {
- return;
- }
- let byte_idx = self.byte_idx(self.cursor);
- if byte_idx == self.text.len() {
- return;
- }
- self.text.remove(byte_idx);
- }
-
- fn move_left(&mut self) {
- self.cursor = self.cursor.saturating_sub(1);
- self.clear_selection();
- }
-
- fn move_right(&mut self) {
- self.cursor = self.cursor.saturating_add(1).min(self.len());
- self.clear_selection();
- }
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -1420,6 +1392,16 @@ pub struct TermWindow {
right_sidebar_local_drop_target: Option<PathBuf>,
/// A local copy waiting on the user's answer about existing files.
pending_local_copy: Option<PendingLocalCopy>,
+ /// A remote operation waiting on its confirmation menu. Superseded (and
+ /// cancelled) by any newer confirmation, and cleared when its menu is
+ /// dismissed without an answer.
+ pending_remote_confirm: Option<PendingRemoteConfirm>,
+ /// A freshly created remote folder that should drop into an inline rename
+ /// as soon as the re-listed directory actually shows its row.
+ pending_remote_rename: Option<(
+ remote_files::RemotePath,
+ remote_files::RemoteOperationOrigin,
+ )>,
/// Bumped by every drop. A preflight walk that comes back carrying an old
/// value has been superseded — two walks can finish out of order, and the
/// slower, older one must not replace the newer prompt.
@@ -2079,6 +2061,8 @@ impl TermWindow {
right_sidebar_remote_drop_target: None,
right_sidebar_local_drop_target: None,
pending_local_copy: None,
+ pending_remote_confirm: None,
+ pending_remote_rename: None,
local_copy_generation: 0,
pending_local_copy_conflict_count: 0,
right_sidebar_remote_file_tree_scroll_offset: 0.0,
@@ -2295,6 +2279,11 @@ impl TermWindow {
window.invalidate();
Ok(true)
}
+ WindowEvent::ContextMenuDismissed => {
+ self.context_menu_was_dismissed();
+ window.invalidate();
+ Ok(true)
+ }
WindowEvent::FocusChanged(focused) => {
self.focus_changed(focused, window);
Ok(true)
@@ -2490,6 +2479,12 @@ impl TermWindow {
if self.copy_dropped_files_into_local_panel(&paths, coords) {
return Ok(true);
}
+ // A drop on the terminal of a REMOTE session: pasting a local
+ // path there would name a file the server does not have, so
+ // upload first and paste the remote path instead.
+ if self.upload_dropped_files_to_remote_terminal(&paths, coords) {
+ return Ok(true);
+ }
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return Ok(true),
@@ -2759,10 +2754,11 @@ impl TermWindow {
// reattach) get their persisted per-pane font scales
// re-applied; the adopt-time application ran before
// these panes existed.
- self.apply_workspace_thread_font_scales();
+ self.stage_workspace_thread_font_scales();
// Remote panes are skipped by Tab::resize. A tab can arrive
// while the connection content view suppresses paint-time
- // pane sync, so impose the actual GUI geometry immediately.
+ // pane sync, so impose the final font-scaled GUI geometry
+ // exactly once.
self.force_sync_active_mux_tab_pane_sizes();
self.persist_workspace_layout_after_mutation("tab added");
}
@@ -2909,16 +2905,24 @@ impl TermWindow {
self.invalidate_fancy_tab_bar();
self.invalidate_modal();
+ // Restore every destination-side geometry input before sizing panes.
+ // consume_pending_sidebar_reflow can synchronously apply dimensions,
+ // so persisted font scales must already be present before it runs.
+ // Otherwise a remote TUI can receive an intermediate SIGWINCH followed
+ // by the final one and corrupt its redraw.
+ self.stage_workspace_thread_font_scales();
+
// The destination window is adopted; a Space switch that changed the
// sidebar width can resize the terminal now without touching the
- // window being left.
+ // window being left. ClientPane and Tab both no-op the explicit final
+ // sync below if this already imposed exactly the same geometry.
self.consume_pending_sidebar_reflow();
// Tab::resize updates the local split tree but deliberately skips
- // remote mirror panes. Force the per-pane GUI-sized resize now rather
- // than waiting for a later paint (a connection view may still be up).
+ // remote mirror panes. Force the final per-pane GUI-sized resize now
+ // rather than waiting for a later paint (a connection view may still
+ // be up).
self.resize_mux_tabs_to_current_terminal_size();
- self.apply_workspace_thread_font_scales();
self.sync_current_workspace_thread();
// A Space/thread switch can replace the active pane without changing
@@ -4857,6 +4861,10 @@ impl TermWindow {
(InlineTabRenameTarget::File(path), UIItemType::RightSidebarFileRow(other)) => {
path == other
}
+ (
+ InlineTabRenameTarget::RemoteFile { path, .. },
+ UIItemType::RightSidebarRemoteFileRow(other),
+ ) => path == other,
_ => false,
}
}
@@ -4868,7 +4876,7 @@ impl TermWindow {
};
if commit {
- let title = rename.text.trim().to_string();
+ let title = rename.input.text().trim().to_string();
match rename.target {
InlineTabRenameTarget::WindowTab(tab_id) => {
if let Some(tab) = Mux::get().get_tab(tab_id) {
@@ -4894,6 +4902,9 @@ impl TermWindow {
InlineTabRenameTarget::File(path) => {
self.commit_sidebar_file_rename(path, &title);
}
+ InlineTabRenameTarget::RemoteFile { path, source_key } => {
+ self.commit_sidebar_remote_file_rename(path, source_key, &title);
+ }
}
}
@@ -4925,7 +4936,7 @@ impl TermWindow {
return;
};
let new_path = parent.join(new_name);
- if new_path.exists() {
+ if remote_files::local_path_is_occupied(&new_path) {
log::warn!(
"not renaming {} to {new_name}: target already exists",
old_path.display()
@@ -4942,18 +4953,130 @@ impl TermWindow {
self.force_right_sidebar_file_rescan();
}
+ pub(crate) fn start_sidebar_remote_file_rename(&mut self, path: remote_files::RemotePath) {
+ self.finish_inline_tab_rename(true);
+ let Some(source_key) = self.right_sidebar_remote_files.current_source_key() else {
+ return;
+ };
+ self.inline_tab_rename = Some(InlineTabRename::new(
+ InlineTabRenameTarget::RemoteFile {
+ path: path.clone(),
+ source_key,
+ },
+ path.file_name().to_string(),
+ ));
+ if let Some(window) = self.window.as_ref() {
+ window.invalidate();
+ }
+ }
+
+ fn commit_sidebar_remote_file_rename(
+ &mut self,
+ old: remote_files::RemotePath,
+ source_key: String,
+ new_name: &str,
+ ) {
+ if new_name.is_empty() || old.file_name() == new_name {
+ return;
+ }
+ if self
+ .right_sidebar_remote_files
+ .current_source_key()
+ .as_deref()
+ != Some(source_key.as_str())
+ {
+ // The editor belonged to a different tree. Never reinterpret its
+ // absolute path against whichever host is visible now.
+ return;
+ }
+ let Some(parent) = old.parent() else {
+ return;
+ };
+ // join_name refuses separators, `..` and NUL; anything else is the
+ // server's to accept or reject.
+ let new = match parent.join_name(new_name) {
+ Ok(new) => new,
+ Err(err) => {
+ self.right_sidebar_remote_files.error_message = Some(err);
+ self.invalidate_window();
+ return;
+ }
+ };
+ let Some(origin) = self.current_remote_operation_origin() else {
+ self.right_sidebar_remote_files.error_message =
+ Some("Remote Files source is no longer available".to_string());
+ self.invalidate_window();
+ return;
+ };
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.right_sidebar_remote_files.error_message =
+ Some("Remote Files connection is no longer available".to_string());
+ self.invalidate_window();
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ promise::spawn::spawn(async move {
+ // No-overwrite by contract: a taken name is the server's failure
+ // to report, and shows up on the panel's notice line.
+ let result = backend.rename(old.clone(), new).await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|message| {
+ remote_files::invalidate_remote_connection_if_dead(
+ &connection_key,
+ connection_id,
+ message,
+ )
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ // A rename and a delete leave the tree in the same state as
+ // far as the OLD path is concerned: gone. Same tail.
+ term_window.finish_remote_entry_removal(
+ old,
+ result,
+ origin,
+ connection_key,
+ connection_id,
+ connection_died,
+ );
+ })));
+ })
+ .detach();
+ }
+
+ pub(crate) fn is_renaming_sidebar_remote_file(&self, path: &remote_files::RemotePath) -> bool {
+ self.inline_tab_rename.as_ref().is_some_and(
+ |rename| matches!(&rename.target, InlineTabRenameTarget::RemoteFile { path: p, .. } if p == path),
+ )
+ }
+
+ pub(crate) fn sidebar_remote_file_rename_input(
+ &self,
+ path: &remote_files::RemotePath,
+ ) -> Option<&TextInputState> {
+ self.inline_tab_rename.as_ref().and_then(|rename| {
+ matches!(
+ &rename.target,
+ InlineTabRenameTarget::RemoteFile { path: current, .. } if current == path
+ )
+ .then_some(&rename.input)
+ })
+ }
+
pub(crate) fn is_renaming_sidebar_file(&self, path: &Path) -> bool {
self.inline_tab_rename.as_ref().is_some_and(
|rename| matches!(&rename.target, InlineTabRenameTarget::File(p) if p == path),
)
}
- pub(crate) fn sidebar_file_row_title(&self, path: &Path, name: &str) -> String {
- self.inline_tab_rename
- .as_ref()
- .filter(|rename| matches!(&rename.target, InlineTabRenameTarget::File(p) if p == path))
- .map(|rename| rename.display_text())
- .unwrap_or_else(|| name.to_string())
+ pub(crate) fn sidebar_file_rename_input(&self, path: &Path) -> Option<&TextInputState> {
+ self.inline_tab_rename.as_ref().and_then(|rename| {
+ matches!(&rename.target, InlineTabRenameTarget::File(current) if current == path)
+ .then_some(&rename.input)
+ })
}
fn inline_window_tab_rename_title(&self, tab_id: TabId) -> Option<String> {
@@ -4972,7 +5095,8 @@ impl TermWindow {
| InlineTabRenameTarget::Space(_)
| InlineTabRenameTarget::Project(_)
| InlineTabRenameTarget::WorkspaceThread(_)
- | InlineTabRenameTarget::File(_) => None,
+ | InlineTabRenameTarget::File(_)
+ | InlineTabRenameTarget::RemoteFile { .. } => None,
})
}
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index d517f37f..ba2bfcd3 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -659,23 +659,16 @@ impl super::TermWindow {
} else {
0.0
};
- let (padding_left, _) = self.padding_left_top();
- let cell_width = self.render_metrics.cell_size.width as f32;
let cell_height = self.render_metrics.cell_size.height as f32;
let x = event.coords.x as f32;
let y = event.coords.y as f32;
let nav_height = self.pane_nav_bar_height() as f32;
for pos in tab.iter_panes_ignoring_zoom() {
- let content_pane_x =
- padding_left + border.left.get() as f32 + pos.left as f32 * cell_width;
- let pane_x = if pos.left == 0 && self.workspace_sidebar_width() > 0 {
- self.tab_bar_left_edge() as f32
- } else {
- content_pane_x
+ let Ok((pane_x, pane_width)) = self.pane_chrome_span(&pos) else {
+ continue;
};
let pane_y = top_bar_height + border.top.get() as f32 + pos.top as f32 * cell_height;
- let pane_width = (content_pane_x + pos.width as f32 * cell_width - pane_x).max(1.0);
if x >= pane_x && x < pane_x + pane_width && y >= pane_y && y < pane_y + nav_height {
return Some(TabWheelSurface::PaneStack(pos.pane_stack_id));
}
@@ -1946,8 +1939,17 @@ impl super::TermWindow {
UIItemType::PaneNav { .. } => {
self.drag_pane_nav_tab(item, start_event, event, context);
}
- UIItemType::RightSidebarFileRow(_) => {
- self.drag_right_sidebar_file_row(item, start_event, event, context);
+ UIItemType::RightSidebarFileRow(ref path) => {
+ if self.is_renaming_sidebar_file(path) {
+ self.drag_right_sidebar_input_selection(item, start_event, event, context);
+ } else {
+ self.drag_right_sidebar_file_row(item, start_event, event, context);
+ }
+ }
+ UIItemType::RightSidebarRemoteFileRow(ref path)
+ if self.is_renaming_sidebar_remote_file(path) =>
+ {
+ self.drag_right_sidebar_input_selection(item, start_event, event, context);
}
_ => {
log::error!("drag not implemented for {:?}", item);
@@ -3502,7 +3504,8 @@ impl super::TermWindow {
context: &dyn WindowOps,
) {
let item_type = item.item_type.clone();
- let is_input = matches!(item_type, UIItemType::RightSidebarFileFilter);
+ let is_input = matches!(item_type, UIItemType::RightSidebarFileFilter)
+ || matches!(&item_type, UIItemType::RightSidebarFileRow(path) if self.is_renaming_sidebar_file(path));
context.set_cursor(Some(if is_input {
MouseCursor::Text
} else {
@@ -3540,8 +3543,26 @@ impl super::TermWindow {
}
(UIItemType::RightSidebarFileRow(path), WMEK::Press(MousePress::Left)) => {
if self.is_renaming_sidebar_file(&path) {
- // Clicking the row that hosts the inline rename editor
- // must not arm a drag or re-open the file.
+ let double_click = self
+ .last_mouse_click
+ .as_ref()
+ .is_some_and(|click| click.streak >= 2);
+ if double_click {
+ if let Some(input) = self.right_sidebar_input_for_item_mut(
+ &UIItemType::RightSidebarFileRow(path),
+ ) {
+ input.caret_select_all();
+ }
+ } else {
+ self.position_right_sidebar_input_caret(
+ &UIItemType::RightSidebarFileRow(path),
+ event.coords.x,
+ false,
+ );
+ self.dragging.replace((item, event));
+ }
+ context.set_cursor(Some(MouseCursor::Text));
+ context.invalidate();
return;
}
self.clear_right_sidebar_text_focus();
@@ -3596,7 +3617,16 @@ impl super::TermWindow {
event: MouseEvent,
context: &dyn WindowOps,
) {
- context.set_cursor(Some(MouseCursor::Hand));
+ let rename_input = matches!(
+ &item.item_type,
+ UIItemType::RightSidebarRemoteFileRow(path)
+ if self.is_renaming_sidebar_remote_file(path)
+ );
+ context.set_cursor(Some(if rename_input {
+ MouseCursor::Text
+ } else {
+ MouseCursor::Hand
+ }));
if let (UIItemType::RightSidebarRemoteFileRow(path), WMEK::Press(MousePress::Right)) =
(&item.item_type, &event.kind)
{
@@ -3612,13 +3642,35 @@ impl super::TermWindow {
self.request_right_sidebar_remote_files_connect(true);
}
UIItemType::RightSidebarRemoteTransfer(id) => {
- self.dismiss_or_cancel_remote_transfer(id);
+ self.remote_transfer_row_clicked(id, event.coords);
}
UIItemType::RightSidebarRemoteFileRefresh => {
self.refresh_right_sidebar_remote_files();
}
- UIItemType::RightSidebarRemoteFileRow(path) => {
- self.open_right_sidebar_remote_file(path);
+ UIItemType::RightSidebarRemoteFileRow(ref path) => {
+ if self.is_renaming_sidebar_remote_file(path) {
+ let double_click = self
+ .last_mouse_click
+ .as_ref()
+ .is_some_and(|click| click.streak >= 2);
+ if double_click {
+ if let Some(input) = self.right_sidebar_input_for_item_mut(
+ &UIItemType::RightSidebarRemoteFileRow(path.clone()),
+ ) {
+ input.caret_select_all();
+ }
+ } else {
+ self.position_right_sidebar_input_caret(
+ &UIItemType::RightSidebarRemoteFileRow(path.clone()),
+ event.coords.x,
+ false,
+ );
+ self.dragging.replace((item, event));
+ }
+ context.invalidate();
+ return;
+ }
+ self.open_right_sidebar_remote_file(path.clone());
}
UIItemType::RightSidebarRemoteFileBack => {
self.close_right_sidebar_remote_file_preview();
diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rs
index 076771a9..65e35838 100644
--- a/wezterm-gui/src/termwindow/remote_files.rs
+++ b/wezterm-gui/src/termwindow/remote_files.rs
@@ -357,10 +357,6 @@ impl TransferFailure {
leftover: None,
}
}
-
- pub(crate) fn was_canceled(&self) -> bool {
- self.message == REMOTE_TRANSFER_CANCELED
- }
}
/// Transfers report richer failures than the rest of the backend, so they get
@@ -371,6 +367,10 @@ type TransferFuture = Pin<Box<dyn Future<Output = Result<u64, TransferFailure>>
pub(crate) enum RemoteTransferKind {
Upload,
Download,
+ /// Removing a remote folder tree. Rides the transfer strip because it has
+ /// the same shape — many round trips, progress, a cancel — even though no
+ /// bytes move.
+ Delete,
/// Copying between two local directories — no connection involved, but it
/// wants the same progress row, cancel and retry as the remote ones.
LocalCopy,
@@ -381,6 +381,7 @@ impl RemoteTransferKind {
match self {
Self::Upload => "Uploading",
Self::Download => "Downloading",
+ Self::Delete => "Deleting",
Self::LocalCopy => "Copying",
}
}
@@ -415,12 +416,47 @@ pub(crate) enum RemoteTransferSource {
Download {
remote: RemotePath,
},
- LocalCopy {
- source: PathBuf,
- destination_dir: PathBuf,
+ /// A whole remote directory. Retrying re-walks and re-reserves from
+ /// scratch — the tree may have changed, and the old reservation is a
+ /// half-written folder the retry must not resume into.
+ DownloadFolder {
+ remote: RemotePath,
},
}
+/// The Files source an operation was created against.
+///
+/// Remote paths are only meaningful together with this identity: `/tmp/a` on
+/// host A is not the same object as `/tmp/a` on host B. Keep the source on
+/// work that can outlive the currently displayed tree (transfers, confirmation
+/// menus and inline edits), then revalidate it immediately before execution.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RemoteOperationOrigin {
+ source_key: String,
+ connection_key: String,
+}
+
+impl RemoteOperationOrigin {
+ pub(crate) fn new(source_key: String, connection_key: String) -> Self {
+ Self {
+ source_key,
+ connection_key,
+ }
+ }
+
+ pub(crate) fn source_key(&self) -> &str {
+ &self.source_key
+ }
+
+ pub(crate) fn connection_key(&self) -> &str {
+ &self.connection_key
+ }
+
+ pub(crate) fn matches(&self, source_key: Option<&str>, connection_key: Option<&str>) -> bool {
+ source_key == Some(self.source_key()) && connection_key == Some(self.connection_key())
+ }
+}
+
/// One transfer in flight, or one that just finished and still has something
/// to report. Lives on the window rather than in [`RemoteFilesState`] because
/// a transfer holds its own lease and must survive the panel switching trees.
@@ -434,6 +470,10 @@ pub(crate) struct RemoteTransfer {
/// Enough to retry. `None` for records that were never a real transfer —
/// a rejected folder, say — which have nothing to retry.
pub source: Option<RemoteTransferSource>,
+ /// Host identity for remote work. Local copies deliberately leave this
+ /// empty; every retryable remote transfer must have both `source` and
+ /// `origin`.
+ pub origin: Option<RemoteOperationOrigin>,
}
impl RemoteTransfer {
@@ -442,7 +482,7 @@ impl RemoteTransfer {
}
pub(crate) fn can_retry(&self) -> bool {
- !self.is_running() && self.source.is_some()
+ !self.is_running() && self.source.is_some() && self.origin.is_some()
}
}
@@ -483,6 +523,36 @@ pub(crate) fn download_name_candidates(file_name: &str) -> impl Iterator<Item =
)
}
+/// The names a downloaded FOLDER will try, in order: the folder's own name,
+/// then ` (1)`, ` (2)`… appended at the end. Never the file rule — a folder
+/// called `my.folder` has no extension to preserve, and splitting it would
+/// produce `my (1).folder`.
+pub(crate) fn folder_download_name_candidates(name: &str) -> impl Iterator<Item = String> + '_ {
+ let sanitized = sanitized_download_name(name);
+ std::iter::once(sanitized.to_string())
+ .chain((1..=DOWNLOAD_NAME_ATTEMPTS).map(move |suffix| format!("{sanitized} ({suffix})")))
+}
+
+/// Claim a fresh directory for a folder download.
+///
+/// `reserve` must CREATE the candidate exclusively (`fs::create_dir`, which
+/// fails if anything already wears the name) and report whether it won; the
+/// successful candidate is both the reservation and the destination, so
+/// everything written under it afterwards is by construction new.
+pub(crate) fn reserve_download_directory(
+ directory: &Path,
+ name: &str,
+ mut reserve: impl FnMut(&Path) -> bool,
+) -> Option<PathBuf> {
+ for candidate in folder_download_name_candidates(name) {
+ let destination = directory.join(&candidate);
+ if reserve(&destination) {
+ return Some(destination);
+ }
+ }
+ None
+}
+
/// Claim a destination and its staging file together.
///
/// `reserve` must create the staging path *exclusively* and report whether it
@@ -572,6 +642,68 @@ pub(crate) trait RemoteFileBackend: Send + Sync {
))
})
}
+
+ /// Stream `remote` into an already-created local file, returning the bytes
+ /// written. Unlike [`Self::download_file`] there is no staging and no
+ /// rename: the caller created `sink` exclusively (through its pinned
+ /// destination handle) and owns cleaning it up on failure. That is what a
+ /// folder download wants — its whole tree is freshly reserved, and every
+ /// write must stay behind the caller's directory handle.
+ fn download_into(
+ &self,
+ remote: RemotePath,
+ sink: std::fs::File,
+ progress: RemoteTransferProgress,
+ ) -> TransferFuture {
+ let _ = (remote, sink, progress);
+ Box::pin(async {
+ Err(TransferFailure::new(
+ "This connection cannot download files",
+ ))
+ })
+ }
+
+ /// Whether anything currently wears this remote name. Advisory only: a
+ /// `false` may be a transport failure or a race, so a caller choosing a
+ /// free name must still create exclusively and treat THAT as the truth.
+ /// The default says "not there", which makes test doubles optimistic and
+ /// keeps the exclusive create as the single honest gate.
+ fn exists(&self, remote: RemotePath) -> RemoteFuture<bool> {
+ let _ = remote;
+ Box::pin(async { Ok(false) })
+ }
+
+ /// Delete a single remote file (or symlink). The default refuses, like
+ /// `upload_file`: only a backend that can actually delete should claim to.
+ fn remove_file(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let _ = remote;
+ Box::pin(async { Err("This connection cannot delete files".to_string()) })
+ }
+
+ /// Delete an EMPTY remote directory. Recursion is the caller's job: the
+ /// protocol offers only rmdir, and hiding a walk in here would bury both
+ /// its per-directory round trips and its cancellation points.
+ fn remove_directory(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let _ = remote;
+ Box::pin(async { Err("This connection cannot delete folders".to_string()) })
+ }
+
+ /// Rename `from` to `to` WITHOUT overwriting: a `to` that already exists
+ /// is the server's error to report. Implementations must reserve the
+ /// destination atomically rather than relying on an advisory existence
+ /// check followed by a potentially-overwriting rename.
+ fn rename(&self, from: RemotePath, to: RemotePath) -> RemoteFuture<()> {
+ let _ = (from, to);
+ Box::pin(async { Err("This connection cannot rename".to_string()) })
+ }
+
+ /// Create a remote directory, failing if ANYTHING already has that name.
+ /// Unlike [`Self::create_directory`], an existing directory is a failure:
+ /// "New Folder" must mint something new, never adopt a neighbour.
+ fn create_directory_exclusive(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let _ = remote;
+ Box::pin(async { Err("This connection cannot create directories".to_string()) })
+ }
}
pub(crate) trait RemoteFileConnector: Send + Sync {
@@ -594,6 +726,145 @@ pub(crate) fn remote_connection_key(source_key: &str, config: &SshDomain) -> Str
format!("{source_key}:{:016x}", hasher.finish())
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum RemoteRenameEntryKind {
+ Directory,
+ Other,
+}
+
+trait RemoteRenameBackend: Send + Sync {
+ fn inspect(&self, path: String) -> RemoteFuture<Option<RemoteRenameEntryKind>>;
+ fn reserve(&self, path: String, kind: RemoteRenameEntryKind) -> RemoteFuture<()>;
+ fn replace(&self, from: String, to: String) -> RemoteFuture<()>;
+ fn release(&self, path: String, kind: RemoteRenameEntryKind) -> RemoteFuture<()>;
+}
+
+async fn rename_without_overwrite(
+ backend: &dyn RemoteRenameBackend,
+ from: &RemotePath,
+ to: &RemotePath,
+) -> Result<(), String> {
+ let source_kind = backend
+ .inspect(from.as_str().to_string())
+ .await
+ .map_err(|err| format!("Unable to inspect {}: {err}", from.as_str()))?
+ .ok_or_else(|| format!("{} does not exist", from.as_str()))?;
+
+ if let Err(reserve_error) = backend.reserve(to.as_str().to_string(), source_kind).await {
+ return match backend.inspect(to.as_str().to_string()).await {
+ Ok(Some(_)) => Err(format!("{} already exists", to.as_str())),
+ Ok(None) => Err(format!(
+ "Unable to reserve {} for rename: {reserve_error}",
+ to.as_str()
+ )),
+ Err(check) => Err(format!(
+ "Unable to verify why {} could not be reserved: {check}",
+ to.as_str()
+ )),
+ };
+ }
+
+ if let Err(rename_error) = backend
+ .replace(from.as_str().to_string(), to.as_str().to_string())
+ .await
+ {
+ let mut message = format!(
+ "Unable to rename {} to {}: {rename_error}",
+ from.as_str(),
+ to.file_name()
+ );
+ // A transport error can be ambiguous: the server may have completed
+ // the rename before the reply was lost. Only remove the placeholder
+ // after proving the source still exists; otherwise `to` may now be
+ // the user's actual data.
+ match backend.inspect(from.as_str().to_string()).await {
+ Ok(Some(_)) => {
+ if let Err(cleanup_error) =
+ backend.release(to.as_str().to_string(), source_kind).await
+ {
+ message.push_str(&format!(
+ "; the reserved placeholder {} could not be removed: {cleanup_error}",
+ to.as_str()
+ ));
+ }
+ }
+ Ok(None) => {
+ message.push_str(&format!(
+ "; the outcome could not be verified, so {} was left untouched",
+ to.as_str()
+ ));
+ }
+ Err(check) => {
+ message.push_str(&format!(
+ "; the outcome could not be verified, so {} was left untouched: {check}",
+ to.as_str()
+ ));
+ }
+ }
+ return Err(message);
+ }
+ Ok(())
+}
+
+#[derive(Clone)]
+struct SftpRemoteRenameBackend {
+ sftp: wezterm_ssh::Sftp,
+}
+
+impl RemoteRenameBackend for SftpRemoteRenameBackend {
+ fn inspect(&self, path: String) -> RemoteFuture<Option<RemoteRenameEntryKind>> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ match sftp.symlink_metadata(path).await {
+ Ok(metadata) => Ok(Some(if metadata.is_dir() {
+ RemoteRenameEntryKind::Directory
+ } else {
+ RemoteRenameEntryKind::Other
+ })),
+ Err(err) if sftp_error_is_missing(&err) => Ok(None),
+ Err(err) => Err(err.to_string()),
+ }
+ })
+ }
+
+ fn reserve(&self, path: String, kind: RemoteRenameEntryKind) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ match kind {
+ RemoteRenameEntryKind::Directory => sftp
+ .create_dir(path, 0o700)
+ .await
+ .map_err(|err| err.to_string()),
+ RemoteRenameEntryKind::Other => sftp
+ .create_new(path)
+ .await
+ .map(drop)
+ .map_err(|err| err.to_string()),
+ }
+ })
+ }
+
+ fn replace(&self, from: String, to: String) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ sftp.rename(from, to, wezterm_ssh::RenameOptions::default())
+ .await
+ .map_err(|err| err.to_string())
+ })
+ }
+
+ fn release(&self, path: String, kind: RemoteRenameEntryKind) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ match kind {
+ RemoteRenameEntryKind::Directory => sftp.remove_dir(path).await,
+ RemoteRenameEntryKind::Other => sftp.remove_file(path).await,
+ }
+ .map_err(|err| err.to_string())
+ })
+ }
+}
+
struct SftpRemoteFileBackend {
// Sftp only retains a request sender. Keep the Session handle alive for
// the lifetime of this independent file connection.
@@ -875,6 +1146,99 @@ impl RemoteFileBackend for SftpRemoteFileBackend {
finish_download(outcome, &partial, &local).await
})
}
+
+ fn download_into(
+ &self,
+ remote: RemotePath,
+ sink: std::fs::File,
+ progress: RemoteTransferProgress,
+ ) -> TransferFuture {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ let mut file = sftp
+ .open(remote.as_str().to_string())
+ .await
+ .map_err(|err| {
+ TransferFailure::new(format!("Unable to open {}: {err}", remote.as_str()))
+ })?;
+ let mut sink = smol::fs::File::from(sink);
+ copy_stream(
+ &mut file,
+ &mut sink,
+ &progress,
+ "the server",
+ "the local file",
+ )
+ .await
+ .map_err(TransferFailure::new)
+ })
+ }
+
+ fn exists(&self, remote: RemotePath) -> RemoteFuture<bool> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ // SFTP v3 cannot distinguish "not found" from other failures, so a
+ // failed stat reads as absent; the exclusive create downstream is
+ // what actually guarantees no clobbering.
+ Ok(sftp.metadata(remote.as_str().to_string()).await.is_ok())
+ })
+ }
+
+ fn remove_file(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ sftp.remove_file(remote.as_str().to_string())
+ .await
+ .map_err(|err| format!("Unable to delete {}: {err}", remote.as_str()))
+ })
+ }
+
+ fn remove_directory(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ sftp.remove_dir(remote.as_str().to_string())
+ .await
+ .map_err(|err| format!("Unable to delete {}: {err}", remote.as_str()))
+ })
+ }
+
+ fn rename(&self, from: RemotePath, to: RemotePath) -> RemoteFuture<()> {
+ let backend = SftpRemoteRenameBackend {
+ sftp: self.sftp.clone(),
+ };
+ Box::pin(async move {
+ // libssh drops RenameOptions and can upgrade a plain rename to
+ // [email protected], which replaces an occupied target.
+ // Atomically CREATE the target first, then replace only the empty
+ // placeholder owned by this operation. A competing creator either
+ // wins the reservation (and we stop) or encounters ours; there is
+ // no check-then-rename gap in which its data can be destroyed.
+ rename_without_overwrite(&backend, &from, &to).await
+ })
+ }
+
+ fn create_directory_exclusive(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ // Unlike create_directory there is no merge tolerance, but the
+ // failure still deserves a precise message: SFTP v3 answers a
+ // bare FAILURE for "exists", indistinguishable from a permission
+ // problem, so ask metadata which one it was.
+ match sftp.create_dir(remote.as_str().to_string(), 0o755).await {
+ Ok(()) => Ok(()),
+ Err(err) => match sftp.symlink_metadata(remote.as_str().to_string()).await {
+ Ok(_) => Err(format!("{} already exists", remote.as_str())),
+ Err(check) if sftp_error_is_missing(&check) => {
+ Err(format!("Unable to create {}: {err}", remote.as_str()))
+ }
+ Err(check) => Err(format!(
+ "Unable to verify why {} could not be created: {check}",
+ remote.as_str()
+ )),
+ },
+ }
+ })
+ }
}
/// Put a finished download in place, or clean up after a failed one.
@@ -903,30 +1267,59 @@ async fn finish_download(
}
};
- // `rename` replaces silently, so re-check that nothing appeared at the
- // destination while the download ran. Uploads refuse to clobber; this side
- // must match, or a long download quietly destroys a file created in the
- // meantime.
- if local.exists() {
- let _ = smol::fs::remove_file(partial).await;
- return Err(TransferFailure::new(format!(
- "{} appeared while downloading, so it was left untouched",
- local.display()
- )));
+ // A plain rename replaces silently and a preceding exists() check follows
+ // symlinks (so a dangling link looks vacant) as well as racing with a
+ // creator. TempPath's no-clobber persistence performs the move with
+ // destination-exists protection and treats a dangling link as occupied.
+ match tempfile::TempPath::from_path(partial).persist_noclobber(local) {
+ Ok(()) => Ok(written),
+ Err(err) => {
+ let message = if local_path_is_occupied(local) {
+ format!(
+ "{} appeared while downloading, so it was left untouched",
+ local.display()
+ )
+ } else {
+ format!("Unable to save {}: {}", local.display(), err.error)
+ };
+ let partial = err.path.to_path_buf();
+ // Dropping the TempPath attempts cleanup. Check afterwards so a
+ // failed cleanup remains visible in the transfer row.
+ drop(err.path);
+ let mut failure = TransferFailure::new(message);
+ if local_path_is_occupied(&partial) {
+ failure.leftover = Some(partial.display().to_string());
+ }
+ Err(failure)
+ }
}
+}
- match smol::fs::rename(partial, local).await {
- Ok(()) => Ok(written),
+/// `true` unless lstat explicitly says the path does not exist.
+///
+/// This is deliberately fail-closed: permission and transient filesystem
+/// errors cannot be interpreted as permission to overwrite.
+pub(crate) fn local_path_is_occupied(path: &Path) -> bool {
+ match std::fs::symlink_metadata(path) {
+ Ok(_) => true,
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
Err(err) => {
- let _ = smol::fs::remove_file(partial).await;
- Err(TransferFailure::new(format!(
- "Unable to save {}: {err}",
- local.display()
- )))
+ log::warn!(
+ "remote files: unable to verify whether {} is free: {err:#}",
+ path.display()
+ );
+ true
}
}
}
+fn sftp_error_is_missing(err: &SftpChannelError) -> bool {
+ matches!(
+ err,
+ SftpChannelError::Sftp(SftpError::NoSuchFile | SftpError::NoSuchPath)
+ )
+}
+
/// Stream `remote` into the already-reserved `partial`. Split out so the
/// caller has exactly one place to clean up from: every `?` in here becomes a
/// single `Err` the caller handles, rather than an early return that walks
@@ -1155,6 +1548,14 @@ impl RemoteConnectionLease {
self.connection_id
}
+ /// Whether two leases name the same pooled connection. Identity is the
+ /// (key, id) pair: a key dialled with since-changed host settings hashes
+ /// differently, and a connection redialled under the same key gets a new
+ /// id.
+ pub(crate) fn is_same_connection(&self, other: &RemoteConnectionLease) -> bool {
+ self.key == other.key && self.connection_id == other.connection_id
+ }
+
pub(crate) fn operation_lease(&self) -> Option<RemoteConnectionLease> {
self.manager
.upgrade()
@@ -1765,6 +2166,11 @@ pub(crate) enum RemoteFilesEvent {
message: String,
},
SelectFile(RemotePath),
+ /// An entry stopped existing under its old path (deleted, or renamed
+ /// away): drop its whole cached subtree NOW, not on the next re-list.
+ /// Orphaned listings would keep eating the row budget, and a selection
+ /// under the old path would keep a preview open for a file that is gone.
+ EntryForgotten(RemotePath),
PreviewFinished {
generation: u64,
path: RemotePath,
@@ -2016,6 +2422,18 @@ impl RemoteFilesState {
path,
}]
}
+ RemoteFilesEvent::EntryForgotten(path) => {
+ // remove_descendants clears everything BELOW the path plus a
+ // selection under it; the path itself needs its own expansion
+ // and selection cleared too.
+ self.remove_descendants(&path);
+ self.expanded.remove(&path);
+ if self.selected.as_ref() == Some(&path) {
+ self.selected = None;
+ self.preview = RemotePreviewStatus::None;
+ }
+ Vec::new()
+ }
RemoteFilesEvent::PreviewFinished {
generation,
path,
@@ -2335,6 +2753,12 @@ impl RemoteFilesState {
.any(|directory| directory.listing.truncated)
}
+ /// Whether this directory currently holds a loaded listing. Used to tell
+ /// "the row is not there" apart from "its directory has not loaded yet".
+ pub(crate) fn has_listing(&self, path: &RemotePath) -> bool {
+ self.directories.contains_key(path)
+ }
+
pub(crate) fn kind_for_path(&self, path: &RemotePath) -> Option<RemoteFileKind> {
if self.root.as_ref() == Some(path) {
return Some(RemoteFileKind::Directory);
@@ -2352,6 +2776,165 @@ mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+ enum FakeRenameResult {
+ #[default]
+ Success,
+ FailBeforeMove,
+ FailAfterMove,
+ }
+
+ #[derive(Default)]
+ struct FakeRenameState {
+ entries: HashMap<String, (RemoteRenameEntryKind, &'static str)>,
+ replace_result: FakeRenameResult,
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeRenameBackend {
+ state: Arc<Mutex<FakeRenameState>>,
+ }
+
+ impl FakeRenameBackend {
+ fn insert(&self, path: &str, kind: RemoteRenameEntryKind, owner: &'static str) {
+ self.state
+ .lock()
+ .unwrap()
+ .entries
+ .insert(path.to_string(), (kind, owner));
+ }
+
+ fn owner(&self, path: &str) -> Option<&'static str> {
+ self.state
+ .lock()
+ .unwrap()
+ .entries
+ .get(path)
+ .map(|(_, owner)| *owner)
+ }
+
+ fn set_replace_result(&self, result: FakeRenameResult) {
+ self.state.lock().unwrap().replace_result = result;
+ }
+ }
+
+ impl RemoteRenameBackend for FakeRenameBackend {
+ fn inspect(&self, path: String) -> RemoteFuture<Option<RemoteRenameEntryKind>> {
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ Ok(state
+ .lock()
+ .unwrap()
+ .entries
+ .get(&path)
+ .map(|(kind, _)| *kind))
+ })
+ }
+
+ fn reserve(&self, path: String, kind: RemoteRenameEntryKind) -> RemoteFuture<()> {
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ let mut state = state.lock().unwrap();
+ if state.entries.contains_key(&path) {
+ return Err("occupied".to_string());
+ }
+ state.entries.insert(path, (kind, "reservation"));
+ Ok(())
+ })
+ }
+
+ fn replace(&self, from: String, to: String) -> RemoteFuture<()> {
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ let mut state = state.lock().unwrap();
+ if state.replace_result == FakeRenameResult::FailBeforeMove {
+ return Err("rename refused".to_string());
+ }
+ let source = state
+ .entries
+ .remove(&from)
+ .ok_or_else(|| "source missing".to_string())?;
+ state.entries.insert(to, source);
+ if state.replace_result == FakeRenameResult::FailAfterMove {
+ Err("reply lost".to_string())
+ } else {
+ Ok(())
+ }
+ })
+ }
+
+ fn release(&self, path: String, kind: RemoteRenameEntryKind) -> RemoteFuture<()> {
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ let mut state = state.lock().unwrap();
+ match state.entries.get(&path) {
+ Some((reserved_kind, "reservation")) if *reserved_kind == kind => {
+ state.entries.remove(&path);
+ Ok(())
+ }
+ _ => Err("not our reservation".to_string()),
+ }
+ })
+ }
+ }
+
+ fn remote_path(path: &str) -> RemotePath {
+ RemotePath::from_server_absolute(path).unwrap()
+ }
+
+ #[test]
+ fn remote_rename_never_replaces_an_existing_target() {
+ let backend = FakeRenameBackend::default();
+ backend.insert("/from", RemoteRenameEntryKind::Other, "source");
+ backend.insert("/to", RemoteRenameEntryKind::Other, "existing");
+
+ let error = smol::block_on(rename_without_overwrite(
+ &backend,
+ &remote_path("/from"),
+ &remote_path("/to"),
+ ))
+ .expect_err("an occupied target must refuse the rename");
+
+ assert!(error.contains("already exists"));
+ assert_eq!(backend.owner("/from"), Some("source"));
+ assert_eq!(backend.owner("/to"), Some("existing"));
+ }
+
+ #[test]
+ fn failed_remote_rename_releases_only_its_own_reservation() {
+ let backend = FakeRenameBackend::default();
+ backend.insert("/from", RemoteRenameEntryKind::Directory, "source");
+ backend.set_replace_result(FakeRenameResult::FailBeforeMove);
+
+ smol::block_on(rename_without_overwrite(
+ &backend,
+ &remote_path("/from"),
+ &remote_path("/to"),
+ ))
+ .expect_err("the fake rejects the move");
+
+ assert_eq!(backend.owner("/from"), Some("source"));
+ assert_eq!(backend.owner("/to"), None);
+ }
+
+ #[test]
+ fn ambiguous_remote_rename_error_never_deletes_the_moved_source() {
+ let backend = FakeRenameBackend::default();
+ backend.insert("/from", RemoteRenameEntryKind::Other, "source");
+ backend.set_replace_result(FakeRenameResult::FailAfterMove);
+
+ let error = smol::block_on(rename_without_overwrite(
+ &backend,
+ &remote_path("/from"),
+ &remote_path("/to"),
+ ))
+ .expect_err("the reply was lost");
+
+ assert!(error.contains("left untouched"));
+ assert_eq!(backend.owner("/from"), None);
+ assert_eq!(backend.owner("/to"), Some("source"));
+ }
+
/// 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)]
@@ -3058,6 +3641,36 @@ mod tests {
assert_eq!(names.next().as_deref(), Some(".bashrc (1)"));
}
+ /// A folder keeps its dots: the file rule would turn `my.folder` into
+ /// `my (1).folder`, naming a sibling that has nothing to do with it.
+ #[test]
+ fn a_downloaded_folder_is_numbered_at_the_end_of_its_name() {
+ let mut names = folder_download_name_candidates("my.folder");
+ assert_eq!(names.next().as_deref(), Some("my.folder"));
+ assert_eq!(names.next().as_deref(), Some("my.folder (1)"));
+
+ // Server-controlled names are reduced to one component, exactly like
+ // file downloads.
+ let mut hostile = folder_download_name_candidates("../../etc");
+ assert_eq!(hostile.next().as_deref(), Some("etc"));
+
+ let dir = Path::new("/home/ada/Downloads");
+ let taken: HashSet<PathBuf> = std::iter::once(dir.join("proj")).collect();
+ assert_eq!(
+ reserve_download_directory(dir, "proj", |path| !taken.contains(path)),
+ Some(dir.join("proj (1)"))
+ );
+ assert_eq!(
+ reserve_download_directory(dir, "notes", |path| !taken.contains(path)),
+ Some(dir.join("notes"))
+ );
+ assert_eq!(
+ reserve_download_directory(dir, "x", |_| false),
+ None,
+ "when nothing can be created, refuse rather than reuse"
+ );
+ }
+
/// Pins the bug this replaced: a download that failed before moving any
/// bytes used to return past the cleanup, leaving the reserved staging
/// file behind forever. That orphan is not just litter — reservation skips
@@ -3114,6 +3727,40 @@ mod tests {
assert!(!partial.exists(), "and the staging file is cleaned up");
}
+ #[cfg(unix)]
+ #[test]
+ fn a_download_does_not_clobber_a_dangling_symlink() {
+ use std::os::unix::fs::symlink;
+
+ let dir = tempfile::tempdir().unwrap();
+ let local = dir.path().join("notes.txt");
+ let partial = partial_download_path(&local);
+ std::fs::write(&partial, b"downloaded").unwrap();
+ symlink(dir.path().join("missing-target"), &local).unwrap();
+
+ assert!(!local.exists(), "stat follows the link and sees no target");
+ assert!(
+ local_path_is_occupied(&local),
+ "lstat must still reserve the directory entry"
+ );
+ let err = smol::block_on(finish_download(Ok(10), &partial, &local))
+ .expect_err("a dangling link is an occupied destination");
+
+ assert!(
+ err.message.contains("appeared while downloading"),
+ "{}",
+ err.message
+ );
+ assert!(
+ std::fs::symlink_metadata(&local)
+ .unwrap()
+ .file_type()
+ .is_symlink(),
+ "the link itself must remain untouched"
+ );
+ assert!(!partial.exists(), "and the staging file is cleaned up");
+ }
+
/// When cleanup itself fails — which is the normal case once the
/// connection is what died — the failure has to carry where the debris is.
/// A log line is not good enough: the user needs to know a partial file is
@@ -3168,6 +3815,33 @@ mod tests {
);
}
+ #[test]
+ fn only_explicit_sftp_missing_errors_mean_a_name_is_free() {
+ assert!(sftp_error_is_missing(&SftpChannelError::Sftp(
+ SftpError::NoSuchFile
+ )));
+ assert!(sftp_error_is_missing(&SftpChannelError::Sftp(
+ SftpError::NoSuchPath
+ )));
+ assert!(!sftp_error_is_missing(&SftpChannelError::Sftp(
+ SftpError::PermissionDenied
+ )));
+ assert!(!sftp_error_is_missing(&SftpChannelError::Sftp(
+ SftpError::Failure
+ )));
+ }
+
+ #[test]
+ fn a_remote_operation_origin_matches_only_its_host_configuration() {
+ let origin =
+ RemoteOperationOrigin::new("ssh-host:a".to_string(), "ssh-host:a:key-1".to_string());
+ assert!(origin.matches(Some("ssh-host:a"), Some("ssh-host:a:key-1")));
+ assert!(!origin.matches(Some("ssh-host:b"), Some("ssh-host:a:key-1")));
+ assert!(!origin.matches(Some("ssh-host:a"), Some("ssh-host:a:key-2")));
+ assert!(!origin.matches(None, Some("ssh-host:a:key-1")));
+ assert!(!origin.matches(Some("ssh-host:a"), None));
+ }
+
/// A folder reports items, not bytes. The trap this pins: a walker that
/// reuses the single-file upload path lets every file call `set_total`
/// with its own size, so the bar reads "100%" on each small file and jumps
@@ -3534,6 +4208,44 @@ mod tests {
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
+ #[test]
+ fn lease_identity_is_the_key_and_id_pair() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let manager = RemoteConnectionManager::new(
+ Arc::new(FakeConnector {
+ calls: Arc::clone(&calls),
+ }),
+ Duration::from_secs(30),
+ );
+ let first =
+ smol::block_on(manager.acquire("source".to_string(), SshDomain::default(), true))
+ .unwrap();
+ let shared =
+ smol::block_on(manager.acquire("source".to_string(), SshDomain::default(), true))
+ .unwrap();
+ assert!(first.is_same_connection(&shared), "one pooled session");
+
+ // What a caller that dialled for itself sees after the pooled session
+ // was replaced: the lease it is holding is NOT the live one.
+ manager.invalidate("source");
+ let redialled =
+ smol::block_on(manager.acquire("source".to_string(), SshDomain::default(), true))
+ .unwrap();
+ assert!(!first.is_same_connection(&redialled));
+
+ // The key half, which the pool cannot produce on its own: changed host
+ // settings hash to a different key while the ids stay whatever they
+ // were.
+ let lease = |key: &str, connection_id| RemoteConnectionLease {
+ key: key.to_string(),
+ backend: Arc::new(FakeBackend) as Arc<dyn RemoteFileBackend>,
+ manager: Weak::new(),
+ connection_id,
+ };
+ assert!(lease("source:aaa", 1).is_same_connection(&lease("source:aaa", 1)));
+ assert!(!lease("source:aaa", 1).is_same_connection(&lease("source:bbb", 1)));
+ }
+
#[test]
fn connection_key_changes_with_endpoint_options_and_credentials() {
let mut first = SshDomain::default();
@@ -4275,6 +4987,54 @@ mod tests {
assert_eq!(state.total_entries(), 1);
}
+ /// A deleted (or renamed-away) directory must drop its cached subtree
+ /// immediately: orphaned listings keep eating the row budget, and a
+ /// selection under the old path keeps a dead preview open.
+ #[test]
+ fn a_forgotten_entry_takes_its_subtree_and_selection_with_it() {
+ let source = unique_source("forgotten");
+ let root = RemotePath::from_server_absolute("/home/me").unwrap();
+ let dir = root.join_name("src").unwrap();
+ let file = dir.join_name("lib.rs").unwrap();
+ let mut state = RemoteFilesState::default();
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target(&source))));
+ let generation = match state.transition(RemoteFilesEvent::ConnectRequested)[0] {
+ RemoteFilesEffect::Connect { generation, .. } => generation,
+ _ => unreachable!(),
+ };
+ state.transition(RemoteFilesEvent::Connected {
+ generation,
+ root: root.clone(),
+ listing: listing(&root, &[("src", RemoteFileKind::Directory)]),
+ });
+ state.transition(RemoteFilesEvent::ToggleDirectory(dir.clone()));
+ state.transition(RemoteFilesEvent::DirectoryLoaded {
+ generation,
+ path: dir.clone(),
+ listing: listing(&dir, &[("lib.rs", RemoteFileKind::File)]),
+ });
+ state.transition(RemoteFilesEvent::SelectFile(file));
+ assert_eq!(state.rows().len(), 3);
+
+ assert!(state
+ .transition(RemoteFilesEvent::EntryForgotten(dir.clone()))
+ .is_empty());
+ assert!(!state.expanded.contains(&dir));
+ assert!(!state.directories.contains_key(&dir));
+ assert!(
+ state.selected.is_none(),
+ "a selection under the forgotten entry must not survive"
+ );
+ assert!(matches!(state.preview, RemotePreviewStatus::None));
+ assert_eq!(state.total_entries(), 1, "only the root listing remains");
+
+ // Forgetting the selected entry itself clears it too.
+ let sibling = root.join_name("src").unwrap();
+ state.transition(RemoteFilesEvent::SelectFile(sibling.clone()));
+ state.transition(RemoteFilesEvent::EntryForgotten(sibling));
+ assert!(state.selected.is_none());
+ }
+
#[test]
fn stale_directory_result_is_ignored_after_panel_closes() {
let source = unique_source("stale_directory_result_is_ignored_after_panel_closes");
diff --git a/wezterm-gui/src/termwindow/remote_walk.rs b/wezterm-gui/src/termwindow/remote_walk.rs
new file mode 100644
index 00000000..17d581f0
--- /dev/null
+++ b/wezterm-gui/src/termwindow/remote_walk.rs
@@ -0,0 +1,645 @@
+//! Turning a remote directory into a flat list of things to download or
+//! delete, before anything moves.
+//!
+//! Deliberately the remote sibling of [`super::transfer_walk`]: walking first
+//! means the item total is known before the first byte (or unlink), every
+//! problem the tree holds — a name the local system cannot store, a listing
+//! too big to trust — surfaces as one refusal up front instead of a
+//! half-processed tree, and the confirmation threshold has a number to ask
+//! about. The walk itself is priced differently though: every directory here
+//! costs a round trip on a single serialized channel, which is why its budget
+//! is a tenth of the local one.
+
+use super::remote_files::{
+ RemoteFileBackend, RemoteFileKind, RemotePath, RemoteTransferProgress, REMOTE_TRANSFER_CANCELED,
+};
+use std::collections::{HashSet, VecDeque};
+use std::path::{Component, Path};
+
+/// Total entries a remote walk will accept before refusing. Each directory is
+/// one round trip, so a tree at this limit already takes real time just to
+/// list — anything bigger deserves a shell, not a sidebar.
+pub(crate) const REMOTE_WALK_ENTRY_LIMIT: usize = 10_000;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum RemoteWalkMode {
+ /// Building a download: symlinks and special files are skipped and
+ /// counted, matching what the local planner does on the way up.
+ Download,
+ /// Building a delete: symlinks and special files become unlink entries
+ /// instead — leaving them behind would make every parent rmdir fail.
+ Delete,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RemoteWalkEntry {
+ pub path: RemotePath,
+ /// This entry's name and those of its ancestors below the walk root, in
+ /// order. Kept as separate components — never pre-joined — so the local
+ /// side assembles them one at a time under its own path rules.
+ pub components: Vec<String>,
+ pub kind: RemoteFileKind,
+ pub size: u64,
+}
+
+impl RemoteWalkEntry {
+ pub(crate) fn is_directory(&self) -> bool {
+ self.kind == RemoteFileKind::Directory
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct RemoteWalkPlan {
+ /// Parents always precede their children, so a consumer can create as it
+ /// goes — or delete as it goes by walking this in reverse.
+ pub entries: Vec<RemoteWalkEntry>,
+ /// Symlinks and special files deliberately left out (Download mode only),
+ /// counted so the user can be told rather than silently losing them.
+ pub skipped: usize,
+ pub total_bytes: u64,
+}
+
+/// Whether a server-supplied name can be stored as exactly one path component
+/// on THIS machine. Host semantics on purpose: `we\ird` is an ordinary Linux
+/// file name and must stay downloadable there, while on Windows the same name
+/// would split into two components (and `C:x` would grow a drive prefix) and
+/// so is refused here, by name, before anything is written.
+fn name_is_single_host_component(name: &str) -> bool {
+ let mut components = Path::new(name).components();
+ matches!(
+ (components.next(), components.next()),
+ (Some(Component::Normal(_)), None)
+ )
+}
+
+/// Filename semantics of the destination that will materialize a download.
+///
+/// Kept explicit rather than hidden behind `cfg` so macOS and Windows
+/// behavior can be exercised by the ordinary Linux test suite.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum DownloadNameRules {
+ Unix,
+ MacOs,
+ Windows,
+}
+
+impl DownloadNameRules {
+ fn host() -> Self {
+ if cfg!(target_os = "windows") {
+ Self::Windows
+ } else if cfg!(target_os = "macos") {
+ // Standard APFS/HFS+ volumes preserve case but compare names
+ // without it. Conservatively reject those collisions up front;
+ // this can reject a valid tree on an explicitly case-sensitive
+ // macOS volume, but never leaves a partial download on the
+ // overwhelmingly common default.
+ Self::MacOs
+ } else {
+ Self::Unix
+ }
+ }
+
+ fn accepts(self, name: &str) -> bool {
+ match self {
+ Self::Unix | Self::MacOs => name_is_single_host_component(name),
+ Self::Windows => windows_download_name_is_valid(name),
+ }
+ }
+
+ fn collision_key(self, name: &str) -> Option<String> {
+ match self {
+ Self::Unix => None,
+ // A conservative Unicode fold catches the common APFS/HFS+ and
+ // NTFS collision class without making Linux downloads
+ // case-insensitive.
+ Self::MacOs | Self::Windows => {
+ Some(name.chars().flat_map(char::to_uppercase).collect())
+ }
+ }
+ }
+}
+
+fn windows_download_name_is_valid(name: &str) -> bool {
+ if name.is_empty()
+ || matches!(name, "." | "..")
+ || name.ends_with([' ', '.'])
+ || name.encode_utf16().count() > 255
+ || name.chars().any(|ch| {
+ ch <= '\u{1f}' || matches!(ch, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
+ })
+ {
+ return false;
+ }
+
+ // Device names remain reserved even with an extension (for example
+ // `CON.txt`). Windows also recognizes the ISO-8859-1 superscript forms of
+ // COM/LPT 1-3.
+ let stem = name.split('.').next().unwrap_or(name).to_uppercase();
+ if matches!(
+ stem.as_str(),
+ "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
+ ) {
+ return false;
+ }
+ let reserved_port = ["COM", "LPT"].iter().any(|prefix| {
+ stem.strip_prefix(prefix).is_some_and(|suffix| {
+ matches!(
+ suffix,
+ "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
+ )
+ })
+ });
+ !reserved_port
+}
+
+/// Walk `root` into a flat, parents-first plan.
+///
+/// Refusals are total: a listing that comes back truncated, a tree over the
+/// entry budget, or (for downloads) a name the local system cannot store all
+/// fail the whole plan rather than shrinking it. A partial plan silently
+/// executed is exactly the "reported success while omitting data" outcome the
+/// planning step exists to prevent.
+pub(crate) async fn plan_remote_walk(
+ backend: &dyn RemoteFileBackend,
+ root: RemotePath,
+ mode: RemoteWalkMode,
+ progress: &RemoteTransferProgress,
+) -> Result<RemoteWalkPlan, String> {
+ plan_remote_walk_with_rules(backend, root, mode, progress, DownloadNameRules::host()).await
+}
+
+async fn plan_remote_walk_with_rules(
+ backend: &dyn RemoteFileBackend,
+ root: RemotePath,
+ mode: RemoteWalkMode,
+ progress: &RemoteTransferProgress,
+ name_rules: DownloadNameRules,
+) -> Result<RemoteWalkPlan, String> {
+ let mut plan = RemoteWalkPlan::default();
+ let mut pending: VecDeque<(RemotePath, Vec<String>)> = VecDeque::new();
+ if mode == RemoteWalkMode::Download
+ && !root.file_name().is_empty()
+ && !name_rules.accepts(root.file_name())
+ {
+ return Err(cannot_store_locally(&root));
+ }
+ pending.push_back((root, Vec::new()));
+
+ while let Some((dir, prefix)) = pending.pop_front() {
+ // Per-directory rather than per-entry: one round trip is also the
+ // granularity at which a cancel can actually take effect.
+ if progress.is_canceled() {
+ return Err(REMOTE_TRANSFER_CANCELED.to_string());
+ }
+ // Skipped entries cost the same round trip as planned ones, so they
+ // spend the budget too: counting only `entries` would let a tree of
+ // symlinks list millions of items while still claiming to stop at the
+ // advertised limit.
+ let seen = plan.entries.len().saturating_add(plan.skipped);
+ let remaining = REMOTE_WALK_ENTRY_LIMIT.saturating_sub(seen);
+ // One extra so "exactly filled the budget" and "went past it" are
+ // distinguishable without trusting the truncation flag alone.
+ let listing = backend
+ .list_directory(dir, remaining.saturating_add(1))
+ .await?;
+ if listing.truncated || listing.entries.len() > remaining {
+ return Err(format!(
+ "That folder holds more than {REMOTE_WALK_ENTRY_LIMIT} items"
+ ));
+ }
+ let mut materialized_names = HashSet::new();
+ for entry in listing.entries {
+ let mut components = prefix.clone();
+ components.push(entry.name.clone());
+ let materializes =
+ matches!(entry.kind, RemoteFileKind::Directory | RemoteFileKind::File);
+ if mode == RemoteWalkMode::Download && materializes {
+ if !name_rules.accepts(&entry.name) {
+ return Err(cannot_store_locally(&entry.path));
+ }
+ if let Some(key) = name_rules.collision_key(&entry.name) {
+ if !materialized_names.insert(key) {
+ return Err(format!(
+ "The names in {} collide on this computer",
+ entry
+ .path
+ .parent()
+ .unwrap_or_else(|| entry.path.clone())
+ .as_str()
+ ));
+ }
+ }
+ }
+ match entry.kind {
+ RemoteFileKind::Directory => {
+ pending.push_back((entry.path.clone(), components.clone()));
+ plan.entries.push(RemoteWalkEntry {
+ path: entry.path,
+ components,
+ kind: RemoteFileKind::Directory,
+ size: 0,
+ });
+ }
+ RemoteFileKind::File => {
+ let size = entry.size.unwrap_or(0);
+ plan.total_bytes = plan.total_bytes.saturating_add(size);
+ plan.entries.push(RemoteWalkEntry {
+ path: entry.path,
+ components,
+ kind: RemoteFileKind::File,
+ size,
+ });
+ }
+ RemoteFileKind::Symlink | RemoteFileKind::Other => match mode {
+ RemoteWalkMode::Download => plan.skipped += 1,
+ // No local name is ever built for these, so no host name
+ // check: the delete talks only in remote paths.
+ RemoteWalkMode::Delete => plan.entries.push(RemoteWalkEntry {
+ path: entry.path,
+ components,
+ kind: entry.kind,
+ size: 0,
+ }),
+ },
+ }
+ }
+ }
+ Ok(plan)
+}
+
+fn cannot_store_locally(path: &RemotePath) -> String {
+ format!(
+ "The name of {} cannot be used on this computer",
+ path.as_str()
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::termwindow::remote_files::{
+ RemoteDirectoryListing, RemoteFileBytes, RemoteFileEntry,
+ };
+ use std::collections::HashMap;
+ use std::future::Future;
+ use std::pin::Pin;
+
+ type RemoteFuture<T> = Pin<Box<dyn Future<Output = Result<T, String>> + Send + 'static>>;
+
+ /// Serves listings from a map; anything absent is an empty directory.
+ struct MapBackend {
+ directories: HashMap<String, Vec<RemoteFileEntry>>,
+ truncate_all: bool,
+ }
+
+ impl MapBackend {
+ fn new(directories: &[(&str, Vec<RemoteFileEntry>)]) -> Self {
+ Self {
+ directories: directories
+ .iter()
+ .map(|(path, entries)| ((*path).to_string(), entries.clone()))
+ .collect(),
+ truncate_all: false,
+ }
+ }
+ }
+
+ fn entry(parent: &str, name: &str, kind: RemoteFileKind, size: u64) -> RemoteFileEntry {
+ let parent = RemotePath::from_server_absolute(parent).unwrap();
+ RemoteFileEntry {
+ path: parent.join_name(name).unwrap(),
+ name: name.to_string(),
+ kind,
+ size: Some(size),
+ }
+ }
+
+ impl RemoteFileBackend for MapBackend {
+ fn resolve_root(&self, _requested: String) -> RemoteFuture<RemotePath> {
+ Box::pin(async { RemotePath::from_server_absolute("/srv") })
+ }
+
+ fn list_directory(
+ &self,
+ path: RemotePath,
+ limit: usize,
+ ) -> RemoteFuture<RemoteDirectoryListing> {
+ let mut entries = self
+ .directories
+ .get(path.as_str())
+ .cloned()
+ .unwrap_or_default();
+ let mut truncated = self.truncate_all;
+ if entries.len() > limit {
+ entries.truncate(limit);
+ truncated = true;
+ }
+ Box::pin(async move { Ok(RemoteDirectoryListing { entries, truncated }) })
+ }
+
+ fn read_file(&self, _path: RemotePath, _limit: usize) -> RemoteFuture<RemoteFileBytes> {
+ Box::pin(async {
+ Ok(RemoteFileBytes {
+ bytes: Vec::new(),
+ truncated: false,
+ })
+ })
+ }
+ }
+
+ fn root() -> RemotePath {
+ RemotePath::from_server_absolute("/srv/proj").unwrap()
+ }
+
+ #[test]
+ fn a_tree_walks_into_a_parents_first_component_list() {
+ let backend = MapBackend::new(&[
+ (
+ "/srv/proj",
+ vec![
+ entry("/srv/proj", "src", RemoteFileKind::Directory, 0),
+ entry("/srv/proj", "top.txt", RemoteFileKind::File, 5),
+ ],
+ ),
+ (
+ "/srv/proj/src",
+ vec![entry("/srv/proj/src", "lib.rs", RemoteFileKind::File, 7)],
+ ),
+ ]);
+ let progress = RemoteTransferProgress::default();
+ let plan = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect("plan");
+
+ let flattened: Vec<String> = plan
+ .entries
+ .iter()
+ .map(|entry| entry.components.join("/"))
+ .collect();
+ assert_eq!(flattened, vec!["src", "top.txt", "src/lib.rs"]);
+ assert_eq!(plan.total_bytes, 12);
+ let files = plan
+ .entries
+ .iter()
+ .filter(|entry| !entry.is_directory())
+ .count();
+ assert_eq!(files, 2);
+ // Every directory precedes everything inside it.
+ for (index, name) in flattened.iter().enumerate() {
+ if let Some((parent, _)) = name.rsplit_once('/') {
+ let parent_index = flattened.iter().position(|other| other == parent);
+ assert!(
+ parent_index.is_some_and(|parent_index| parent_index < index),
+ "{} must precede {} in {:?}",
+ parent,
+ name,
+ flattened
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn download_mode_skips_links_but_delete_mode_unlinks_them() {
+ let backend = MapBackend::new(&[(
+ "/srv/proj",
+ vec![
+ entry("/srv/proj", "real.txt", RemoteFileKind::File, 1),
+ entry("/srv/proj", "link", RemoteFileKind::Symlink, 0),
+ entry("/srv/proj", "socket", RemoteFileKind::Other, 0),
+ ],
+ )]);
+ let progress = RemoteTransferProgress::default();
+
+ let download = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect("download plan");
+ assert_eq!(download.entries.len(), 1, "only the real file is planned");
+ assert_eq!(download.skipped, 2);
+
+ // A delete that skipped them would strand every parent rmdir.
+ let delete = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Delete,
+ &progress,
+ ))
+ .expect("delete plan");
+ assert_eq!(delete.entries.len(), 3);
+ assert_eq!(delete.skipped, 0);
+ }
+
+ #[test]
+ fn a_truncated_listing_fails_the_whole_plan() {
+ let mut backend = MapBackend::new(&[(
+ "/srv/proj",
+ vec![entry("/srv/proj", "a.txt", RemoteFileKind::File, 1)],
+ )]);
+ backend.truncate_all = true;
+ let progress = RemoteTransferProgress::default();
+ let err = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect_err("an incomplete listing must not become a partial plan");
+ assert!(err.contains("more than"), "{}", err);
+ }
+
+ #[test]
+ fn a_tree_over_the_entry_budget_is_refused() {
+ let wide: Vec<RemoteFileEntry> = (0..REMOTE_WALK_ENTRY_LIMIT + 1)
+ .map(|index| {
+ entry(
+ "/srv/proj",
+ &format!("file-{index}"),
+ RemoteFileKind::File,
+ 1,
+ )
+ })
+ .collect();
+ let backend = MapBackend::new(&[("/srv/proj", wide)]);
+ let progress = RemoteTransferProgress::default();
+ let err = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect_err("over budget must refuse");
+ assert!(
+ err.contains(&REMOTE_WALK_ENTRY_LIMIT.to_string()),
+ "{}",
+ err
+ );
+ }
+
+ #[test]
+ fn skipped_entries_still_consume_the_walk_budget() {
+ // Two directories of symlinks: a download plans none of them, but each
+ // one still cost a round trip, and together they are over the budget.
+ // Counting only what lands in the plan would let this walk run for as
+ // long as the tree is wide while still claiming a 10,000-item stop.
+ let half = REMOTE_WALK_ENTRY_LIMIT / 2;
+ let links = |parent: &str| -> Vec<RemoteFileEntry> {
+ (0..half)
+ .map(|index| entry(parent, &format!("link-{index}"), RemoteFileKind::Symlink, 0))
+ .collect()
+ };
+ let backend = MapBackend::new(&[
+ (
+ "/srv/proj",
+ vec![
+ entry("/srv/proj", "a", RemoteFileKind::Directory, 0),
+ entry("/srv/proj", "b", RemoteFileKind::Directory, 0),
+ ],
+ ),
+ ("/srv/proj/a", links("/srv/proj/a")),
+ ("/srv/proj/b", links("/srv/proj/b")),
+ ]);
+ let progress = RemoteTransferProgress::default();
+ let err = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect_err("skipped entries must spend the budget too");
+ assert!(
+ err.contains(&REMOTE_WALK_ENTRY_LIMIT.to_string()),
+ "{}",
+ err
+ );
+ }
+
+ #[test]
+ fn a_canceled_walk_stops_before_listing() {
+ let backend = MapBackend::new(&[(
+ "/srv/proj",
+ vec![entry("/srv/proj", "a.txt", RemoteFileKind::File, 1)],
+ )]);
+ let progress = RemoteTransferProgress::default();
+ progress.request_cancel();
+ let err = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect_err("canceled");
+ assert_eq!(err, REMOTE_TRANSFER_CANCELED);
+ }
+
+ /// Host semantics, pinned for the Unix half: a backslash is an ordinary
+ /// file name character here and must stay downloadable. The Windows
+ /// rejection branch of `name_is_single_host_component` cannot execute on
+ /// this platform — it is covered by the cross-compile check instead.
+ #[cfg(unix)]
+ #[test]
+ fn a_backslash_name_stays_downloadable_on_unix() {
+ let backend = MapBackend::new(&[(
+ "/srv/proj",
+ vec![entry("/srv/proj", r"we\ird.txt", RemoteFileKind::File, 1)],
+ )]);
+ let progress = RemoteTransferProgress::default();
+ let plan = smol::block_on(plan_remote_walk(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &progress,
+ ))
+ .expect("host semantics accept it");
+ assert_eq!(plan.entries.len(), 1);
+ assert!(name_is_single_host_component(r"we\ird.txt"));
+ }
+
+ #[test]
+ fn windows_rejects_names_that_cannot_be_created() {
+ for name in [
+ "report?.txt",
+ "foo:bar",
+ "bad<name",
+ "bad|name",
+ "trailing.",
+ "trailing ",
+ "CON",
+ "con.txt",
+ "AUX.log",
+ "COM1",
+ "LPT9.data",
+ "COM¹",
+ "CONIN$",
+ ] {
+ assert!(
+ !windows_download_name_is_valid(name),
+ "{:?} must be rejected",
+ name
+ );
+ }
+ for name in ["report.txt", "console.txt", "COM10", "LPT0", "résumé.md"] {
+ assert!(
+ windows_download_name_is_valid(name),
+ "{:?} should remain usable",
+ name
+ );
+ }
+ }
+
+ #[test]
+ fn case_insensitive_targets_reject_collisions_before_download() {
+ let backend = MapBackend::new(&[(
+ "/srv/proj",
+ vec![
+ entry("/srv/proj", "Readme.md", RemoteFileKind::File, 1),
+ entry("/srv/proj", "README.MD", RemoteFileKind::File, 1),
+ ],
+ )]);
+
+ for rules in [DownloadNameRules::MacOs, DownloadNameRules::Windows] {
+ let err = smol::block_on(plan_remote_walk_with_rules(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &RemoteTransferProgress::default(),
+ rules,
+ ))
+ .expect_err("case variants cannot share a default macOS or Windows directory");
+ assert!(err.contains("collide"), "{}", err);
+ }
+
+ let unix = smol::block_on(plan_remote_walk_with_rules(
+ &backend,
+ root(),
+ RemoteWalkMode::Download,
+ &RemoteTransferProgress::default(),
+ DownloadNameRules::Unix,
+ ))
+ .expect("Unix keeps case-distinct names");
+ assert_eq!(unix.entries.len(), 2);
+ }
+
+ #[test]
+ fn windows_validates_the_download_root_before_listing() {
+ let backend = MapBackend::new(&[]);
+ let progress = RemoteTransferProgress::default();
+ let root = RemotePath::from_server_absolute("/srv/CON").unwrap();
+ let err = smol::block_on(plan_remote_walk_with_rules(
+ &backend,
+ root,
+ RemoteWalkMode::Download,
+ &progress,
+ DownloadNameRules::Windows,
+ ))
+ .expect_err("a reserved root name must fail before destination creation");
+ assert!(err.contains("/srv/CON"), "{}", err);
+ }
+}
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index 77b74d22..3a3b9eb4 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -572,6 +572,11 @@ impl crate::TermWindow {
// Clear out UI item positions; we'll rebuild these as we render
self.ui_items.clear();
+ // The right sidebar is part of the local window geometry. A deferred
+ // content-view resize or an asynchronous remote resync can leave the
+ // active mux tab at its old full width; heal that before any pane
+ // positions, hit targets or quads are derived from it.
+ self.reconcile_active_mux_tab_size_before_paint();
self.sync_pane_font_sizes();
let panes = self.get_panes_to_render();
let focused = self.focused.is_some();
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index 992ecb13..5fd756bc 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -36,6 +36,72 @@ use wezterm_term::{Line, StableRowIndex};
use window::color::LinearRgba;
use window::MouseEventKind as WMEK;
+fn clamp_pane_horizontal_span(
+ pane_left: f32,
+ candidate_right: f32,
+ viewport_right: f32,
+) -> (f32, f32) {
+ let viewport_right = viewport_right.max(0.0);
+ if viewport_right <= 0.0 {
+ return (0.0, 0.0);
+ }
+
+ // Leave a one-pixel span even for corrupt/stale geometry whose left edge
+ // is already beyond the viewport. Normal pane layouts never need this,
+ // but it keeps every caller's rectangle valid without allowing it to
+ // cross into the sidebar.
+ let pane_left = pane_left.max(0.0).min((viewport_right - 1.0).max(0.0));
+ let pane_right = candidate_right.max(pane_left + 1.0).min(viewport_right);
+ (pane_left, (pane_right - pane_left).max(0.0))
+}
+
+fn visible_render_columns(
+ requested_cols: usize,
+ content_left: f32,
+ viewport_right: f32,
+ cell_width: f32,
+) -> usize {
+ if requested_cols == 0 || cell_width <= 0.0 {
+ return 0;
+ }
+ let visible_width = (viewport_right - content_left).max(0.0);
+ requested_cols.min((visible_width / cell_width).floor().max(0.0) as usize)
+}
+
+#[cfg(test)]
+mod pane_geometry_tests {
+ use super::{clamp_pane_horizontal_span, visible_render_columns};
+
+ #[test]
+ fn stale_pane_geometry_stops_at_the_sidebar_edge() {
+ let (left, width) = clamp_pane_horizontal_span(354.0, 1_210.0, 802.0);
+ assert_eq!(left, 354.0);
+ assert_eq!(left + width, 802.0);
+ }
+
+ #[test]
+ fn valid_split_spans_still_meet_without_a_gap() {
+ let (left_x, left_width) = clamp_pane_horizontal_span(0.0, 354.0, 802.0);
+ let (right_x, right_width) = clamp_pane_horizontal_span(354.0, 802.0, 802.0);
+ assert_eq!(left_x + left_width, right_x);
+ assert_eq!(right_x + right_width, 802.0);
+ }
+
+ #[test]
+ fn a_pane_starting_beyond_the_viewport_cannot_escape_it() {
+ let (left, width) = clamp_pane_horizontal_span(900.0, 1_210.0, 802.0);
+ assert!(left >= 0.0);
+ assert_eq!(left + width, 802.0);
+ }
+
+ #[test]
+ fn terminal_columns_are_clipped_while_old_geometry_is_being_repaired() {
+ assert_eq!(visible_render_columns(100, 354.0, 802.0, 10.0), 44);
+ assert_eq!(visible_render_columns(30, 354.0, 802.0, 10.0), 30);
+ assert_eq!(visible_render_columns(100, 900.0, 802.0, 10.0), 0);
+ }
+}
+
/// Milliseconds since the mux server last responded, when the pane's
/// connection looks unhealthy (a reconnect is pending or in progress).
/// None for local panes and for healthy client panes.
@@ -63,6 +129,14 @@ impl crate::TermWindow {
)
}
+ pub(crate) fn terminal_viewport_right(&self) -> f32 {
+ let border = self.get_os_border();
+ self.dimensions
+ .pixel_width
+ .saturating_sub(border.right.get() as usize)
+ .saturating_sub(self.right_sidebar_width()) as f32
+ }
+
fn pane_content_origin(&self, pos: &PositionedPane) -> anyhow::Result<(f32, f32)> {
let tab_bar_height = if self.show_tab_bar {
self.tab_bar_pixel_height()
@@ -102,16 +176,16 @@ impl crate::TermWindow {
content_pane_x - cell_w / 2.0
};
let is_rightmost = pos.left + pos.width >= self.terminal_size.cols;
- let right = if is_rightmost {
- let border = self.get_os_border();
- (self.dimensions.pixel_width as f32
- - border.right.get() as f32
- - self.right_sidebar_width() as f32)
- .max(content_pane_right)
+ let candidate_right = if is_rightmost {
+ self.terminal_viewport_right()
} else {
content_pane_right + cell_w / 2.0
};
- Ok((pane_x, (right - pane_x).max(1.0)))
+ Ok(clamp_pane_horizontal_span(
+ pane_x,
+ candidate_right,
+ self.terminal_viewport_right(),
+ ))
}
pub(crate) fn pane_frame_rect(&self, pos: &PositionedPane) -> anyhow::Result<RectF> {
@@ -1057,7 +1131,19 @@ impl crate::TermWindow {
let (fonts, metrics) = self.pane_font_resources(pane_font_scale)?;
(Some(fonts), metrics)
};
- let render_dims = dims;
+ let content_left = padding_left
+ + border.left.get() as f32
+ + pos.left as f32 * global_render_metrics.cell_size.width as f32;
+ let visible_cols = visible_render_columns(
+ dims.cols,
+ content_left,
+ self.terminal_viewport_right(),
+ pane_render_metrics.cell_size.width.max(1) as f32,
+ );
+ let mut render_dims = dims;
+ render_dims.cols = visible_cols;
+ render_dims.pixel_width =
+ visible_cols.saturating_mul(pane_render_metrics.cell_size.width.max(1) as usize);
let gl_state = self.render_state.as_ref().unwrap();
@@ -1112,15 +1198,17 @@ impl crate::TermWindow {
cell_height,
)
};
+ let candidate_right = if pos.left + pos.width >= self.terminal_size.cols as usize {
+ self.terminal_viewport_right()
+ } else {
+ x + (pos.width as f32 * cell_width) + width_delta
+ };
+ let (x, width) =
+ clamp_pane_horizontal_span(x, candidate_right, self.terminal_viewport_right());
euclid::rect(
x,
y,
- // Go all the way to the right edge if we're right-most
- if pos.left + pos.width >= self.terminal_size.cols as usize {
- self.dimensions.pixel_width as f32 - x
- } else {
- (pos.width as f32 * cell_width) + width_delta
- },
+ width,
// Go all the way to the bottom if we're bottom-most
if pos.top + pos.height >= self.terminal_size.rows as usize {
self.dimensions.pixel_height as f32 - y
@@ -1328,9 +1416,7 @@ impl crate::TermWindow {
error: Option<anyhow::Error>,
}
- let left_pixel_x = padding_left
- + border.left.get() as f32
- + (pos.left as f32 * global_render_metrics.cell_size.width as f32);
+ let left_pixel_x = content_left;
let pane_top_pixel_y = top_pixel_y
+ (pos.top as f32 * global_render_metrics.cell_size.height as f32)
+ pane_nav_height as f32;
@@ -1631,15 +1717,21 @@ impl crate::TermWindow {
)
};
- let background_rect = euclid::rect(
+ let candidate_background_right = if pos.left + pos.width >= self.terminal_size.cols as usize
+ {
+ self.terminal_viewport_right()
+ } else {
+ x + (pos.width as f32 * cell_width) + width_delta
+ };
+ let (background_x, background_width) = clamp_pane_horizontal_span(
x,
+ candidate_background_right,
+ self.terminal_viewport_right(),
+ );
+ let background_rect = euclid::rect(
+ background_x,
y,
- // Go all the way to the right edge if we're right-most
- if pos.left + pos.width >= self.terminal_size.cols as usize {
- self.dimensions.pixel_width as f32 - x
- } else {
- (pos.width as f32 * cell_width) + width_delta
- },
+ background_width,
// Go all the way to the bottom if we're bottom-most
if pos.top + pos.height >= self.terminal_size.rows as usize {
self.dimensions.pixel_height as f32 - y
@@ -1649,11 +1741,17 @@ impl crate::TermWindow {
);
// Bounds for the terminal cells
+ let content_x = padding_left + border.left.get() as f32 - (cell_width / 2.0)
+ + (pos.left as f32 * cell_width);
+ let (content_x, content_width) = clamp_pane_horizontal_span(
+ content_x,
+ content_x + pos.width as f32 * cell_width,
+ self.terminal_viewport_right(),
+ );
let content_rect = euclid::rect(
- padding_left + border.left.get() as f32 - (cell_width / 2.0)
- + (pos.left as f32 * cell_width),
+ content_x,
top_pixel_y + (pos.top as f32 * cell_height) - (cell_height / 2.0),
- pos.width as f32 * cell_width,
+ content_width,
pos.height as f32 * cell_height,
);
diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs
index cd08ec51..e1da69c1 100644
--- a/wezterm-gui/src/termwindow/resize.rs
+++ b/wezterm-gui/src/termwindow/resize.rs
@@ -66,10 +66,13 @@ impl super::TermWindow {
);
}
- fn apply_font_scales_to_mux_window_panes(&mut self, font_scales: HashMap<PaneId, Option<f64>>) {
+ fn apply_font_scales_to_mux_window_panes(
+ &mut self,
+ font_scales: HashMap<PaneId, Option<f64>>,
+ ) -> bool {
let mux = Mux::get();
let Some(mux_window) = mux.get_window(self.mux_window_id) else {
- return;
+ return false;
};
let mut changed = false;
@@ -89,10 +92,9 @@ impl super::TermWindow {
if !changed {
// Called per TabAddedToWindow during resyncs; skip the cache
// flush when nothing actually changed.
- return;
+ return false;
}
- self.sync_pane_font_sizes();
self.quad_generation += 1;
self.shape_generation += 1;
self.pane_font_cache.borrow_mut().clear();
@@ -105,20 +107,30 @@ impl super::TermWindow {
if let Some(window) = self.window.as_ref() {
window.invalidate();
}
+ true
}
- pub(crate) fn apply_workspace_thread_font_scales(&mut self) {
+ /// Restore the destination thread's per-pane scale state without resizing
+ /// any pane. Adoption paths use this to stage every geometry input before
+ /// issuing their single, final pane-size synchronization.
+ pub(crate) fn stage_workspace_thread_font_scales(&mut self) -> bool {
let mux = Mux::get();
let Some(window) = mux.get_window(self.mux_window_id) else {
- return;
+ return false;
};
let Some(font_scales) = crate::workspace_threads::workspace_pane_font_scales(
window.get_workspace(),
self.mux_window_id,
) else {
- return;
+ return false;
};
- self.apply_font_scales_to_mux_window_panes(font_scales);
+ self.apply_font_scales_to_mux_window_panes(font_scales)
+ }
+
+ pub(crate) fn apply_workspace_thread_font_scales(&mut self) {
+ if self.stage_workspace_thread_font_scales() {
+ self.sync_pane_font_sizes();
+ }
}
pub(crate) fn apply_native_terminal_settings(&mut self) {
@@ -359,6 +371,40 @@ impl super::TermWindow {
self.force_sync_active_mux_tab_pane_sizes();
}
+ /// Repair a missed/deferred sidebar reflow before terminal geometry is
+ /// consumed by paint. Most size changes arrive through
+ /// `apply_dimensions`, but a content-view handoff or remote mux resync can
+ /// briefly leave the active tab carrying the prior full-width geometry.
+ ///
+ /// The comparison is important: `Tab::resize` emits `TabResized`, which a
+ /// client domain answers with a resync. Only repairing a real mismatch
+ /// keeps this recovery path convergent rather than creating a resize loop.
+ pub(crate) fn reconcile_active_mux_tab_size_before_paint(&mut self) {
+ if self.content_view_foreground() {
+ return;
+ }
+
+ let mux = Mux::get();
+ let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) else {
+ return;
+ };
+ if tab.get_size() == self.terminal_size {
+ return;
+ }
+
+ log::debug!(
+ "repairing active tab {} geometry before paint: {:?} -> {:?}",
+ tab.tab_id(),
+ tab.get_size(),
+ self.terminal_size
+ );
+ if !tab.resize(self.terminal_size) {
+ return;
+ }
+ self.reapply_collapsed_panes_for_window();
+ self.force_sync_active_mux_tab_pane_sizes();
+ }
+
pub fn resize(
&mut self,
dimensions: Dimensions,
diff --git a/wezterm-gui/src/termwindow/transfer_walk.rs b/wezterm-gui/src/termwindow/transfer_walk.rs
index 3e1791c7..772e79ca 100644
--- a/wezterm-gui/src/termwindow/transfer_walk.rs
+++ b/wezterm-gui/src/termwindow/transfer_walk.rs
@@ -288,6 +288,16 @@ mod unix_root {
}
}
+ /// Create a directory only if the final name is completely vacant.
+ pub(crate) fn create_dir_exclusive(&self, relative: &Path) -> Result<()> {
+ let (parent, name) = self.parent_of(relative)?;
+ if unsafe { libc::mkdirat(parent.as_raw_fd(), name.as_ptr(), 0o777) } == 0 {
+ Ok(())
+ } else {
+ Err(Error::last_os_error())
+ }
+ }
+
/// Create a new file, failing if anything already holds that name —
/// including a symlink, which is never followed.
pub(crate) fn create_file(&self, relative: &Path) -> Result<File> {
@@ -341,6 +351,16 @@ mod unix_root {
}
}
+ pub(crate) fn remove_dir(&self, relative: &Path) -> Result<()> {
+ let (parent, name) = self.parent_of(relative)?;
+ if unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), libc::AT_REMOVEDIR) } == 0
+ {
+ Ok(())
+ } else {
+ Err(Error::last_os_error())
+ }
+ }
+
pub(crate) fn join(&self, relative: &Path) -> PathBuf {
self.path.join(relative)
}
@@ -349,10 +369,17 @@ mod unix_root {
/// Path-based stand-in for platforms without `openat`.
///
-/// Present so the crate builds everywhere; the local copy that uses it is
-/// reachable only on X11 and macOS, because the Windows and Wayland backends
-/// report no drop position. If that ever changes, this needs the same
-/// handle-based treatment before it can be trusted.
+/// Reachable on Windows since remote FOLDER downloads: they start from a
+/// context menu, not from the drag-drop path whose missing drop position kept
+/// this module dead there. Weaker than the unix version — an intermediate
+/// directory component that is a symlink is followed rather than refused —
+/// but the folder-download use keeps the risk small: its whole tree starts
+/// from a freshly, exclusively created directory, and files are created with
+/// `create_new`, which fails if anything (a link included) wears the name.
+/// The local drag-drop copy remains unreachable here (Windows and Wayland
+/// report no drop position); if that changes, this needs the same
+/// handle-based treatment before it can be trusted for arbitrary
+/// destinations.
#[cfg(not(unix))]
mod portable_root {
use super::DestinationRoot;
@@ -401,6 +428,11 @@ mod portable_root {
}
}
+ pub(crate) fn create_dir_exclusive(&self, relative: &Path) -> Result<()> {
+ checked(relative)?;
+ fs::create_dir(self.join(relative))
+ }
+
pub(crate) fn create_file(&self, relative: &Path) -> Result<File> {
checked(relative)?;
fs::OpenOptions::new()
@@ -420,6 +452,11 @@ mod portable_root {
fs::remove_file(self.join(relative))
}
+ pub(crate) fn remove_dir(&self, relative: &Path) -> Result<()> {
+ checked(relative)?;
+ fs::remove_dir(self.join(relative))
+ }
+
pub(crate) fn join(&self, relative: &Path) -> PathBuf {
self.path.join(relative)
}
@@ -551,10 +588,6 @@ pub(crate) struct TransferPreflight {
}
impl TransferPreflight {
- pub(crate) fn entry_count(&self) -> usize {
- self.plans.iter().map(|(_, plan)| plan.entries.len()).sum()
- }
-
/// What to tell the user about things the walk deliberately left out.
/// Silence here would mean reporting success while quietly omitting data.
pub(crate) fn omission_note(&self) -> Option<String> {
@@ -618,7 +651,7 @@ mod tests {
let plan = plan_transfer(&src).unwrap();
let names = relatives(&plan);
- assert!(names.contains(&"proj".to_string()), "{names:?}");
+ assert!(names.contains(&"proj".to_string()), "{:?}", names);
assert_eq!(plan.file_count(), 3);
assert_eq!(plan.total_bytes, 8);
@@ -629,7 +662,10 @@ mod tests {
let parent_index = names.iter().position(|other| other == parent);
assert!(
parent_index.is_some_and(|parent_index| parent_index < index),
- "{parent} must precede {name} in {names:?}"
+ "{} must precede {} in {:?}",
+ parent,
+ name,
+ names
);
}
}
diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rs
index dbac7395..95b15e8b 100644
--- a/wezterm-gui/src/termwindow/ui/context_menu.rs
+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs
@@ -221,8 +221,50 @@ impl crate::TermWindow {
) => {
self.toggle_workspace_sidebar_status_filter(status);
}
- crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path) => {
- self.download_right_sidebar_remote_file(path);
+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile {
+ path,
+ origin,
+ } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.download_right_sidebar_remote_file(path);
+ }
+ }
+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFolder {
+ path,
+ anchor,
+ origin,
+ } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.download_right_sidebar_remote_folder(path, anchor);
+ }
+ }
+ crate::termwindow::ContextMenuApplicationAction::DeleteRemoteEntry {
+ path,
+ anchor,
+ origin,
+ } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.delete_right_sidebar_remote_entry(path, anchor);
+ }
+ }
+ crate::termwindow::ContextMenuApplicationAction::RenameRemoteEntry { path, origin } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.start_sidebar_remote_file_rename(path);
+ }
+ }
+ crate::termwindow::ContextMenuApplicationAction::NewRemoteFolder { parent, origin } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.create_right_sidebar_remote_folder(parent);
+ }
+ }
+ crate::termwindow::ContextMenuApplicationAction::RetryRemoteTransfer { id, anchor } => {
+ self.retry_remote_transfer(id, anchor);
+ }
+ crate::termwindow::ContextMenuApplicationAction::DismissRemoteTransfer(id) => {
+ self.remove_remote_transfer_row(id);
+ }
+ crate::termwindow::ContextMenuApplicationAction::ResolveRemoteConfirm(proceed) => {
+ self.resolve_pending_remote_confirm(proceed);
}
crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewSelection => {
self.copy_right_sidebar_selected_file_preview_text();
@@ -349,10 +391,17 @@ impl crate::TermWindow {
/// immediately *before* a chosen action — cancelling there would swallow
/// the very choice being made.
pub(crate) fn dismiss_fallback_context_menu(&mut self) {
- // A copy waiting on an answer takes dismissal as "no". Leaving the
+ self.context_menu_was_dismissed();
+ self.close_fallback_context_menu();
+ }
+
+ /// Unified tail for native and fallback menus that closed without leaving
+ /// an actionable pending choice behind.
+ pub(crate) fn context_menu_was_dismissed(&mut self) {
+ // Anything waiting on an answer takes dismissal as "no". Leaving the
// plan behind would keep it alive with no way to reach it again.
self.cancel_pending_local_copy();
- self.close_fallback_context_menu();
+ self.cancel_pending_remote_confirm();
}
pub(crate) fn close_fallback_context_menu(&mut self) {
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index aba4d731..d8b70a64 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -8,11 +8,15 @@ use crate::markdown_editor::{
};
use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
use crate::termwindow::remote_files::{
- invalidate_remote_connection, invalidate_remote_connection_if_dead, remote_connection_key,
- remote_connection_manager, reserve_download_path, RemoteAcquireError, RemoteFileBytes,
+ download_name_candidates, invalidate_remote_connection, invalidate_remote_connection_if_dead,
+ local_path_is_occupied, remote_connection_key, remote_connection_manager,
+ reserve_download_directory, reserve_download_path, RemoteAcquireError, RemoteFileBytes,
RemoteFileKind, RemoteFileRow, RemoteFilesEffect, RemoteFilesEvent, RemoteFilesPhase,
- RemotePath, RemoteTransfer, RemoteTransferKind, RemoteTransferProgress, RemoteTransferSource,
- RemoteTransferStatus, REMOTE_TRANSFER_CANCELED,
+ RemoteOperationOrigin, RemotePath, RemoteTransfer, RemoteTransferKind, RemoteTransferProgress,
+ RemoteTransferSource, RemoteTransferStatus, TransferFailure, REMOTE_TRANSFER_CANCELED,
+};
+use crate::termwindow::remote_walk::{
+ plan_remote_walk, RemoteWalkEntry, RemoteWalkMode, RemoteWalkPlan,
};
use crate::termwindow::transfer_walk::{
apply_conflict_choice, destination_escapes_source, destination_stays_within, is_same_file,
@@ -29,12 +33,13 @@ use crate::termwindow::ui::tokens::{
WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,
};
use crate::termwindow::{
- NoteEditorCommand, PendingLocalCopy, RightSidebarFileCharBag, RightSidebarFileField,
- RightSidebarFileIndex, RightSidebarFileIndexEntry, RightSidebarFileIndexStatus,
- RightSidebarFilePreviewImage, RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,
- RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSliceCacheKey,
- RightSidebarFilePreviewSliceCacheValue, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,
- RightSidebarFileView, RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,
+ NoteEditorCommand, PendingLocalCopy, PendingRemoteConfirm, RightSidebarFileCharBag,
+ RightSidebarFileField, RightSidebarFileIndex, RightSidebarFileIndexEntry,
+ RightSidebarFileIndexStatus, RightSidebarFilePreviewImage, RightSidebarFilePreviewLine,
+ RightSidebarFilePreviewSelection, RightSidebarFilePreviewSelectionPoint,
+ RightSidebarFilePreviewSliceCacheKey, RightSidebarFilePreviewSliceCacheValue,
+ RightSidebarFilePreviewSpan, RightSidebarFileTreeRow, RightSidebarFileView,
+ RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,
RightSidebarNoteImageSource, RightSidebarNoteTableLayout, RightSidebarNoteView,
RightSidebarOpenWithCacheEntry, RightSidebarSnippetField, RightSidebarSnippetView,
TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup,
@@ -44,6 +49,7 @@ use crate::utilsprites::RenderMetrics;
use crate::workspace_threads;
use anyhow::Context;
use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource, KeyAssignment};
+use mux::pane::PaneId;
use mux::Mux;
use std::borrow::Cow;
use std::cmp::Ordering;
@@ -156,8 +162,36 @@ const FILE_PREVIEW_HEADER_HEIGHT: usize = 64;
/// oldest finished ones. The strip eats into the tree, so it stays small;
/// running transfers are never dropped, however many there are.
const REMOTE_TRANSFER_STRIP_MAX: usize = 3;
-/// Thickness of the progress line under a running transfer's label.
-const REMOTE_TRANSFER_PROGRESS_HEIGHT: usize = 3;
+/// Thickness of the progress track under a running transfer's label. Five
+/// design pixels remains compact while being visible at a glance.
+const REMOTE_TRANSFER_PROGRESS_HEIGHT: usize = 5;
+static REMOTE_TRANSFER_ANIMATION_EPOCH: OnceLock<Instant> = OnceLock::new();
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum RemoteLeaseFailureDisposition {
+ FailedConnectionInstalled,
+ ReplacementForSameTarget,
+ ReplacementForDifferentTarget,
+ NoLease,
+}
+
+fn remote_lease_failure_disposition(
+ current: Option<(&str, u64)>,
+ failed_key: &str,
+ failed_id: u64,
+) -> RemoteLeaseFailureDisposition {
+ match current {
+ Some((key, id)) if key == failed_key && id == failed_id => {
+ RemoteLeaseFailureDisposition::FailedConnectionInstalled
+ }
+ Some((key, _)) if key == failed_key => {
+ RemoteLeaseFailureDisposition::ReplacementForSameTarget
+ }
+ Some(_) => RemoteLeaseFailureDisposition::ReplacementForDifferentTarget,
+ None => RemoteLeaseFailureDisposition::NoLease,
+ }
+}
+
const FILE_PREVIEW_MAX_BYTES: usize = 256 * 1024;
const FILE_PREVIEW_TRUNCATED_LABEL: &str = "Preview truncated to 256 KiB";
const FILE_PREVIEW_IMAGE_MAX_BYTES: usize = 16 * 1024 * 1024;
@@ -4667,6 +4701,10 @@ impl crate::TermWindow {
UIItemType::RightSidebarFileFilter => Some(&self.right_sidebar_file_filter),
UIItemType::RightSidebarSnippetSearch => Some(&self.right_sidebar_snippet_search),
UIItemType::RightSidebarSnippetTitle => Some(&self.right_sidebar_snippet_title),
+ UIItemType::RightSidebarFileRow(path) => self.sidebar_file_rename_input(path),
+ UIItemType::RightSidebarRemoteFileRow(path) => {
+ self.sidebar_remote_file_rename_input(path)
+ }
_ => None,
}
}
@@ -4704,7 +4742,7 @@ impl crate::TermWindow {
Some(best_idx)
}
- fn right_sidebar_input_for_item_mut(
+ pub(crate) fn right_sidebar_input_for_item_mut(
&mut self,
item_type: &UIItemType,
) -> Option<&mut TextInputState> {
@@ -4712,6 +4750,23 @@ impl crate::TermWindow {
UIItemType::RightSidebarFileFilter => Some(&mut self.right_sidebar_file_filter),
UIItemType::RightSidebarSnippetSearch => Some(&mut self.right_sidebar_snippet_search),
UIItemType::RightSidebarSnippetTitle => Some(&mut self.right_sidebar_snippet_title),
+ UIItemType::RightSidebarFileRow(path) => {
+ let rename = self.inline_tab_rename.as_mut()?;
+ matches!(
+ &rename.target,
+ crate::termwindow::InlineTabRenameTarget::File(current) if current == path
+ )
+ .then_some(&mut rename.input)
+ }
+ UIItemType::RightSidebarRemoteFileRow(path) => {
+ let rename = self.inline_tab_rename.as_mut()?;
+ matches!(
+ &rename.target,
+ crate::termwindow::InlineTabRenameTarget::RemoteFile { path: current, .. }
+ if current == path
+ )
+ .then_some(&mut rename.input)
+ }
_ => None,
}
}
@@ -9337,7 +9392,7 @@ impl crate::TermWindow {
if running { foreground } else { muted_fg },
)?;
- if let (true, Some(fraction)) = (running, fraction) {
+ if running {
let bar_height = self.ui_px(REMOTE_TRANSFER_PROGRESS_HEIGHT).max(1);
let bar_y = y + row_metrics.row_height.saturating_sub(bar_height);
let radius = (bar_height as f32) / 2.0;
@@ -9350,19 +9405,38 @@ impl crate::TermWindow {
text_width as f32,
bar_height as f32,
),
- chrome.sidebar_button_hover_bg,
+ chrome.separator.mul_alpha(0.72),
radius,
)
.context("remote transfer progress track")?;
- let filled = (text_width as f32 * fraction).max(radius * 2.0);
- self.fill_rounded_rectangle(
- layers,
- 1,
- euclid::rect(text_x as f32, bar_y as f32, filled, bar_height as f32),
- chrome.selected_bg,
- radius,
- )
- .context("remote transfer progress fill")?;
+ let (fill_x, filled) = match fraction {
+ Some(fraction) => (
+ text_x as f32,
+ (text_width as f32 * fraction).max(radius * 2.0),
+ ),
+ None => {
+ // While a remote tree is still being enumerated there is
+ // no honest denominator. Show a moving segment instead of
+ // hiding the bar and making the operation look stuck.
+ let epoch = REMOTE_TRANSFER_ANIMATION_EPOCH.get_or_init(Instant::now);
+ let phase = epoch.elapsed().as_secs_f32() % 1.2 / 1.2;
+ let segment = (text_width as f32 * 0.3).max(radius * 2.0);
+ let raw_start = phase * (text_width as f32 + segment) - segment;
+ let start = raw_start.max(0.0);
+ let end = (raw_start + segment).min(text_width as f32);
+ (text_x as f32 + start, (end - start).max(0.0))
+ }
+ };
+ if filled > 0.0 {
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(fill_x, bar_y as f32, filled, bar_height as f32),
+ chrome.selected_bg,
+ radius,
+ )
+ .context("remote transfer progress fill")?;
+ }
// A running transfer must keep repainting even when nothing else
// changes, or the percentage freezes until the next event.
self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(100)));
@@ -9482,24 +9556,50 @@ impl crate::TermWindow {
}
}
let text_x = icon_x + row_metrics.icon_size + row_metrics.icon_gap;
- self.paint_sidebar_text(
- layers,
- ui_font,
- ui_metrics,
- &row.entry.name,
- text_x,
- y + row_metrics
- .row_height
- .saturating_sub(ui_metrics.cell_size.height as usize)
- / 2,
- x.saturating_add(width)
- .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET)),
- if row.entry.is_directory() || is_selected {
- foreground
- } else {
- muted_fg
- },
- )
+ let text_width = x
+ .saturating_add(width)
+ .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET));
+ if let Some(input) = self
+ .sidebar_remote_file_rename_input(&row.entry.path)
+ .cloned()
+ {
+ self.paint_snippet_text_box(
+ layers,
+ 1,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ text_x,
+ y + self.ui_px(2),
+ text_width,
+ row_metrics.row_height.saturating_sub(self.ui_px(4)),
+ None,
+ "",
+ &input,
+ true,
+ UIItemType::RightSidebarRemoteFileRow(row.entry.path.clone()),
+ false,
+ )
+ } else {
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ &row.entry.name,
+ text_x,
+ y + row_metrics
+ .row_height
+ .saturating_sub(ui_metrics.cell_size.height as usize)
+ / 2,
+ text_width,
+ if row.entry.is_directory() || is_selected {
+ foreground
+ } else {
+ muted_fg
+ },
+ )
+ }
}
fn active_remote_project_for_files(
@@ -9683,6 +9783,20 @@ impl crate::TermWindow {
drop(lease);
return;
}
+ if term_window
+ .current_remote_connection_key()
+ .as_deref()
+ != Some(lease.connection_key())
+ {
+ drop(lease);
+ term_window
+ .reconnect_remote_files_after_connection_change(
+ generation,
+ "Remote Files configuration changed while connecting"
+ .to_string(),
+ );
+ return;
+ }
term_window.right_sidebar_remote_files_lease = Some(lease);
let effects = term_window.right_sidebar_remote_files.transition(
RemoteFilesEvent::Connected {
@@ -9731,6 +9845,16 @@ impl crate::TermWindow {
);
continue;
};
+ if self.current_remote_connection_key().as_deref()
+ != Some(lease.connection_key())
+ {
+ self.reconnect_remote_files_after_connection_change(
+ generation,
+ "Remote Files configuration changed before loading the folder"
+ .to_string(),
+ );
+ continue;
+ }
let Some(operation_lease) = lease.operation_lease() else {
self.right_sidebar_remote_files_lease.take();
self.close_right_sidebar_file_preview();
@@ -9765,6 +9889,7 @@ impl crate::TermWindow {
.current_source_key()
.as_deref()
!= Some(source_key.as_str())
+ || term_window.right_sidebar_remote_files.generation != generation
{
return;
}
@@ -9775,7 +9900,35 @@ impl crate::TermWindow {
listing,
},
Err(message) if connection_died => {
- term_window.right_sidebar_remote_files_lease.take();
+ match term_window.remote_files_lease_failure_disposition(
+ &connection_key,
+ connection_id,
+ ) {
+ RemoteLeaseFailureDisposition::ReplacementForSameTarget => {
+ term_window.apply_right_sidebar_remote_files_effects(
+ vec![RemoteFilesEffect::ListDirectory {
+ generation,
+ source_key,
+ path,
+ limit,
+ }],
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ RemoteLeaseFailureDisposition::ReplacementForDifferentTarget => {
+ term_window
+ .reconnect_remote_files_after_connection_change(
+ generation,
+ "Remote Files connection changed while loading the folder"
+ .to_string(),
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ RemoteLeaseFailureDisposition::FailedConnectionInstalled
+ | RemoteLeaseFailureDisposition::NoLease => {}
+ }
term_window.close_right_sidebar_file_preview();
RemoteFilesEvent::ConnectionFailed {
generation,
@@ -9790,6 +9943,9 @@ impl crate::TermWindow {
};
let effects = term_window.right_sidebar_remote_files.transition(event);
term_window.apply_right_sidebar_remote_files_effects(effects);
+ // A just-created folder waits for its listing to
+ // land before its inline rename can begin.
+ term_window.maybe_begin_pending_remote_rename();
term_window.invalidate_window();
})));
})
@@ -9859,6 +10015,280 @@ impl crate::TermWindow {
}
}
+ /// Files dropped onto the TERMINAL of a remote session: upload them and
+ /// paste the remote paths, where a local session would have pasted local
+ /// ones. Returns false when the active Space is not remote, so the caller
+ /// falls back to the plain local-path paste.
+ pub(crate) fn upload_dropped_files_to_remote_terminal(
+ &mut self,
+ paths: &[PathBuf],
+ coords: Option<Point>,
+ ) -> bool {
+ let Ok(Some(target)) = self.active_remote_project_for_files() else {
+ return false;
+ };
+ let Some(pane) = self.get_active_pane_or_overlay() else {
+ return false;
+ };
+ let pane_id = pane.pane_id();
+ // Align the panel's state machine with this Space's target (idempotent
+ // when it already matches): every origin check downstream reads the
+ // state machine's source key, which is unset until someone sets it.
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::TargetChanged(Some(target.clone())));
+ self.apply_right_sidebar_remote_files_effects(effects);
+
+ let source_key =
+ crate::termwindow::remote_files::RemoteFilesState::source_key(&target.source);
+ let config = match Self::ssh_config_for_remote_files_target(&target) {
+ Ok(config) => config,
+ Err(message) => {
+ for path in paths {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ display_name(path),
+ message.clone(),
+ None,
+ );
+ }
+ self.invalidate_window();
+ return true;
+ }
+ };
+
+ let setting = crate::native_settings::remote_drop_destination();
+ // The cwd is only consulted when asked for, and only as a hint: a pane
+ // that has not reported OSC 7 yet falls back to the default folder
+ // rather than failing the drop.
+ let cwd = (setting == crate::native_settings::REMOTE_DROP_DESTINATION_CWD)
+ .then(|| {
+ pane.get_current_working_dir(mux::pane::CachePolicy::AllowStale)
+ .and_then(|url| {
+ percent_encoding::percent_decode_str(url.path())
+ .decode_utf8()
+ .ok()
+ .map(|path| path.to_string())
+ })
+ })
+ .flatten();
+ let destination = resolve_drop_destination(&setting, cwd.as_deref());
+
+ let Some(window) = self.window.as_ref().cloned() else {
+ return true;
+ };
+ // A drop is an explicit ask, so dialing is allowed — and a successful
+ // dial authorizes the source exactly as the panel's Connect click
+ // would (the session credentials are the same either way).
+ let connection_key = remote_connection_key(&source_key, &config);
+ let batch: Vec<PathBuf> = paths.to_vec();
+ let anchor = coords.unwrap_or_else(|| Point::new(0, 0));
+ promise::spawn::spawn(async move {
+ let manager = remote_connection_manager();
+ let prepared = match manager.acquire(connection_key, config, true).await {
+ Ok(lease) => {
+ let backend = lease.backend();
+ match backend.resolve_root(destination).await {
+ // Merge-tolerant creation: the folder existing already
+ // is the normal case after the first drop.
+ Ok(directory) => match backend.create_directory(directory.clone()).await {
+ Ok(()) => Ok((lease, directory)),
+ Err(message) => Err(message),
+ },
+ Err(message) => Err(message),
+ }
+ }
+ Err(RemoteAcquireError::Failed(message)) => Err(message),
+ Err(RemoteAcquireError::NotConnected) => {
+ Err("Remote Files connection is not available".to_string())
+ }
+ };
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.dispatch_terminal_drop(prepared, batch, source_key, pane_id, anchor);
+ })));
+ })
+ .detach();
+ true
+ }
+
+ /// The prepared half of a terminal drop, back on the window thread: adopt
+ /// the connection, then hand every dropped path to the ordinary upload
+ /// machinery with the pane recorded as the paste target.
+ fn dispatch_terminal_drop(
+ &mut self,
+ prepared: Result<
+ (
+ crate::termwindow::remote_files::RemoteConnectionLease,
+ RemotePath,
+ ),
+ String,
+ >,
+ paths: Vec<PathBuf>,
+ source_key: String,
+ pane_id: PaneId,
+ anchor: Point,
+ ) {
+ let (lease, directory) = match prepared {
+ Ok(prepared) => prepared,
+ Err(message) => {
+ for path in &paths {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ display_name(path),
+ message.clone(),
+ None,
+ );
+ }
+ self.invalidate_window();
+ return;
+ }
+ };
+ let origin =
+ RemoteOperationOrigin::new(source_key.clone(), lease.connection_key().to_string());
+ if !self.remote_operation_origin_matches(&origin) {
+ for path in &paths {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ display_name(path),
+ "The window moved to another host while connecting".to_string(),
+ None,
+ );
+ }
+ self.invalidate_window();
+ return;
+ }
+ crate::termwindow::remote_files::authorize_remote_source(&source_key);
+ // Lend the fresh connection to the panel's lease slot unless the slot
+ // already holds this exact connection: `remote_transfer_handles` reads
+ // that slot, so every upload below — and the Files panel itself — uses
+ // whatever sits there. A slot left holding a session that died without
+ // any failure callback noticing, or one dialled before this host's
+ // settings changed, would otherwise defeat the reconnect we just did.
+ let already_installed = self
+ .right_sidebar_remote_files_lease
+ .as_ref()
+ .is_some_and(|current| current.is_same_connection(&lease));
+ if !already_installed {
+ self.right_sidebar_remote_files_lease = Some(lease);
+ }
+ for path in paths {
+ if path.is_dir() {
+ self.start_remote_folder_upload(path, directory.clone(), anchor, Some(pane_id));
+ continue;
+ }
+ let Some(name) = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .map(str::to_string)
+ else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ path.to_string_lossy().to_string(),
+ "That file name is not valid UTF-8".to_string(),
+ None,
+ );
+ continue;
+ };
+ self.spawn_terminal_drop_file_upload(
+ path,
+ name,
+ directory.clone(),
+ pane_id,
+ origin.clone(),
+ );
+ }
+ self.invalidate_window();
+ }
+
+ /// One dropped file: settle a free remote name off-thread, then run the
+ /// ordinary single-file upload with the pane as paste target.
+ fn spawn_terminal_drop_file_upload(
+ &mut self,
+ local: PathBuf,
+ name: String,
+ directory: RemotePath,
+ pane_id: PaneId,
+ origin: RemoteOperationOrigin,
+ ) {
+ let Some((backend, operation_lease, _connection_key, _connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ "Remote Files connection is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ promise::spawn::spawn(async move {
+ let chosen = pick_free_remote_name(&*backend, &directory, &name).await;
+ drop(operation_lease);
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ // Reserving the name is another round trip, and the window can
+ // be pointed at a different host while it runs:
+ // `start_remote_upload` takes both its origin and its backend
+ // from whatever is displayed NOW, so an unchecked hand-off
+ // would write this host's absolute path onto the other one and
+ // then paste it into a pane where it means something else.
+ if !term_window.remote_operation_origin_matches(&origin) {
+ term_window.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ "The window moved to another host before the upload started".to_string(),
+ None,
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ match chosen {
+ Ok(remote) => {
+ term_window.start_remote_upload(local, remote, directory, Some(pane_id));
+ }
+ Err(message) => {
+ term_window.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ message,
+ None,
+ );
+ }
+ }
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+
+ /// Put a landed file's remote path on the pane's command line.
+ ///
+ /// Always POSIX-quoted, regardless of `quote_dropped_files`: that setting
+ /// is about the LOCAL platform's shell, while this path is by construction
+ /// on a POSIX server. The distinction bites immediately — the default
+ /// SpacesOnly mode leaves `(` bare, and our collision names (` (1)`) put
+ /// parentheses in every re-dropped screenshot. Verified live: bash chokes
+ /// on the unquoted form.
+ pub(crate) fn paste_remote_path_to_pane(&mut self, pane_id: PaneId, remote: &RemotePath) {
+ let Some(pane) = Mux::get().get_pane(pane_id) else {
+ // The pane closed while the upload ran; the transfer row already
+ // says where the file went.
+ return;
+ };
+ let text = format!(
+ "{} ",
+ config::DroppedFileQuoting::Posix.escape(remote.as_str())
+ );
+ if let Err(err) = pane.send_paste(&text) {
+ log::error!(
+ "failed to paste the uploaded path {}: {err:#}",
+ remote.as_str()
+ );
+ }
+ }
+
/// Take files dropped onto the remote tree and upload them. Returns false
/// when the drop was not aimed at the panel, so the caller can fall back
/// to its usual handling.
@@ -9892,7 +10322,7 @@ impl crate::TermWindow {
for path in paths {
if path.is_dir() {
- self.start_remote_folder_upload(path.clone(), directory.clone());
+ self.start_remote_folder_upload(path.clone(), directory.clone(), coords, None);
continue;
}
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
@@ -9919,7 +10349,7 @@ impl crate::TermWindow {
continue;
}
};
- self.start_remote_upload(path.clone(), remote, directory.clone());
+ self.start_remote_upload(path.clone(), remote, directory.clone(), None);
}
self.invalidate_window();
true
@@ -9929,7 +10359,13 @@ impl crate::TermWindow {
///
/// One row, not one per file: running rows are never evicted from the
/// strip, so a thousand-file folder would otherwise bury the panel.
- fn start_remote_folder_upload(&mut self, source: PathBuf, directory: RemotePath) {
+ fn start_remote_folder_upload(
+ &mut self,
+ source: PathBuf,
+ directory: RemotePath,
+ anchor: Point,
+ paste_to: Option<PaneId>,
+ ) {
// The walk and its metadata calls must not run here: a large or
// network-backed tree would freeze the window for as long as it takes,
// before even a progress row appears.
@@ -9941,7 +10377,7 @@ impl crate::TermWindow {
// whatever happens to be connected when the walk finishes would put
// the files on the wrong machine, at a path that means something else
// there.
- let aimed_at = self.right_sidebar_remote_files.current_source_key();
+ let aimed_at = self.current_remote_operation_origin();
promise::spawn::spawn(async move {
let planned = promise::spawn::spawn_into_new_thread(move || {
Ok::<_, anyhow::Error>((source.clone(), plan_transfer(&source)))
@@ -9951,7 +10387,8 @@ impl crate::TermWindow {
return;
};
window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
- term_window.apply_remote_folder_plan(source, directory, plan, aimed_at);
+ term_window
+ .apply_remote_folder_plan(source, directory, plan, aimed_at, anchor, paste_to);
})));
})
.detach();
@@ -9965,10 +10402,21 @@ impl crate::TermWindow {
crate::termwindow::transfer_walk::TransferPlan,
crate::termwindow::transfer_walk::TransferPlanError,
>,
- aimed_at: Option<String>,
+ aimed_at: Option<RemoteOperationOrigin>,
+ anchor: Point,
+ paste_to: Option<PaneId>,
) {
let name = display_name(&source);
- if aimed_at.is_none() || self.right_sidebar_remote_files.current_source_key() != aimed_at {
+ let Some(origin) = aimed_at else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ "The Remote Files connection is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
+ if !self.remote_operation_origin_matches(&origin) {
// Refuse rather than retarget: the same remote path on a different
// host is a different place entirely.
self.push_remote_transfer_failure(
@@ -10000,49 +10448,109 @@ impl crate::TermWindow {
);
return;
}
+
+ // Where the uploaded folder itself will live — the path a terminal
+ // drop wants pasted once the tree has landed.
+ let paste_target = paste_to.and_then(|pane_id| {
+ directory
+ .join_name(&name)
+ .ok()
+ .map(|remote| (pane_id, remote))
+ });
+
+ // The row exists from here whichever way the size question goes, so
+ // the confirmation has something on screen to be about.
+ let id = self.next_remote_transfer_id();
+ let progress = RemoteTransferProgress::default();
+ self.right_sidebar_remote_transfers.push(RemoteTransfer {
+ id,
+ kind: RemoteTransferKind::Upload,
+ name,
+ progress,
+ status: RemoteTransferStatus::Running,
+ source: None,
+ origin: Some(origin.clone()),
+ });
+ self.trim_remote_transfers();
+
// Every remote entry costs at least one round trip on a single
// serialized session, so a big tree is slow in a way the user cannot
- // see coming. Say so rather than appearing to hang.
+ // see coming. Ask, with the number on the table, instead of either
+ // refusing outright or appearing to hang.
if plan.entries.len() > TRANSFER_CONFIRM_THRESHOLD {
- self.push_remote_transfer_failure(
- RemoteTransferKind::Upload,
- name,
- format!(
- "That folder holds {} items; upload it in smaller pieces",
- plan.entries.len()
- ),
- None,
+ self.set_pending_remote_confirm(
+ PendingRemoteConfirm::FolderUpload {
+ transfer_id: id,
+ directory,
+ plan,
+ origin,
+ paste_target,
+ },
+ anchor,
);
+ self.invalidate_window();
return;
}
+ self.start_remote_folder_upload_execution(id, directory, plan, paste_target);
+ self.invalidate_window();
+ }
+ /// The planned (and, if it was big, confirmed) folder upload.
+ fn start_remote_folder_upload_execution(
+ &mut self,
+ id: u64,
+ directory: RemotePath,
+ plan: crate::termwindow::transfer_walk::TransferPlan,
+ paste_target: Option<(PaneId, RemotePath)>,
+ ) {
+ let Some(transfer) = self
+ .right_sidebar_remote_transfers
+ .iter()
+ .find(|transfer| transfer.id == id)
+ else {
+ return;
+ };
+ let progress = transfer.progress.clone();
+ let Some(origin) = transfer.origin.clone() else {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "Remote transfer lost its source identity".to_string(),
+ ),
+ );
+ return;
+ };
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host before the upload started".to_string(),
+ ),
+ );
+ return;
+ }
+ if progress.is_canceled() {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(REMOTE_TRANSFER_CANCELED.to_string()),
+ );
+ return;
+ }
let Some((backend, operation_lease, connection_key, connection_id)) =
- self.remote_transfer_handles()
+ self.remote_transfer_handles(&origin)
else {
- self.push_remote_transfer_failure(
- RemoteTransferKind::Upload,
- name,
- "Remote Files connection is no longer available".to_string(),
- None,
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "Remote Files connection is no longer available".to_string(),
+ ),
);
return;
};
let Some(window) = self.window.as_ref().cloned() else {
return;
};
-
- let id = self.next_remote_transfer_id();
- let progress = RemoteTransferProgress::default();
progress.set_item_total(plan.entries.len() as u64);
- self.right_sidebar_remote_transfers.push(RemoteTransfer {
- id,
- kind: RemoteTransferKind::Upload,
- name,
- progress: progress.clone(),
- status: RemoteTransferStatus::Running,
- source: None,
- });
- self.trim_remote_transfers();
// Symlinks and unreadable nodes were deliberately left out; saying so
// is the difference between a truthful success and one that quietly
@@ -10074,16 +10582,25 @@ impl crate::TermWindow {
Some(note) => format!("Uploaded ({note})"),
None => "Uploaded".to_string(),
};
+ let succeeded = result.is_ok();
let status = transfer_status_from_result(&result, &done_detail);
term_window.finish_remote_transfer(id, status);
+ if succeeded {
+ if let Some((pane_id, folder_remote)) = paste_target {
+ term_window.paste_remote_path_to_pane(pane_id, &folder_remote);
+ }
+ }
// Re-list either way: a partial upload leaves real files the
// tree would otherwise never show.
- let effects = term_window
- .right_sidebar_remote_files
- .transition(RemoteFilesEvent::DirectoryInvalidated(refresh_dir));
- term_window.apply_right_sidebar_remote_files_effects(effects);
+ if term_window.remote_operation_origin_matches(&origin) {
+ let effects = term_window
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::DirectoryInvalidated(refresh_dir));
+ term_window.apply_right_sidebar_remote_files_effects(effects);
+ }
if connection_died {
- term_window.right_sidebar_remote_files_lease.take();
+ term_window
+ .release_remote_files_lease_if_connection(&connection_key, connection_id);
}
term_window.invalidate_window();
})));
@@ -10110,6 +10627,9 @@ impl crate::TermWindow {
source: Option<RemoteTransferSource>,
) {
let id = self.next_remote_transfer_id();
+ let origin = source
+ .as_ref()
+ .and_then(|_| self.current_remote_operation_origin());
self.right_sidebar_remote_transfers.push(RemoteTransfer {
id,
kind,
@@ -10117,6 +10637,7 @@ impl crate::TermWindow {
progress: RemoteTransferProgress::default(),
status: RemoteTransferStatus::Failed(message),
source,
+ origin,
});
self.trim_remote_transfers();
}
@@ -10136,15 +10657,30 @@ impl crate::TermWindow {
}
}
- fn start_remote_upload(&mut self, local: PathBuf, remote: RemotePath, directory: RemotePath) {
+ fn start_remote_upload(
+ &mut self,
+ local: PathBuf,
+ remote: RemotePath,
+ directory: RemotePath,
+ paste_to: Option<PaneId>,
+ ) {
let name = remote.file_name().to_string();
+ let Some(origin) = self.current_remote_operation_origin() else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ "Remote Files source is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
let retry = RemoteTransferSource::Upload {
local: local.clone(),
remote: remote.clone(),
directory: directory.clone(),
};
let Some((backend, operation_lease, connection_key, connection_id)) =
- self.remote_transfer_handles()
+ self.remote_transfer_handles(&origin)
else {
// A missing lease is exactly the kind of failure retrying fixes,
// once the panel has reconnected.
@@ -10169,6 +10705,7 @@ impl crate::TermWindow {
progress: progress.clone(),
status: RemoteTransferStatus::Running,
source: Some(retry),
+ origin: Some(origin.clone()),
});
self.trim_remote_transfers();
@@ -10176,7 +10713,9 @@ impl crate::TermWindow {
// A single dropped file refuses to clobber; there is no prompt on
// this path, so silently replacing would be a choice the user
// never made.
- let result = backend.upload_file(local, remote, progress, false).await;
+ let result = backend
+ .upload_file(local, remote.clone(), progress, false)
+ .await;
drop(operation_lease);
let connection_died = result.as_ref().is_err_and(|failure| {
invalidate_remote_connection_if_dead(
@@ -10189,16 +10728,27 @@ impl crate::TermWindow {
let succeeded = result.is_ok();
let status = transfer_status_from_result(&result, "Uploaded");
term_window.finish_remote_transfer(id, status);
+ if succeeded {
+ if let Some(pane_id) = paste_to {
+ // A drop on a remote terminal wants the file's REMOTE
+ // path on the command line, exactly where a local drop
+ // would have pasted the local one.
+ term_window.paste_remote_path_to_pane(pane_id, &remote);
+ }
+ }
// Re-list either way. On failure the directory may now hold a
// partial file the tree would otherwise never show — and the
// user would then hit "already exists" on retry with nothing
// on screen to explain it.
- let effects = term_window
- .right_sidebar_remote_files
- .transition(RemoteFilesEvent::DirectoryInvalidated(directory));
- term_window.apply_right_sidebar_remote_files_effects(effects);
+ if term_window.remote_operation_origin_matches(&origin) {
+ let effects = term_window
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::DirectoryInvalidated(directory));
+ term_window.apply_right_sidebar_remote_files_effects(effects);
+ }
if !succeeded && connection_died {
- term_window.right_sidebar_remote_files_lease.take();
+ term_window
+ .release_remote_files_lease_if_connection(&connection_key, connection_id);
}
term_window.invalidate_window();
})));
@@ -10206,30 +10756,98 @@ impl crate::TermWindow {
.detach();
}
- /// Right-clicking a remote row. Only a file offers anything so far, so a
- /// directory gets no menu rather than an empty one.
+ /// Right-clicking a remote row: the file-operations menu, shaped by what
+ /// the row is. The root gets only what cannot orphan the whole panel —
+ /// no Rename, no Delete.
pub(crate) fn show_right_sidebar_remote_file_context_menu(
&mut self,
context: &dyn WindowOps,
anchor: Point,
path: RemotePath,
) {
- if self.right_sidebar_remote_files.kind_for_path(&path) != Some(RemoteFileKind::File) {
+ let Some(kind) = self.right_sidebar_remote_files.kind_for_path(&path) else {
return;
- }
- // A transfer needs a live lease; offering Download without one would
- // only produce a failure row.
+ };
+ let Some(origin) = self.current_remote_operation_origin() else {
+ return;
+ };
+ let is_root = self.right_sidebar_remote_files.root.as_ref() == Some(&path);
+ // Every operation needs a live lease; offering one without would only
+ // produce a failure row.
let enabled = self.right_sidebar_remote_files_lease.is_some();
+ let path_string = path.as_str().to_string();
+
+ // One pass: beginning the block clears the action table, so a second
+ // call mid-assembly would turn the earlier items into dead entries.
self.begin_context_menu_application_actions();
- let item = self.context_menu_application_item_with_icon(
- "Download",
- // No dedicated download glyph in the shared icon set; Save is the
- // closest fit and already maps on every platform.
- ContextMenuIcon::Save,
- crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path),
- enabled,
- );
- self.show_term_context_menu(context, anchor, vec![item]);
+ let mut items = Vec::new();
+ match kind {
+ RemoteFileKind::File => {
+ items.push(self.context_menu_application_item_with_icon(
+ "Download",
+ // No dedicated download glyph in the shared icon set; Save
+ // is the closest fit and already maps on every platform.
+ ContextMenuIcon::Save,
+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile {
+ path: path.clone(),
+ origin: origin.clone(),
+ },
+ enabled,
+ ));
+ }
+ RemoteFileKind::Directory => {
+ items.push(self.context_menu_application_item_with_icon(
+ "Download",
+ ContextMenuIcon::Save,
+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFolder {
+ path: path.clone(),
+ anchor,
+ origin: origin.clone(),
+ },
+ enabled,
+ ));
+ items.push(self.context_menu_application_item_with_icon(
+ "New Folder",
+ ContextMenuIcon::FolderAdd,
+ crate::termwindow::ContextMenuApplicationAction::NewRemoteFolder {
+ parent: path.clone(),
+ origin: origin.clone(),
+ },
+ enabled,
+ ));
+ }
+ // A link's target could be anywhere; downloading "it" would really
+ // download something else. Rename and Delete below still apply.
+ RemoteFileKind::Symlink | RemoteFileKind::Other => {}
+ }
+ items.push(ContextMenuItem::item_with_icon(
+ "Copy Path",
+ ContextMenuIcon::Copy,
+ KeyAssignment::CopyFilePathToClipboard(path_string),
+ ));
+ if !is_root {
+ items.push(self.context_menu_application_item_with_icon(
+ "Rename\u{2026}",
+ ContextMenuIcon::Edit,
+ crate::termwindow::ContextMenuApplicationAction::RenameRemoteEntry {
+ path: path.clone(),
+ origin: origin.clone(),
+ },
+ enabled,
+ ));
+ items.push(ContextMenuItem::Separator);
+ items.push(self.context_menu_application_item_with_icon(
+ "Delete\u{2026}",
+ ContextMenuIcon::Delete,
+ crate::termwindow::ContextMenuApplicationAction::DeleteRemoteEntry {
+ path,
+ anchor,
+ origin,
+ },
+ enabled,
+ ));
+ }
+ self.show_term_context_menu(context, anchor, items);
}
/// Which local directory a pointer at `(x, y)` is aiming at.
@@ -10355,7 +10973,6 @@ impl crate::TermWindow {
plans: preflight.plans,
directory,
conflicts: preflight.conflicts,
- anchor,
note,
});
}
@@ -10402,7 +11019,6 @@ impl crate::TermWindow {
self.show_term_context_menu(context, anchor, vec![overwrite, skip, cancel]);
}
- /// Resolve a queued copy once the user has answered the conflict prompt.
/// Resolve a queued copy once the user has answered the conflict prompt.
pub(crate) fn resolve_pending_local_copy(&mut self, choice: ConflictChoice) {
let Some(pending) = self.pending_local_copy.take() else {
@@ -10420,7 +11036,6 @@ impl crate::TermWindow {
plans,
directory,
conflicts,
- anchor: _,
note,
} = pending;
let plans = plans
@@ -10474,6 +11089,7 @@ impl crate::TermWindow {
progress: progress.clone(),
status: RemoteTransferStatus::Running,
source: None,
+ origin: None,
});
self.trim_remote_transfers();
self.invalidate_window();
@@ -10528,6 +11144,9 @@ impl crate::TermWindow {
let Some(path) = self.right_sidebar_remote_files.selected.clone() else {
return;
};
+ let Some(origin) = self.current_remote_operation_origin() else {
+ return;
+ };
// Snapshot the gating up front: the item builders below take `&mut
// self`, so reading these inline would fight the borrow checker.
let has_selection = self.right_sidebar_file_preview_selected_text().is_some();
@@ -10555,7 +11174,7 @@ impl crate::TermWindow {
let download = self.context_menu_application_item_with_icon(
"Download",
ContextMenuIcon::Save,
- crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path),
+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile { path, origin },
can_download,
);
@@ -10575,6 +11194,15 @@ impl crate::TermWindow {
pub(crate) fn download_right_sidebar_remote_file(&mut self, remote: RemotePath) {
let name = remote.file_name().to_string();
+ let Some(origin) = self.current_remote_operation_origin() else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Download,
+ name,
+ "Remote Files source is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
let retry = RemoteTransferSource::Download {
remote: remote.clone(),
};
@@ -10602,18 +11230,15 @@ impl crate::TermWindow {
// staging file exclusively. Two downloads that would land on the same
// name therefore take different ones, and an unrelated `X.part` that
// happens to be sitting there is never truncated or deleted.
- let Some((local, partial)) = reserve_download_path(
- &directory,
- &name,
- |path| path.exists(),
- |partial| {
+ let Some((local, partial)) =
+ reserve_download_path(&directory, &name, local_path_is_occupied, |partial| {
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(partial)
.is_ok()
- },
- ) else {
+ })
+ else {
self.push_remote_transfer_failure(
RemoteTransferKind::Download,
name,
@@ -10635,7 +11260,7 @@ impl crate::TermWindow {
};
let Some((backend, operation_lease, connection_key, connection_id)) =
- self.remote_transfer_handles()
+ self.remote_transfer_handles(&origin)
else {
release_reservation(&partial);
self.push_remote_transfer_failure(
@@ -10660,48 +11285,1054 @@ impl crate::TermWindow {
progress: progress.clone(),
status: RemoteTransferStatus::Running,
source: Some(retry),
+ origin: Some(origin),
+ });
+ self.trim_remote_transfers();
+ self.invalidate_window();
+
+ promise::spawn::spawn(async move {
+ let landed = local.clone();
+ let result = backend.download_file(remote, local, progress).await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|failure| {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ connection_id,
+ &failure.message,
+ )
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let landed_in = landed
+ .parent()
+ .map(|parent| parent.display().to_string())
+ .unwrap_or_else(|| landed.display().to_string());
+ let status = transfer_status_from_result(&result, &format!("Saved to {landed_in}"));
+ term_window.finish_remote_transfer(id, status);
+ if connection_died {
+ term_window
+ .release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+
+ /// Right-clicked "Download" on a remote directory: walk it first, ask if
+ /// it is big, then pull the whole tree into the Downloads folder.
+ pub(crate) fn download_right_sidebar_remote_folder(
+ &mut self,
+ remote: RemotePath,
+ anchor: Point,
+ ) {
+ let name = remote.file_name().to_string();
+ let Some(origin) = self.current_remote_operation_origin() else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Download,
+ name,
+ "Remote Files source is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
+ let retry = RemoteTransferSource::DownloadFolder {
+ remote: remote.clone(),
+ };
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Download,
+ name,
+ "Remote Files connection is no longer available".to_string(),
+ Some(retry),
+ );
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+
+ // The row exists from the walk onwards: listing a big tree takes real
+ // time on a serialized channel, and a click on the row is the only
+ // way to abort it.
+ let id = self.next_remote_transfer_id();
+ let progress = RemoteTransferProgress::default();
+ self.right_sidebar_remote_transfers.push(RemoteTransfer {
+ id,
+ kind: RemoteTransferKind::Download,
+ name,
+ progress: progress.clone(),
+ status: RemoteTransferStatus::Running,
+ source: Some(retry),
+ origin: Some(origin.clone()),
});
self.trim_remote_transfers();
self.invalidate_window();
-
- promise::spawn::spawn(async move {
- let landed = local.clone();
- let result = backend.download_file(remote, local, progress).await;
- drop(operation_lease);
- let connection_died = result.as_ref().is_err_and(|failure| {
- invalidate_remote_connection_if_dead(
- &connection_key,
- connection_id,
- &failure.message,
- )
- });
- window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
- let landed_in = landed
- .parent()
- .map(|parent| parent.display().to_string())
- .unwrap_or_else(|| landed.display().to_string());
- let status = transfer_status_from_result(&result, &format!("Saved to {landed_in}"));
- term_window.finish_remote_transfer(id, status);
- if connection_died {
- term_window.right_sidebar_remote_files_lease.take();
- }
- term_window.invalidate_window();
- })));
- })
- .detach();
+
+ // Same guard as folder uploads: the walk is slow, and the panel can
+ // be pointed at another host meanwhile — a plan built against one
+ // server must never execute against another.
+ promise::spawn::spawn(async move {
+ let plan =
+ plan_remote_walk(&*backend, remote, RemoteWalkMode::Download, &progress).await;
+ drop(operation_lease);
+ let connection_died = plan.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.apply_remote_folder_download_plan(
+ id,
+ plan,
+ origin,
+ anchor,
+ connection_key,
+ connection_id,
+ connection_died,
+ );
+ })));
+ })
+ .detach();
+ }
+
+ fn apply_remote_folder_download_plan(
+ &mut self,
+ id: u64,
+ plan: Result<RemoteWalkPlan, String>,
+ origin: RemoteOperationOrigin,
+ anchor: Point,
+ connection_key: String,
+ connection_id: u64,
+ connection_died: bool,
+ ) {
+ if connection_died {
+ self.release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host while this folder was being read".to_string(),
+ ),
+ );
+ self.invalidate_window();
+ return;
+ }
+ let plan = match plan {
+ Ok(plan) => plan,
+ Err(message) => {
+ self.finish_remote_transfer(id, RemoteTransferStatus::Failed(message));
+ self.invalidate_window();
+ return;
+ }
+ };
+ if plan.entries.len() > TRANSFER_CONFIRM_THRESHOLD {
+ self.set_pending_remote_confirm(
+ PendingRemoteConfirm::FolderDownload {
+ transfer_id: id,
+ plan,
+ origin,
+ },
+ anchor,
+ );
+ } else {
+ self.start_remote_folder_download_execution(id, plan);
+ }
+ self.invalidate_window();
+ }
+
+ /// The plan is final and (if it was big) confirmed: reserve a fresh
+ /// destination folder and stream the tree into it.
+ fn start_remote_folder_download_execution(&mut self, id: u64, plan: RemoteWalkPlan) {
+ let Some(transfer) = self
+ .right_sidebar_remote_transfers
+ .iter()
+ .find(|transfer| transfer.id == id)
+ else {
+ return;
+ };
+ let progress = transfer.progress.clone();
+ let folder_name = transfer.name.clone();
+ let Some(origin) = transfer.origin.clone() else {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "Remote transfer lost its source identity".to_string(),
+ ),
+ );
+ return;
+ };
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host before the download started".to_string(),
+ ),
+ );
+ return;
+ }
+ if progress.is_canceled() {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(REMOTE_TRANSFER_CANCELED.to_string()),
+ );
+ return;
+ }
+ let Some(directory) = crate::native_settings::effective_remote_download_directory() else {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed("Unable to locate a Downloads folder".to_string()),
+ );
+ return;
+ };
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "Remote Files connection is no longer available".to_string(),
+ ),
+ );
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+
+ progress.set_item_total(plan.entries.len() as u64);
+ let note = (plan.skipped > 0).then(|| format!("{} symlink(s) skipped", plan.skipped));
+ promise::spawn::spawn(async move {
+ let result = download_remote_tree(
+ &*backend,
+ &directory,
+ &folder_name,
+ &plan.entries,
+ &progress,
+ )
+ .await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|failure| {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ connection_id,
+ &failure.message,
+ )
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let status = match &result {
+ Ok(destination) => {
+ let mut detail = format!("Saved to {}", destination.display());
+ if let Some(note) = &note {
+ detail.push_str(&format!(" ({note})"));
+ }
+ RemoteTransferStatus::Done(detail)
+ }
+ Err(failure) => match &failure.leftover {
+ Some(leftover) => RemoteTransferStatus::FailedWithLeftover {
+ message: failure.message.clone(),
+ leftover: leftover.clone(),
+ },
+ None => RemoteTransferStatus::Failed(failure.message.clone()),
+ },
+ };
+ term_window.finish_remote_transfer(id, status);
+ if connection_died {
+ term_window
+ .release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+
+ /// Put a confirmation menu on screen and remember what it is asking
+ /// about. Show first, then record — opening a menu tears the previous one
+ /// down, and that teardown is where an unanswered pending is cancelled,
+ /// so recording first would have it cancel itself (the same ordering
+ /// [`Self::apply_local_copy_preflight`] relies on).
+ fn set_pending_remote_confirm(&mut self, pending: PendingRemoteConfirm, anchor: Point) {
+ self.cancel_pending_remote_confirm();
+ let Some(window) = self.window.as_ref().cloned() else {
+ self.finish_pending_remote_confirm_row(&pending);
+ return;
+ };
+ let (proceed_label, proceed_icon) = match &pending {
+ PendingRemoteConfirm::FolderDownload { plan, .. } => (
+ format!("Download {} items", plan.entries.len()),
+ ContextMenuIcon::Save,
+ ),
+ PendingRemoteConfirm::FolderDelete { plan, .. } => (
+ // +1: the folder itself goes too.
+ format!("Delete {} items permanently", plan.entries.len() + 1),
+ ContextMenuIcon::Delete,
+ ),
+ PendingRemoteConfirm::FileDelete { remote, .. } => (
+ format!("Delete \u{201c}{}\u{201d} permanently", remote.file_name()),
+ ContextMenuIcon::Delete,
+ ),
+ PendingRemoteConfirm::FolderUpload { plan, .. } => (
+ format!("Upload {} items", plan.entries.len()),
+ ContextMenuIcon::Save,
+ ),
+ };
+ self.begin_context_menu_application_actions();
+ let proceed = self.context_menu_application_item_with_icon(
+ proceed_label,
+ proceed_icon,
+ crate::termwindow::ContextMenuApplicationAction::ResolveRemoteConfirm(true),
+ true,
+ );
+ let cancel = self.context_menu_application_item_with_icon(
+ "Cancel",
+ ContextMenuIcon::Close,
+ crate::termwindow::ContextMenuApplicationAction::ResolveRemoteConfirm(false),
+ true,
+ );
+ self.show_term_context_menu(&window, anchor, vec![proceed, cancel]);
+ self.pending_remote_confirm = Some(pending);
+ }
+
+ /// Drop a confirmation nobody answered — its menu was dismissed, or a
+ /// newer confirmation is taking the slot.
+ pub(crate) fn cancel_pending_remote_confirm(&mut self) {
+ if let Some(pending) = self.pending_remote_confirm.take() {
+ self.finish_pending_remote_confirm_row(&pending);
+ self.invalidate_window();
+ }
+ }
+
+ /// A pending confirmation that will never run still owns a Running
+ /// transfer row; leave it saying "Canceled" rather than spinning forever.
+ fn finish_pending_remote_confirm_row(&mut self, pending: &PendingRemoteConfirm) {
+ let transfer_id = match pending {
+ PendingRemoteConfirm::FolderDownload { transfer_id, .. }
+ | PendingRemoteConfirm::FolderDelete { transfer_id, .. }
+ | PendingRemoteConfirm::FolderUpload { transfer_id, .. } => Some(*transfer_id),
+ PendingRemoteConfirm::FileDelete { .. } => None,
+ };
+ if let Some(id) = transfer_id {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(REMOTE_TRANSFER_CANCELED.to_string()),
+ );
+ }
+ }
+
+ pub(crate) fn resolve_pending_remote_confirm(&mut self, proceed: bool) {
+ let Some(pending) = self.pending_remote_confirm.take() else {
+ return;
+ };
+ if !proceed {
+ self.finish_pending_remote_confirm_row(&pending);
+ self.invalidate_window();
+ return;
+ }
+ match pending {
+ PendingRemoteConfirm::FolderDownload {
+ transfer_id,
+ plan,
+ origin,
+ } => {
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ transfer_id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host while waiting".to_string(),
+ ),
+ );
+ } else {
+ self.start_remote_folder_download_execution(transfer_id, plan);
+ }
+ }
+ PendingRemoteConfirm::FolderDelete {
+ transfer_id,
+ remote,
+ plan,
+ origin,
+ } => {
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ transfer_id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host while waiting".to_string(),
+ ),
+ );
+ } else {
+ self.start_remote_folder_delete_execution(transfer_id, remote, plan);
+ }
+ }
+ PendingRemoteConfirm::FileDelete { remote, origin } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.execute_remote_file_delete(remote, origin);
+ }
+ }
+ PendingRemoteConfirm::FolderUpload {
+ transfer_id,
+ directory,
+ plan,
+ origin,
+ paste_target,
+ } => {
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ transfer_id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host while waiting".to_string(),
+ ),
+ );
+ } else {
+ self.start_remote_folder_upload_execution(
+ transfer_id,
+ directory,
+ plan,
+ paste_target,
+ );
+ }
+ }
+ }
+ self.invalidate_window();
+ }
+
+ /// Right-clicked "Delete…" on a remote row. A directory is walked first so
+ /// the confirmation can say how much it is really about to remove; a file
+ /// (or link) goes straight to its confirmation. Everything here confirms —
+ /// there is no trash on the far side to undo from.
+ pub(crate) fn delete_right_sidebar_remote_entry(&mut self, path: RemotePath, anchor: Point) {
+ match self.right_sidebar_remote_files.kind_for_path(&path) {
+ Some(RemoteFileKind::Directory) => self.begin_remote_folder_delete(path, anchor),
+ Some(_) => {
+ if let Some(origin) = self.current_remote_operation_origin() {
+ self.set_pending_remote_confirm(
+ PendingRemoteConfirm::FileDelete {
+ remote: path,
+ origin,
+ },
+ anchor,
+ );
+ }
+ }
+ None => {}
+ }
+ }
+
+ /// The confirmed single-file delete. No transfer row: it is one round
+ /// trip, and a failure reports through the panel's notice line.
+ fn execute_remote_file_delete(&mut self, remote: RemotePath, origin: RemoteOperationOrigin) {
+ if !self.remote_operation_origin_matches(&origin) {
+ return;
+ }
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.right_sidebar_remote_files.error_message =
+ Some("Remote Files connection is no longer available".to_string());
+ self.invalidate_window();
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ promise::spawn::spawn(async move {
+ let result = backend.remove_file(remote.clone()).await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.finish_remote_entry_removal(
+ remote,
+ result,
+ origin,
+ connection_key,
+ connection_id,
+ connection_died,
+ );
+ })));
+ })
+ .detach();
+ }
+
+ /// Shared tail of a delete or rename: the entry no longer exists under
+ /// its old path, so forget its subtree, close a preview that was showing
+ /// it, and re-list the directory it lived in.
+ pub(crate) fn finish_remote_entry_removal(
+ &mut self,
+ remote: RemotePath,
+ result: Result<(), String>,
+ origin: RemoteOperationOrigin,
+ connection_key: String,
+ connection_id: u64,
+ connection_died: bool,
+ ) {
+ if connection_died {
+ self.release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ if !self.remote_operation_origin_matches(&origin) {
+ // A different tree is on screen now; neither the error nor the
+ // refresh belongs to it.
+ return;
+ }
+ match result {
+ Ok(()) => self.forget_remote_entry_and_refresh_parent(&remote),
+ Err(message) => {
+ self.right_sidebar_remote_files.error_message = Some(message);
+ }
+ }
+ self.invalidate_window();
+ }
+
+ /// Drop `remote`'s cached subtree, close a preview living under it, and
+ /// re-list its parent so the tree reflects what the server now holds.
+ fn forget_remote_entry_and_refresh_parent(&mut self, remote: &RemotePath) {
+ // Decided BEFORE the transition, which clears the selection.
+ let preview_dies = self
+ .right_sidebar_remote_files
+ .selected
+ .as_ref()
+ .is_some_and(|selected| selected == remote || selected.is_descendant_of(remote));
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::EntryForgotten(remote.clone()));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ if preview_dies {
+ self.close_right_sidebar_file_preview();
+ }
+ if let Some(parent) = remote.parent() {
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::DirectoryInvalidated(parent));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+ }
+
+ /// Walk a directory that is about to be deleted. The row exists from the
+ /// walk onwards so the listing phase is visible and abortable, exactly
+ /// like a folder download's.
+ fn begin_remote_folder_delete(&mut self, remote: RemotePath, anchor: Point) {
+ let name = remote.file_name().to_string();
+ let Some(origin) = self.current_remote_operation_origin() else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Delete,
+ name,
+ "Remote Files source is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Delete,
+ name,
+ "Remote Files connection is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ let id = self.next_remote_transfer_id();
+ let progress = RemoteTransferProgress::default();
+ self.right_sidebar_remote_transfers.push(RemoteTransfer {
+ id,
+ kind: RemoteTransferKind::Delete,
+ name,
+ progress: progress.clone(),
+ status: RemoteTransferStatus::Running,
+ // Deliberately no retry: a delete that half-happened changed the
+ // tree, and "run it again" deserves a fresh look, not a replay.
+ source: None,
+ origin: Some(origin.clone()),
+ });
+ self.trim_remote_transfers();
+ self.invalidate_window();
+
+ promise::spawn::spawn(async move {
+ let plan =
+ plan_remote_walk(&*backend, remote.clone(), RemoteWalkMode::Delete, &progress)
+ .await;
+ drop(operation_lease);
+ let connection_died = plan.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.apply_remote_folder_delete_plan(
+ id,
+ remote,
+ plan,
+ origin,
+ anchor,
+ connection_key,
+ connection_id,
+ connection_died,
+ );
+ })));
+ })
+ .detach();
+ }
+
+ fn apply_remote_folder_delete_plan(
+ &mut self,
+ id: u64,
+ remote: RemotePath,
+ plan: Result<RemoteWalkPlan, String>,
+ origin: RemoteOperationOrigin,
+ anchor: Point,
+ connection_key: String,
+ connection_id: u64,
+ connection_died: bool,
+ ) {
+ if connection_died {
+ self.release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host while this folder was being read".to_string(),
+ ),
+ );
+ self.invalidate_window();
+ return;
+ }
+ let plan = match plan {
+ Ok(plan) => plan,
+ Err(message) => {
+ self.finish_remote_transfer(id, RemoteTransferStatus::Failed(message));
+ self.invalidate_window();
+ return;
+ }
+ };
+ // A folder delete confirms at ANY size — unlike the transfer
+ // threshold, this is about irreversibility, not time.
+ self.set_pending_remote_confirm(
+ PendingRemoteConfirm::FolderDelete {
+ transfer_id: id,
+ remote,
+ plan,
+ origin,
+ },
+ anchor,
+ );
+ self.invalidate_window();
+ }
+
+ /// The confirmed folder delete: children first, the folder itself last.
+ fn start_remote_folder_delete_execution(
+ &mut self,
+ id: u64,
+ remote: RemotePath,
+ plan: RemoteWalkPlan,
+ ) {
+ let Some(transfer) = self
+ .right_sidebar_remote_transfers
+ .iter()
+ .find(|transfer| transfer.id == id)
+ else {
+ return;
+ };
+ let progress = transfer.progress.clone();
+ let Some(origin) = transfer.origin.clone() else {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "Remote transfer lost its source identity".to_string(),
+ ),
+ );
+ return;
+ };
+ if !self.remote_operation_origin_matches(&origin) {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "The panel moved to another host before the delete started".to_string(),
+ ),
+ );
+ return;
+ }
+ if progress.is_canceled() {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(REMOTE_TRANSFER_CANCELED.to_string()),
+ );
+ return;
+ }
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.finish_remote_transfer(
+ id,
+ RemoteTransferStatus::Failed(
+ "Remote Files connection is no longer available".to_string(),
+ ),
+ );
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ // +1: the folder itself is the last deletion.
+ progress.set_item_total(plan.entries.len() as u64 + 1);
+ promise::spawn::spawn(async move {
+ let result = delete_remote_tree(&*backend, &remote, &plan.entries, &progress).await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let status = match &result {
+ Ok(removed) => RemoteTransferStatus::Done(format!("Deleted {removed} items")),
+ Err(message) => RemoteTransferStatus::Failed(message.clone()),
+ };
+ term_window.finish_remote_transfer(id, status);
+ if connection_died {
+ term_window
+ .release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ // Success or not, the subtree changed underneath the cache:
+ // forget it and re-list the parent. After a partial failure
+ // the directory still exists — the fresh parent listing keeps
+ // it, collapsed, and expanding shows what is left.
+ if term_window.remote_operation_origin_matches(&origin) {
+ term_window.forget_remote_entry_and_refresh_parent(&remote);
+ }
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+
+ /// "New Folder" on a remote directory: mint `untitled folder` (or the
+ /// first numbered variant that is free) and drop into renaming it once
+ /// its row appears.
+ pub(crate) fn create_right_sidebar_remote_folder(&mut self, parent: RemotePath) {
+ let Some(origin) = self.current_remote_operation_origin() else {
+ self.right_sidebar_remote_files.error_message =
+ Some("Remote Files source is no longer available".to_string());
+ self.invalidate_window();
+ return;
+ };
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles(&origin)
+ else {
+ self.right_sidebar_remote_files.error_message =
+ Some("Remote Files connection is no longer available".to_string());
+ self.invalidate_window();
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ promise::spawn::spawn(async move {
+ let mut created: Result<RemotePath, String> =
+ Err("Unable to find a free folder name".to_string());
+ for attempt in 0..100u32 {
+ let name = if attempt == 0 {
+ "untitled folder".to_string()
+ } else {
+ format!("untitled folder {}", attempt + 1)
+ };
+ let path = match parent.join_name(&name) {
+ Ok(path) => path,
+ Err(err) => {
+ created = Err(err);
+ break;
+ }
+ };
+ match backend.create_directory_exclusive(path.clone()).await {
+ Ok(()) => {
+ created = Ok(path);
+ break;
+ }
+ // The exclusive-create contract spells an occupied name
+ // exactly this way; anything else is a real failure.
+ Err(message) if message.ends_with("already exists") => continue,
+ Err(message) => {
+ created = Err(message);
+ break;
+ }
+ }
+ }
+ drop(operation_lease);
+ let connection_died = created.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.finish_remote_folder_creation(
+ parent,
+ created,
+ origin,
+ connection_key,
+ connection_id,
+ connection_died,
+ );
+ })));
+ })
+ .detach();
+ }
+
+ fn finish_remote_folder_creation(
+ &mut self,
+ parent: RemotePath,
+ result: Result<RemotePath, String>,
+ origin: RemoteOperationOrigin,
+ connection_key: String,
+ connection_id: u64,
+ connection_died: bool,
+ ) {
+ if connection_died {
+ self.release_remote_files_lease_if_connection(&connection_key, connection_id);
+ }
+ if !self.remote_operation_origin_matches(&origin) {
+ return;
+ }
+ match result {
+ Ok(path) => {
+ // Open the parent so the new row can appear, re-list it, and
+ // remember to start renaming once the listing lands — the row
+ // does not exist to edit until then.
+ self.right_sidebar_remote_files
+ .expanded
+ .insert(parent.clone());
+ self.pending_remote_rename = Some((path, origin));
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::DirectoryInvalidated(parent));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+ Err(message) => {
+ self.right_sidebar_remote_files.error_message = Some(message);
+ }
+ }
+ self.invalidate_window();
+ }
+
+ /// Fire the deferred rename of a just-created folder once (and only once)
+ /// its row is really on screen. Runs after every remote listing lands.
+ fn maybe_begin_pending_remote_rename(&mut self) {
+ let Some((pending, origin)) = self.pending_remote_rename.clone() else {
+ return;
+ };
+ if !self.remote_operation_origin_matches(&origin) {
+ self.pending_remote_rename = None;
+ return;
+ }
+ match self.right_sidebar_remote_files.kind_for_path(&pending) {
+ Some(RemoteFileKind::Directory) => {
+ self.pending_remote_rename = None;
+ self.start_sidebar_remote_file_rename(pending);
+ }
+ Some(_) => {
+ // Something else wears the name now; renaming it would edit
+ // the wrong thing.
+ self.pending_remote_rename = None;
+ }
+ None => {
+ // Give up once the parent has a fresh listing that does not
+ // hold the row; before that, some other directory just loaded.
+ if pending
+ .parent()
+ .is_some_and(|parent| self.right_sidebar_remote_files.has_listing(&parent))
+ {
+ self.pending_remote_rename = None;
+ }
+ }
+ }
+ }
+
+ /// A click on a transfer row. Running: stop it. Finished with a recorded
+ /// source: ask Retry-or-Dismiss rather than guessing which the click
+ /// meant. Anything else: clear the notice away, as before.
+ pub(crate) fn remote_transfer_row_clicked(&mut self, id: u64, anchor: Point) {
+ let Some(transfer) = self
+ .right_sidebar_remote_transfers
+ .iter()
+ .find(|transfer| transfer.id == id)
+ else {
+ return;
+ };
+ if transfer.is_running() {
+ transfer.progress.request_cancel();
+ self.invalidate_window();
+ return;
+ }
+ if transfer.can_retry() {
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ self.begin_context_menu_application_actions();
+ let retry = self.context_menu_application_item_with_icon(
+ "Retry",
+ ContextMenuIcon::Refresh,
+ crate::termwindow::ContextMenuApplicationAction::RetryRemoteTransfer { id, anchor },
+ true,
+ );
+ let dismiss = self.context_menu_application_item_with_icon(
+ "Dismiss",
+ ContextMenuIcon::Close,
+ crate::termwindow::ContextMenuApplicationAction::DismissRemoteTransfer(id),
+ true,
+ );
+ self.show_term_context_menu(&window, anchor, vec![retry, dismiss]);
+ return;
+ }
+ self.remove_remote_transfer_row(id);
+ }
+
+ pub(crate) fn remove_remote_transfer_row(&mut self, id: u64) {
+ if let Some(index) = self
+ .right_sidebar_remote_transfers
+ .iter()
+ .position(|transfer| transfer.id == id)
+ {
+ self.right_sidebar_remote_transfers.remove(index);
+ self.invalidate_window();
+ }
+ }
+
+ /// Run a failed transfer again from its recorded source.
+ pub(crate) fn retry_remote_transfer(&mut self, id: u64, anchor: Point) {
+ let Some(index) = self
+ .right_sidebar_remote_transfers
+ .iter()
+ .position(|transfer| transfer.id == id)
+ else {
+ return;
+ };
+ let Some(origin) = self.right_sidebar_remote_transfers[index].origin.clone() else {
+ return;
+ };
+ if !self.remote_operation_origin_matches(&origin) {
+ // Keep the row and its source intact so switching back makes the
+ // same Retry action useful. Never replay an absolute path against
+ // the host that merely happens to be visible now.
+ self.right_sidebar_remote_transfers[index].status = RemoteTransferStatus::Failed(
+ "Switch Files back to the original host to retry".to_string(),
+ );
+ self.invalidate_window();
+ return;
+ }
+ let transfer = self.right_sidebar_remote_transfers.remove(index);
+ let Some(source) = transfer.source else {
+ return;
+ };
+ match source {
+ RemoteTransferSource::Upload {
+ local,
+ remote,
+ directory,
+ } => self.start_remote_upload(local, remote, directory, None),
+ RemoteTransferSource::Download { remote } => {
+ self.download_right_sidebar_remote_file(remote)
+ }
+ RemoteTransferSource::DownloadFolder { remote } => {
+ self.download_right_sidebar_remote_folder(remote, anchor)
+ }
+ }
+ self.invalidate_window();
}
/// Everything a transfer worker needs from the panel's lease. Takes an
/// operation lease so the pooled connection cannot expire mid-transfer.
- fn remote_transfer_handles(
+ fn current_remote_connection_key(&self) -> Option<String> {
+ let target = self.right_sidebar_remote_files.target.as_ref()?;
+ let source_key =
+ crate::termwindow::remote_files::RemoteFilesState::source_key(&target.source);
+ let config = Self::ssh_config_for_remote_files_target(target).ok()?;
+ Some(remote_connection_key(&source_key, &config))
+ }
+
+ pub(crate) fn current_remote_operation_origin(&self) -> Option<RemoteOperationOrigin> {
+ let source_key = self.right_sidebar_remote_files.current_source_key()?;
+ let connection_key = self.current_remote_connection_key()?;
+ let lease = self.right_sidebar_remote_files_lease.as_ref()?;
+ (lease.connection_key() == connection_key)
+ .then(|| RemoteOperationOrigin::new(source_key, connection_key))
+ }
+
+ pub(crate) fn remote_operation_origin_matches(&self, origin: &RemoteOperationOrigin) -> bool {
+ let current_connection_key = self.current_remote_connection_key();
+ origin.matches(
+ self.right_sidebar_remote_files
+ .current_source_key()
+ .as_deref(),
+ current_connection_key.as_deref(),
+ )
+ }
+
+ /// Drop the panel lease only if it is the exact connection that failed.
+ /// A delayed callback from host A must not disconnect host B, nor a newer
+ /// replacement connection for A.
+ pub(crate) fn release_remote_files_lease_if_connection(
+ &mut self,
+ connection_key: &str,
+ connection_id: u64,
+ ) -> bool {
+ let disposition = remote_lease_failure_disposition(
+ self.right_sidebar_remote_files_lease
+ .as_ref()
+ .map(|lease| (lease.connection_key(), lease.connection_id())),
+ connection_key,
+ connection_id,
+ );
+ let matches = disposition == RemoteLeaseFailureDisposition::FailedConnectionInstalled;
+ if matches {
+ self.right_sidebar_remote_files_lease.take();
+ }
+ matches
+ }
+
+ fn remote_files_lease_failure_disposition(
+ &mut self,
+ connection_key: &str,
+ connection_id: u64,
+ ) -> RemoteLeaseFailureDisposition {
+ let disposition = remote_lease_failure_disposition(
+ self.right_sidebar_remote_files_lease
+ .as_ref()
+ .map(|lease| (lease.connection_key(), lease.connection_id())),
+ connection_key,
+ connection_id,
+ );
+ if disposition == RemoteLeaseFailureDisposition::FailedConnectionInstalled {
+ self.right_sidebar_remote_files_lease.take();
+ }
+ disposition
+ }
+
+ fn reconnect_remote_files_after_connection_change(&mut self, generation: u64, message: String) {
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message,
+ });
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ConnectRequested);
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+
+ pub(crate) fn remote_transfer_handles(
&self,
+ origin: &RemoteOperationOrigin,
) -> Option<(
Arc<dyn crate::termwindow::remote_files::RemoteFileBackend>,
crate::termwindow::remote_files::RemoteConnectionLease,
String,
u64,
)> {
+ if !self.remote_operation_origin_matches(origin) {
+ return None;
+ }
let lease = self.right_sidebar_remote_files_lease.as_ref()?;
+ if lease.connection_key() != origin.connection_key() {
+ return None;
+ }
let operation_lease = lease.operation_lease()?;
Some((
lease.backend(),
@@ -10722,26 +12353,6 @@ impl crate::TermWindow {
self.trim_remote_transfers();
}
- /// Clicking a transfer row: stop it if it is still going, otherwise clear
- /// the notice away.
- pub(crate) fn dismiss_or_cancel_remote_transfer(&mut self, id: u64) {
- let Some(index) = self
- .right_sidebar_remote_transfers
- .iter()
- .position(|transfer| transfer.id == id)
- else {
- return;
- };
- if self.right_sidebar_remote_transfers[index].is_running() {
- self.right_sidebar_remote_transfers[index]
- .progress
- .request_cancel();
- } else {
- self.right_sidebar_remote_transfers.remove(index);
- }
- self.invalidate_window();
- }
-
pub(crate) fn request_right_sidebar_remote_files_connect(&mut self, explicit: bool) {
let event = if explicit {
RemoteFilesEvent::ConnectRequested
@@ -10823,6 +12434,13 @@ impl crate::TermWindow {
});
return;
};
+ if self.current_remote_connection_key().as_deref() != Some(lease.connection_key()) {
+ self.reconnect_remote_files_after_connection_change(
+ generation,
+ "Remote Files configuration changed before loading the preview".to_string(),
+ );
+ return;
+ }
let Some(operation_lease) = lease.operation_lease() else {
self.right_sidebar_remote_files_lease.take();
self.close_right_sidebar_file_preview();
@@ -10893,7 +12511,28 @@ impl crate::TermWindow {
}
let error = result.message.clone();
if connection_died {
- term_window.right_sidebar_remote_files_lease.take();
+ match term_window
+ .remote_files_lease_failure_disposition(&connection_key, connection_id)
+ {
+ RemoteLeaseFailureDisposition::ReplacementForSameTarget => {
+ term_window.spawn_right_sidebar_remote_file_preview(
+ generation, source_key, path,
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ RemoteLeaseFailureDisposition::ReplacementForDifferentTarget => {
+ term_window.reconnect_remote_files_after_connection_change(
+ generation,
+ "Remote Files connection changed while loading the preview"
+ .to_string(),
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ RemoteLeaseFailureDisposition::FailedConnectionInstalled
+ | RemoteLeaseFailureDisposition::NoLease => {}
+ }
term_window.close_right_sidebar_file_preview();
term_window.right_sidebar_remote_files.transition(
RemoteFilesEvent::ConnectionFailed {
@@ -11516,25 +13155,47 @@ impl crate::TermWindow {
}
}
let text_x = file_icon_x + row_icon_size + row_metrics.icon_gap;
- let row_title = self.sidebar_file_row_title(&row.path, &row.name);
- self.paint_sidebar_text(
- layers,
- ui_font,
- ui_metrics,
- &row_title,
- text_x,
- y + (row_metrics
- .row_height
- .saturating_sub(ui_metrics.cell_size.height as usize))
- / 2,
- x.saturating_add(width)
- .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET)),
- if row.is_dir || is_selected {
- foreground
- } else {
- muted_fg
- },
- )
+ let text_width = x
+ .saturating_add(width)
+ .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET));
+ if let Some(input) = self.sidebar_file_rename_input(&row.path).cloned() {
+ self.paint_snippet_text_box(
+ layers,
+ 1,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ text_x,
+ y + self.ui_px(2),
+ text_width,
+ row_metrics.row_height.saturating_sub(self.ui_px(4)),
+ None,
+ "",
+ &input,
+ true,
+ UIItemType::RightSidebarFileRow(row.path.clone()),
+ false,
+ )
+ } else {
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ &row.name,
+ text_x,
+ y + (row_metrics
+ .row_height
+ .saturating_sub(ui_metrics.cell_size.height as usize))
+ / 2,
+ text_width,
+ if row.is_dir || is_selected {
+ foreground
+ } else {
+ muted_fg
+ },
+ )
+ }
}
#[allow(clippy::too_many_arguments)]
@@ -14352,6 +16013,223 @@ fn display_name(path: &Path) -> String {
.unwrap_or_else(|| path.display().to_string())
}
+/// Where a terminal drop should upload, given the setting and (when the
+/// setting asks for it) the pane's reported working directory. Pure, so the
+/// fallback rules stay testable: `cwd` without a usable cwd must degrade to
+/// the default folder, never fail the drop.
+fn resolve_drop_destination(setting: &str, cwd: Option<&str>) -> String {
+ if setting == crate::native_settings::REMOTE_DROP_DESTINATION_CWD {
+ match cwd {
+ Some(cwd) if !cwd.trim().is_empty() => cwd.to_string(),
+ _ => crate::native_settings::DEFAULT_REMOTE_DROP_DESTINATION.to_string(),
+ }
+ } else {
+ setting.to_string()
+ }
+}
+
+/// First free name for an uploaded file, browser-style: the file's own name,
+/// then ` (1)`, ` (2)`… before the extension. The probe is advisory — the
+/// upload's exclusive create remains the authority — but it turns the common
+/// re-drop of the same screenshot into a rename instead of a failure.
+async fn pick_free_remote_name(
+ backend: &dyn crate::termwindow::remote_files::RemoteFileBackend,
+ directory: &RemotePath,
+ file_name: &str,
+) -> Result<RemotePath, String> {
+ for candidate in download_name_candidates(file_name) {
+ let remote = directory.join_name(&candidate)?;
+ if !backend.exists(remote.clone()).await? {
+ return Ok(remote);
+ }
+ }
+ Err(format!(
+ "Unable to find a free name for {file_name} in {}",
+ directory.as_str()
+ ))
+}
+
+/// Delete a planned remote tree — children first, the root folder last —
+/// returning how many things were removed.
+///
+/// Stops at the first failure, keeping the count honest: what was already
+/// deleted is gone, and the message says how far it got. There is no rollback
+/// to offer; inventing one would mean re-creating files whose bytes no longer
+/// exist anywhere.
+async fn delete_remote_tree(
+ backend: &dyn crate::termwindow::remote_files::RemoteFileBackend,
+ root: &RemotePath,
+ entries: &[RemoteWalkEntry],
+ progress: &RemoteTransferProgress,
+) -> Result<u64, String> {
+ let total = entries.len() + 1;
+ let mut removed = 0u64;
+ // The plan is parents-first; deleting must be children-first, or every
+ // rmdir would find its directory still occupied.
+ for entry in entries.iter().rev() {
+ if progress.is_canceled() {
+ return Err(format!(
+ "{REMOTE_TRANSFER_CANCELED} — stopped after {removed} of {total}"
+ ));
+ }
+ let result = if entry.is_directory() {
+ backend.remove_directory(entry.path.clone()).await
+ } else {
+ // Files, symlinks and specials all go through unlink.
+ backend.remove_file(entry.path.clone()).await
+ };
+ if let Err(message) = result {
+ return Err(format!("{message} — stopped after {removed} of {total}"));
+ }
+ removed += 1;
+ progress.finish_item();
+ }
+ if progress.is_canceled() {
+ return Err(format!(
+ "{REMOTE_TRANSFER_CANCELED} — stopped after {removed} of {total}"
+ ));
+ }
+ backend
+ .remove_directory(root.clone())
+ .await
+ .map_err(|message| format!("{message} — stopped after {removed} of {total}"))?;
+ progress.finish_item();
+ Ok(removed + 1)
+}
+
+/// Download a planned remote tree into a freshly reserved folder under
+/// `downloads_dir`, returning where it landed.
+///
+/// The reservation (`fs::create_dir`, exclusive) is what makes the rest
+/// simple: everything under the new folder is new by construction, so files
+/// are created exclusively through the pinned [`DestinationRoot`] handle with
+/// no staging names — a failed file is deleted through that same handle, and
+/// what already landed is kept and reported, matching the local copy's
+/// stop-and-say-how-far semantics.
+async fn download_remote_tree(
+ backend: &dyn crate::termwindow::remote_files::RemoteFileBackend,
+ downloads_dir: &Path,
+ folder_name: &str,
+ entries: &[RemoteWalkEntry],
+ progress: &RemoteTransferProgress,
+) -> Result<PathBuf, TransferFailure> {
+ if let Err(err) = fs::create_dir_all(downloads_dir) {
+ return Err(TransferFailure::new(format!(
+ "Unable to use {}: {err}",
+ downloads_dir.display()
+ )));
+ }
+ let root = DestinationRoot::open(downloads_dir).map_err(|err| {
+ TransferFailure::new(format!("Unable to use {}: {err}", downloads_dir.display()))
+ })?;
+ let Some(destination) = reserve_download_directory(downloads_dir, folder_name, |candidate| {
+ candidate
+ .file_name()
+ .is_some_and(|name| root.create_dir_exclusive(Path::new(name)).is_ok())
+ }) else {
+ return Err(TransferFailure::new(format!(
+ "Unable to find a free name in {}",
+ downloads_dir.display()
+ )));
+ };
+ // The reserved name is a single component by construction. Keeping the
+ // Downloads handle (not reopening the new directory by path) pins every
+ // subsequent operation beneath the same verified root.
+ let top = PathBuf::from(
+ destination
+ .file_name()
+ .expect("a reserved directory always has a name"),
+ );
+
+ let total = entries.len();
+ for (index, entry) in entries.iter().enumerate() {
+ if progress.is_canceled() {
+ return Err(failed_folder_download(
+ &root,
+ &top,
+ &destination,
+ format!("{REMOTE_TRANSFER_CANCELED} — stopped after {index} of {total}"),
+ ));
+ }
+ let mut relative = top.clone();
+ for component in &entry.components {
+ relative.push(component);
+ }
+ if entry.is_directory() {
+ if let Err(err) = root.create_dir(&relative) {
+ return Err(failed_folder_download(
+ &root,
+ &top,
+ &destination,
+ format!(
+ "Unable to create {}: {err} — stopped after {index} of {total}",
+ root.join(&relative).display()
+ ),
+ ));
+ }
+ } else {
+ // Only plain files reach here: the Download walk skips symlinks
+ // and specials by construction.
+ let sink = match root.create_file(&relative) {
+ Ok(sink) => sink,
+ Err(err) => {
+ return Err(failed_folder_download(
+ &root,
+ &top,
+ &destination,
+ format!(
+ "Unable to create {}: {err} — stopped after {index} of {total}",
+ root.join(&relative).display()
+ ),
+ ))
+ }
+ };
+ if let Err(mut failure) = backend
+ .download_into(entry.path.clone(), sink, progress.clone())
+ .await
+ {
+ failure.message = format!("{} — stopped after {index} of {total}", failure.message);
+ // A half-written file must not survive wearing a whole file's
+ // name. Deleted through the handle — cleanup runs exactly when
+ // something has gone wrong, the worst moment to trust a path.
+ if let Err(err) = root.remove_file(&relative) {
+ log::warn!(
+ "remote files: unable to clean up the partial download {}: {err:#}",
+ root.join(&relative).display()
+ );
+ }
+ return Err(failed_folder_download(
+ &root,
+ &top,
+ &destination,
+ failure.message,
+ ));
+ }
+ }
+ progress.finish_item();
+ }
+ Ok(destination)
+}
+
+/// Turn a folder-download error into an honest cleanup result.
+///
+/// Removing the top directory succeeds only while it is still empty. If any
+/// earlier item landed (or cleanup of the current partial failed), keep the
+/// useful partial tree and tell the user exactly where it is.
+fn failed_folder_download(
+ root: &DestinationRoot,
+ top: &Path,
+ destination: &Path,
+ message: String,
+) -> TransferFailure {
+ let _ = root.remove_dir(top);
+ let mut failure = TransferFailure::new(message);
+ if local_path_is_occupied(destination) {
+ failure.leftover = Some(destination.display().to_string());
+ }
+ failure
+}
+
/// Walk every dropped path and find what already exists, all off the GUI
/// thread. Rejections are collected rather than thrown, so one bad source does
/// not sink the rest of a multi-select.
@@ -15634,26 +17512,29 @@ fn snippet_cursor_visible(now_ms: u128, blink_ms: u64) -> bool {
mod tests {
use super::{
approximate_note_text_width, build_right_sidebar_file_index, clip_note_texture,
- copy_entries_blocking, copy_file_chunked, file_preview_close_requires_reflow,
- file_release_action, file_row_placement, full_line_colors_by_byte,
- image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,
- naturalish_cmp, note_code_highlight_key, note_code_highlight_lines, note_code_row_height,
- note_image_display_size, note_open_pending_for_vault, note_release_action,
- open_with_candidate_allowed, path_key, preflight_local_copy, preview_line_count,
- preview_lines_from_text, preview_plain_lines_from_text, preview_text_range,
- preview_visible_colored, preview_visible_line_range, resolve_local_drop_target,
- resolve_remote_drop_target, right_sidebar_file_browse_rows_from_index,
- right_sidebar_file_row_metrics, right_sidebar_open_with_cache_key, sanitize_preview_text,
- scrollable_note_table_columns, search_right_sidebar_file_index, snippet_cursor_visible,
- snippet_run_buffer, sorted_open_with_candidates, virtual_note_line_range,
- visible_code_block_rounded_edges, visible_file_row_range, wrap_snippet_text_for_width,
- FileReleaseAction, FileRowPlacement, NoteApproximateTextMetrics, NoteCodeHighlightEntry,
- NoteCodeHighlightState, NoteReleaseAction, FILE_PREVIEW_MAX_BYTES, LOCAL_COPY_CHUNK,
+ copy_entries_blocking, copy_file_chunked, failed_folder_download,
+ file_preview_close_requires_reflow, file_release_action, file_row_placement,
+ full_line_colors_by_byte, image_pixels_within_preview_budget, load_file_preview,
+ load_file_preview_image, naturalish_cmp, note_code_highlight_key,
+ note_code_highlight_lines, note_code_row_height, note_image_display_size,
+ note_open_pending_for_vault, note_release_action, open_with_candidate_allowed, path_key,
+ pick_free_remote_name, preflight_local_copy, preview_line_count, preview_lines_from_text,
+ preview_plain_lines_from_text, preview_text_range, preview_visible_colored,
+ preview_visible_line_range, remote_lease_failure_disposition, resolve_drop_destination,
+ resolve_local_drop_target, resolve_remote_drop_target,
+ right_sidebar_file_browse_rows_from_index, right_sidebar_file_row_metrics,
+ right_sidebar_open_with_cache_key, sanitize_preview_text, scrollable_note_table_columns,
+ search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,
+ sorted_open_with_candidates, virtual_note_line_range, visible_code_block_rounded_edges,
+ visible_file_row_range, wrap_snippet_text_for_width, FileReleaseAction, FileRowPlacement,
+ NoteApproximateTextMetrics, NoteCodeHighlightEntry, NoteCodeHighlightState,
+ NoteReleaseAction, RemoteLeaseFailureDisposition, FILE_PREVIEW_MAX_BYTES, LOCAL_COPY_CHUNK,
NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,
};
use crate::markdown_editor::{NoteLineGeometry, ProjectedCodeBlock};
use crate::termwindow::remote_files::{
- RemoteFileKind, RemotePath, RemoteTransferProgress, REMOTE_TRANSFER_CANCELED,
+ RemoteFileBytes, RemoteFileKind, RemotePath, RemoteTransferProgress,
+ REMOTE_TRANSFER_CANCELED,
};
use crate::termwindow::transfer_walk::{DestinationRoot, OverwritePolicy, TransferEntryKind};
use crate::termwindow::{
@@ -15678,6 +17559,34 @@ mod tests {
assert!(file_preview_close_requires_reflow(true, 320, 320));
}
+ #[test]
+ fn folder_download_failures_clean_empty_reservations_and_report_partial_trees() {
+ let downloads = tempfile::tempdir().unwrap();
+ let root = DestinationRoot::open(downloads.path()).unwrap();
+
+ root.create_dir_exclusive(Path::new("empty")).unwrap();
+ let empty = downloads.path().join("empty");
+ let failure =
+ failed_folder_download(&root, Path::new("empty"), &empty, "stopped".to_string());
+ assert_eq!(failure.leftover, None);
+ assert!(!empty.exists(), "an empty reservation should be removed");
+
+ root.create_dir_exclusive(Path::new("partial")).unwrap();
+ let partial = downloads.path().join("partial");
+ fs::write(partial.join("landed.txt"), b"data").unwrap();
+ let failure = failed_folder_download(
+ &root,
+ Path::new("partial"),
+ &partial,
+ "connection lost".to_string(),
+ );
+ assert_eq!(
+ failure.leftover.as_deref(),
+ Some(partial.display().to_string().as_str())
+ );
+ assert!(partial.join("landed.txt").exists());
+ }
+
#[test]
fn preview_close_skips_a_tree_only_noop_but_tracks_width_changes() {
assert!(!file_preview_close_requires_reflow(false, 320, 320));
@@ -15716,6 +17625,124 @@ mod tests {
]
}
+ /// The `cwd` setting is a request, not a promise: a pane that has not
+ /// reported its working directory yet must still land the drop somewhere
+ /// stable rather than failing it.
+ #[test]
+ fn a_terminal_drop_destination_degrades_from_cwd_to_the_default() {
+ use crate::native_settings::{
+ DEFAULT_REMOTE_DROP_DESTINATION, REMOTE_DROP_DESTINATION_CWD,
+ };
+ assert_eq!(
+ resolve_drop_destination(DEFAULT_REMOTE_DROP_DESTINATION, None),
+ DEFAULT_REMOTE_DROP_DESTINATION
+ );
+ assert_eq!(
+ resolve_drop_destination(REMOTE_DROP_DESTINATION_CWD, Some("/srv/app")),
+ "/srv/app"
+ );
+ assert_eq!(
+ resolve_drop_destination(REMOTE_DROP_DESTINATION_CWD, None),
+ DEFAULT_REMOTE_DROP_DESTINATION
+ );
+ assert_eq!(
+ resolve_drop_destination(REMOTE_DROP_DESTINATION_CWD, Some(" ")),
+ DEFAULT_REMOTE_DROP_DESTINATION
+ );
+ // A custom path never consults the cwd, even when one is around.
+ assert_eq!(
+ resolve_drop_destination("~/inbox", Some("/srv/app")),
+ "~/inbox"
+ );
+ }
+
+ /// Backend double whose `exists` answers from a fixed set of taken names.
+ struct TakenNamesBackend {
+ taken: std::collections::HashSet<String>,
+ }
+
+ impl crate::termwindow::remote_files::RemoteFileBackend for TakenNamesBackend {
+ fn resolve_root(
+ &self,
+ _requested: String,
+ ) -> std::pin::Pin<
+ Box<dyn std::future::Future<Output = Result<RemotePath, String>> + Send + 'static>,
+ > {
+ Box::pin(async { RemotePath::from_server_absolute("/srv") })
+ }
+
+ fn list_directory(
+ &self,
+ _path: RemotePath,
+ _limit: usize,
+ ) -> std::pin::Pin<
+ Box<
+ dyn std::future::Future<
+ Output = Result<
+ crate::termwindow::remote_files::RemoteDirectoryListing,
+ String,
+ >,
+ > + Send
+ + 'static,
+ >,
+ > {
+ Box::pin(async {
+ Ok(crate::termwindow::remote_files::RemoteDirectoryListing {
+ entries: Vec::new(),
+ truncated: false,
+ })
+ })
+ }
+
+ fn read_file(
+ &self,
+ _path: RemotePath,
+ _limit: usize,
+ ) -> std::pin::Pin<
+ Box<dyn std::future::Future<Output = Result<RemoteFileBytes, String>> + Send + 'static>,
+ > {
+ Box::pin(async {
+ Ok(RemoteFileBytes {
+ bytes: Vec::new(),
+ truncated: false,
+ })
+ })
+ }
+
+ fn exists(
+ &self,
+ remote: RemotePath,
+ ) -> std::pin::Pin<
+ Box<dyn std::future::Future<Output = Result<bool, String>> + Send + 'static>,
+ > {
+ let taken = self.taken.contains(remote.as_str());
+ Box::pin(async move { Ok(taken) })
+ }
+ }
+
+ /// Re-dropping the same screenshot must become ` (1)`, ` (2)` — the
+ /// browser rule — with the extension kept whole.
+ #[test]
+ fn a_terminal_drop_picks_the_first_free_remote_name() {
+ let directory = RemotePath::from_server_absolute("/home/x/ThinkTerm_Uploads").unwrap();
+ let backend = TakenNamesBackend {
+ taken: [
+ "/home/x/ThinkTerm_Uploads/shot.png",
+ "/home/x/ThinkTerm_Uploads/shot (1).png",
+ ]
+ .iter()
+ .map(|name| (*name).to_string())
+ .collect(),
+ };
+ let chosen =
+ smol::block_on(pick_free_remote_name(&backend, &directory, "shot.png")).unwrap();
+ assert_eq!(chosen.as_str(), "/home/x/ThinkTerm_Uploads/shot (2).png");
+
+ let untouched =
+ smol::block_on(pick_free_remote_name(&backend, &directory, "fresh.txt")).unwrap();
+ assert_eq!(untouched.as_str(), "/home/x/ThinkTerm_Uploads/fresh.txt");
+ }
+
#[test]
fn a_drop_lands_in_the_directory_it_is_aimed_at() {
let root = RemotePath::from_server_absolute("/home/me").unwrap();
@@ -15813,7 +17840,7 @@ mod tests {
&progress,
)
.expect_err("a canceled copy fails");
- assert!(err.contains(REMOTE_TRANSFER_CANCELED), "{err}");
+ assert!(err.contains(REMOTE_TRANSFER_CANCELED), "{}", err);
assert_eq!(
fs::read(&destination).unwrap(),
@@ -15827,7 +17854,7 @@ mod tests {
.map(|entry| entry.file_name().to_string_lossy().to_string())
.filter(|name| name != "src.txt")
.collect();
- assert!(leftovers.is_empty(), "left behind: {leftovers:?}");
+ assert!(leftovers.is_empty(), "left behind: {:?}", leftovers);
}
/// Goes through the real `copy_file_chunked` Replace path and forces its
@@ -15873,7 +17900,7 @@ mod tests {
&progress,
)
.expect_err("a canceled replace fails");
- assert!(err.contains(REMOTE_TRANSFER_CANCELED), "{err}");
+ assert!(err.contains(REMOTE_TRANSFER_CANCELED), "{}", err);
assert!(
bystander.exists(),
@@ -15892,7 +17919,8 @@ mod tests {
.collect();
assert!(
leftovers.is_empty(),
- "the staging file must be removed from where it was made: {leftovers:?}"
+ "the staging file must be removed from where it was made: {:?}",
+ leftovers
);
}
@@ -15984,7 +18012,7 @@ mod tests {
&progress,
)
.expect_err("copying a file over itself must be refused");
- assert!(err.contains("already at the destination"), "{err}");
+ assert!(err.contains("already at the destination"), "{}", err);
assert_eq!(
fs::read(&source).unwrap(),
b"important data",
@@ -17051,4 +19079,24 @@ mod tests {
assert!(!snippet_cursor_visible(999, 500));
assert!(snippet_cursor_visible(1000, 500));
}
+
+ #[test]
+ fn a_failed_lease_distinguishes_replacements_from_the_connection_that_failed() {
+ assert_eq!(
+ remote_lease_failure_disposition(Some(("host:key", 7)), "host:key", 7),
+ RemoteLeaseFailureDisposition::FailedConnectionInstalled,
+ );
+ assert_eq!(
+ remote_lease_failure_disposition(Some(("host:key", 8)), "host:key", 7),
+ RemoteLeaseFailureDisposition::ReplacementForSameTarget,
+ );
+ assert_eq!(
+ remote_lease_failure_disposition(Some(("host:new-key", 8)), "host:key", 7),
+ RemoteLeaseFailureDisposition::ReplacementForDifferentTarget,
+ );
+ assert_eq!(
+ remote_lease_failure_disposition(None, "host:key", 7),
+ RemoteLeaseFailureDisposition::NoLease,
+ );
+ }
}
diff --git a/window/examples/async.rs b/window/examples/async.rs
index 55e1d967..d375fe32 100644
--- a/window/examples/async.rs
+++ b/window/examples/async.rs
@@ -90,6 +90,7 @@ impl MyWindow {
| WindowEvent::DroppedString(_)
| WindowEvent::PerformKeyAssignment(_)
| WindowEvent::PerformContextMenuAction(_)
+ | WindowEvent::ContextMenuDismissed
| WindowEvent::NativeTextInputReplace { .. }
| WindowEvent::ToggleWorkspaceSidebar
| WindowEvent::MouseLeave
diff --git a/window/src/lib.rs b/window/src/lib.rs
index 2c3dd43b..93c4d6b2 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -574,6 +574,9 @@ pub enum WindowEvent {
/// Dispatches an application-private action selected from a native menu.
PerformContextMenuAction(u64),
+ /// A native context menu finished tracking without a selected item.
+ ContextMenuDismissed,
+
AdviseModifiersLedStatus(Modifiers, KeyboardLedStatus),
}
diff --git a/window/src/os/macos/menu.rs b/window/src/os/macos/menu.rs
index e235c5de..cd8e11a7 100644
--- a/window/src/os/macos/menu.rs
+++ b/window/src/os/macos/menu.rs
@@ -97,15 +97,17 @@ impl Menu {
}
}
- pub fn pop_up_at(&self, view: id, x: f64, y: f64) {
+ /// Tracks the menu and returns whether the user selected an item.
+ pub fn pop_up_at(&self, view: id, x: f64, y: f64) -> bool {
unsafe {
let point = NSPoint::new(x, y);
- let _: BOOL = msg_send![
+ let selected: BOOL = msg_send![
*self.menu,
popUpMenuPositioningItem:nil
atLocation:point
inView:view
];
+ selected != NO
}
}
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 58a55add..80130035 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -1703,7 +1703,7 @@ impl WindowInner {
// pop-up until after our caller releases the borrow.
let view = self.view.clone();
promise::spawn::spawn(async move {
- unsafe {
+ let selected = unsafe {
let frame = NSView::frame(*view as *mut _);
let backing_frame = NSView::convertRectToBacking(*view as *mut _, frame);
let scale = if frame.size.width > 0.0 {
@@ -1712,7 +1712,21 @@ impl WindowInner {
1.0
};
- menu.pop_up_at(*view, coords.x as f64 / scale, coords.y as f64 / scale);
+ menu.pop_up_at(*view, coords.x as f64 / scale, coords.y as f64 / scale)
+ };
+ // Cocoa dispatches a selected action synchronously while tracking
+ // the menu. That action may open another native menu and install
+ // new pending confirmation state before this call returns, so the
+ // original menu must only cancel state when it closed *without*
+ // a selection (Escape or a click outside).
+ if !selected {
+ if let Some(window_view) = WindowView::get_this(unsafe { &**view }) {
+ window_view
+ .inner
+ .borrow_mut()
+ .events
+ .dispatch(WindowEvent::ContextMenuDismissed);
+ }
}
})
.detach();