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.

Avoid overwriting unreadable store; add shaped-text cache

RoversXc88a1aab239e
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index e815889a..7de759d9 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -3472,6 +3472,13 @@ pub struct PaneEntry {
/// Whether the pane is showing the alternate screen. Carried here as well
/// as in render changes so that a renderer knows it the moment it learns
/// the pane exists, rather than only once something in it next changes.
+ ///
+ /// Defaulted for the same reason as `PaneStackEntry::pane_stack_id`: this
+ /// type is the on-disk format of a Thread's saved layout, and every
+ /// snapshot written before the field existed omits it. Without a default,
+ /// adding it made all of them fail to decode, which meant every Thread
+ /// opened as a single empty pane and then overwrote its own saved layout.
+ #[serde(default)]
pub alt_screen: bool,
pub workspace: String,
pub cursor_pos: StableCursorPosition,
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 50d3447b..2c0cfdc5 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -991,6 +991,10 @@ fn setup_mux(
// Register ThinkTerm's saved SSH hosts as runtime mux domains so that
// reconnecting / restoring remote sessions can resolve them by name.
crate::ssh_hosts::register_saved_hosts();
+ // Both sources of domain names are registered by now, so a Space naming
+ // one that still does not exist belongs to a host that has been deleted.
+ // Local removal only; the server keeps its copy.
+ crate::ssh_hosts::forget_spaces_of_deleted_hosts();
let default_name =
default_domain_name.unwrap_or(config.default_domain.as_deref().unwrap_or("local"));
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 75ddc414..64e98de6 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -1,4 +1,5 @@
use crate::customglyph::{BlockKey, Poly};
+use crate::glyphcache::CachedGlyph;
use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
use crate::renderstate::{RenderContext, RenderState};
use crate::termwindow::render::corners::{
@@ -16,6 +17,7 @@ use crate::utilsprites::RenderMetrics;
use anyhow::Context;
use config::{configuration, Dimension, GeometryOrigin};
use std::cell::{Cell, RefCell};
+use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -1318,6 +1320,31 @@ pub fn show() {
}
}
+/// One string, shaped and glyph-resolved once for one font.
+///
+/// `width` is the same sum the painter walks, so a measurement and the paint
+/// that follows it can never disagree about how wide a label is.
+struct ShapedText {
+ glyphs: Vec<Rc<CachedGlyph>>,
+ width: f32,
+}
+
+/// Identifies a shaped run. The font id covers family, size, weight and DPI,
+/// so a settings change that rebuilds the fonts cannot be served stale entries
+/// even before the cache is cleared.
+#[derive(PartialEq, Eq, Hash)]
+struct ShapedTextKey {
+ font_id: usize,
+ text: String,
+}
+
+/// Distinct strings held before the cache is dropped and rebuilt.
+///
+/// The window's own labels are a fixed set in the low hundreds; the headroom
+/// above that is for text the user types into a field, which produces a new
+/// string per keystroke and is the only unbounded source here.
+const SHAPED_TEXT_CACHE_LIMIT: usize = 2048;
+
struct SettingsWindow {
instance_id: u64,
cleaned_up: bool,
@@ -1339,6 +1366,21 @@ struct SettingsWindow {
ui_context: UiContext<SettingsAction>,
compatibility_import: CompatibilityImportState,
status: String,
+ /// Shaped runs for this window's proportional text.
+ ///
+ /// This window paints entirely from immediate-mode code: every label is
+ /// measured and then drawn from scratch on each frame, and measuring an
+ /// over-long one used to shape it once more per step of a binary search.
+ /// Shaping is by far the most expensive part of that and the one part that
+ /// does not change between frames.
+ ///
+ /// Latin text hid the cost. Text the UI font does not cover does not:
+ /// `blocking_shape` hands those characters to the fallback resolver and
+ /// blocks the UI thread until it answers, so scrolling in Chinese or
+ /// Japanese dropped frames. Blocking is also why the result is safe to
+ /// keep — it returns only once the fallback is in place, so a cached run
+ /// is final rather than a first guess to be revised.
+ shape_cache: RefCell<HashMap<ShapedTextKey, Rc<ShapedText>>>,
}
impl SettingsWindow {
@@ -1437,6 +1479,7 @@ impl SettingsWindow {
ui_context: UiContext::default(),
compatibility_import: CompatibilityImportState::default(),
status: Self::initial_status(),
+ shape_cache: RefCell::new(HashMap::new()),
}));
let event_settings = Rc::clone(&settings);
@@ -1587,6 +1630,7 @@ impl SettingsWindow {
if let Some(render_state) = self.render_state.as_mut() {
render_state.recreate_texture_atlas(&self.fonts, &self.metrics, None)?;
}
+ self.invalidate_shaped_text();
}
if let Some(webgpu) = self.webgpu.as_ref() {
webgpu.resize(dimensions);
@@ -2601,6 +2645,7 @@ impl SettingsWindow {
SIDEBAR_BRAND_FONT_WEIGHT,
)?;
self.metrics = RenderMetrics::with_font_metrics(&self.ui_font.metrics());
+ self.invalidate_shaped_text();
Ok(())
}
@@ -3425,12 +3470,15 @@ impl SettingsWindow {
{
let size = size.max(current_size);
crate::perf::log_counter("settings_atlas_reallocate", size);
- if let Err(err) = self
+ let recreated = self
.render_state
.as_mut()
.unwrap()
- .recreate_texture_atlas(&self.fonts, &self.metrics, Some(size))
- {
+ .recreate_texture_atlas(&self.fonts, &self.metrics, Some(size));
+ // Every cached glyph now points into the old atlas,
+ // whether or not the new one was allocated.
+ self.invalidate_shaped_text();
+ if let Err(err) = recreated {
log::error!("settings window texture atlas resize failed: {err:#}");
break;
}
@@ -7692,18 +7740,16 @@ impl SettingsWindow {
return Ok(());
}
- let infos = font.blocking_shape(&display_text, None, Direction::LeftToRight, None, None)?;
- let render_state = self.render_state.as_ref().unwrap();
- let mut glyph_cache = render_state.glyph_cache.borrow_mut();
- let style = font.style();
+ let Some(shaped) = self.shaped_text(font, &display_text) else {
+ return Ok(());
+ };
let mut pos_x = x;
let baseline = self.metrics.cell_size.height as f32 + self.metrics.descender.get() as f32;
let left_offset = self.dimensions.pixel_width as f32 / 2.0;
let top_offset = self.dimensions.pixel_height as f32 / 2.0;
let right_edge = x + max_width;
- for info in infos {
- let glyph = glyph_cache.cached_glyph(&info, style, false, font, &self.metrics, 1)?;
+ for glyph in &shaped.glyphs {
if let Some(texture) = glyph.texture.as_ref() {
let glyph_x = (pos_x + (glyph.x_offset + glyph.bearing_x).get() as f32).round();
let glyph_y =
@@ -7736,25 +7782,67 @@ impl SettingsWindow {
Ok(())
}
- fn measure_text_width(&self, font: &Rc<LoadedFont>, text: &str) -> f32 {
+ /// Shape and glyph-resolve `text`, reusing the previous frame's work.
+ fn shaped_text(&self, font: &Rc<LoadedFont>, text: &str) -> Option<Rc<ShapedText>> {
if text.is_empty() {
- return 0.0;
+ return None;
}
- let Ok(infos) = font.blocking_shape(text, None, Direction::LeftToRight, None, None) else {
- return 0.0;
+ let key = ShapedTextKey {
+ font_id: font.id(),
+ text: text.to_string(),
};
- let render_state = self.render_state.as_ref().unwrap();
+ if let Some(shaped) = self.shape_cache.borrow().get(&key) {
+ return Some(Rc::clone(shaped));
+ }
+
+ let infos = font
+ .blocking_shape(text, None, Direction::LeftToRight, None, None)
+ .ok()?;
+ let render_state = self.render_state.as_ref()?;
let mut glyph_cache = render_state.glyph_cache.borrow_mut();
let style = font.style();
- infos
+ let glyphs: Vec<Rc<CachedGlyph>> = infos
.into_iter()
.filter_map(|info| {
glyph_cache
.cached_glyph(&info, style, false, font, &self.metrics, 1)
.ok()
- .map(|glyph| glyph.x_advance.get() as f32)
})
- .sum()
+ .collect();
+ drop(glyph_cache);
+
+ let shaped = Rc::new(ShapedText {
+ width: glyphs
+ .iter()
+ .map(|glyph| glyph.x_advance.get() as f32)
+ .sum(),
+ glyphs,
+ });
+
+ let mut cache = self.shape_cache.borrow_mut();
+ // Dropping the whole map rather than one entry: there is no recency
+ // order to evict by, and the labels it is full of are about to be
+ // re-shaped on the very next frame anyway.
+ if cache.len() >= SHAPED_TEXT_CACHE_LIMIT {
+ cache.clear();
+ }
+ cache.insert(key, Rc::clone(&shaped));
+ Some(shaped)
+ }
+
+ /// Drop shaped runs that a new font, DPI or glyph atlas has invalidated.
+ ///
+ /// The atlas cases matter as much as the font ones: a cached run holds
+ /// glyphs by texture coordinate, and those describe the atlas that was
+ /// current when they were rasterized.
+ fn invalidate_shaped_text(&self) {
+ self.shape_cache.borrow_mut().clear();
+ }
+
+ fn measure_text_width(&self, font: &Rc<LoadedFont>, text: &str) -> f32 {
+ self.shaped_text(font, text)
+ .map(|shaped| shaped.width)
+ .unwrap_or(0.0)
}
fn text_with_ellipsis(&self, font: &Rc<LoadedFont>, text: &str, max_width: f32) -> String {
@@ -7772,31 +7860,31 @@ impl SettingsWindow {
return String::new();
}
- let mut boundaries = text
- .char_indices()
- .map(|(idx, _)| idx)
- .chain(std::iter::once(text.len()))
- .collect::<Vec<_>>();
- boundaries.dedup();
-
- let mut low = 0;
- let mut high = boundaries.len().saturating_sub(1);
- let mut best = 0;
- while low <= high {
- let mid = (low + high) / 2;
- let candidate = &text[..boundaries[mid]];
- let width = self.measure_text_width(font, candidate) + ellipsis_width;
- if width <= max_width {
- best = mid;
- low = mid + 1;
- } else if mid == 0 {
+ // Walk the run already shaped above rather than binary-searching by
+ // re-measuring prefixes. The old search shaped log2(len) extra strings
+ // per label per frame and left every one of those prefixes behind,
+ // which would now be junk filling the cache as well as time spent.
+ let Some(shaped) = self.shaped_text(font, text) else {
+ return String::new();
+ };
+ let budget = max_width - ellipsis_width;
+ let mut width = 0.0;
+ let mut chars = text.char_indices();
+ let mut end = 0;
+ // One glyph per character is the common case and the assumption the
+ // painter already makes; zip stops at whichever runs out first, so a
+ // string that shapes to fewer glyphs truncates early rather than
+ // indexing past the end.
+ for (glyph, (idx, _)) in shaped.glyphs.iter().zip(&mut chars) {
+ let advance = glyph.x_advance.get() as f32;
+ if width + advance > budget {
break;
- } else {
- high = mid - 1;
}
+ width += advance;
+ end = idx + text[idx..].chars().next().map_or(0, char::len_utf8);
}
- format!("{}{}", text[..boundaries[best]].trim_end(), ellipsis)
+ format!("{}{}", text[..end].trim_end(), ellipsis)
}
fn native_settings_path() -> PathBuf {
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
index 12a1504d..fcf088b6 100644
--- a/wezterm-gui/src/ssh_hosts.rs
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -486,6 +486,67 @@ pub fn register_saved_hosts() {
}
}
+/// Every name this host can be connected under.
+///
+/// A ThinkTerm Connect host attaches its persistent mux domain under the
+/// user's label; a direct host registers as `ssh:user@host`. A Space mirrored
+/// from that machine is tagged with whichever one it arrived through.
+pub fn domain_names_for_host(spec: &SshHostSpec) -> Vec<String> {
+ let mut names = vec![ssh_domain_name(spec)];
+ let label = spec.label.trim();
+ if !label.is_empty() && !names.iter().any(|name| name == label) {
+ names.push(label.to_string());
+ }
+ names
+}
+
+/// Whether a mux domain of this name can still be reached.
+///
+/// Deliberately the same question `connect_domain_from_ssh_host` answers, so
+/// "reachable" here means exactly "something would happen if you clicked it":
+/// a lua-configured or already-attached domain, or a saved host that would be
+/// connected under this name.
+fn domain_name_is_reachable(domain_name: &str) -> bool {
+ if Mux::get().get_domain_by_name(domain_name).is_some() {
+ return true;
+ }
+ list_all_hosts()
+ .into_iter()
+ .any(|entry| entry.spec.label == domain_name || entry.id == domain_name)
+}
+
+/// Drop this device's copy of every Space whose mux server it can no longer
+/// name.
+///
+/// Deleting a host used to leave its Spaces in the sidebar forever: they
+/// cannot be connected to (nothing resolves the domain), and they cannot be
+/// renamed or removed through the server either, because every mutation is
+/// refused while the domain is unattached. Removal is local — the server keeps
+/// its Spaces and other devices never notice — so re-adding the host brings
+/// them straight back.
+///
+/// Call once at startup, after both lua domains and saved hosts are
+/// registered and before any window exists.
+pub fn forget_spaces_of_deleted_hosts() {
+ let unreachable = crate::workspace_threads::remote_space_domains()
+ .into_iter()
+ .filter(|domain| !domain_name_is_reachable(domain))
+ .collect::<Vec<_>>();
+ if unreachable.is_empty() {
+ return;
+ }
+ for space_id in crate::workspace_threads::space_ids_for_domains(&unreachable) {
+ match crate::workspace_threads::forget_space_locally(&space_id) {
+ Ok(_) => log::info!(
+ "removed Space {space_id} from this device: the host its mux \
+ server was reached through is no longer saved. The server \
+ keeps it; re-adding the host brings it back."
+ ),
+ Err(err) => log::warn!("cannot remove unreachable Space {space_id}: {err:?}"),
+ }
+ }
+}
+
pub fn list_system_hosts() -> Vec<SshHostEntry> {
let path = config::HOME_DIR.join(".ssh").join("config");
match parse_system_ssh_config(&path) {
@@ -673,6 +734,36 @@ Host prod *.internal
.ends_with("/.ssh/prod"));
}
+ /// The two names one host can attach a mux domain under. A Space is tagged
+ /// with whichever one it arrived through, so deleting the host has to look
+ /// for both or it leaves half of them stranded.
+ #[test]
+ fn a_host_is_reachable_under_both_its_label_and_its_endpoint() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.label = "DO SYD".to_string();
+ spec.username = Some("x".to_string());
+
+ assert_eq!(
+ domain_names_for_host(&spec),
+ vec!["ssh:[email protected]".to_string(), "DO SYD".to_string()]
+ );
+
+ // A host left unlabelled must not contribute an empty name, which
+ // would match nothing and read as a bug at the call site.
+ spec.label = " ".to_string();
+ assert_eq!(
+ domain_names_for_host(&spec),
+ vec!["ssh:[email protected]".to_string()]
+ );
+
+ // And a label that is already the endpoint is not worth saying twice.
+ spec.label = "ssh:[email protected]".to_string();
+ assert_eq!(
+ domain_names_for_host(&spec),
+ vec!["ssh:[email protected]".to_string()]
+ );
+ }
+
fn spec_with_options(ssh_options: HashMap<String, String>) -> SshHostSpec {
SshHostSpec {
label: "t".to_string(),
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 1a87219c..22e36b3e 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -3624,7 +3624,7 @@ impl TermWindow {
self.start_delete_space(space_id, removal, false);
}
- fn start_delete_space(
+ pub(crate) fn start_delete_space(
&mut self,
space_id: &str,
removal: crate::workspace_threads::SpaceRemoval,
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
index d71e4892..753b2311 100644
--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -600,18 +600,51 @@ impl SshHostsView {
ContentViewResponse::Redraw
}
SshViewAction::Delete(i) => {
- if let Some(entry) = self.filtered.get(i) {
- let id = entry.id.clone();
- if entry.source == SshHostSource::ThinkTerm {
- if let Err(err) = ssh_hosts::try_remove_host(&id) {
- log::error!("failed to delete SSH host {id}: {err:#}");
- } else {
- let _ = workspace_threads::remove_project(&id);
- }
- self.refresh();
- }
+ let Some(entry) = self
+ .filtered
+ .get(i)
+ .filter(|entry| entry.source == SshHostSource::ThinkTerm)
+ else {
+ return ContentViewResponse::Redraw;
+ };
+ let id = entry.id.clone();
+ // Read what this host brought in while the record naming it is
+ // still here. A ThinkTerm Connect host mirrors whole Spaces
+ // from its mux server, and those are keyed by domain name, not
+ // by host id — so `remove_project` below, which matches the
+ // host id, never sees them. Left behind they are unreachable:
+ // nothing resolves the domain to connect, and every rename or
+ // delete is refused because it has to go through a server this
+ // device can no longer name.
+ let orphaned_spaces =
+ workspace_threads::space_ids_for_domains(&ssh_hosts::domain_names_for_host(
+ &entry.spec,
+ ));
+
+ if let Err(err) = ssh_hosts::try_remove_host(&id) {
+ log::error!("failed to delete SSH host {id}: {err:#}");
+ self.refresh();
+ return ContentViewResponse::Redraw;
}
- ContentViewResponse::Redraw
+ let _ = workspace_threads::remove_project(&id);
+ self.refresh();
+
+ if orphaned_spaces.is_empty() {
+ return ContentViewResponse::Redraw;
+ }
+ // Through the window, because one of them may be the Space
+ // this very window is showing; that path moves it off first.
+ // Local removal: the server keeps its Spaces, so re-adding the
+ // host brings them back.
+ ContentViewResponse::Run(Box::new(move |term_window| {
+ for space_id in orphaned_spaces {
+ term_window.start_delete_space(
+ &space_id,
+ workspace_threads::SpaceRemoval::Local,
+ false,
+ );
+ }
+ }))
}
SshViewAction::FocusField(n) => {
let count = self
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index f0caabd0..b53378f6 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -337,12 +337,21 @@ pub struct SpaceView {
lazy_static::lazy_static! {
static ref THREAD_STORE: Mutex<WorkspaceThreadStore> =
Mutex::new(load_workspace_thread_store().unwrap_or_else(|err| {
- log::warn!("failed to load ThinkTerm workspace thread store: {err:#}");
+ log::error!("cannot read the ThinkTerm workspace store: {err:#}");
+ preserve_unreadable_workspace_thread_store();
+ STORE_IS_UNREADABLE.store(true, Ordering::Release);
WorkspaceThreadStore::default()
}));
static ref WINDOW_SPACES: Mutex<HashMap<u64, SpaceId>> = Mutex::new(HashMap::new());
static ref MATERIALIZING_LAYOUT_WORKSPACES: Mutex<HashMap<String, usize>> =
Mutex::new(HashMap::new());
+ /// Workspaces whose saved layout this build could not decode. They opened
+ /// as a single terminal, so snapshotting them would write that one pane
+ /// over the arrangement we failed to read — turning a version skew into
+ /// permanent data loss. Held in memory only: a build that can read the
+ /// file again starts with an empty set and resumes saving normally.
+ static ref UNREADABLE_LAYOUT_WORKSPACES: Mutex<std::collections::HashSet<String>> =
+ Mutex::new(std::collections::HashSet::new());
static ref WORK_RUNNING_LAST_SEEN: Mutex<HashMap<String, std::time::Instant>> =
Mutex::new(HashMap::new());
static ref WORK_STATUS_RECHECK_PENDING: Mutex<std::collections::HashSet<String>> =
@@ -375,6 +384,15 @@ lazy_static::lazy_static! {
static THREAD_STORE_PERSIST_SCHEDULED: AtomicBool = AtomicBool::new(false);
static THREAD_STORE_PERSIST_DIRTY: AtomicBool = AtomicBool::new(false);
+/// Set when the store on disk exists but could not be read.
+///
+/// Nothing may be written while it is set. The in-memory store is empty in
+/// that case, so saving would replace a file this build could not parse with
+/// one describing nothing at all — every Space, Project and Thread the user
+/// has, and the evidence needed to work out why, gone in a single atomic
+/// rename. The same shape as a layout snapshot the renderer cannot decode,
+/// and the same answer: read failures must not be allowed to write.
+static STORE_IS_UNREADABLE: AtomicBool = AtomicBool::new(false);
static NEXT_SPACE_OWNER_ID: AtomicU64 = AtomicU64::new(1);
fn publish_thinkterm_session_changed() {
wezterm_mux_server_impl::thinkterm_session::publish_changed();
@@ -531,6 +549,35 @@ fn migrate_legacy_remote_hosts(value: &serde_json::Value) {
}
}
+/// Copy a store that could not be read to a name that will not be reopened.
+///
+/// Refusing to write already keeps the original safe; this makes it safe from
+/// the user too, who has no reason to suspect the untouched-looking file is
+/// the only copy of their workspace and may well delete it while trying to get
+/// a working app back.
+fn preserve_unreadable_workspace_thread_store() {
+ let path = workspace_thread_store_path();
+ let Some(name) = path.file_stem().and_then(|stem| stem.to_str()) else {
+ return;
+ };
+ let preserved = path.with_file_name(format!("{name}.unreadable-{}.json", now_ts()));
+ if preserved.exists() {
+ return;
+ }
+ match fs::copy(&path, &preserved) {
+ Ok(_) => log::error!(
+ "kept a copy of the unreadable workspace store at {}. \
+ ThinkTerm will not save over the original, so nothing further \
+ is lost; this session's changes are not being saved either.",
+ preserved.display()
+ ),
+ Err(err) => log::error!(
+ "cannot copy the unreadable workspace store to {}: {err:#}",
+ preserved.display()
+ ),
+ }
+}
+
pub fn save_workspace_thread_store(store: &WorkspaceThreadStore) -> Result<()> {
save_workspace_thread_store_to_path(&workspace_thread_store_path(), store)
}
@@ -856,6 +903,34 @@ pub enum SpaceRemoval {
Everywhere,
}
+/// Every mux domain this device currently mirrors Spaces from.
+pub fn remote_space_domains() -> Vec<String> {
+ THREAD_STORE.lock().remote_space_domains()
+}
+
+/// The Spaces this device mirrored from a mux server it reaches under any of
+/// `domain_names`.
+///
+/// A host is connected under more than one name — the label for a ThinkTerm
+/// Connect domain, `ssh:user@host` for a direct one — and the Space records
+/// whichever one it arrived through, so a caller asking "what did this host
+/// bring in" has to ask about all of them.
+pub fn space_ids_for_domains(domain_names: &[String]) -> Vec<SpaceId> {
+ THREAD_STORE.lock().space_ids_for_domains(domain_names)
+}
+
+/// Owner id no live window can have: they are handed out from 1.
+const NO_WINDOW_OWNER: u64 = 0;
+
+/// Drop this device's copy of `space_id` with no window in the picture.
+///
+/// The windowed path ([`TermWindow::start_delete_space`]) exists because a
+/// window showing the Space has to be moved off it first. At startup there are
+/// no windows yet, so there is nothing to move.
+pub fn forget_space_locally(space_id: &str) -> Result<DeletedSpace, DeleteSpaceError> {
+ delete_space_for_window_local(NO_WINDOW_OWNER, space_id, SpaceRemoval::Local)
+}
+
fn delete_space_for_window_local(
owner_id: u64,
space_id: &str,
@@ -1578,6 +1653,16 @@ pub fn acknowledge_thread_work_for_workspace_deferred(workspace: &str) -> bool {
change.changed
}
+fn mark_layout_unreadable(workspace: &str) {
+ UNREADABLE_LAYOUT_WORKSPACES
+ .lock()
+ .insert(workspace.to_string());
+}
+
+fn layout_is_unreadable(workspace: &str) -> bool {
+ UNREADABLE_LAYOUT_WORKSPACES.lock().contains(workspace)
+}
+
pub fn is_materializing_thread_layout(workspace: &str) -> bool {
MATERIALIZING_LAYOUT_WORKSPACES
.lock()
@@ -1625,6 +1710,13 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(
return;
}
+ // The window standing in for a layout we could not read describes one
+ // empty pane, and saving that would destroy the arrangement it stands in
+ // for. Keep the file as it is; a build that can read it restores it.
+ if layout_is_unreadable(workspace) {
+ return;
+ }
+
// Domain-owned windows (remote mux windows, tmux) must never have
// their LAYOUT snapshotted locally: the remote mux server owns the
// layout truth, and a local snapshot would fight it on restore. Font
@@ -1705,16 +1797,29 @@ pub async fn materialize_thread(
return Ok(());
}
+ // Decoding before the branch, rather than inside `materialize_layout`, is
+ // what makes a layout this build cannot read a lost *arrangement* instead
+ // of a Thread that will not open: an undecodable snapshot falls through to
+ // the plain spawn below, which still lands in the project directory.
let layout = layout.and_then(|layout| {
if layout.tabs.is_empty() {
- None
- } else {
- Some(layout)
+ return None;
}
+ let tabs = decode_layout_tabs(&workspace_name, &layout)?;
+ Some((layout, tabs))
});
- if let Some(layout) = layout {
+ if let Some((layout, tabs)) = layout {
let _guard = MaterializeThreadLayoutGuard::new(workspace_name.clone());
- materialize_layout(mux, workspace_name, layout, initial_cwd, size, term_config).await
+ materialize_layout(
+ mux,
+ workspace_name,
+ layout,
+ tabs,
+ initial_cwd,
+ size,
+ term_config,
+ )
+ .await
} else {
// A thread whose Space lives on a mux server needs its window tagged
// with that domain. `spawn_tab_or_window` makes untagged windows, and
@@ -3177,6 +3282,34 @@ impl WorkspaceThreadStore {
.collect()
}
+ /// The same question across several names, in sidebar order because the
+ /// caller removes them one at a time and a nondeterministic order would
+ /// make which Space a window lands on depend on hashing.
+ fn space_ids_for_domains(&self, domain_names: &[String]) -> Vec<SpaceId> {
+ self.spaces
+ .iter()
+ .filter(|space| {
+ space
+ .client_domain
+ .as_ref()
+ .is_some_and(|domain| domain_names.iter().any(|name| name == domain))
+ })
+ .map(|space| space.id.clone())
+ .collect()
+ }
+
+ fn remote_space_domains(&self) -> Vec<String> {
+ let mut domains: Vec<String> = Vec::new();
+ for space in &self.spaces {
+ if let Some(domain) = space.client_domain.as_ref() {
+ if !domains.iter().any(|known| known == domain) {
+ domains.push(domain.clone());
+ }
+ }
+ }
+ domains
+ }
+
#[cfg(test)]
fn materialized_workspaces_for_space(&self, space_id: &str) -> Vec<String> {
self.projects
@@ -4957,6 +5090,11 @@ fn valid_font_scale(font_scale: Option<f64>) -> Option<f64> {
}
fn persist_locked(store: &WorkspaceThreadStore) {
+ // See `STORE_IS_UNREADABLE`: this write is the one that would destroy the
+ // file, so it is the one that has to be refused.
+ if STORE_IS_UNREADABLE.load(Ordering::Acquire) {
+ return;
+ }
if let Err(err) = save_workspace_thread_store(store) {
log::warn!("failed to save ThinkTerm thread store: {err:#}");
}
@@ -5163,10 +5301,41 @@ fn collect_pane_entries<'a>(node: &'a PaneNode, entries: &mut Vec<&'a PaneEntry>
}
}
+/// Decode a saved layout's tabs, or `None` if this build cannot read it.
+///
+/// `PaneNode` is the mux's wire type as well as this file's on-disk format.
+/// Adding a field to it is free on the wire — the codec version rises and both
+/// ends move together — but every layout already on disk was written by an
+/// older shape and stays that way forever. So a decode failure here is a
+/// routine forward-compatibility event, not a bug in the file, and it must not
+/// take the whole Thread down with it.
+fn decode_layout_tabs(
+ workspace_name: &str,
+ layout: &WorkspaceThreadLayoutSnapshot,
+) -> Option<Vec<PaneNode>> {
+ let mut tabs = Vec::with_capacity(layout.tabs.len());
+ for tab_value in &layout.tabs {
+ match serde_json::from_value::<PaneNode>(tab_value.clone()) {
+ Ok(node) => tabs.push(node),
+ Err(err) => {
+ log::error!(
+ "cannot read the saved layout for {workspace_name}: {err:#}. \
+ Opening a single terminal instead; the saved layout is left \
+ on disk untouched."
+ );
+ mark_layout_unreadable(workspace_name);
+ return None;
+ }
+ }
+ }
+ Some(tabs)
+}
+
async fn materialize_layout(
mux: Arc<Mux>,
workspace_name: String,
layout: WorkspaceThreadLayoutSnapshot,
+ tabs: Vec<PaneNode>,
initial_cwd: Option<String>,
size: TerminalSize,
term_config: Arc<dyn TerminalConfiguration>,
@@ -5178,10 +5347,8 @@ async fn materialize_layout(
.collect::<HashMap<_, _>>();
let mut window_id = None;
let mut spawned_tabs = 0usize;
- for tab_value in &layout.tabs {
- let node: PaneNode =
- serde_json::from_value(tab_value.clone()).context("decode thread tab layout")?;
- let first_entry = first_pane_entry(&node);
+ for node in &tabs {
+ let first_entry = first_pane_entry(node);
let cwd = first_entry
.and_then(|entry| working_dir_for_entry(entry, &terminal_specs))
.or_else(|| initial_cwd.clone());
@@ -5206,7 +5373,7 @@ async fn materialize_layout(
restore_node(
Arc::clone(&mux),
pane.pane_id(),
- &node,
+ node,
&terminal_specs,
Arc::clone(&term_config),
)
@@ -6077,6 +6244,111 @@ mod tests {
store
}
+ /// A store that fails to parse must not come back as an empty one that
+ /// then overwrites the file it could not read. The parse is strict, so the
+ /// next field added to `Space`, `Project` or `WorkspaceThread` without a
+ /// default lands here — and unlike a layout snapshot, what it would take
+ /// with it is every Space, Project and Thread the user has.
+ #[test]
+ fn a_store_that_cannot_be_parsed_is_an_error_rather_than_an_empty_store() {
+ let dir = tempdir().unwrap();
+ let path = dir.path().join("workspace_threads.json");
+
+ // A thread as an older build wrote it, missing a field a later one
+ // made required.
+ std::fs::write(
+ &path,
+ serde_json::json!({
+ "spaces": [{"id": "space-1", "name": "Default", "active_project_id": null}],
+ "projects": [{
+ "id": "project-1",
+ "space_id": "space-1",
+ "name": "thinkterm",
+ "path": "/tmp/thinkterm",
+ "active_thread_id": null,
+ "threads": [{
+ "id": "thread-1",
+ "name": "main",
+ "project_id": "project-1",
+ "layout": null,
+ "materialized_workspace_name": null
+ // last_active_at, which the struct requires, is absent
+ }]
+ }]
+ })
+ .to_string(),
+ )
+ .unwrap();
+
+ let err = load_workspace_thread_store_from_path(&path)
+ .expect_err("a store missing a required field must not parse as empty");
+ assert!(
+ format!("{err:#}").contains("last_active_at"),
+ "the error should name the field: {err:#}"
+ );
+
+ // And the file is still there to be recovered from.
+ assert!(path.exists());
+ }
+
+ /// `WorkspaceThreadLayoutSnapshot::tabs` holds serialized `PaneNode`s, so
+ /// that type is this file's on-disk format as much as it is the mux's wire
+ /// format. A field added to it without a default invalidates every layout
+ /// a user has ever saved: `materialize_layout` fails to decode, the Thread
+ /// comes up as a single empty pane, and the next snapshot writes that over
+ /// the layout it could not read. This is the shape of a tab saved before
+ /// `PaneEntry::alt_screen` existed.
+ #[test]
+ fn layout_snapshot_saved_before_alt_screen_still_decodes() {
+ let stored = serde_json::json!({
+ "Leaf": {
+ "window_id": 1,
+ "tab_id": 1,
+ "pane_id": 6,
+ "title": "zsh",
+ "size": {"rows": 24, "cols": 80, "pixel_width": 0, "pixel_height": 0, "dpi": 0},
+ "working_dir": "file:///Users/someone/project",
+ "is_active_pane": true,
+ "is_zoomed_pane": false,
+ "workspace": "default",
+ "cursor_pos": {"x": 0, "y": 0, "shape": "Default", "visibility": "Visible"},
+ "physical_top": 0,
+ "top_row": 0,
+ "left_col": 0,
+ "tty_name": null
+ }
+ });
+
+ let node: PaneNode =
+ serde_json::from_value(stored).expect("decode a layout saved before alt_screen");
+ let PaneNode::Leaf(entry) = node else {
+ panic!("expected a leaf");
+ };
+ assert_eq!(entry.pane_id, 6);
+ assert!(!entry.alt_screen);
+ }
+
+ /// The next field added to `PaneEntry` without a default will land here
+ /// again. When it does, the Thread must still open — and the arrangement
+ /// we could not read must still be on disk afterwards, so that a build
+ /// which can read it gets it back.
+ #[test]
+ fn an_undecodable_layout_is_refused_rather_than_overwritten() {
+ let workspace = "test-workspace-undecodable-layout";
+ let layout = WorkspaceThreadLayoutSnapshot {
+ active_tab: 0,
+ tabs: vec![serde_json::json!({"Leaf": {"a field from the future": true}})],
+ terminal_specs: vec![],
+ };
+
+ assert!(!layout_is_unreadable(workspace));
+ // No tabs to spawn from, so `materialize_thread` falls through to the
+ // plain project-directory spawn instead of failing the Thread.
+ assert!(decode_layout_tabs(workspace, &layout).is_none());
+ // And the single pane that spawn produces must not be saved over it.
+ assert!(layout_is_unreadable(workspace));
+ }
+
fn test_project(id: &str, name: &str, path: PathBuf, threads: Vec<WorkspaceThread>) -> Project {
test_project_in_space(&default_space_id(), id, name, path, threads)
}
@@ -8500,6 +8772,48 @@ mod tests {
WINDOW_SPACES.lock().remove(&owner_id);
}
+ /// Deleting a host has to find every Space that host brought in, and a
+ /// host is connectable under more than one name: the label for a ThinkTerm
+ /// Connect domain, `ssh:user@host` for a direct one. Matching only one of
+ /// them leaves the other's Spaces stranded — visible, unconnectable, and
+ /// refusing every rename or delete because those go through a server this
+ /// device can no longer name.
+ #[test]
+ fn a_hosts_spaces_are_found_under_every_name_it_connects_under() {
+ let mut store = remote_test_store("DO SYD");
+ store.spaces.push(Space {
+ id: "space-direct".to_string(),
+ name: "direct".to_string(),
+ active_project_id: None,
+ note_vault: None,
+ is_default: false,
+ client_domain: Some("ssh:[email protected]".to_string()),
+ });
+ store.spaces.push(Space {
+ id: "space-elsewhere".to_string(),
+ name: "another server".to_string(),
+ active_project_id: None,
+ note_vault: None,
+ is_default: false,
+ client_domain: Some("DO AMS".to_string()),
+ });
+
+ let names = vec!["ssh:[email protected]".to_string(), "DO SYD".to_string()];
+ assert_eq!(
+ store.space_ids_for_domains(&names),
+ vec!["space-remote".to_string(), "space-direct".to_string()]
+ );
+
+ // Another server's Spaces, and the purely local one, stay put.
+ assert!(!store
+ .space_ids_for_domains(&names)
+ .contains(&"space-elsewhere".to_string()));
+
+ let mut domains = store.remote_space_domains();
+ domains.sort();
+ assert_eq!(domains, vec!["DO AMS", "DO SYD", "ssh:[email protected]"]);
+ }
+
/// Ending the sessions of one Space must not reach into its siblings on
/// the same server, which the domain id alone cannot distinguish.
#[test]