A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Make remote workspace state server-authoritative
RoversX122656a0e074
diff --git a/Cargo.lock b/Cargo.lockindex a03d7c95..f3903bff 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7575,7 +7575,9 @@ dependencies = ["promise","rangeset","rcgen",+ "serde_json","smol",+ "tempfile","termwiz","url","wezterm-client",diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex 8c5c17de..67327def 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -36,6 +36,12 @@ use thiserror::Error;use wezterm_term::color::ColorPalette;use wezterm_term::{Alert, ClipboardSelection, StableRowIndex, TerminalSize};+pub mod thinkterm_tree;+pub use thinkterm_tree::{+ apply_op, ensure_unique_thread_names, ThinkTermTree, TreeOp, TtProject, TtProjectId, TtSpace,+ TtSpaceId, TtThread, TtThreadId,+};+#[derive(Error, Debug)]#[error("Corrupt Response: {0}")]pub struct CorruptResponse(String);@@ -445,7 +451,8 @@ macro_rules! pdu {/// 48: MovePaneToStack moves an existing pane into another pane stack./// 49: Palette advisories are client-only, application palette state is/// explicit, and SetFocusedPane carries the focusing client's palette.-pub const CODEC_VERSION: usize = 49;+/// 50: The server owns the ThinkTerm sidebar tree (Space/Project/Thread).+pub const CODEC_VERSION: usize = 51;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -510,6 +517,9 @@ pdu! {ActivatePaneInStack: 64,MovePaneToStack: 65,SetApplicationPalette: 66,+ GetThinkTermTree: 67,+ MutateThinkTermTree: 68,+ ThinkTermTreeState: 69,}impl Pdu {@@ -843,6 +853,32 @@ pub struct NotifyAlert {pub alert: Alert,}+/// Fetch the server's ThinkTerm sidebar tree. Responds with+/// `ThinkTermTreeState`.+#[derive(Deserialize, Serialize, PartialEq, Debug)]+pub struct GetThinkTermTree {}++/// Apply mutations to the server's ThinkTerm sidebar tree, in order. Responds+/// with `ThinkTermTreeState` carrying the tree as it stands afterwards; when+/// anything changed the same state is also pushed unilaterally to every other+/// connected client.+///+/// A batch is what lets a client seed a fresh server — "here is everything I+/// have for you" — in one round trip and one broadcast instead of a storm of+/// single-op RPCs.+#[derive(Deserialize, Serialize, PartialEq, Debug)]+pub struct MutateThinkTermTree {+ pub ops: Vec<TreeOp>,+}++/// The whole tree. It is small enough (tens of KB) that shipping it in full on+/// every change is cheaper than maintaining a delta protocol, and it removes+/// an entire class of resync bugs. Doubles as the server's unilateral push.+#[derive(Deserialize, Serialize, PartialEq, Debug)]+pub struct ThinkTermTreeState {+ pub tree: ThinkTermTree,+}+#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct TabAddedToWindow {pub tab_id: TabId,@@ -1259,6 +1295,72 @@ mod test {);}+ #[test]+ fn thinkterm_tree_round_trip() {+ let mut tree = ThinkTermTree::default();+ for op in [+ TreeOp::CreateSpace {+ space_id: "s1".into(),+ name: "Work".into(),+ },+ TreeOp::CreateProject {+ project_id: "p1".into(),+ space_id: "s1".into(),+ name: "thinkterm".into(),+ path: "/home/x/github/ThinkTerm".into(),+ },+ TreeOp::CreateThread {+ thread_id: "t1".into(),+ project_id: "p1".into(),+ name: "main".into(),+ workspace: Some("thinkterm:p1:t1".into()),+ created_at: 1_700_000_000,+ },+ TreeOp::SetThreadPinned {+ thread_id: "t1".into(),+ pinned: true,+ last_active_at: 1_700_000_001,+ },+ ] {+ assert!(apply_op(&mut tree, &op));+ }++ let mut encoded = Vec::new();+ Pdu::ThinkTermTreeState(ThinkTermTreeState { tree: tree.clone() })+ .encode(&mut encoded, 0x11)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x11,+ pdu: Pdu::ThinkTermTreeState(ThinkTermTreeState { tree }),+ }+ );++ // The ops travel in the other direction, in batches.+ let ops = vec![+ TreeOp::MoveThreadBefore {+ project_id: "p1".into(),+ thread_id: "t2".into(),+ before: None,+ },+ TreeOp::DeleteSpace {+ space_id: "s1".into(),+ },+ ];+ let mut encoded = Vec::new();+ Pdu::MutateThinkTermTree(MutateThinkTermTree { ops: ops.clone() })+ .encode(&mut encoded, 0x12)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x12,+ pdu: Pdu::MutateThinkTermTree(MutateThinkTermTree { ops }),+ }+ );+ }+#[test]fn application_palette_state_round_trip() {for palette in [None, Some(ColorPalette::default())] {diff --git a/codec/src/thinkterm_tree.rs b/codec/src/thinkterm_tree.rsnew file mode 100644index 00000000..6c309eed--- /dev/null+++ b/codec/src/thinkterm_tree.rs@@ -0,0 +1,993 @@+//! The ThinkTerm sidebar tree (Space -> Project -> Thread) as it lives on the+//! mux server.+//!+//! The mux protocol proper only knows about workspaces, windows, tabs and+//! panes. Everything the ThinkTerm sidebar draws above a workspace — which+//! Space a workspace belongs to, what the user named it, the order of the+//! rows, pins — used to live only in the GUI client's local store, so a second+//! device attaching to the same server saw nothing.+//!+//! This module holds the wire representation of that tree plus `apply_op`,+//! the single implementation of every mutation's semantics. The server runs+//! it against the current authoritative tree and broadcasts the result;+//! clients may use it only for a connection-scoped in-flight presentation+//! overlay. A server response always replaces that prediction.+//!+//! Only *shared* state belongs here. Per-device state (which Space/Thread this+//! device is looking at, collapse state, font scales, note bindings) stays in+//! the client's own store: `ClientId` is pid+epoch and does not survive a+//! client restart, so it cannot key durable per-device records.++use serde::{Deserialize, Serialize};++pub type TtSpaceId = String;+pub type TtProjectId = String;+pub type TtThreadId = String;++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct TtSpace {+ pub id: TtSpaceId,+ pub name: String,+}++/// A Project is the sidebar's "globe row" — the UI calls it a Workspace.+/// `path` is a directory on the *server*, so it stays a plain string rather+/// than a `PathBuf` that a client might be tempted to resolve locally. The+/// server's own row carries the `wezterm-mux://` sentinel instead of a cwd.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct TtProject {+ pub id: TtProjectId,+ pub space_id: TtSpaceId,+ pub name: String,+ pub path: String,+ pub threads: Vec<TtThread>,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct TtThread {+ pub id: TtThreadId,+ pub project_id: TtProjectId,+ pub name: String,+ /// The mux workspace this thread resolves to once it has been created on+ /// the server; `planned_` is the name reserved for it beforehand. Both are+ /// shared: they are how any device finds the thread's panes again.+ pub planned_workspace_name: Option<String>,+ pub materialized_workspace_name: Option<String>,+ pub last_active_at: i64,+ pub is_pinned: bool,+ pub is_unread: bool,+}++/// Projects are a flat list carrying their `space_id`, mirroring the GUI+/// store's layout so that row-order semantics translate one to one.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ThinkTermTree {+ pub spaces: Vec<TtSpace>,+ pub projects: Vec<TtProject>,+ /// How many times the server has changed this tree. Zero means "no client+ /// has ever written to this server", which is the only state in which a+ /// client may treat an empty tree as *unset* and seed it from its own+ /// rows. Once it is non-zero an empty tree means the user really did+ /// delete the last Space, and stale caches must not resurrect it.+ ///+ /// Only the server ever advances this; `apply_op` deliberately leaves it+ /// alone so that a client's optimistic local apply cannot invent a+ /// revision the server has not issued.+ #[serde(default)]+ pub revision: u64,+}++impl ThinkTermTree {+ /// True when this server has never had a tree written to it, so its+ /// emptiness carries no information and a client should offer its own+ /// rows as the seed.+ pub fn is_uninitialized(&self) -> bool {+ self.revision == 0 && self.spaces.is_empty()+ }+}++/// Every mutation of the shared tree.+///+/// Ids are generated by the requesting client, but become real only when the+/// server includes them in its returned tree. Timestamps travel in the op too;+/// naming and referential invariants are still settled against the server's+/// current tree rather than trusted from a client's cached snapshot.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub enum TreeOp {+ CreateSpace {+ space_id: TtSpaceId,+ name: String,+ },+ RenameSpace {+ space_id: TtSpaceId,+ name: String,+ },+ DeleteSpace {+ space_id: TtSpaceId,+ },+ CreateProject {+ project_id: TtProjectId,+ space_id: TtSpaceId,+ name: String,+ path: String,+ },+ RenameProject {+ project_id: TtProjectId,+ name: String,+ },+ RemoveProject {+ project_id: TtProjectId,+ },+ MoveProjectBefore {+ space_id: TtSpaceId,+ project_id: TtProjectId,+ before: Option<TtProjectId>,+ },+ CreateThread {+ thread_id: TtThreadId,+ project_id: TtProjectId,+ name: String,+ workspace: Option<String>,+ created_at: i64,+ },+ /// `name` is the requested name. The server de-duplicates it against the+ /// authoritative project; `last_active_at` is the requested recency.+ RenameThread {+ thread_id: TtThreadId,+ name: String,+ last_active_at: i64,+ },+ DeleteThread {+ thread_id: TtThreadId,+ },+ MoveThreadBefore {+ project_id: TtProjectId,+ thread_id: TtThreadId,+ before: Option<TtThreadId>,+ },+ /// Pinning also counts as touching the thread; see `RenameThread`.+ SetThreadPinned {+ thread_id: TtThreadId,+ pinned: bool,+ last_active_at: i64,+ },+ SetThreadUnread {+ thread_id: TtThreadId,+ unread: bool,+ },+ SetThreadWorkspaceName {+ thread_id: TtThreadId,+ planned: Option<String>,+ materialized: Option<String>,+ },+ TouchThread {+ thread_id: TtThreadId,+ at: i64,+ },+}++impl ThinkTermTree {+ pub fn space(&self, space_id: &str) -> Option<&TtSpace> {+ self.spaces.iter().find(|space| space.id == space_id)+ }++ pub fn project(&self, project_id: &str) -> Option<&TtProject> {+ self.projects+ .iter()+ .find(|project| project.id == project_id)+ }++ pub fn thread(&self, thread_id: &str) -> Option<&TtThread> {+ self.projects+ .iter()+ .flat_map(|project| project.threads.iter())+ .find(|thread| thread.id == thread_id)+ }++ /// The project that owns `thread_id`, if any.+ pub fn project_of_thread(&self, thread_id: &str) -> Option<&TtProject> {+ self.projects+ .iter()+ .find(|project| project.threads.iter().any(|thread| thread.id == thread_id))+ }++ pub fn projects_in_space<'a>(+ &'a self,+ space_id: &'a str,+ ) -> impl Iterator<Item = &'a TtProject> + 'a {+ self.projects+ .iter()+ .filter(move |project| project.space_id == space_id)+ }++ fn thread_mut(&mut self, thread_id: &str) -> Option<&mut TtThread> {+ self.projects+ .iter_mut()+ .flat_map(|project| project.threads.iter_mut())+ .find(|thread| thread.id == thread_id)+ }+}++fn thread_name_in_use(project: &TtProject, ignored_thread_id: Option<&str>, name: &str) -> bool {+ project+ .threads+ .iter()+ .any(|thread| ignored_thread_id != Some(thread.id.as_str()) && thread.name == name)+}++fn next_thread_name(project: &TtProject) -> String {+ let mut index = project.threads.len().saturating_add(1).max(1);+ loop {+ let candidate = format!("Thread {index}");+ if !thread_name_in_use(project, None, &candidate) {+ return candidate;+ }+ index += 1;+ }+}++/// Settle a client-requested thread name against the project as it exists in+/// the authoritative tree. Clients can race from the same snapshot, so the+/// server must not assume that the name they computed is still available.+fn unique_thread_name(+ project: &TtProject,+ ignored_thread_id: Option<&str>,+ requested: &str,+) -> String {+ let requested = requested.trim();+ if requested.is_empty() {+ return next_thread_name(project);+ }+ if !thread_name_in_use(project, ignored_thread_id, requested) {+ return requested.to_string();+ }++ let mut index = 2;+ loop {+ let candidate = format!("{requested} {index}");+ if !thread_name_in_use(project, ignored_thread_id, &candidate) {+ return candidate;+ }+ index += 1;+ }+}++/// Repair legacy or externally-written trees before the server exposes them.+/// Project order is authoritative, so the first occurrence keeps its name and+/// later collisions receive the same suffixes used for live mutations.+pub fn ensure_unique_thread_names(tree: &mut ThinkTermTree) -> bool {+ let mut changed = false;+ for project in &mut tree.projects {+ let mut settled = TtProject {+ id: project.id.clone(),+ space_id: project.space_id.clone(),+ name: project.name.clone(),+ path: project.path.clone(),+ threads: Vec::with_capacity(project.threads.len()),+ };+ for mut thread in std::mem::take(&mut project.threads) {+ let name = unique_thread_name(&settled, None, &thread.name);+ if thread.name != name {+ thread.name = name;+ changed = true;+ }+ settled.threads.push(thread);+ }+ project.threads = settled.threads;+ }+ changed+}++/// Apply `op` to `tree`, returning whether anything actually changed.+///+/// Unknown ids and no-op moves return false rather than erroring: an op can+/// legitimately race a concurrent delete from another device, and the caller's+/// contract is only "broadcast when something changed".+pub fn apply_op(tree: &mut ThinkTermTree, op: &TreeOp) -> bool {+ match op {+ TreeOp::CreateSpace { space_id, name } => {+ if tree.space(space_id).is_some() {+ return false;+ }+ tree.spaces.push(TtSpace {+ id: space_id.clone(),+ name: name.clone(),+ });+ true+ }++ TreeOp::RenameSpace { space_id, name } => {+ let name = name.trim();+ if name.is_empty() {+ return false;+ }+ match tree.spaces.iter_mut().find(|space| space.id == *space_id) {+ Some(space) if space.name != name => {+ space.name = name.to_string();+ true+ }+ _ => false,+ }+ }++ TreeOp::DeleteSpace { space_id } => {+ let Some(index) = tree.spaces.iter().position(|space| space.id == *space_id) else {+ return false;+ };+ tree.spaces.remove(index);+ tree.projects+ .retain(|project| project.space_id != *space_id);+ true+ }++ TreeOp::CreateProject {+ project_id,+ space_id,+ name,+ path,+ } => {+ if tree.project(project_id).is_some() || tree.space(space_id).is_none() {+ return false;+ }+ tree.projects.push(TtProject {+ id: project_id.clone(),+ space_id: space_id.clone(),+ name: name.clone(),+ path: path.clone(),+ threads: vec![],+ });+ true+ }++ TreeOp::RenameProject { project_id, name } => {+ let name = name.trim();+ if name.is_empty() {+ return false;+ }+ match tree+ .projects+ .iter_mut()+ .find(|project| project.id == *project_id)+ {+ Some(project) if project.name != name => {+ project.name = name.to_string();+ true+ }+ _ => false,+ }+ }++ TreeOp::RemoveProject { project_id } => {+ let Some(index) = tree+ .projects+ .iter()+ .position(|project| project.id == *project_id)+ else {+ return false;+ };+ tree.projects.remove(index);+ true+ }++ // Mirrors WorkspaceThreadStore::move_project_before: the anchor is a+ // position in the space-filtered view, and `before: None` means "after+ // the space's last project" rather than "end of the whole Vec".+ TreeOp::MoveProjectBefore {+ space_id,+ project_id,+ before,+ } => {+ let Some(from) = tree+ .projects+ .iter()+ .position(|project| project.id == *project_id && project.space_id == *space_id)+ else {+ return false;+ };+ let to = match before {+ Some(before_id) => {+ if before_id == project_id {+ return false;+ }+ let Some(index) = tree.projects.iter().position(|project| {+ project.id == *before_id && project.space_id == *space_id+ }) else {+ return false;+ };+ index+ }+ None => {+ let Some(last) = tree+ .projects+ .iter()+ .rposition(|project| project.space_id == *space_id)+ else {+ return false;+ };+ last + 1+ }+ };+ if to == from || to == from + 1 {+ return false;+ }+ let project = tree.projects.remove(from);+ let to = if to > from { to - 1 } else { to };+ tree.projects.insert(to, project);+ true+ }++ TreeOp::CreateThread {+ thread_id,+ project_id,+ name,+ workspace,+ created_at,+ } => {+ if tree.thread(thread_id).is_some() {+ return false;+ }+ let Some(project) = tree+ .projects+ .iter_mut()+ .find(|project| project.id == *project_id)+ else {+ return false;+ };+ let name = unique_thread_name(project, None, name);+ project.threads.push(TtThread {+ id: thread_id.clone(),+ project_id: project_id.clone(),+ name,+ planned_workspace_name: None,+ materialized_workspace_name: workspace.clone(),+ last_active_at: *created_at,+ is_pinned: false,+ is_unread: false,+ });+ true+ }++ TreeOp::RenameThread {+ thread_id,+ name,+ last_active_at,+ } => {+ if name.trim().is_empty() {+ return false;+ }+ for project in &mut tree.projects {+ let Some(index) = project+ .threads+ .iter()+ .position(|thread| thread.id == *thread_id)+ else {+ continue;+ };+ let name = unique_thread_name(project, Some(thread_id), name);+ let thread = &mut project.threads[index];+ if thread.name == name && thread.last_active_at == *last_active_at {+ return false;+ }+ thread.name = name;+ thread.last_active_at = *last_active_at;+ return true;+ }+ false+ }++ TreeOp::DeleteThread { thread_id } => {+ for project in tree.projects.iter_mut() {+ if let Some(index) = project+ .threads+ .iter()+ .position(|thread| thread.id == *thread_id)+ {+ project.threads.remove(index);+ return true;+ }+ }+ false+ }++ // Mirrors WorkspaceThreadStore::move_thread_before: pinned threads+ // render in the sidebar's separate cross-project section, so they are+ // neither movable nor valid anchors.+ TreeOp::MoveThreadBefore {+ project_id,+ thread_id,+ before,+ } => {+ let Some(project) = tree+ .projects+ .iter_mut()+ .find(|project| project.id == *project_id)+ else {+ return false;+ };+ let Some(from) = project+ .threads+ .iter()+ .position(|thread| thread.id == *thread_id)+ else {+ return false;+ };+ if project.threads[from].is_pinned {+ return false;+ }+ let to = match before {+ Some(before_id) => {+ if before_id == thread_id {+ return false;+ }+ let Some(index) = project+ .threads+ .iter()+ .position(|thread| thread.id == *before_id && !thread.is_pinned)+ else {+ return false;+ };+ index+ }+ None => project.threads.len(),+ };+ if to == from || to == from + 1 {+ return false;+ }+ let thread = project.threads.remove(from);+ let to = if to > from { to - 1 } else { to };+ project.threads.insert(to, thread);+ true+ }++ TreeOp::SetThreadPinned {+ thread_id,+ pinned,+ last_active_at,+ } => match tree.thread_mut(thread_id) {+ Some(thread)+ if thread.is_pinned != *pinned || thread.last_active_at != *last_active_at =>+ {+ thread.is_pinned = *pinned;+ thread.last_active_at = *last_active_at;+ true+ }+ _ => false,+ },++ TreeOp::SetThreadUnread { thread_id, unread } => match tree.thread_mut(thread_id) {+ Some(thread) if thread.is_unread != *unread => {+ thread.is_unread = *unread;+ true+ }+ _ => false,+ },++ TreeOp::SetThreadWorkspaceName {+ thread_id,+ planned,+ materialized,+ } => match tree.thread_mut(thread_id) {+ Some(thread)+ if thread.planned_workspace_name != *planned+ || thread.materialized_workspace_name != *materialized =>+ {+ thread.planned_workspace_name = planned.clone();+ thread.materialized_workspace_name = materialized.clone();+ true+ }+ _ => false,+ },++ TreeOp::TouchThread { thread_id, at } => match tree.thread_mut(thread_id) {+ Some(thread) if thread.last_active_at != *at => {+ thread.last_active_at = *at;+ true+ }+ _ => false,+ },+ }+}++#[cfg(test)]+mod test {+ use super::*;++ fn seeded() -> ThinkTermTree {+ let mut tree = ThinkTermTree::default();+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateSpace {+ space_id: "s1".into(),+ name: "Work".into()+ }+ ));+ for (id, name) in [("p1", "alpha"), ("p2", "beta"), ("p3", "gamma")] {+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateProject {+ project_id: id.into(),+ space_id: "s1".into(),+ name: name.into(),+ path: format!("/srv/{name}"),+ }+ ));+ }+ for (id, project) in [("t1", "p1"), ("t2", "p1"), ("t3", "p1")] {+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateThread {+ thread_id: id.into(),+ project_id: project.into(),+ name: id.into(),+ workspace: None,+ created_at: 100,+ }+ ));+ }+ tree+ }++ fn project_ids(tree: &ThinkTermTree, space_id: &str) -> Vec<String> {+ tree.projects_in_space(space_id)+ .map(|project| project.id.clone())+ .collect()+ }++ fn thread_ids(tree: &ThinkTermTree, project_id: &str) -> Vec<String> {+ tree.project(project_id)+ .map(|project| project.threads.iter().map(|t| t.id.clone()).collect())+ .unwrap_or_default()+ }++ #[test]+ fn creates_are_idempotent_and_require_a_parent() {+ let mut tree = seeded();+ assert!(!apply_op(+ &mut tree,+ &TreeOp::CreateSpace {+ space_id: "s1".into(),+ name: "Work again".into()+ }+ ));+ // A project whose Space does not exist is refused rather than+ // creating an unreachable row.+ assert!(!apply_op(+ &mut tree,+ &TreeOp::CreateProject {+ project_id: "px".into(),+ space_id: "nope".into(),+ name: "orphan".into(),+ path: "/srv/orphan".into(),+ }+ ));+ assert!(tree.project("px").is_none());+ assert!(!apply_op(+ &mut tree,+ &TreeOp::CreateThread {+ thread_id: "t1".into(),+ project_id: "p1".into(),+ name: "dupe".into(),+ workspace: None,+ created_at: 1,+ }+ ));+ assert_eq!(thread_ids(&tree, "p1"), vec!["t1", "t2", "t3"]);+ }++ #[test]+ fn a_project_moves_before_a_sibling_and_to_the_end() {+ let mut tree = seeded();+ assert!(apply_op(+ &mut tree,+ &TreeOp::MoveProjectBefore {+ space_id: "s1".into(),+ project_id: "p3".into(),+ before: Some("p1".into()),+ }+ ));+ assert_eq!(project_ids(&tree, "s1"), vec!["p3", "p1", "p2"]);++ assert!(apply_op(+ &mut tree,+ &TreeOp::MoveProjectBefore {+ space_id: "s1".into(),+ project_id: "p3".into(),+ before: None,+ }+ ));+ assert_eq!(project_ids(&tree, "s1"), vec!["p1", "p2", "p3"]);++ // Already in place: no change, so no broadcast.+ assert!(!apply_op(+ &mut tree,+ &TreeOp::MoveProjectBefore {+ space_id: "s1".into(),+ project_id: "p3".into(),+ before: None,+ }+ ));+ assert!(!apply_op(+ &mut tree,+ &TreeOp::MoveProjectBefore {+ space_id: "s1".into(),+ project_id: "p1".into(),+ before: Some("p2".into()),+ }+ ));+ }++ #[test]+ fn a_project_move_stays_inside_its_space() {+ let mut tree = seeded();+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateSpace {+ space_id: "s2".into(),+ name: "Side".into()+ }+ ));+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateProject {+ project_id: "q1".into(),+ space_id: "s2".into(),+ name: "delta".into(),+ path: "/srv/delta".into(),+ }+ ));+ // An anchor from another Space is not a sibling.+ assert!(!apply_op(+ &mut tree,+ &TreeOp::MoveProjectBefore {+ space_id: "s1".into(),+ project_id: "p1".into(),+ before: Some("q1".into()),+ }+ ));+ assert_eq!(project_ids(&tree, "s1"), vec!["p1", "p2", "p3"]);+ assert_eq!(project_ids(&tree, "s2"), vec!["q1"]);+ }++ #[test]+ fn threads_reorder_and_pinned_rows_stay_put() {+ let mut tree = seeded();+ assert!(apply_op(+ &mut tree,+ &TreeOp::MoveThreadBefore {+ project_id: "p1".into(),+ thread_id: "t3".into(),+ before: Some("t1".into()),+ }+ ));+ assert_eq!(thread_ids(&tree, "p1"), vec!["t3", "t1", "t2"]);++ assert!(apply_op(+ &mut tree,+ &TreeOp::SetThreadPinned {+ thread_id: "t1".into(),+ pinned: true,+ last_active_at: 101,+ }+ ));+ // A pinned thread is neither a movable row nor a valid anchor.+ assert!(!apply_op(+ &mut tree,+ &TreeOp::MoveThreadBefore {+ project_id: "p1".into(),+ thread_id: "t1".into(),+ before: Some("t2".into()),+ }+ ));+ assert!(!apply_op(+ &mut tree,+ &TreeOp::MoveThreadBefore {+ project_id: "p1".into(),+ thread_id: "t2".into(),+ before: Some("t1".into()),+ }+ ));+ assert_eq!(thread_ids(&tree, "p1"), vec!["t3", "t1", "t2"]);+ }++ #[test]+ fn deleting_a_space_takes_its_projects_with_it() {+ let mut tree = seeded();+ assert!(apply_op(+ &mut tree,+ &TreeOp::DeleteSpace {+ space_id: "s1".into()+ }+ ));+ assert!(tree.spaces.is_empty());+ assert!(tree.projects.is_empty());+ assert!(!apply_op(+ &mut tree,+ &TreeOp::DeleteSpace {+ space_id: "s1".into()+ }+ ));+ }++ #[test]+ fn thread_flags_and_names_only_report_real_changes() {+ let mut tree = seeded();+ assert!(apply_op(+ &mut tree,+ &TreeOp::RenameThread {+ thread_id: "t1".into(),+ name: " build ".into(),+ last_active_at: 200,+ }+ ));+ assert_eq!(tree.thread("t1").unwrap().name, "build");+ assert!(!apply_op(+ &mut tree,+ &TreeOp::RenameThread {+ thread_id: "t1".into(),+ name: "build".into(),+ last_active_at: 200,+ }+ ));+ assert!(!apply_op(+ &mut tree,+ &TreeOp::RenameThread {+ thread_id: "t1".into(),+ name: " ".into(),+ last_active_at: 300,+ }+ ));+ assert!(apply_op(+ &mut tree,+ &TreeOp::SetThreadWorkspaceName {+ thread_id: "t1".into(),+ planned: None,+ materialized: Some("thinkterm:p1:t1".into()),+ }+ ));+ assert!(!apply_op(+ &mut tree,+ &TreeOp::SetThreadWorkspaceName {+ thread_id: "t1".into(),+ planned: None,+ materialized: Some("thinkterm:p1:t1".into()),+ }+ ));+ assert_eq!(+ tree.project_of_thread("t1")+ .map(|project| project.id.clone()),+ Some("p1".to_string())+ );+ }++ #[test]+ fn authoritative_tree_deduplicates_concurrent_thread_names() {+ let mut tree = seeded();+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateThread {+ thread_id: "t4".into(),+ project_id: "p1".into(),+ name: "t1".into(),+ workspace: None,+ created_at: 101,+ }+ ));+ assert_eq!(tree.thread("t4").unwrap().name, "t1 2");++ assert!(apply_op(+ &mut tree,+ &TreeOp::RenameThread {+ thread_id: "t2".into(),+ name: "t1".into(),+ last_active_at: 102,+ }+ ));+ assert_eq!(tree.thread("t2").unwrap().name, "t1 3");+ let names = tree+ .project("p1")+ .unwrap()+ .threads+ .iter()+ .map(|thread| thread.name.as_str())+ .collect::<std::collections::HashSet<_>>();+ assert_eq!(names.len(), tree.project("p1").unwrap().threads.len());+ }++ #[test]+ fn loading_repair_keeps_the_first_duplicate_and_renames_the_rest() {+ let mut tree = seeded();+ tree.thread_mut("t2").unwrap().name = "same".into();+ tree.thread_mut("t3").unwrap().name = "same".into();+ tree.thread_mut("t1").unwrap().name = "same".into();++ assert!(ensure_unique_thread_names(&mut tree));+ let names = tree+ .project("p1")+ .unwrap()+ .threads+ .iter()+ .map(|thread| thread.name.as_str())+ .collect::<Vec<_>>();+ assert_eq!(names, ["same", "same 2", "same 3"]);+ assert!(!ensure_unique_thread_names(&mut tree));+ }++ /// An empty tree means two very different things, and only the revision+ /// tells them apart: a server nobody has written to yet wants seeding,+ /// while a server whose last Space was deleted must not have it put back+ /// by whichever device still holds a stale cache.+ #[test]+ fn only_a_server_that_was_never_written_to_invites_a_seed() {+ assert!(ThinkTermTree::default().is_uninitialized());++ let emptied = ThinkTermTree {+ revision: 7,+ ..Default::default()+ };+ assert!(!emptied.is_uninitialized());++ // Rows are proof of a write even when an older server never recorded+ // a revision, so they settle it on their own.+ let mut unversioned = ThinkTermTree::default();+ assert!(apply_op(+ &mut unversioned,+ &TreeOp::CreateSpace {+ space_id: "s1".into(),+ name: "Work".into()+ }+ ));+ assert_eq!(unversioned.revision, 0);+ assert!(!unversioned.is_uninitialized());+ }++ /// The client applies an op locally and the server applies the same op to+ /// its own copy; the two must land on identical trees, otherwise the+ /// authoritative broadcast would visibly snap the UI back.+ #[test]+ fn client_and_server_converge_on_the_same_tree() {+ let ops = vec![+ TreeOp::CreateSpace {+ space_id: "s9".into(),+ name: "Side".into(),+ },+ TreeOp::CreateProject {+ project_id: "p9".into(),+ space_id: "s9".into(),+ name: "blog".into(),+ path: "/srv/blog".into(),+ },+ TreeOp::CreateThread {+ thread_id: "t9".into(),+ project_id: "p9".into(),+ name: "main".into(),+ workspace: None,+ created_at: 7,+ },+ TreeOp::SetThreadPinned {+ thread_id: "t9".into(),+ pinned: true,+ last_active_at: 8,+ },+ TreeOp::MoveProjectBefore {+ space_id: "s1".into(),+ project_id: "p2".into(),+ before: None,+ },+ TreeOp::DeleteThread {+ thread_id: "t2".into(),+ },+ ];++ let mut client = seeded();+ let mut server = seeded();+ for op in &ops {+ let client_changed = apply_op(&mut client, op);+ let server_changed = apply_op(&mut server, op);+ assert_eq!(+ client_changed, server_changed,+ "divergent verdict on {op:?}"+ );+ }+ assert_eq!(client, server);+ }+}diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rsindex d9f58acc..ecefbeeb 100644--- a/config/src/keyassignment.rs+++ b/config/src/keyassignment.rs@@ -591,10 +591,19 @@ pub enum KeyAssignment {PromptRenameWorkspaceThread(String),PromptRenameSpace(String),CreateSpace,+ /// Create a Space that lives on the named mux server rather than locally.+ /// One server can host several.+ CreateSpaceOnDomain(String),SwitchSpace(String),+ /// Remove the Space from this device. A remote Space lives on its mux+ /// server, so this only drops the local copy: the Space is still there for+ /// other devices and comes back on the next connect.DeleteSpace(String),- /// Like DeleteSpace, but for a remote (mux-domain) Space also kill its- /// sessions on the remote mux server before detaching.+ /// Delete a remote Space on the server that hosts it, so it disappears+ /// from every device.+ DeleteSpaceEverywhere(String),+ /// Like DeleteSpaceEverywhere, but also kill the Space's sessions on the+ /// remote mux server first.DeleteSpaceAndRemoteSessions(String),CreateWorkspaceThread(String),ToggleWorkspaceThreadsCollapsed(String),diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 04412cb7..205ae4bf 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -98,6 +98,10 @@ pub enum MuxNotification {old_workspace: String,new_workspace: String,},+ /// The mux server's ThinkTerm sidebar tree (Space/Project/Thread) changed;+ /// every connection re-sends it. Raised only on the server side — a GUI+ /// mux never owns a tree of its own.+ ThinkTermTreeChanged,}static SUB_ID: AtomicUsize = AtomicUsize::new(0);diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 1ceee344..6ab2a1c0 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -329,6 +329,24 @@ fn process_unilateral(.detach();return Ok(());}+ Pdu::ThinkTermTreeState(_) => {+ // Another device (or this one) changed the server's sidebar tree.+ // Hand the whole thing to the GUI, which merges it with this+ // device's own view state.+ let Pdu::ThinkTermTreeState(state) = decoded.pdu else {+ unreachable!("matched ThinkTermTreeState above");+ };+ promise::spawn::spawn_into_main_thread(async move {+ let mux = Mux::try_get().ok_or_else(|| anyhow!("no more mux"))?;+ let domain = mux+ .get_domain(local_domain_id)+ .ok_or_else(|| anyhow!("no such domain {}", local_domain_id))?;+ crate::domain::deliver_thinkterm_tree(domain.domain_name(), state.tree);+ anyhow::Result::<()>::Ok(())+ })+ .detach();+ return Ok(());+ }Pdu::TabResized(_) | Pdu::TabAddedToWindow(_) => {log::trace!("resync due to {:?}", decoded.pdu);promise::spawn::spawn_into_main_thread(async move {@@ -1621,6 +1639,16 @@ impl Client {MovePaneToNewTab,MovePaneToNewTabResponse);+ rpc!(+ get_thinkterm_tree,+ GetThinkTermTree = (),+ ThinkTermTreeState+ );+ rpc!(+ mutate_thinkterm_tree,+ MutateThinkTermTree,+ ThinkTermTreeState+ );rpc!(write_to_pane, WriteToPane, UnitResponse);rpc!(send_paste, SendPaste, UnitResponse);rpc!(key_down, SendKeyDown, UnitResponse);diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex c458d477..52e9bf57 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -527,6 +527,51 @@ fn mux_notify_client_domain(local_domain_id: DomainId, notif: MuxNotification) -true}+/// Receives a mux server's ThinkTerm sidebar tree whenever it arrives, either+/// as the answer to a fetch or as a server push.+///+/// `wezterm-client` has no way to reach into the GUI's store, and the GUI is+/// the only thing that knows how to merge a shared tree with this device's own+/// state, so it registers a sink here at startup. Headless clients (the CLI,+/// the mux server's own client domains) simply never register one and the+/// trees are dropped.+pub type ThinkTermTreeSink = fn(domain_name: &str, tree: codec::ThinkTermTree);++/// Announces a fresh connection to a server, before anything is asked of it.+///+/// Trees do not carry which connection they belong to, and the client has to+/// know: everything it believes about a server's tree describes the previous+/// connection, and a server that comes back having lost or rolled back its own+/// copy must be able to say so rather than be dismissed as out of date.+pub type ThinkTermConnectSink = fn(domain_name: &str);++lazy_static::lazy_static! {+ static ref THINKTERM_TREE_SINK: Mutex<Option<ThinkTermTreeSink>> = Mutex::new(None);+ static ref THINKTERM_CONNECT_SINK: Mutex<Option<ThinkTermConnectSink>> = Mutex::new(None);+}++pub fn set_thinkterm_tree_sink(sink: ThinkTermTreeSink) {+ THINKTERM_TREE_SINK.lock().unwrap().replace(sink);+}++pub fn set_thinkterm_connect_sink(sink: ThinkTermConnectSink) {+ THINKTERM_CONNECT_SINK.lock().unwrap().replace(sink);+}++pub(crate) fn deliver_thinkterm_tree(domain_name: &str, tree: codec::ThinkTermTree) {+ let sink = *THINKTERM_TREE_SINK.lock().unwrap();+ if let Some(sink) = sink {+ sink(domain_name, tree);+ }+}++pub(crate) fn deliver_thinkterm_connected(domain_name: &str) {+ let sink = *THINKTERM_CONNECT_SINK.lock().unwrap();+ if let Some(sink) = sink {+ sink(domain_name);+ }+}+impl ClientDomain {pub fn new(config: ClientDomainConfig) -> Self {let local_domain_id = alloc_domain_id();@@ -637,12 +682,45 @@ impl ClientDomain {/// more tabs at the time that a disconnect was detected, and/// it's also possible that another client connected and adjusted/// the set of tabs since we were connected, so we need to re-sync.+ /// Take up a connection that was re-established after an outage.+ ///+ /// This is the funnel every automatic reconnect passes through, so it has+ /// to do everything a first attach does and not only re-pull the panes.pub async fn reattach(domain_id: DomainId, ui: ConnectionUI) -> anyhow::Result<()> {let inner = Self::get_client_inner_for_domain(domain_id)?;+ let domain = Mux::get().get_domain(domain_id);++ // A reconnect begins a new connection generation. The revision+ // baseline, any old connection-scoped presentation overlay, and the+ // Spaces a local disconnect hid all belong to the connection that just+ // died — and this is the "next connect" the Disconnect menu item+ // promises. Announced first so the tree below, and any push that+ // overtakes it, is measured against this connection; a push that beats+ // the announcement is at worst dropped as stale and put right by that+ // same fetch.+ if let Some(domain) = &domain {+ deliver_thinkterm_connected(domain.domain_name());+ }let panes = inner.client.list_panes().await?;Self::process_pane_list(inner, panes, None, true)?;+ // Pull the tree exactly as a first attach does. Pushes only carry what+ // changes from now on, so without this the sidebar would keep showing+ // whatever it held when the link dropped. Remote edits are rejected+ // while reconnecting; there is deliberately no client queue to flush.+ if let Some(client) = domain+ .as_ref()+ .and_then(|domain| domain.downcast_ref::<ClientDomain>())+ {+ if let Err(err) = client.fetch_thinkterm_tree().await {+ log::warn!(+ "failed to fetch the ThinkTerm tree after reconnecting to {}: {err:#}",+ client.config.name()+ );+ }+ }+ui.close();Ok(())}@@ -669,6 +747,38 @@ impl ClientDomain {Ok(())}+ /// Send mutations of the server's ThinkTerm sidebar tree, hand the+ /// authoritative result to the sink and return it to the initiating+ /// workflow. Returning the tree lets destructive callers wait for an+ /// explicit server acknowledgement before tearing down the transport that+ /// carries the request.+ pub async fn mutate_thinkterm_tree(+ &self,+ ops: Vec<codec::TreeOp>,+ ) -> anyhow::Result<codec::ThinkTermTree> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let response = inner+ .client+ .mutate_thinkterm_tree(codec::MutateThinkTermTree { ops })+ .await?;+ let tree = response.tree;+ deliver_thinkterm_tree(self.config.name(), tree.clone());+ Ok(tree)+ }++ /// Pull the server's tree and hand it to the sink. Used on attach and+ /// whenever a client wants to force a resync of the sidebar structure.+ pub async fn fetch_thinkterm_tree(&self) -> anyhow::Result<()> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let response = inner.client.get_thinkterm_tree().await?;+ deliver_thinkterm_tree(self.config.name(), response.tree);+ Ok(())+ }+pub fn process_remote_window_title_change(&self, remote_window_id: WindowId, title: String) {if let Some(inner) = self.inner() {if let Some(local_window_id) = inner.remote_to_local_window(remote_window_id) {@@ -1132,18 +1242,12 @@ impl Domain for ClientDomain {let target_pane = mux.get_pane(target_local_pane_id).ok_or_else(|| anyhow!("target pane_id {target_local_pane_id} is invalid"))?;- let source_client_pane =- source_pane- .downcast_ref::<ClientPane>()- .ok_or_else(|| {- anyhow!("source pane_id {source_local_pane_id} is not a ClientPane")- })?;- let target_client_pane =- target_pane- .downcast_ref::<ClientPane>()- .ok_or_else(|| {- anyhow!("target pane_id {target_local_pane_id} is not a ClientPane")- })?;+ let source_client_pane = source_pane+ .downcast_ref::<ClientPane>()+ .ok_or_else(|| anyhow!("source pane_id {source_local_pane_id} is not a ClientPane"))?;+ let target_client_pane = target_pane+ .downcast_ref::<ClientPane>()+ .ok_or_else(|| anyhow!("target pane_id {target_local_pane_id} is not a ClientPane"))?;if !source_client_pane.belongs_to_client(&inner)|| !target_client_pane.belongs_to_client(&inner){@@ -1385,12 +1489,7 @@ impl Domain for ClientDomain {// post-response update below.let optimistic_move_applied = if let Some((moved_pane, _)) = moved_local_pane.as_ref() {if source_tab_id == Some(tab_id) {- mux.move_pane_to_split(- moved_pane.pane_id(),- tab_id,- pane_id,- split_request,- )?;+ mux.move_pane_to_split(moved_pane.pane_id(), tab_id, pane_id, split_request)?;true} else {false@@ -1610,6 +1709,21 @@ impl ClientDomain {e})?;+ // Announce the new connection before asking it anything, so that the+ // answer — and any push that overtakes it — is measured against this+ // connection rather than the last one.+ deliver_thinkterm_connected(self.config.name());++ // The sidebar structure lives on the server. Fetching it is not worth+ // failing an otherwise-good attach over: without it the Space simply+ // shows no rows until the next push or reconnect.+ if let Err(err) = self.fetch_thinkterm_tree().await {+ log::warn!(+ "failed to fetch the ThinkTerm tree from {}: {err:#}",+ self.config.name()+ );+ }+ui.output_str("Attached!\n");drop(activity);ui.close();diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex 047164fa..d78fcac6 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -541,15 +541,27 @@ impl ClientPane {}/// Arrange to suppress the next Pane::kill call.- /// This is a bit of a hack that we use when closing a window;- /// our Domain::local_window_is_closing impl calls this for each- /// ClientPane in the window so that closing a window effectively- /// "detaches" the window so that reconnecting later will resume- /// from where they left off.- /// It isn't perfect.+ ///+ /// ThinkTerm uses this when it intentionally discards a local mirror+ /// (for example, Disconnect or Delete Space) while leaving the pane alive+ /// on the mux server. Native GUI closure can keep the whole mux window in+ /// the background instead, so it does not need this one-shot suppression.pub fn ignore_next_kill(&self) {*self.ignore_next_kill.lock() = true;}++ /// End the remote pane and wait for the mux server to acknowledge it.+ /// Destructive compound workflows use this instead of `Pane::kill`, whose+ /// fire-and-forget task can lose a race with detaching the last window.+ pub async fn kill_remote_and_wait(&self) -> anyhow::Result<()> {+ self.client+ .client+ .kill_pane(KillPane {+ pane_id: self.remote_pane_id,+ })+ .await?;+ Ok(())+ }}#[async_trait(?Send)]diff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftlindex adb37066..3ba65f14 100644--- a/wezterm-gui/i18n/en-US.ftl+++ b/wezterm-gui/i18n/en-US.ftl@@ -143,10 +143,17 @@ menu-remove-project = Remove Projectmenu-space-occupied = { $name } (occupied)menu-space-remote = { $name } (Remote)menu-new-space = New Space+menu-space-server-group = { $name }+menu-space-server-group-offline = { $name } (disconnected)+menu-space-server-group-connecting = { $name } (connecting…)+menu-space-server-group-reconnecting = { $name } (reconnecting…)+remote-tree-mutation-offline = { $name } is disconnected. Reconnect and try again.+menu-new-space-here = New Space Heremenu-rename-space = Rename Space…menu-rename-named-space = Rename “{ $name }”…menu-disconnect-space = Disconnect “{ $name }” (Server Keeps Running)menu-delete-space = Delete “{ $name }”+menu-delete-space-everywhere = Delete “{ $name }” on the Server (All Devices)menu-delete-space-and-sessions = Delete “{ $name }” & End Remote Sessionsmenu-delete-other-space = Delete Other Spacemenu-status-running = Runningdiff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftlindex 433a998c..e77a825a 100644--- a/wezterm-gui/i18n/fr-FR.ftl+++ b/wezterm-gui/i18n/fr-FR.ftl@@ -143,10 +143,17 @@ menu-remove-project = Supprimer le projetmenu-space-occupied = { $name } (occupé)menu-space-remote = { $name } (distant)menu-new-space = Nouvel espace+menu-space-server-group = { $name }+menu-space-server-group-offline = { $name } (déconnecté)+menu-space-server-group-connecting = { $name } (connexion…)+menu-space-server-group-reconnecting = { $name } (reconnexion…)+remote-tree-mutation-offline = { $name } est déconnecté. Reconnectez-vous et réessayez.+menu-new-space-here = Nouvel espace icimenu-rename-space = Renommer l’espace…menu-rename-named-space = Renommer « { $name } »…menu-disconnect-space = Déconnecter « { $name } » (le serveur reste actif)menu-delete-space = Supprimer « { $name } »+menu-delete-space-everywhere = Supprimer « { $name } » sur le serveur (tous les appareils)menu-delete-space-and-sessions = Supprimer « { $name } » et terminer les sessions distantesmenu-delete-other-space = Supprimer un autre espacemenu-status-running = En coursdiff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftlindex ec8511f2..549e5ed0 100644--- a/wezterm-gui/i18n/ja-JP.ftl+++ b/wezterm-gui/i18n/ja-JP.ftl@@ -143,10 +143,17 @@ menu-remove-project = プロジェクトを削除menu-space-occupied = { $name }(使用中)menu-space-remote = { $name }(リモート)menu-new-space = 新しいスペース+menu-space-server-group = { $name }+menu-space-server-group-offline = { $name }(切断)+menu-space-server-group-connecting = { $name }(接続中…)+menu-space-server-group-reconnecting = { $name }(再接続中…)+remote-tree-mutation-offline = { $name } は切断されています。再接続してからもう一度お試しください。+menu-new-space-here = このサーバーに新しいスペースmenu-rename-space = スペース名を変更…menu-rename-named-space = 「{ $name }」の名前を変更…menu-disconnect-space = 「{ $name }」を切断(サーバーは実行を継続)menu-delete-space = 「{ $name }」を削除+menu-delete-space-everywhere = サーバー上の「{ $name }」を削除(全デバイス)menu-delete-space-and-sessions = 「{ $name }」を削除してリモートセッションを終了menu-delete-other-space = 別のスペースを削除menu-status-running = 実行中diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftlindex ced33e29..fc7c4413 100644--- a/wezterm-gui/i18n/zh-CN.ftl+++ b/wezterm-gui/i18n/zh-CN.ftl@@ -143,10 +143,17 @@ menu-remove-project = 移除项目menu-space-occupied = { $name }(已被占用)menu-space-remote = { $name }(远程)menu-new-space = 新建空间+menu-space-server-group = { $name }+menu-space-server-group-offline = { $name }(已断开)+menu-space-server-group-connecting = { $name }(连接中…)+menu-space-server-group-reconnecting = { $name }(重连中…)+remote-tree-mutation-offline = { $name } 已断开。请重新连接后再试。+menu-new-space-here = 在此服务器新建空间menu-rename-space = 重命名空间…menu-rename-named-space = 重命名“{ $name }”…menu-disconnect-space = 断开“{ $name }”(服务器继续运行)menu-delete-space = 删除“{ $name }”+menu-delete-space-everywhere = 在服务器上删除“{ $name }”(所有设备)menu-delete-space-and-sessions = 删除“{ $name }”并结束远程会话menu-delete-other-space = 删除其他空间menu-status-running = 运行中diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rsindex 5426bc78..451b39a3 100644--- a/wezterm-gui/src/commands.rs+++ b/wezterm-gui/src/commands.rs@@ -944,6 +944,14 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Commmenubar: &[],icon: Some("md_add"),},+ CreateSpaceOnDomain(_) => CommandDef {+ brief: "New Space Here".into(),+ doc: "Creates a new ThinkTerm space on this mux server".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: Some("md_add"),+ },SwitchSpace(_) => CommandDef {brief: "Switch Space".into(),doc: "Switches the active ThinkTerm space for this window".into(),@@ -960,10 +968,20 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Commmenubar: &[],icon: Some("md_delete"),},+ DeleteSpaceEverywhere(_) => CommandDef {+ brief: "Delete Space Everywhere".into(),+ doc: "Deletes the Space on the mux server that hosts it, so it \+ disappears from every device"+ .into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: Some("md_delete"),+ },DeleteSpaceAndRemoteSessions(_) => CommandDef {brief: "Delete Space & End Remote Sessions".into(),doc: "Kills the Space's sessions on the remote mux server, then \- deletes the local records"+ deletes the Space everywhere".into(),keys: vec![],args: &[ArgType::ActiveWindow],diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex 61c0932d..58a5af19 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -127,6 +127,9 @@ impl GuiFrontEnd {MuxNotification::TabTitleChanged { .. } => {}MuxNotification::WindowTitleChanged { .. } => {}MuxNotification::TabResized(_) => {}+ // Server-side only: a GUI mux owns no ThinkTerm tree. The+ // remote tree arrives as a pushed PDU, not as a notification.+ MuxNotification::ThinkTermTreeChanged => {}MuxNotification::TabAddedToWindow { .. } => {}MuxNotification::PaneRemoved(_) => {}MuxNotification::WindowInvalidated(_) => {}diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 6ec0f1b6..8e278805 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -294,6 +294,31 @@ fn have_panes_in_domain_and_ws(domain: &Arc<dyn Domain>, workspace: &Option<Stri}}+/// Backoff for a retrying in-window connection, waking frequently enough that+/// closing the empty ConnectionUI window is a real cancellation rather than a+/// hidden retry loop that keeps the process alive.+async fn wait_connect_backoff_while_window_exists(+ window_id: mux::window::WindowId,+ duration: std::time::Duration,+) -> bool {+ let deadline = std::time::Instant::now() + duration;+ loop {+ if Mux::get().get_window(window_id).is_none() {+ return false;+ }+ let now = std::time::Instant::now();+ if now >= deadline {+ return true;+ }+ smol::Timer::after(+ deadline+ .saturating_duration_since(now)+ .min(std::time::Duration::from_millis(100)),+ )+ .await;+ }+}+/// Returns the domain id to tag domain-owned mux windows with, when the/// domain is a ClientDomain (remote mux). Tagged windows are exempt from/// the frontend's saved-thread restore/adoption and local layout snapshots.@@ -499,29 +524,69 @@ pub(crate) async fn connect_domain_into_space(..Default::default()});loop {+ if mux.get_window(window_id).is_none() {+ ui.close();+ return Ok(());+ }let attempt = match domain.downcast_ref::<ClientDomain>() {Some(client) => client.attach_with_ui(Some(window_id), ui.clone()).await,None => domain.attach(Some(window_id)).await,};match attempt {- Ok(()) => break,+ Ok(()) => {+ // The transport can finish connecting just after the user+ // closes its GUI. Do not turn that late success into a+ // headless attached domain.+ if mux.get_window(window_id).is_none() {+ ui.close();+ if domain.state() == DomainState::Attached {+ domain.detach()?;+ }+ return Ok(());+ }+ break;+ }Err(err) => {log::error!("attaching {domain_name} failed: {err:#}; retrying in {backoff:?}");ui.output_str(&format!("Will retry in {backoff:?}...\n"));- smol::Timer::after(backoff).await;+ if !wait_connect_backoff_while_window_exists(window_id, backoff).await {+ ui.close();+ return Ok(());+ }backoff = (backoff * 2).min(MAX_BACKOFF);}}}}+ // The server owns the sidebar tree and only hands it over as part of the+ // attach, so the Space and thread picked above were a guess: a device+ // meeting this server for the first time has to invent a Space before it+ // can authenticate, and learns the real ones only now. Ask again against+ // the tree that has since landed, then push up whatever the server is+ // still missing (its tree can legitimately be empty — the last Space was+ // deleted from another device — in which case the Space we invented is+ // the right answer and wants seeding).+ let settled = workspace_threads::ensure_mux_domain_space(&domain_name);+ let settled_workspace = workspace_threads::ensure_mux_thread_workspace(&settled);+ workspace_threads::reconcile_remote_subtree(&domain_name);+// Spawn the thread's first shell when its workspace has no panes on the// server. Keying this off "does the domain have any panes at all" left// the connect window empty whenever the server had unrelated windows// (its own startup window, other threads) — the old blind window// adoption papered over that by grabbing one of them as a tab.- let thread_workspace_filter = Some(thread_workspace);- if !have_panes_in_domain_and_ws(&domain, &thread_workspace_filter) {+ let thread_workspace_filter = Some(thread_workspace.clone());+ if settled_workspace != thread_workspace {+ // The invented Space is gone from the store, so the window created+ // above is being re-homed onto one the server really has, and that+ // path materializes the destination thread itself. Spawning here+ // would strand a shell in a workspace no row on the server names.+ log::info!(+ "{domain_name} has its own Spaces; leaving {settled_workspace} \+ to the re-home instead of spawning into {thread_workspace}"+ );+ } else if !have_panes_in_domain_and_ws(&domain, &thread_workspace_filter) {let _config_subscription = config::subscribe_to_config_reload(move || {promise::spawn::spawn_into_main_thread(async move {if let Err(err) = update_mux_domains(&config::configuration()) {@@ -961,6 +1026,16 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->set_window_position(pos.clone());}+ // A mux server owns the sidebar tree for its Spaces; wezterm-client hands+ // every copy it receives to this sink, which merges it with the parts of+ // the view that belong to this device alone.+ wezterm_client::domain::set_thinkterm_tree_sink(|domain_name, tree| {+ crate::workspace_threads::ingest_remote_tree(domain_name, tree);+ });+ wezterm_client::domain::set_thinkterm_connect_sink(|domain_name| {+ crate::workspace_threads::note_remote_connected(domain_name);+ });+let config = config::configuration();let need_builder = !opts.prog.is_empty() || opts.cwd.is_some();diff --git a/wezterm-gui/src/overlay/confirm_close_pane.rs b/wezterm-gui/src/overlay/confirm_close_pane.rsindex bc11bc37..c069079a 100644--- a/wezterm-gui/src/overlay/confirm_close_pane.rs+++ b/wezterm-gui/src/overlay/confirm_close_pane.rs@@ -6,6 +6,14 @@ use mux::termwiztermtab::TermWizTerminal;use mux::window::WindowId;use mux::Mux;+fn close_window_confirmation_prompt(preserve_mux_window: bool) -> &'static str {+ if preserve_mux_window {+ "Really close this window? Remote sessions will continue running."+ } else {+ "🛑 Really kill this window and all contained tabs and panes?"+ }+}+pub fn confirm_close_pane(pane_id: PaneId,mut term: TermWizTerminal,@@ -54,14 +62,18 @@ pub fn confirm_close_window(mux_window_id: WindowId,window: ::window::Window,tab_id: TabId,+ preserve_mux_window: bool,) -> anyhow::Result<()> {- if confirm::run_confirmation(- "🛑 Really kill this window and all contained tabs and panes?",- &mut term,- )? {+ let prompt = close_window_confirmation_prompt(preserve_mux_window);+ if confirm::run_confirmation(prompt, &mut term)? {+ let gui_window = window.clone();promise::spawn::spawn_into_main_thread(async move {- let mux = Mux::get();- mux.kill_window(mux_window_id);+ if preserve_mux_window {+ TermWindow::close_gui_window_preserving_mux(&gui_window);+ } else {+ let mux = Mux::get();+ mux.kill_window(mux_window_id);+ }}).detach();}@@ -70,6 +82,23 @@ pub fn confirm_close_window(Ok(())}+#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn window_close_prompt_matches_close_semantics() {+ assert_eq!(+ close_window_confirmation_prompt(true),+ "Really close this window? Remote sessions will continue running."+ );+ assert_eq!(+ close_window_confirmation_prompt(false),+ "🛑 Really kill this window and all contained tabs and panes?"+ );+ }+}+pub fn confirm_quit_program(mut term: TermWizTerminal,window: ::window::Window,diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 6b5f5808..b4d24b13 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -43,6 +43,7 @@ use config::{};use lfucache::*;use mlua::{FromLua, LuaSerdeExt, UserData, UserDataFields};+use mux::domain::DomainId;use mux::pane::{CachePolicy, CloseReason, Pane, PaneId, Pattern as MuxPattern, PerformAssignmentResult,};@@ -74,6 +75,65 @@ use wezterm_term::color::{ColorAttribute, ColorPalette};use wezterm_term::input::LastMouseClick;use wezterm_term::{Alert, Progress, StableRowIndex, TerminalConfiguration, TerminalSize};+/// A domain-owned remote window should stay in the local mux when its native+/// GUI window closes. The origin tag is authoritative; the Space/domain+/// fallback covers a window created before that tag was available, but only+/// when every pane in the actual mux window belongs to that same domain.+/// Requiring all panes avoids treating a local Space containing one manually+/// opened remote tab as a remote-owned window.+fn preserve_mux_window_on_gui_close(+ origin_client_domain: Option<DomainId>,+ active_space_domain: Option<DomainId>,+ pane_domains: &[DomainId],+ client_pane_domains: &[DomainId],+) -> bool {+ if let Some(domain_id) = origin_client_domain {+ // A tag identifies ownership, but an empty/tag-only connection window+ // has no remote session to preserve. Requiring a real ClientPane is+ // also what lets close cancel an initial failed attach.+ return client_pane_domains+ .iter()+ .any(|pane_domain| *pane_domain == domain_id);+ }++ active_space_domain.is_some_and(|domain_id| {+ !pane_domains.is_empty()+ && pane_domains.len() == client_pane_domains.len()+ && client_pane_domains+ .iter()+ .all(|pane_domain| *pane_domain == domain_id)+ })+}++#[cfg(test)]+mod window_close_tests {+ use super::preserve_mux_window_on_gui_close;++ #[test]+ fn close_disposition_uses_origin_then_matching_space_domain() {+ assert!(preserve_mux_window_on_gui_close(Some(7), None, &[7], &[7]));+ assert!(preserve_mux_window_on_gui_close(+ None,+ Some(7),+ &[7, 7],+ &[7, 7]+ ));++ // A tag alone is not a remote session. This is the initial failed+ // connection case: close must remove the mux window and cancel retry.+ assert!(!preserve_mux_window_on_gui_close(Some(7), None, &[], &[]));+ assert!(!preserve_mux_window_on_gui_close(None, None, &[7], &[7]));+ assert!(!preserve_mux_window_on_gui_close(None, Some(7), &[], &[]));+ assert!(!preserve_mux_window_on_gui_close(+ None,+ Some(7),+ &[7, 8],+ &[7]+ ));+ assert!(!preserve_mux_window_on_gui_close(None, Some(7), &[8], &[8]));+ }+}+fn gpu_debug_enabled() -> bool {std::env::var_os("THINKTERM_GPU_DEBUG").is_some()}@@ -1350,6 +1410,12 @@ pub struct TermWindow {workspace_sidebar_collapsed: bool,workspace_sidebar_scroll_offset: f32,workspace_sidebar_scrollbar_visible_until: Option<Instant>,+ /// Last notification state painted by this GUI window. Comparing identities+ /// and statuses (rather than just the count) lets the bell pulse when one+ /// notification replaces another without changing the total.+ workspace_notification_snapshot:+ Option<HashMap<String, crate::workspace_threads::WorkspaceThreadWorkStatus>>,+ workspace_notification_pulse_started_at: Option<Instant>,right_sidebar_width: usize,right_sidebar_collapsed: bool,right_sidebar_mode: RightSidebarMode,@@ -1604,25 +1670,79 @@ impl TermWindow {self.remember_workspace_layout_structure_fingerprint();}+ fn should_preserve_mux_window_on_gui_close(&self) -> bool {+ let mux = Mux::get();+ let Some((origin_domain, pane_domains, client_pane_domains)) =+ mux.get_window(self.mux_window_id).map(|window| {+ let panes = window+ .iter()+ .flat_map(|tab| tab.iter_all_panes())+ .collect::<Vec<_>>();+ let pane_domains = panes+ .iter()+ .map(|pane| pane.domain_id())+ .collect::<Vec<_>>();+ let client_pane_domains = panes+ .iter()+ .filter(|pane| {+ pane.downcast_ref::<wezterm_client::pane::ClientPane>()+ .is_some()+ })+ .map(|pane| pane.domain_id())+ .collect::<Vec<_>>();+ (window.origin_domain(), pane_domains, client_pane_domains)+ })+ else {+ return false;+ };++ let origin_client_domain = origin_domain+ .and_then(|domain_id| mux.get_domain(domain_id))+ .filter(|domain| domain.downcast_ref::<ClientDomain>().is_some())+ .map(|domain| domain.domain_id());++ let active_space_domain =+ crate::workspace_threads::client_domain_for_space(&self.active_space_id)+ .and_then(|domain_name| mux.get_domain_by_name(&domain_name))+ .filter(|domain| domain.downcast_ref::<ClientDomain>().is_some())+ .map(|domain| domain.domain_id());++ preserve_mux_window_on_gui_close(+ origin_client_domain,+ active_space_domain,+ &pane_domains,+ &client_pane_domains,+ )+ }++ pub(crate) fn close_gui_window_preserving_mux(window: &Window) {+ window.close();+ front_end().forget_known_window(window);+ }++ fn close_gui_window_now(&self, window: &Window, preserve_mux_window: bool) {+ if !preserve_mux_window {+ // Local windows retain the established destructive close behavior.+ Mux::get().kill_window(self.mux_window_id);+ }+ Self::close_gui_window_preserving_mux(window);+ }+fn close_requested(&mut self, window: &Window) {self.flush_right_sidebar_note_blocking();self.persist_workspace_layout_after_mutation("window close requested");let mux = Mux::get();+ let preserve_mux_window = self.should_preserve_mux_window_on_gui_close();match self.config.window_close_confirmation {WindowCloseConfirmation::NeverPrompt => {- // Immediately kill the tabs and allow the window to close- mux.kill_window(self.mux_window_id);- window.close();- front_end().forget_known_window(window);+ self.close_gui_window_now(window, preserve_mux_window);}WindowCloseConfirmation::AlwaysPrompt => {let tab = match mux.get_active_tab_for_window(self.mux_window_id) {Some(tab) => tab,None => {- mux.kill_window(self.mux_window_id);- window.close();- front_end().forget_known_window(window);+ self.close_gui_window_now(window, preserve_mux_window);return;}};@@ -1633,14 +1753,12 @@ impl TermWindow {.get_window(mux_window_id).map_or(false, |w| w.can_close_without_prompting());if can_close {- mux.kill_window(self.mux_window_id);- window.close();- front_end().forget_known_window(window);+ self.close_gui_window_now(window, preserve_mux_window);return;}let window = self.window.clone().unwrap();let (overlay, future) = start_overlay(self, &tab, move |tab_id, term| {- confirm_close_window(term, mux_window_id, window, tab_id)+ confirm_close_window(term, mux_window_id, window, tab_id, preserve_mux_window)});self.assign_overlay(tab.tab_id(), overlay);promise::spawn::spawn(future).detach();@@ -2046,6 +2164,8 @@ impl TermWindow {workspace_sidebar_collapsed: !native_settings.onboarding.show_left_sidebar_by_default,workspace_sidebar_scroll_offset: 0.0,workspace_sidebar_scrollbar_visible_until: None,+ workspace_notification_snapshot: None,+ workspace_notification_pulse_started_at: None,right_sidebar_width: ui::right_sidebar_width_for_metrics(&render_metrics, dpi as usize),right_sidebar_collapsed: true,right_sidebar_mode: RightSidebarMode::Snippets,@@ -2854,6 +2974,10 @@ impl TermWindow {MuxNotification::SaveToDownloads { .. } => {// Handled by frontend}+ MuxNotification::ThinkTermTreeChanged => {+ // Server-side only; the remote tree reaches this process+ // as a pushed ThinkTermTreeState PDU instead.+ }MuxNotification::PaneFocused(pane_id) => {// Also handled by clientpaneself.refresh_thread_work_for_pane(pane_id);@@ -3297,6 +3421,7 @@ impl TermWindow {| MuxNotification::ActiveWorkspaceChanged(_)| MuxNotification::WorkspaceRenamed { .. }| MuxNotification::Empty+ | MuxNotification::ThinkTermTreeChanged| MuxNotification::WindowWorkspaceChanged(_) => return true,MuxNotification::Alert {alert: Alert::PaletteChanged { .. },@@ -3370,6 +3495,32 @@ impl TermWindow {self.invalidate_window_if(crate::workspace_threads::refresh_all_thread_work());}+ /// Move this window off a Space that no longer exists.+ ///+ /// A device connecting to a mux server for the first time has to choose a+ /// Space before it can authenticate, so it invents one; the server's real+ /// list only arrives afterwards and replaces it. `rehome` pairs each+ /// affected window with somewhere that does exist.+ pub(crate) fn rehome_if_space_vanished(&mut self, rehome: &[(u64, String)]) {+ let Some(target) = rehome+ .iter()+ .find(|(owner_id, _)| *owner_id == self.space_owner_id)+ .map(|(_, space_id)| space_id.clone())+ else {+ return;+ };+ if self.active_space_id == target {+ return;+ }+ log::info!(+ "Space {} is gone from its server; moving this window to {target}",+ self.active_space_id+ );+ if let Some(window) = self.window.clone() {+ self.switch_space(target, &window);+ }+ }+pub(crate) fn switch_space(&mut self, space_id: String, window: &Window) {self.switch_space_to_thread(space_id, None, window);}@@ -3431,47 +3582,63 @@ impl TermWindow {true}- /// Delete a remote Space AND end its sessions on the server: send a- /// remote kill for every pane of the Space's client domain, then delete- /// the Space (which detaches). The deletion is deferred a moment so the- /// KillPane PDUs can flush before the detach tears the transport down.+ /// Delete a remote Space AND end its sessions on the server. The shared+ /// tree deletion is acknowledged before any local mirror is removed, so+ /// the last window cannot detach the domain while its DeleteSpace RPC is+ /// still waiting to be polled.fn delete_space_and_remote_sessions(&mut self, space_id: &str) {- let attached_domain = crate::workspace_threads::client_domain_for_space(space_id)- .and_then(|name| Mux::get().get_domain_by_name(&name))- .filter(|domain| domain.state() == mux::domain::DomainState::Attached);-- let Some(domain) = attached_domain else {- let window = self.window.clone();- self.delete_space(space_id, window.as_ref());- return;- };+ self.start_delete_space(+ space_id,+ crate::workspace_threads::SpaceRemoval::Everywhere,+ true,+ );+ }- let domain_id = domain.domain_id();- for pane in Mux::get().iter_panes() {- if pane.domain_id() == domain_id {- pane.kill();- }- }+ fn delete_space(+ &mut self,+ space_id: &str,+ _window: Option<&Window>,+ removal: crate::workspace_threads::SpaceRemoval,+ ) {+ self.start_delete_space(space_id, removal, false);+ }+ fn start_delete_space(+ &mut self,+ space_id: &str,+ removal: crate::workspace_threads::SpaceRemoval,+ end_remote_sessions: bool,+ ) {+ let owner_id = self.space_owner_id;let space_id = space_id.to_string();let gui_window = self.window.clone();- promise::spawn::spawn(async move {- smol::Timer::after(Duration::from_millis(400)).await;+ promise::spawn::spawn_into_main_thread(async move {+ let result = crate::workspace_threads::delete_space_for_window(+ owner_id,+ &space_id,+ removal,+ end_remote_sessions,+ )+ .await;if let Some(gui_window) = gui_window {gui_window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {- let window = term_window.window.clone();- term_window.delete_space(&space_id, window.as_ref());- if let Some(window) = window {- window.invalidate();- }+ term_window.finish_delete_space(&space_id, result);})));}}).detach();}- fn delete_space(&mut self, space_id: &str, window: Option<&Window>) {- match crate::workspace_threads::delete_space_for_window(self.space_owner_id, space_id) {+ fn finish_delete_space(+ &mut self,+ space_id: &str,+ result: Result<+ crate::workspace_threads::DeletedSpace,+ crate::workspace_threads::DeleteSpaceError,+ >,+ ) {+ let window = self.window.clone();+ match result {Ok(deleted) => {let deleted_active_space = self.active_space_id == space_id;if deleted_active_space {@@ -3484,7 +3651,7 @@ impl TermWindow {// adopted so the resize does not hit the deleted Space's// panes.self.pending_sidebar_reflow_width = Some(previous_sidebar_width);- if let Some(window) = window {+ if let Some(window) = window.as_ref() {if let Some(thread_id) =crate::workspace_threads::ensure_active_thread_for_space(&self.active_space_id,@@ -3500,15 +3667,46 @@ impl TermWindow {}}+ // Mirror teardown happens only after the server tree has+ // acknowledged the deletion. Normal server/local disconnect+ // preserves sessions; the explicit end-sessions action sends+ // remote kills, still scoped to this Space's workspaces.let mux = Mux::get();for workspace in deleted.materialized_workspace_names {for window_id in mux.iter_windows_in_workspace(&workspace) {+ let panes = mux+ .get_window(window_id)+ .map(|window| {+ window+ .iter()+ .flat_map(|tab| tab.iter_all_panes())+ .collect::<Vec<_>>()+ })+ .unwrap_or_default();+ for pane in panes {+ if let Some(client) =+ pane.downcast_ref::<wezterm_client::pane::ClientPane>()+ {+ // Explicit end-session deletions already used+ // the awaited KillPane path before the server+ // tree was removed. Any mirrors still present+ // here must not send a duplicate request while+ // the window is torn down.+ client.ignore_next_kill();+ }+ }mux.kill_window(window_id);}}+ if let Some(window) = window {+ window.invalidate();+ }}Err(err) => {log::warn!("failed to delete ThinkTerm space {space_id}: {err:?}");+ if let Some(window) = window {+ window.invalidate();+ }}}}@@ -5800,13 +5998,43 @@ impl TermWindow {window.invalidate();}}+ CreateSpaceOnDomain(domain_name) => {+ match crate::workspace_threads::create_space_on_domain(domain_name, None) {+ Ok(space_id) => {+ if let Some(window) = window.as_ref() {+ self.switch_space(space_id.clone(), window);+ self.prompt_rename_space(space_id);+ window.invalidate();+ }+ }+ Err(err) => {+ log::warn!("failed to create Space on {domain_name}: {err:#}");+ }+ }+ }SwitchSpace(space_id) => {if let Some(window) = window.as_ref() {self.switch_space(space_id.clone(), window);}}DeleteSpace(space_id) => {- self.delete_space(space_id, window.as_ref());+ // A remote Space belongs to its server; removing it here is a+ // disconnect, and it returns on the next connect.+ self.delete_space(+ space_id,+ window.as_ref(),+ crate::workspace_threads::SpaceRemoval::Local,+ );+ if let Some(window) = window.as_ref() {+ window.invalidate();+ }+ }+ DeleteSpaceEverywhere(space_id) => {+ self.delete_space(+ space_id,+ window.as_ref(),+ crate::workspace_threads::SpaceRemoval::Everywhere,+ );if let Some(window) = window.as_ref() {window.invalidate();}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 0b5582a5..136211a2 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -2,6 +2,7 @@ use crate::frontend::front_end;use crate::tabbar::TabBarItem;use crate::termwindow::content_view::ContentViewId;use crate::termwindow::ui::platform_chrome::WindowTabChromeParams;+use crate::termwindow::ui::sidebar::SpaceConnectionState;use crate::termwindow::ui::tokens::{PANE_NAV_BUTTON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_GAP, TAB_ROW_START_PADDING,TAB_VERTICAL_PADDING, WINDOW_TAB_ACTION_RESERVED_WIDTH, WINDOW_TAB_GAP,@@ -4415,14 +4416,19 @@ impl super::TermWindow {]}+ /// One row per Space, grouped by the server hosting it.+ ///+ /// A remote server is a *connection*, not a Space: it can host several, and+ /// they all go up and down together. So it appears as a disabled group+ /// header carrying the connection's state, with its Spaces listed beneath+ /// and a "New Space Here" entry of its own. Local Spaces stay at the top,+ /// ungrouped.fn space_menu_items(&self) -> Vec<ContextMenuItem> {let spaces = crate::workspace_threads::spaces_for_window(self.space_owner_id);- let mut items = vec![];- for space in &spaces {++ let space_item = |space: &crate::workspace_threads::SpaceView| {let label = if space.is_occupied_by_other_window {tr_with_name("menu-space-occupied", &space.name)- } else if space.is_remote {- tr_with_name("menu-space-remote", &space.name)} else {space.name.clone()};@@ -4430,8 +4436,6 @@ impl super::TermWindow {label,if space.is_default {ContextMenuIcon::Home- } else if space.is_remote {- ContextMenuIcon::Server} else {ContextMenuIcon::Stack},@@ -4441,7 +4445,65 @@ impl super::TermWindow {if space.is_occupied_by_other_window {item = item.disabled();}- items.push(item);+ item+ };++ let mut items = vec![];+ for space in spaces.iter().filter(|space| space.domain.is_none()) {+ items.push(space_item(space));+ }++ // Keep the servers in the order their Spaces appear rather than+ // sorting: that order is the user's.+ let mut domains: Vec<&str> = vec![];+ for domain in spaces.iter().filter_map(|space| space.domain.as_deref()) {+ if !domains.contains(&domain) {+ domains.push(domain);+ }+ }++ for domain in domains {+ items.push(ContextMenuItem::Separator);+ let state = spaces+ .iter()+ .find(|space| space.domain.as_deref() == Some(domain))+ .map(|space| self.space_connection_state(&space.id))+ .unwrap_or(SpaceConnectionState::Connected);+ let header = match state {+ SpaceConnectionState::Connected => tr_with_name("menu-space-server-group", domain),+ SpaceConnectionState::Connecting => {+ tr_with_name("menu-space-server-group-connecting", domain)+ }+ // Distinct from disconnected: the transport is being retried,+ // and calling that "disconnected" reads as though the Spaces+ // below are unreachable for good.+ SpaceConnectionState::Reconnecting => {+ tr_with_name("menu-space-server-group-reconnecting", domain)+ }+ SpaceConnectionState::Disconnected => {+ tr_with_name("menu-space-server-group-offline", domain)+ }+ };+ // Disabled: a server is a heading, not something to switch to.+ items.push(+ ContextMenuItem::item_with_icon(+ header,+ ContextMenuIcon::Server,+ KeyAssignment::Nop,+ )+ .disabled(),+ );+ for space in spaces+ .iter()+ .filter(|space| space.domain.as_deref() == Some(domain))+ {+ items.push(space_item(space));+ }+ items.push(ContextMenuItem::item_with_icon(+ crate::i18n::tr("menu-new-space-here"),+ ContextMenuIcon::New,+ KeyAssignment::CreateSpaceOnDomain(domain.to_string()),+ ));}items.push(ContextMenuItem::Separator);@@ -4463,10 +4525,11 @@ impl super::TermWindow {.iter().find(|space| space.is_active).map(|space| space.id.clone());+ // A remote Space lives on its server, so removing it here only drops+ // this device's copy: the Space is untouched for everyone else and+ // returns on the next connect. Deleting it for real is a separate,+ // more-consequential entry offered alongside.let delete_item = |space: crate::workspace_threads::SpaceView| {- // Deleting a remote Space only detaches and removes the local- // records; the remote mux server and everything running in it- // are untouched. Label it accordingly.ContextMenuItem::item_with_icon(if space.is_remote {tr_with_name("menu-disconnect-space", &space.name)@@ -4487,9 +4550,10 @@ impl super::TermWindow {.find(|space| active_space_id.as_deref() == Some(space.id.as_str())).cloned();if let Some(space) = active_delete {- // For a currently-connected remote Space, also offer really- // ending the sessions on the server before removing it.- let offer_remote_kill = space.is_remote+ let is_remote = space.is_remote;+ // Ending the sessions too only makes sense while we are actually+ // connected to the server.+ let offer_remote_kill = is_remote&& crate::workspace_threads::client_domain_for_space(&space.id).and_then(|name| Mux::get().get_domain_by_name(&name)).map_or(false, |domain| {@@ -4497,6 +4561,13 @@ impl super::TermWindow {});let (name, id) = (space.name.clone(), space.id.clone());items.push(delete_item(space));+ if is_remote {+ items.push(ContextMenuItem::item_with_icon(+ tr_with_name("menu-delete-space-everywhere", &name),+ ContextMenuIcon::Delete,+ KeyAssignment::DeleteSpaceEverywhere(id.clone()),+ ));+ }if offer_remote_kill {items.push(ContextMenuItem::item_with_icon(tr_with_name("menu-delete-space-and-sessions", &name),@@ -4824,7 +4895,14 @@ impl super::TermWindow {}pub(crate) fn create_workspace_thread(&mut self, project_id: &str, context: &dyn WindowOps) {- let thread_id = crate::workspace_threads::create_thread(project_id, None);+ let thread_id = match crate::workspace_threads::create_thread(project_id, None) {+ Ok(thread_id) => thread_id,+ Err(err) => {+ log::warn!("failed to create ThinkTerm thread: {err:#}");+ context.invalidate();+ return;+ }+ };if !self.open_remote_workspace_thread_without_connecting(&thread_id, context) {self.activate_workspace_thread(thread_id, context);}diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rsindex d4d5df5e..ceca52d1 100644--- a/wezterm-gui/src/termwindow/ui/sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs@@ -20,7 +20,9 @@ use crate::workspace_threads;use anyhow::Context;use mux::Mux;use std::borrow::Cow;+use std::collections::HashMap;use std::rc::Rc;+use std::time::{Duration, Instant};use wezterm_font::LoadedFont;use window::color::LinearRgba;use window::{MouseEventKind as WMEK, RectF};@@ -48,13 +50,17 @@ const SESSION_STATUS_ACTIVE_ICON_SIZE: usize = 26;const SESSION_STATUS_DONE_COLOR: LinearRgba = LinearRgba::with_components(0.20, 0.78, 0.36, 1.0);const SESSION_STATUS_OPEN_COLOR: LinearRgba = LinearRgba::with_components(0.12, 0.48, 1.0, 1.0);const SPACE_DISCONNECTED_COLOR: LinearRgba = LinearRgba::with_components(0.86, 0.45, 0.12, 1.0);+const NOTIFICATION_BADGE_COLOR: LinearRgba = LinearRgba::with_components(0.96, 0.16, 0.22, 1.0);+const NOTIFICATION_BADGE_PULSE_DURATION: Duration = Duration::from_millis(1800);+const NOTIFICATION_BADGE_PULSE_COUNT: f32 = 3.0;+const NOTIFICATION_BADGE_FRAME_MS: u64 = 33;const SIDEBAR_SECTION_ACTION_SIZE: usize = 48;const SIDEBAR_SECTION_ACTION_ICON_INSET: usize = 6;/// Connection health of the active Space's mux client domain, as shown by/// the sidebar indicator. Local Spaces are always Connected.#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum SpaceConnectionState {+pub(crate) enum SpaceConnectionState {Connected,/// An attach is in flight (initial connect or manual re-attach); not an/// error state, so no alert icon and no Reconnect button.@@ -311,11 +317,99 @@ impl crate::TermWindow {}}+ /// Update this window's notification snapshot and return the expanding+ /// halo phase for a newly arrived notification. An initial snapshot does+ /// not pulse: notifications restored at startup are unread, but not new.+ fn workspace_notification_badge_pulse(+ &mut self,+ notifications: &[workspace_threads::ThreadWorkNotification],+ ) -> Option<f32> {+ let current = notifications+ .iter()+ .map(|notification| (notification.thread_id.clone(), notification.status))+ .collect::<HashMap<_, _>>();++ let has_new_notification = notification_snapshot_has_new_entry(+ self.workspace_notification_snapshot.as_ref(),+ ¤t,+ );+ let has_current_notifications = !current.is_empty();+ self.workspace_notification_snapshot = Some(current);++ if !has_current_notifications {+ self.workspace_notification_pulse_started_at = None;+ return None;+ }++ let now = Instant::now();+ if has_new_notification {+ self.workspace_notification_pulse_started_at = Some(now);+ }++ let started_at = self.workspace_notification_pulse_started_at?;+ let Some(phase) = notification_badge_pulse_phase(now.saturating_duration_since(started_at))+ else {+ self.workspace_notification_pulse_started_at = None;+ return None;+ };++ self.update_next_frame_time(Some(+ now + Duration::from_millis(NOTIFICATION_BADGE_FRAME_MS),+ ));+ Some(phase)+ }++ fn paint_workspace_notification_badge(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ layer: usize,+ action_x: usize,+ action_y: usize,+ action_size: usize,+ pulse_phase: Option<f32>,+ ) -> anyhow::Result<()> {+ let badge_size = self.ui_px(9).max(4);+ let badge_x = (action_x + action_size).saturating_sub(badge_size + self.ui_px(6));+ let badge_y = action_y + self.ui_px(6);++ if let Some(phase) = pulse_phase {+ // Keep the core visible and radiate a short, fading halo three+ // times. This attracts attention without a continuously blinking+ // control once the animation ends.+ let expansion = self.ui_f32(10.0) * phase;+ let halo_size = badge_size as f32 + expansion;+ let halo_x = badge_x as f32 + badge_size as f32 / 2.0 - halo_size / 2.0;+ let halo_y = badge_y as f32 + badge_size as f32 / 2.0 - halo_size / 2.0;+ self.fill_rounded_rectangle(+ layers,+ layer,+ euclid::rect(halo_x, halo_y, halo_size, halo_size),+ NOTIFICATION_BADGE_COLOR.mul_alpha(0.48 * (1.0 - phase)),+ halo_size / 2.0,+ )+ .context("sidebar notification badge pulse")?;+ }++ self.fill_rounded_rectangle(+ layers,+ layer,+ euclid::rect(+ badge_x as f32,+ badge_y as f32,+ badge_size as f32,+ badge_size as f32,+ ),+ NOTIFICATION_BADGE_COLOR,+ badge_size as f32 / 2.0,+ )+ .context("sidebar notification badge")+ }+/// Connection health of a client-domain Space. While the Space is/// remote we keep a slow self-driven repaint tick going: a dead/// connection produces no output, so nothing else would repaint the/// indicator when the state flips.- fn space_connection_state(&self, space_id: &str) -> SpaceConnectionState {+ pub(crate) fn space_connection_state(&self, space_id: &str) -> SpaceConnectionState {const SUSTAINED_LAG_MS: u64 = 5000;let Some(domain_name) = workspace_threads::client_domain_for_space(space_id) else {return SpaceConnectionState::Connected;@@ -1274,6 +1368,12 @@ impl crate::TermWindow {)?;let notification_icon_size =top_action_icon_size.min(notification_action_size.saturating_sub(14));+ let notification_count = workspace_threads::pending_work_notification_count();+ let notifications = workspace_threads::pending_work_notifications();+ // Treat either snapshot as authoritative for this frame if work state+ // changes between the two short store reads.+ let has_notifications = notification_count > 0 || !notifications.is_empty();+ let notification_badge_pulse = self.workspace_notification_badge_pulse(¬ifications);self.paint_sidebar_icon(layers,SvgIcon::Bell,@@ -1288,23 +1388,16 @@ impl crate::TermWindow {muted_fg},)?;- if workspace_threads::pending_work_notification_count() > 0 {- // Unread badge; reuses the attention hue the Space indicators use.- let badge_size = self.ui_px(8).max(4);- self.fill_rounded_rectangle(+ if has_notifications {+ self.paint_workspace_notification_badge(layers,2,- euclid::rect(- (notification_action_x + notification_action_size)- .saturating_sub(badge_size + self.ui_px(6)) as f32,- (notification_action_y + self.ui_px(6)) as f32,- badge_size as f32,- badge_size as f32,- ),- SPACE_DISCONNECTED_COLOR,- badge_size as f32 / 2.0,+ notification_action_x,+ notification_action_y,+ notification_action_size,+ notification_badge_pulse,)- .context("sidebar notification badge")?;+ .context("sidebar notification badge initial paint")?;}let list_top = layout.list_top;let row_gap = self.ui_px(SIDEBAR_ROW_GAP);@@ -2104,6 +2197,20 @@ impl crate::TermWindow {muted_fg},)?;+ if has_notifications {+ // The layer-2 header mask above covers the initial header+ // paint. Repaint the badge here too, after the button and bell,+ // so the unread indicator is actually visible.+ self.paint_workspace_notification_badge(+ layers,+ 2,+ notification_action_x,+ notification_action_y,+ notification_action_size,+ notification_badge_pulse,+ )+ .context("sidebar notification badge repaint")?;+ }}if max_scroll > 0.0 && scroll_offset > 0.0 {@@ -2837,9 +2944,35 @@ fn snapped_rounded_corner_radius(rect: RectF, radius: f32) -> f32 {.floor()}+fn notification_snapshot_has_new_entry(+ previous: Option<&HashMap<String, workspace_threads::WorkspaceThreadWorkStatus>>,+ current: &HashMap<String, workspace_threads::WorkspaceThreadWorkStatus>,+) -> bool {+ let Some(previous) = previous else {+ return false;+ };+ current+ .iter()+ .any(|(thread_id, status)| previous.get(thread_id) != Some(status))+}++fn notification_badge_pulse_phase(elapsed: Duration) -> Option<f32> {+ if elapsed >= NOTIFICATION_BADGE_PULSE_DURATION {+ return None;+ }+ let total_progress = elapsed.as_secs_f32() / NOTIFICATION_BADGE_PULSE_DURATION.as_secs_f32();+ Some((total_progress * NOTIFICATION_BADGE_PULSE_COUNT).fract())+}+#[cfg(test)]mod tests {- use super::{ellipsize_cut_byte, snapped_rounded_corner_radius};+ use super::{+ ellipsize_cut_byte, notification_badge_pulse_phase, notification_snapshot_has_new_entry,+ snapped_rounded_corner_radius, NOTIFICATION_BADGE_PULSE_DURATION,+ };+ use crate::workspace_threads::WorkspaceThreadWorkStatus;+ use std::collections::HashMap;+ use std::time::Duration;// Build (advance, cluster) pairs for an ASCII or per-char string where every// char is one glyph of `advance` px and the cluster is its byte offset.@@ -2894,4 +3027,58 @@ mod tests {assert_eq!(snapped_rounded_corner_radius(even_height, 999.0), 17.0);assert_eq!(snapped_rounded_corner_radius(even_height, 10.75), 10.0);}++ #[test]+ fn notification_snapshot_ignores_initial_state_and_detects_replacements() {+ let current = HashMap::from([(+ "thread-a".to_string(),+ WorkspaceThreadWorkStatus::FinishedUnseen,+ )]);+ assert!(!notification_snapshot_has_new_entry(None, ¤t));+ assert!(!notification_snapshot_has_new_entry(+ Some(¤t),+ ¤t+ ));++ // Total count is still one, but a different thread completed.+ let replacement = HashMap::from([(+ "thread-b".to_string(),+ WorkspaceThreadWorkStatus::FinishedUnseen,+ )]);+ assert!(notification_snapshot_has_new_entry(+ Some(¤t),+ &replacement+ ));+ }++ #[test]+ fn notification_snapshot_detects_status_transition() {+ let attention = HashMap::from([(+ "thread-a".to_string(),+ WorkspaceThreadWorkStatus::NeedsAttention,+ )]);+ let finished = HashMap::from([(+ "thread-a".to_string(),+ WorkspaceThreadWorkStatus::FinishedUnseen,+ )]);+ assert!(notification_snapshot_has_new_entry(+ Some(&attention),+ &finished+ ));+ }++ #[test]+ fn notification_badge_pulses_three_times_then_stops() {+ assert_eq!(notification_badge_pulse_phase(Duration::ZERO), Some(0.0));+ assert_eq!(+ notification_badge_pulse_phase(NOTIFICATION_BADGE_PULSE_DURATION),+ None+ );++ // Halfway through each 600ms cycle, the expanding halo is halfway out.+ for elapsed_ms in [300, 900, 1500] {+ let phase = notification_badge_pulse_phase(Duration::from_millis(elapsed_ms)).unwrap();+ assert!((phase - 0.5).abs() < 0.001);+ }+ }}diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex ad249677..7125f7b9 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -1,6 +1,7 @@use anyhow::{ensure, Context, Result};use chrono::Utc;use config::keyassignment::{SpawnCommand, SpawnTabDomain};+use fluent_bundle::FluentArgs;use futures::future::LocalBoxFuture;use mux::domain::SplitSource;use mux::pane::PaneId;@@ -39,6 +40,11 @@ pub struct WorkspaceThreadStore {pub last_active_space_id: Option<SpaceId>,#[serde(default, skip_serializing)]pub active_project_id: Option<ProjectId>,+ /// Which Space this device was last looking at on each mux domain. A+ /// server can host several Spaces, so reconnecting has to pick one; this+ /// is per-device by nature and never travels to the server.+ #[serde(default)]+ pub last_space_per_domain: HashMap<String, SpaceId>,pub projects: Vec<Project>,}@@ -283,6 +289,8 @@ pub enum DeleteSpaceError {DefaultSpace,LastSpace,Occupied,+ RemoteUnavailable,+ ServerRejected,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -292,10 +300,13 @@ pub struct SpaceView {pub is_active: bool,pub is_default: bool,pub is_occupied_by_other_window: bool,- /// True for a Space dedicated to a remote mux client domain+ /// True for a Space that lives on a remote mux client domain/// (`thinkterm connect`); the UI labels these distinctly and their- /// "delete" is local-only (the remote server keeps running).+ /// "disconnect" is local-only (the remote server keeps running).pub is_remote: bool,+ /// The mux domain hosting this Space, when it is remote. One server can+ /// host several Spaces, so the Space menu groups by this.+ pub domain: Option<String>,}lazy_static::lazy_static! {@@ -311,6 +322,30 @@ lazy_static::lazy_static! {Mutex::new(HashMap::new());static ref WORK_STATUS_RECHECK_PENDING: Mutex<std::collections::HashSet<String>> =Mutex::new(std::collections::HashSet::new());+ /// The sidebar tree each mux server last told us it had, keyed by domain+ /// name. A reconcile diffs against this: rows that still match it are left+ /// alone (another device may have changed them since), and rows it has+ /// that we no longer do are the ones to delete.+ static ref LAST_KNOWN_REMOTE_TREES: Mutex<HashMap<String, codec::ThinkTermTree>> =+ Mutex::new(HashMap::new());+ /// Online mutations currently in flight, keyed by domain name. This is a+ /// short-lived presentation overlay only: it is never persisted or+ /// replayed after a disconnect. A remote edit is rejected while the+ /// domain is unavailable, and a reconnect always starts from the server's+ /// tree rather than from client intent left over from the old connection.+ static ref IN_FLIGHT_TREE_OPS: Mutex<HashMap<String, Vec<codec::TreeOp>>> =+ Mutex::new(HashMap::new());+ /// Remote Spaces this device has disconnected from, keyed by domain name.+ /// The server still has them and other devices still see them; this device+ /// filters them out of every push until it reconnects to that server.+ static ref LOCALLY_HIDDEN_SPACES: Mutex<HashMap<String, std::collections::HashSet<SpaceId>>> =+ Mutex::new(HashMap::new());+ /// Servers we have just connected to and not yet heard a tree from. The+ /// first tree of a connection is the one that catches this device up, and+ /// it is not necessarily the answer to our own fetch — a broadcast can+ /// overtake it.+ static ref FIRST_TREE_PENDING: Mutex<std::collections::HashSet<String>> =+ Mutex::new(std::collections::HashSet::new());}static THREAD_STORE_PERSIST_SCHEDULED: AtomicBool = AtomicBool::new(false);@@ -584,6 +619,7 @@ pub fn switch_window_space(owner_id: u64, space_id: &str) -> bool {return false;}store.last_active_space_id = Some(space_id.to_string());+ store.remember_space_for_domain(space_id);persist_locked(&store);drop(store);@@ -610,6 +646,7 @@ pub fn spaces_for_window(owner_id: u64) -> Vec<SpaceView> {.iter().any(|(owner, active_space)| *owner != owner_id && active_space == &space.id),is_remote: space.client_domain.is_some(),+ domain: space.client_domain.clone(),}).collect()}@@ -692,6 +729,47 @@ pub fn create_space(name: Option<String>) -> SpaceId {id}+/// Add another Space to a remote server.+///+/// The Space lives on the server like any other, so it is created locally with+/// a fresh id and the same id is sent up; every other device attached to that+/// server sees it appear. The domain's own project (the one carrying the+/// `wezterm-mux://` sentinel path) and its first thread come along, because a+/// Space with nothing in it has nowhere to put a terminal.+pub fn create_space_on_domain(domain_name: &str, name: Option<String>) -> Result<SpaceId> {+ ensure!(+ remote_tree_mutation_allowed(Some(domain_name)),+ "{domain_name} is disconnected"+ );+ let mut store = THREAD_STORE.lock();+ store.normalize_after_load();+ let name = name.unwrap_or_else(|| next_space_name(&store.spaces));+ let space_id = store.create_space_record_for_domain(name, Some(domain_name.to_string()));++ let project_id = remote_project_id_for_space(&space_id, &mux_domain_host_id(domain_name));+ let thread = WorkspaceThread::new(project_id.clone(), "main".to_string(), None);+ let thread_id = thread.id.clone();+ store.projects.push(Project {+ id: project_id.clone(),+ space_id: space_id.clone(),+ name: domain_name.to_string(),+ path: PathBuf::from(format!("wezterm-mux://{domain_name}")),+ threads: vec![thread],+ active_thread_id: Some(thread_id),+ threads_collapsed: false,+ active_note_path: None,+ });+ if let Some(space) = store.spaces.iter_mut().find(|space| space.id == space_id) {+ space.active_project_id = Some(project_id);+ }+ store.last_active_space_id = Some(space_id.clone());+ persist_locked(&store);+ drop(store);++ reconcile_remote_subtree(domain_name);+ Ok(space_id)+}+pub fn ensure_space_named(name: &str) -> SpaceId {let name = name.trim();let name = if name.is_empty() { "Default" } else { name };@@ -718,16 +796,42 @@ pub fn ensure_space_named(name: &str) -> SpaceId {pub fn rename_space(space_id: &str, name: String) -> bool {let mut store = THREAD_STORE.lock();- let changed = store.rename_space(space_id, name);+ let domain = tree_domain_for_space(&store, space_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }+ let changed = store.rename_space(space_id, name.clone());if changed {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::RenameSpace {+ space_id: space_id.to_string(),+ name,+ },+ );+ }persist_locked(&store);}changed}-pub fn delete_space_for_window(+/// What removing a Space from this window should mean.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SpaceRemoval {+ /// Drop this device's copy only. For a remote Space the rows are a cache+ /// of the server's tree, so the Space comes back on the next connect and+ /// other devices never notice — this is "disconnect", not "delete".+ Local,+ /// Delete the Space on the server that hosts it, so it disappears+ /// everywhere. Falls back to a local removal for a local Space.+ Everywhere,+}++fn delete_space_for_window_local(owner_id: u64,space_id: &str,+ removal: SpaceRemoval,) -> Result<DeletedSpace, DeleteSpaceError> {let window_was_active = WINDOW_SPACES.lock()@@ -743,6 +847,8 @@ pub fn delete_space_for_window(}let mut store = THREAD_STORE.lock();+ // Resolve the owning server before the Space record is gone.+ let domain = tree_domain_for_space(&store, space_id);let mut deleted = store.delete_space(space_id)?;if window_was_active {let fallback_space_id = store@@ -771,6 +877,163 @@ pub fn delete_space_for_window(.lock().insert(owner_id, deleted.fallback_space_id.clone());}++ if let Some(domain) = domain {+ match removal {+ SpaceRemoval::Everywhere => {+ submit_tree_op(+ domain,+ codec::TreeOp::DeleteSpace {+ space_id: space_id.to_string(),+ },+ );+ }+ SpaceRemoval::Local => {+ // The server keeps the Space and other devices keep seeing it,+ // so its next push still carries it. Remember to filter it out+ // here until this device connects to that server again, which+ // is when the menu says it comes back.+ hide_space_locally(&domain, space_id);+ }+ }+ }++ Ok(deleted)+}++/// Delete a Space, waiting for the owning mux server before changing any+/// local ownership or tearing down mirror windows. Keeping the windows alive+/// across the await also keeps the last ClientDomain reference attached, so a+/// sole-Space delete cannot strand its request in a detached client.+pub async fn delete_space_for_window(+ owner_id: u64,+ space_id: &str,+ removal: SpaceRemoval,+ end_remote_sessions: bool,+) -> Result<DeletedSpace, DeleteSpaceError> {+ let domain_name = {+ let store = THREAD_STORE.lock();+ tree_domain_for_space(&store, space_id)+ };++ if removal != SpaceRemoval::Everywhere || domain_name.is_none() {+ return delete_space_for_window_local(owner_id, space_id, removal);+ }++ // Validate without changing the real store, and capture the remote+ // workspaces while the authoritative response still has their rows.+ let (window_was_active, occupied_by_other, mut deleted) = {+ let window_was_active = WINDOW_SPACES+ .lock()+ .get(&owner_id)+ .is_some_and(|active_space| active_space == space_id);+ let occupied_by_other = WINDOW_SPACES+ .lock()+ .iter()+ .filter_map(|(owner, active_space)| (*owner != owner_id).then(|| active_space.clone()))+ .collect::<std::collections::HashSet<_>>();+ if occupied_by_other.contains(space_id) {+ return Err(DeleteSpaceError::Occupied);+ }+ let store = THREAD_STORE.lock();+ let mut staged = store.clone();+ let deleted = staged.delete_space(space_id)?;+ (window_was_active, occupied_by_other, deleted)+ };++ let domain_name = domain_name.unwrap();+ if !remote_tree_domain_is_attached(&domain_name) {+ notify_remote_tree_mutation_unavailable(&domain_name);+ return Err(DeleteSpaceError::RemoteUnavailable);+ }+ let domain = Mux::get()+ .get_domain_by_name(&domain_name)+ .ok_or(DeleteSpaceError::RemoteUnavailable)?;+ let client = domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .ok_or(DeleteSpaceError::RemoteUnavailable)?;+ // Keep empty mirror windows from being pruned while the final remote+ // panes and tree row are removed. Without this guard the last KillPane+ // notification can detach the domain before DeleteSpace reaches it.+ let _delete_activity = mux::activity::Activity::new();+ if end_remote_sessions {+ let mut panes = Vec::new();+ let mut seen = std::collections::HashSet::new();+ for workspace in &deleted.materialized_workspace_names {+ for window_id in Mux::get().iter_windows_in_workspace(workspace) {+ if let Some(window) = Mux::get().get_window(window_id) {+ for pane in window.iter().flat_map(|tab| tab.iter_all_panes()) {+ if pane.domain_id() == domain.domain_id()+ && pane+ .downcast_ref::<wezterm_client::pane::ClientPane>()+ .is_some()+ && seen.insert(pane.pane_id())+ {+ panes.push(pane);+ }+ }+ }+ }+ }+ for pane in panes {+ let remote = pane+ .downcast_ref::<wezterm_client::pane::ClientPane>()+ .expect("filtered ClientPane");+ if let Err(err) = remote.kill_remote_and_wait().await {+ log::error!(+ "failed to end pane {} while deleting Space {space_id} on {domain_name}: {err:#}",+ pane.pane_id()+ );+ notify_remote_tree_mutation_unavailable(&domain_name);+ return Err(DeleteSpaceError::RemoteUnavailable);+ }+ }+ }++ let tree = match client+ .mutate_thinkterm_tree(vec![codec::TreeOp::DeleteSpace {+ space_id: space_id.to_string(),+ }])+ .await+ {+ Ok(tree) => tree,+ Err(err) => {+ log::error!("failed to delete Space {space_id} on {domain_name}: {err:#}");+ notify_remote_tree_mutation_unavailable(&domain_name);+ return Err(DeleteSpaceError::RemoteUnavailable);+ }+ };+ if tree.space(space_id).is_some() {+ log::error!("{domain_name} rejected deletion of ThinkTerm Space {space_id}");+ return Err(DeleteSpaceError::ServerRejected);+ }++ // `mutate_thinkterm_tree` synchronously delivered the response through+ // ingest_remote_tree, so the shared row is already gone. Only per-device+ // selection state remains to be committed here.+ if window_was_active {+ let mut store = THREAD_STORE.lock();+ let fallback_space_id = store+ .spaces+ .iter()+ .find(|space| space.is_default && !occupied_by_other.contains(&space.id))+ .or_else(|| {+ store+ .spaces+ .iter()+ .find(|space| !occupied_by_other.contains(&space.id))+ })+ .map(|space| space.id.clone())+ .unwrap_or_else(|| {+ let name = next_space_name(&store.spaces);+ store.create_space_record(name)+ });+ store.last_active_space_id = Some(fallback_space_id.clone());+ persist_locked(&store);+ deleted.fallback_space_id = fallback_space_id.clone();+ WINDOW_SPACES.lock().insert(owner_id, fallback_space_id);+ }+Ok(deleted)}@@ -900,15 +1163,41 @@ pub fn sync_current_project(space_id: &str, active_workspace: &str) -> bool {let changed = store.sync_current_project(space_id, active_workspace);if changed {persist_locked(&store);+ if let Some(thread_id) = store.thread_id_for_workspace(space_id, active_workspace) {+ submit_thread_state(&store, &thread_id);+ }}changed}-pub fn create_thread(project_id: &str, name: Option<String>) -> WorkspaceThreadId {+pub fn create_thread(project_id: &str, name: Option<String>) -> Result<WorkspaceThreadId> {let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_project(&store, project_id);+ ensure!(+ remote_tree_mutation_allowed(domain.as_deref()),+ "remote project is disconnected"+ );let thread_id = store.create_thread(project_id, name);persist_locked(&store);- thread_id+ // The id is generated here rather than by the server so that callers can+ // go straight on to activating the thread; the server just adopts it.+ let created = store+ .thread_record(&thread_id)+ .map(|thread| (thread.name.clone(), thread.last_active_at));+ drop(store);+ if let (Some(domain), Some((name, created_at))) = (domain, created) {+ submit_tree_op(+ domain,+ codec::TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id: project_id.to_string(),+ name,+ workspace: None,+ created_at,+ },+ );+ }+ Ok(thread_id)}/// Pick the thread a GUI window should fall back to after the mux window@@ -1001,6 +1290,9 @@ pub fn activate_thread_record(let mut store = THREAD_STORE.lock();let plan = store.activate_thread_record(thread_id, live_workspaces);persist_locked(&store);+ if plan.is_some() {+ submit_thread_state(&store, thread_id);+ }plan}@@ -1251,9 +1543,22 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(// part keyed by the remote pane id: the local pane ids die with the// mirror window on switch-away and are reissued by the resync on// switch-back.- if Mux::get()- .get_window(window_id)- .map_or(false, |w| w.origin_domain().is_some())+ //+ // The window's origin tag alone is not enough to recognize one. A thread+ // materialized after the connect gets its mux window from the generic+ // spawn path, which does not tag it, and the tag never appears later+ // because the resync binds the remote window to that same untagged one.+ // Such a window used to fall through to the local branch, which then+ // refused it for being a client-domain Space — so the scale was written+ // nowhere and every switch away lost it. Asking the same question the+ // store asks (`is_client_domain_space`, below in+ // `snapshot_active_space_thread_layout`) keeps the two in step whatever+ // the tag says; the tag is still honoured so tmux keeps its behaviour.+ let space_is_remote = client_domain_for_space(space_id).is_some();+ if space_is_remote+ || Mux::get()+ .get_window(window_id)+ .map_or(false, |w| w.origin_domain().is_some()){let mut scales: HashMap<PaneId, f64> = HashMap::new();let mut remote_panes = 0usize;@@ -1322,9 +1627,47 @@ pub async fn materialize_thread(let _guard = MaterializeThreadLayoutGuard::new(workspace_name.clone());materialize_layout(mux, workspace_name, layout, initial_cwd, size, term_config).await} else {- let (_tab, pane, _window_id) = mux+ // A thread whose Space lives on a mux server needs its window tagged+ // with that domain. `spawn_tab_or_window` makes untagged windows, and+ // the resync then binds the remote window to this one for good, so a+ // tag missed here never appears later. Everything that asks "which+ // server owns this window" reads that tag: font-scale persistence,+ // re-connect focus, orphan adoption, and the frontend's+ // local-vs-domain-owned split.+ //+ // Only client domains are tagged. Tagging whatever domain the pane+ // happens to come from would mark ordinary local windows as+ // domain-owned, which is a far worse misclassification than the one+ // being fixed.+ let origin = mux+ .resolve_spawn_tab_domain(None, &default_domain)+ .ok()+ .and_then(|domain| {+ domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .map(|_| domain.domain_id())+ });++ // The builder carries an Activity, and that Activity is the only thing+ // stopping a still-empty window from being pruned. Spawning into a+ // remote domain is a round trip, so the builder has to outlive the+ // await — dropping it early can prune the window before its first tab+ // lands. `connect_domain_into_space` holds a `connect_activity` across+ // its own attach+spawn for exactly this reason.+ let tagged_window = origin.map(|domain_id| {+ mux.new_empty_window_for_domain(Some(workspace_name.clone()), None, Some(domain_id))+ });+ let window_id = tagged_window.as_ref().map(|builder| **builder);+ if let (Some(window_id), Some(domain_id)) = (window_id, origin) {+ log::debug!(+ "materialize_thread: window {window_id} for {workspace_name} \+ tagged with client domain {domain_id}"+ );+ }++ let spawned = mux.spawn_tab_or_window(- None,+ window_id,default_domain,None,initial_cwd,@@ -1333,8 +1676,10 @@ pub async fn materialize_thread(workspace_name,None,)- .await- .context("spawn default thread window")?;+ .await;+ drop(tagged_window);++ let (_tab, pane, _window_id) = spawned.context("spawn default thread window")?;pane.set_config(term_config);let _ = src_window_id;Ok(())@@ -1661,8 +2006,21 @@ pub fn workspace_pane_font_scales(pub fn rename_project(project_id: &str, name: String) -> bool {let mut store = THREAD_STORE.lock();- let changed = store.rename_project(project_id, name);+ let domain = tree_domain_for_project(&store, project_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }+ let changed = store.rename_project(project_id, name.clone());if changed {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::RenameProject {+ project_id: project_id.to_string(),+ name,+ },+ );+ }persist_locked(&store);}changed@@ -1670,8 +2028,21 @@ pub fn rename_project(project_id: &str, name: String) -> bool {pub fn remove_project(project_id: &str) -> Option<RemovedProject> {let mut store = THREAD_STORE.lock();+ // Resolve the owner before the record is gone.+ let domain = tree_domain_for_project(&store, project_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return None;+ }let removed = store.remove_project(project_id);if removed.is_some() {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::RemoveProject {+ project_id: project_id.to_string(),+ },+ );+ }persist_locked(&store);}removed@@ -1679,8 +2050,26 @@ pub fn remove_project(project_id: &str) -> Option<RemovedProject> {pub fn rename_thread(thread_id: &str, name: String) -> bool {let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_thread(&store, thread_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }+ let requested_name = name.clone();let changed = store.rename_thread(thread_id, name);if changed {+ // The local store predicts a unique name for immediate feedback, but+ // the op carries the user's request. The server re-settles it against+ // the current authoritative project and its response wins.+ if let (Some(domain), Some(thread)) = (domain, store.thread_record(thread_id)) {+ submit_tree_op(+ domain,+ codec::TreeOp::RenameThread {+ thread_id: thread_id.to_string(),+ name: requested_name,+ last_active_at: thread.last_active_at,+ },+ );+ }persist_locked(&store);}changed@@ -1688,8 +2077,22 @@ pub fn rename_thread(thread_id: &str, name: String) -> bool {pub fn toggle_thread_pinned(thread_id: &str) -> bool {let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_thread(&store, thread_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }let changed = store.toggle_thread_pinned(thread_id);if changed {+ if let (Some(domain), Some(thread)) = (domain, store.thread_record(thread_id)) {+ submit_tree_op(+ domain,+ codec::TreeOp::SetThreadPinned {+ thread_id: thread_id.to_string(),+ pinned: thread.is_pinned,+ last_active_at: thread.last_active_at,+ },+ );+ }persist_locked(&store);}changed@@ -1697,49 +2100,650 @@ pub fn toggle_thread_pinned(thread_id: &str) -> bool {pub fn mark_thread_unread(thread_id: &str) -> bool {let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_thread(&store, thread_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }let changed = store.mark_thread_unread(thread_id);if changed {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::SetThreadUnread {+ thread_id: thread_id.to_string(),+ unread: true,+ },+ );+ }persist_locked(&store);}changed}-#[allow(dead_code)]-pub fn delete_thread(thread_id: &str) -> Option<DeletedWorkspaceThread> {- let mut store = THREAD_STORE.lock();- let deleted = store.delete_thread(thread_id);- if deleted.is_some() {- persist_locked(&store);+#[allow(dead_code)]+pub fn delete_thread(thread_id: &str) -> Option<DeletedWorkspaceThread> {+ let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_thread(&store, thread_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return None;+ }+ let deleted = store.delete_thread(thread_id);+ if deleted.is_some() {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::DeleteThread {+ thread_id: thread_id.to_string(),+ },+ );+ }+ persist_locked(&store);+ }+ deleted+}++pub fn end_workspace_thread_record(thread_id: &str) -> EndWorkspaceThreadResult {+ let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_thread(&store, thread_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return EndWorkspaceThreadResult::Noop;+ }+ let result = store.end_workspace_thread_record(thread_id);+ if !matches!(result, EndWorkspaceThreadResult::Noop) {+ persist_locked(&store);+ }+ drop(store);+ // Ending the last thread of a Space's last project also creates a+ // replacement project and removes the old one; restating the subtree is+ // more reliable than tracking that sequence op by op.+ if let Some(domain) = domain {+ if !matches!(result, EndWorkspaceThreadResult::Noop) {+ reconcile_remote_subtree(&domain);+ }+ }+ result+}++pub fn disconnect_workspace_thread_record(+ thread_id: &str,+ live_workspaces: &[String],+) -> Option<DisconnectedWorkspaceThread> {+ let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_thread(&store, thread_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return None;+ }+ let (disconnected, changed) =+ store.disconnect_workspace_thread_record(thread_id, live_workspaces);+ if changed {+ persist_locked(&store);+ }+ drop(store);+ // Disconnecting a Space's active thread can also mint a replacement+ // project and its first thread to land on. Restating the subtree covers+ // that, where a targeted op for the thread being disconnected would leave+ // the new rows unknown to the server — and the next push would delete them+ // out from under the activation that is about to use them.+ if changed {+ if let Some(domain) = domain {+ reconcile_remote_subtree(&domain);+ }+ }+ disconnected+}++/// Route `op` to the mux server that owns `domain_name`.+///+/// The caller has already applied the equivalent mutation to the local store,+/// so the UI is already correct; this tells the server (and through it every+/// other attached device). The server's reply and broadcast both come back+/// through `ingest_remote_tree`, which is what corrects us if the server saw+/// things differently — a racing delete from another device, say.+fn submit_tree_op(domain_name: String, op: codec::TreeOp) {+ submit_tree_ops(domain_name, vec![op]);+}++fn submit_tree_ops(domain_name: String, ops: Vec<codec::TreeOp>) {+ if ops.is_empty() {+ return;+ }+ if !remote_tree_domain_is_attached(&domain_name) {+ // This is the transport layer, not necessarily a user action. Space+ // disconnect, window re-home and reconnect bookkeeping can all leave+ // a harmless late state-sync here after the domain has deliberately+ // detached. Roll it back to the server baseline without telling the+ // user to undo the disconnect they just requested. Explicit editing+ // commands use `remote_tree_mutation_allowed` before changing the+ // store, and that higher layer owns the user-facing notification.+ log::warn!(+ "dropping {} late ThinkTerm tree ops for {domain_name}: domain is unavailable",+ ops.len()+ );+ schedule_restore_last_authoritative_tree(domain_name);+ return;+ }+ queue_in_flight_tree_ops(&domain_name, &ops);+ send_tree_ops(domain_name, ops);+}++/// Put an already-approved online mutation on the wire. A failure retires the+/// presentation overlay instead of turning it into an offline command: the+/// next authoritative tree is allowed to restore what the server actually has.+fn send_tree_ops(domain_name: String, ops: Vec<codec::TreeOp>) {+ promise::spawn::spawn_into_main_thread(async move {+ let Some(domain) = Mux::get().get_domain_by_name(&domain_name) else {+ retire_sent_tree_ops(&domain_name, &ops);+ log::warn!("cannot mutate ThinkTerm tree for {domain_name}: domain disappeared");+ restore_last_authoritative_tree(&domain_name);+ return;+ };+ let Some(client) = domain.downcast_ref::<wezterm_client::domain::ClientDomain>() else {+ log::warn!("{domain_name} is not a mux client domain; dropping ThinkTerm tree ops");+ retire_sent_tree_ops(&domain_name, &ops);+ restore_last_authoritative_tree(&domain_name);+ return;+ };+ if !remote_tree_domain_is_attached(&domain_name) {+ retire_sent_tree_ops(&domain_name, &ops);+ log::warn!("cannot mutate ThinkTerm tree for {domain_name}: domain detached");+ restore_last_authoritative_tree(&domain_name);+ return;+ }+ match client.mutate_thinkterm_tree(ops.clone()).await {+ Ok(tree) => {+ // The domain delivers the reply to the tree sink before this+ // future resumes. At that point this batch is deliberately+ // still part of the presentation overlay, so a server-side+ // canonicalization (for example de-duplicating a Thread+ // name) can be hidden by the client's requested value. Drop+ // the acknowledged intent and ingest the same reply once+ // more: the server's result is the final word, while any+ // genuinely later batch remains overlaid until its own ack.+ retire_sent_tree_ops(&domain_name, &ops);+ ingest_remote_tree(&domain_name, tree);+ }+ Err(err) => {+ retire_sent_tree_ops(&domain_name, &ops);+ log::error!("failed to send ThinkTerm tree ops to {domain_name}: {err:#}");+ restore_last_authoritative_tree(&domain_name);+ }+ }+ })+ .detach();+}++fn restore_last_authoritative_tree(domain_name: &str) {+ let tree = LAST_KNOWN_REMOTE_TREES.lock().get(domain_name).cloned();+ if let Some(tree) = tree {+ ingest_remote_tree(domain_name, tree);+ }+}++fn schedule_restore_last_authoritative_tree(domain_name: String) {+ promise::spawn::spawn_into_main_thread(async move {+ restore_last_authoritative_tree(&domain_name);+ })+ .detach();+}++/// Cap connection-scoped in-flight presentation overlays. This is not an+/// offline queue and is cleared whenever the connection generation changes.+const MAX_IN_FLIGHT_TREE_OPS: usize = 1024;++/// Remember `ops` only until this connection's response shows the server has+/// them or the connection is replaced.+fn queue_in_flight_tree_ops(domain_name: &str, ops: &[codec::TreeOp]) {+ let mut in_flight = IN_FLIGHT_TREE_OPS.lock();+ let queue = in_flight.entry(domain_name.to_string()).or_default();+ if queue.len() >= MAX_IN_FLIGHT_TREE_OPS {+ log::warn!(+ "dropping {} ThinkTerm tree ops for {domain_name}: {} already waiting to be acked",+ ops.len(),+ queue.len()+ );+ return;+ }+ queue.extend(ops.iter().cloned());+}++fn take_in_flight_tree_ops(domain_name: &str) -> Vec<codec::TreeOp> {+ IN_FLIGHT_TREE_OPS+ .lock()+ .remove(domain_name)+ .unwrap_or_default()+}++/// Put back the ops an arriving tree did not account for, bypassing the cap:+/// this is the same set coming round again, not new growth.+fn restore_in_flight_tree_ops(domain_name: &str, ops: Vec<codec::TreeOp>) {+ IN_FLIGHT_TREE_OPS+ .lock()+ .insert(domain_name.to_string(), ops);+}++/// Drop the ops the server has just told us it processed.+///+/// One occurrence each, by value: a batch that creates a row and deletes it+/// again is settled the moment the server has run both, and re-deriving that+/// from the resulting tree is impossible — the net effect is invisible there.+fn retire_sent_tree_ops(domain_name: &str, sent: &[codec::TreeOp]) {+ let mut in_flight = IN_FLIGHT_TREE_OPS.lock();+ let Some(queue) = in_flight.get_mut(domain_name) else {+ return;+ };+ for op in sent {+ if let Some(index) = queue.iter().position(|queued| queued == op) {+ queue.remove(index);+ }+ }+ if queue.is_empty() {+ in_flight.remove(domain_name);+ }+}++/// Drop `space_id` from this device's view of `domain_name` without touching+/// the server's copy.+///+/// It is removed from the last-known tree as well, so the reconcile that+/// follows neither deletes it on the server nor offers to recreate it: as far+/// as diffing is concerned this device has simply never heard of it.+fn hide_space_locally(domain_name: &str, space_id: &str) {+ LOCALLY_HIDDEN_SPACES+ .lock()+ .entry(domain_name.to_string())+ .or_default()+ .insert(space_id.to_string());+ if let Some(tree) = LAST_KNOWN_REMOTE_TREES.lock().get_mut(domain_name) {+ let mut just_this_one = std::collections::HashSet::new();+ just_this_one.insert(space_id.to_string());+ strip_hidden_spaces(tree, &just_this_one);+ }+}++fn strip_hidden_spaces(+ tree: &mut codec::ThinkTermTree,+ hidden: &std::collections::HashSet<SpaceId>,+) {+ if hidden.is_empty() {+ return;+ }+ tree.spaces.retain(|space| !hidden.contains(&space.id));+ tree.projects+ .retain(|project| !hidden.contains(&project.space_id));+}++/// The mux domain owning `space_id`, when it is a remote Space.+fn tree_domain_for_space(store: &WorkspaceThreadStore, space_id: &str) -> Option<String> {+ store+ .spaces+ .iter()+ .find(|space| space.id == space_id)+ .and_then(|space| space.client_domain.clone())+}++fn tree_domain_for_project(store: &WorkspaceThreadStore, project_id: &str) -> Option<String> {+ let space_id = store+ .projects+ .iter()+ .find(|project| project.id == project_id)+ .map(|project| project.space_id.clone())?;+ tree_domain_for_space(store, &space_id)+}++fn tree_domain_for_thread(store: &WorkspaceThreadStore, thread_id: &str) -> Option<String> {+ let project_id = store+ .projects+ .iter()+ .find(|project| project.threads.iter().any(|thread| thread.id == thread_id))+ .map(|project| project.id.clone())?;+ tree_domain_for_project(store, &project_id)+}++fn remote_tree_domain_is_attached(domain_name: &str) -> bool {+ Mux::get()+ .get_domain_by_name(domain_name)+ .is_some_and(|domain| {+ let Some(client) = domain.downcast_ref::<wezterm_client::domain::ClientDomain>() else {+ return false;+ };+ remote_tree_connection_can_mutate(+ domain.state(),+ client.is_attaching(),+ client.is_reconnecting(),+ client.is_reconnect_suspended(),+ )+ })+}++fn remote_tree_connection_can_mutate(+ state: mux::domain::DomainState,+ attaching: bool,+ reconnecting: bool,+ reconnect_suspended: bool,+) -> bool {+ state == mux::domain::DomainState::Attached+ && !attaching+ && !reconnecting+ && !reconnect_suspended+}++/// Report an unavailable server for an explicit user edit. Background state+/// synchronization must stay silent and only restore the authoritative tree.+fn notify_remote_tree_mutation_unavailable(domain_name: &str) {+ log::warn!(+ "ThinkTerm tree mutation for {domain_name} was rejected: reconnect to the server first"+ );+ if crate::frontend::try_front_end().is_some() {+ let mut args = FluentArgs::new();+ args.set("name", domain_name.to_string());+ wezterm_toast_notification::persistent_toast_notification(+ "ThinkTerm",+ &crate::i18n::tr_args("remote-tree-mutation-offline", &args),+ );+ }+}++/// Shared remote rows are not an offline-editable cache. Call this before+/// changing the store; a missing domain means the row is local and remains+/// immediately editable.+fn remote_tree_mutation_allowed(domain_name: Option<&str>) -> bool {+ let Some(domain_name) = domain_name else {+ return true;+ };+ if remote_tree_domain_is_attached(domain_name) {+ true+ } else {+ notify_remote_tree_mutation_unavailable(domain_name);+ false+ }+}++/// Adopt a mux server's sidebar tree.+///+/// The server owns which Spaces/Projects/Threads exist, their names, order and+/// pins; this device owns where it is looking and how it is displayed. So the+/// remote records are rebuilt from the tree while every per-device field is+/// carried across by id.+pub fn ingest_remote_tree(domain_name: &str, tree: codec::ThinkTermTree) {+ let mut tree = tree;+ if let Some(hidden) = LOCALLY_HIDDEN_SPACES.lock().get(domain_name) {+ strip_hidden_spaces(&mut tree, hidden);+ }++ // Before anything else, and before the emptiness below is given any+ // meaning: a tree older than the one we hold is stale news, whichever+ // route it took. Trees arrive both as RPC answers and as broadcasts, on+ // schedules that can swap them over, and a reply cut before a push must+ // not undo it — least of all by looking "uninitialized" and sending us+ // back round the seeding path.+ let known_revision = LAST_KNOWN_REMOTE_TREES+ .lock()+ .get(domain_name)+ .map(|known| known.revision);+ if tree_is_stale(tree.revision, known_revision) {+ log::debug!(+ "ignoring ThinkTerm tree from {domain_name}: revision {} is older than \+ the {known_revision:?} we hold",+ tree.revision+ );+ return;+ }++ // The first tree of a connection is the only place allowed to invent a+ // Space when the server has none. Online mutations from the previous+ // connection are deliberately not carried across this boundary.+ let first_of_connection = FIRST_TREE_PENDING.lock().remove(domain_name);++ // A server nobody has ever written to answers with an empty tree, and that+ // emptiness says "unset", not "the user deleted everything" — seed it from+ // what we hold. Once it has a revision an empty tree is the truth, and a+ // device with a stale cache must not resurrect the deleted rows.+ if tree.is_uninitialized() {+ // An uninitialized server is the one explicit bootstrap exception:+ // it has no authoritative rows yet, so the cached subtree may seed it.+ take_in_flight_tree_ops(domain_name);+ LAST_KNOWN_REMOTE_TREES+ .lock()+ .insert(domain_name.to_string(), tree);+ reconcile_remote_subtree(domain_name);+ return;+ }++ // A push can overtake an online RPC. Fold only this connection's in-flight+ // presentation overlay into that push so the row does not flicker while+ // the request is on the wire. These ops are never persisted separately,+ // never accepted while offline and never re-sent after reconnect.+ //+ // An op that no longer changes the server's tree is one the server has+ // accounted for, so it retires here; the rest go back on the queue. The+ // last-known tree deliberately stays the server's own copy: until it says+ // otherwise these ops are still a local difference.+ //+ let mut unacked = take_in_flight_tree_ops(domain_name);+ let mut patched = tree.clone();+ unacked.retain(|op| codec::apply_op(&mut patched, op));+ if !unacked.is_empty() {+ restore_in_flight_tree_ops(domain_name, unacked.clone());+ }+ let tree_for_store = patched;++ let mut store = THREAD_STORE.lock();+ // Which Spaces belonged to this server *before* it spoke. Only a window+ // parked on one of these can have been orphaned by this push, and the set+ // has to be taken now because the ingest below is what removes them.+ let owned_before = store.space_ids_for_domain(domain_name);+ let mut changed = store.ingest_remote_tree(domain_name, &tree_for_store);+ // A server can legitimately have no Spaces left — its last one was deleted+ // from here or from another device. A device that is connecting to it+ // right now still needs somewhere on *that server* to land, so build one+ // before the re-home below has to reach for a fallback and drop the window+ // onto an unrelated local Space. Only on the connection's first tree: a+ // broadcast reaching several attached devices at once would otherwise have+ // every one of them invent a Space.+ let minted_space =+ if first_of_connection && store.preferred_space_for_domain(domain_name).is_none() {+ let plan = store.ensure_mux_domain_space(domain_name);+ log::info!(+ "{domain_name} has no Spaces left; created {}",+ plan.space_id+ );+ changed = true;+ true+ } else {+ false+ };+ if changed {+ persist_locked(&store);+ }+ // A window can be left sitting on a Space the server does not have: the+ // connect flow has to pick a Space before it can authenticate, so a device+ // connecting for the first time invents one and only learns the real ones+ // here.+ let rehome = orphaned_window_spaces(&store, domain_name, &owned_before);+ drop(store);++ LAST_KNOWN_REMOTE_TREES+ .lock()+ .insert(domain_name.to_string(), tree);++ if minted_space {+ // The replacement Space exists only here so far; the server is the one+ // place it has to reach for the other devices to see it too.+ reconcile_remote_subtree(domain_name);+ }++ if changed {+ if let Some(front_end) = crate::frontend::try_front_end() {+ front_end.invalidate_all_windows();+ }+ }+ if !rehome.is_empty() {+ rehome_orphaned_windows(rehome);+ }+}++/// A fresh connection to `domain_name`, announced before anything is asked of+/// it.+///+/// Everything this device believes about that server's tree describes the+/// connection that just ended, so it is dropped here — once — and whatever+/// arrives next sets the baseline afresh. That is what lets a server which+/// lost or rolled back its own copy be re-adopted instead of having every one+/// of its trees dismissed as out of date, without exempting a whole class of+/// arrival from the ordering check.+///+/// Reconnecting is also when Spaces this device disconnected from come back,+/// which is exactly what the menu promises.+pub fn note_remote_connected(domain_name: &str) {+ LAST_KNOWN_REMOTE_TREES.lock().remove(domain_name);+ IN_FLIGHT_TREE_OPS.lock().remove(domain_name);+ LOCALLY_HIDDEN_SPACES.lock().remove(domain_name);+ FIRST_TREE_PENDING.lock().insert(domain_name.to_string());+}++/// Whether an arriving tree is older news than what we already hold.+///+/// Trees arrive by two routes — the answer to an RPC and the server's own+/// broadcast — that are resumed on different schedules, so a reply cut before+/// a push can still be handed over after it. Adopting it would walk the+/// sidebar backwards. Revisions only climb within one connection, so a lower+/// one is stale by definition; a server that restarted lower announces itself+/// through `note_remote_connected`, which clears the baseline rather than+/// asking this to make an exception.+fn tree_is_stale(arriving: u64, known: Option<u64>) -> bool {+ known.map_or(false, |known| arriving < known)+}++/// Windows whose recorded Space vanished, paired with where they should go.+///+/// `owned_before` is the set of Spaces this server had immediately before the+/// arriving tree was applied, and a window only qualifies if it was sitting on+/// one of them. "Any Space the store no longer has" looks equivalent but is+/// not: a re-home is a notification the destination window has yet to act on,+/// so a window orphaned by server A is still on A's dead Space when B's next+/// push lands, and B would drag it onto one of *its* Spaces.+fn orphaned_window_spaces(+ store: &WorkspaceThreadStore,+ domain_name: &str,+ owned_before: &std::collections::HashSet<SpaceId>,+) -> Vec<(u64, SpaceId)> {+ let fallback = store+ .preferred_space_for_domain(domain_name)+ // The server can end up with no Spaces at all — the last one was+ // deleted on another device. A window parked on one of them still has+ // to land somewhere that exists, so fall back to a local Space rather+ // than leaving it pointing at a row nothing can draw.+ .or_else(|| {+ store+ .spaces+ .iter()+ .find(|space| space.is_default)+ .or_else(|| store.spaces.first())+ .map(|space| space.id.clone())+ });+ let Some(fallback) = fallback else {+ return vec![];+ };+ WINDOW_SPACES+ .lock()+ .iter()+ .filter(|(_, space_id)| owned_before.contains(*space_id) && !store.has_space(space_id))+ .map(|(owner_id, _)| (*owner_id, fallback.clone()))+ .collect()+}++/// Move each orphaned window onto a Space that exists.+///+/// `switch_space` is the sanctioned path — it snapshots the outgoing layout,+/// updates the window's own notion of its Space and activates a thread — so+/// the windows are asked to do it themselves rather than having the map+/// rewritten underneath them.+fn rehome_orphaned_windows(rehome: Vec<(u64, SpaceId)>) {+ let Some(front_end) = crate::frontend::try_front_end() else {+ return;+ };+ use ::window::WindowOps;+ for gui_window in front_end.gui_windows() {+ let rehome = rehome.clone();+ gui_window+ .window+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(+ move |term_window| {+ term_window.rehome_if_space_vanished(&rehome);+ },+ )));}- deleted}-pub fn end_workspace_thread_record(thread_id: &str) -> EndWorkspaceThreadResult {- let mut store = THREAD_STORE.lock();- let result = store.end_workspace_thread_record(thread_id);- if !matches!(result, EndWorkspaceThreadResult::Noop) {- persist_locked(&store);- }- result+/// Bring the server's copy of `domain_name`'s subtree in line with ours.+///+/// Called from the paths that build or tear down rows in more than one step,+/// where restating the result is more reliable than enumerating the edits.+/// See `WorkspaceThreadStore::reconcile_ops_for_domain`.+pub fn reconcile_remote_subtree(domain_name: &str) {+ let last_known = LAST_KNOWN_REMOTE_TREES+ .lock()+ .get(domain_name)+ .cloned()+ .unwrap_or_default();+ let ops = {+ let store = THREAD_STORE.lock();+ store.reconcile_ops_for_domain(domain_name, &last_known)+ };+ submit_tree_ops(domain_name.to_string(), ops);}-pub fn disconnect_workspace_thread_record(- thread_id: &str,- live_workspaces: &[String],-) -> Option<DisconnectedWorkspaceThread> {- let mut store = THREAD_STORE.lock();- let (disconnected, changed) =- store.disconnect_workspace_thread_record(thread_id, live_workspaces);- if changed {- persist_locked(&store);- }- disconnected+/// Push a thread's shared scalar state to its server.+///+/// Activating a thread binds it to a mux workspace, stamps its recency and+/// clears its unread mark all at once; sending the resulting values together+/// keeps the two copies identical without one op per field at each call site.+/// A no-op for local threads.+fn submit_thread_state(store: &WorkspaceThreadStore, thread_id: &str) {+ let Some(domain) = tree_domain_for_thread(store, thread_id) else {+ return;+ };+ let Some(thread) = store.thread_record(thread_id) else {+ return;+ };+ submit_tree_ops(+ domain,+ vec![+ codec::TreeOp::SetThreadWorkspaceName {+ thread_id: thread_id.to_string(),+ planned: thread.planned_workspace_name.clone(),+ materialized: thread.materialized_workspace_name.clone(),+ },+ codec::TreeOp::TouchThread {+ thread_id: thread_id.to_string(),+ at: thread.last_active_at,+ },+ codec::TreeOp::SetThreadUnread {+ thread_id: thread_id.to_string(),+ unread: thread.is_unread,+ },+ ],+ );}pub fn move_project_before(space_id: &str, project_id: &str, before: Option<&str>) -> bool {let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_space(&store, space_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }let changed = store.move_project_before(space_id, project_id, before);if changed {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::MoveProjectBefore {+ space_id: space_id.to_string(),+ project_id: project_id.to_string(),+ before: before.map(|id| id.to_string()),+ },+ );+ }persist_locked(&store);}changed@@ -1747,8 +2751,22 @@ pub fn move_project_before(space_id: &str, project_id: &str, before: Option<&strpub fn move_thread_before(project_id: &str, thread_id: &str, before: Option<&str>) -> bool {let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_project(&store, project_id);+ if !remote_tree_mutation_allowed(domain.as_deref()) {+ return false;+ }let changed = store.move_thread_before(project_id, thread_id, before);if changed {+ if let Some(domain) = domain {+ submit_tree_op(+ domain,+ codec::TreeOp::MoveThreadBefore {+ project_id: project_id.to_string(),+ thread_id: thread_id.to_string(),+ before: before.map(|id| id.to_string()),+ },+ );+ }persist_locked(&store);}changed@@ -1949,6 +2967,51 @@ impl WorkspaceThreadStore {})}+ /// The Space to open on `domain_name`: the one this device last used if it+ /// is still there, otherwise the domain's first Space in tree order.+ /// `None` when the domain has no Spaces at all.+ fn preferred_space_for_domain(&self, domain_name: &str) -> Option<SpaceId> {+ let belongs = |space_id: &str| {+ self.spaces.iter().any(|space| {+ space.id == space_id && space.client_domain.as_deref() == Some(domain_name)+ })+ };+ self.last_space_per_domain+ .get(domain_name)+ .filter(|space_id| belongs(space_id))+ .cloned()+ .or_else(|| {+ self.spaces+ .iter()+ .find(|space| space.client_domain.as_deref() == Some(domain_name))+ .map(|space| space.id.clone())+ })+ }++ /// Remember which Space this device is using on a remote server, so the+ /// next connect comes back to it instead of the server's first one.+ fn remember_space_for_domain(&mut self, space_id: &str) -> bool {+ let Some(domain_name) = self+ .spaces+ .iter()+ .find(|space| space.id == space_id)+ .and_then(|space| space.client_domain.clone())+ else {+ return false;+ };+ if self+ .last_space_per_domain+ .get(&domain_name)+ .map(String::as_str)+ == Some(space_id)+ {+ return false;+ }+ self.last_space_per_domain+ .insert(domain_name, space_id.to_string());+ true+ }+fn is_client_domain_space(&self, space_id: &str) -> bool {self.spaces.iter()@@ -2016,6 +3079,25 @@ impl WorkspaceThreadStore {})}+ /// The Spaces currently attributed to `domain_name`.+ fn space_ids_for_domain(&self, domain_name: &str) -> std::collections::HashSet<SpaceId> {+ self.spaces+ .iter()+ .filter(|space| space.client_domain.as_deref() == Some(domain_name))+ .map(|space| space.id.clone())+ .collect()+ }++ #[cfg(test)]+ fn materialized_workspaces_for_space(&self, space_id: &str) -> Vec<String> {+ self.projects+ .iter()+ .filter(|project| project.space_id == space_id)+ .flat_map(|project| project.threads.iter())+ .filter_map(|thread| thread.materialized_workspace_name.clone())+ .collect()+ }+fn active_project_id_for_space(&self, space_id: &str) -> Option<ProjectId> {self.spaces.iter()@@ -2762,6 +3844,347 @@ impl WorkspaceThreadStore {.filter(|scales| !scales.is_empty())}+ /// Ops that make the server's copy of this domain's subtree match ours.+ ///+ /// Every mutation with a simple shape sends its own targeted op; this is+ /// for the compound ones (ending a thread, adopting an orphaned window,+ /// first connect) where enumerating the individual edits would be more+ /// error-prone than restating the result.+ ///+ /// `last_known` is the tree the server last told us about, and every op+ /// here is a *difference* from it. That is what keeps a reconcile from+ /// trampling another device: if a row still looks exactly as the server+ /// last described it we have nothing to say about that row, so a rename+ /// that landed there after our snapshot is left alone instead of being+ /// reverted to our stale copy. Only rows we actually changed — and rows+ /// the server has that we no longer do — produce ops.+ ///+ /// Row *order* is not reconciled: reorders have their own ops, and the+ /// paths that call this only ever append on both sides.+ fn reconcile_ops_for_domain(+ &self,+ domain_name: &str,+ last_known: &codec::ThinkTermTree,+ ) -> Vec<codec::TreeOp> {+ let space_ids: Vec<SpaceId> = self+ .spaces+ .iter()+ .filter(|space| space.client_domain.as_deref() == Some(domain_name))+ .map(|space| space.id.clone())+ .collect();++ let mut ops = vec![];+ let mut live_projects: std::collections::HashSet<&str> = Default::default();+ let mut live_threads: std::collections::HashSet<&str> = Default::default();++ for space in self+ .spaces+ .iter()+ .filter(|space| space.client_domain.as_deref() == Some(domain_name))+ {+ match last_known.space(&space.id) {+ None => ops.push(codec::TreeOp::CreateSpace {+ space_id: space.id.clone(),+ name: space.name.clone(),+ }),+ Some(known) if known.name != space.name => ops.push(codec::TreeOp::RenameSpace {+ space_id: space.id.clone(),+ name: space.name.clone(),+ }),+ Some(_) => {}+ }+ }++ for project in self+ .projects+ .iter()+ .filter(|project| space_ids.contains(&project.space_id))+ {+ live_projects.insert(project.id.as_str());+ let known_project = last_known.project(&project.id);+ match known_project {+ None => ops.push(codec::TreeOp::CreateProject {+ project_id: project.id.clone(),+ space_id: project.space_id.clone(),+ name: project.name.clone(),+ path: project.path.to_string_lossy().to_string(),+ }),+ Some(known) if known.name != project.name => {+ ops.push(codec::TreeOp::RenameProject {+ project_id: project.id.clone(),+ name: project.name.clone(),+ })+ }+ Some(_) => {}+ }+ for thread in &project.threads {+ live_threads.insert(thread.id.as_str());+ let Some(known) = last_known.thread(&thread.id) else {+ ops.push(codec::TreeOp::CreateThread {+ thread_id: thread.id.clone(),+ project_id: project.id.clone(),+ name: thread.name.clone(),+ workspace: thread.materialized_workspace_name.clone(),+ created_at: thread.last_active_at,+ });+ if thread.planned_workspace_name.is_some() {+ ops.push(codec::TreeOp::SetThreadWorkspaceName {+ thread_id: thread.id.clone(),+ planned: thread.planned_workspace_name.clone(),+ materialized: thread.materialized_workspace_name.clone(),+ });+ }+ if thread.is_pinned {+ ops.push(codec::TreeOp::SetThreadPinned {+ thread_id: thread.id.clone(),+ pinned: true,+ last_active_at: thread.last_active_at,+ });+ }+ if thread.is_unread {+ ops.push(codec::TreeOp::SetThreadUnread {+ thread_id: thread.id.clone(),+ unread: true,+ });+ }+ continue;+ };++ // `SetThreadPinned` and `RenameThread` carry the recency stamp+ // because toggling a pin and renaming both bump it locally.+ // Sending a bare `TouchThread` when neither fired avoids+ // restating a name we may no longer own.+ let mut stamp_sent = false;+ if known.is_pinned != thread.is_pinned {+ ops.push(codec::TreeOp::SetThreadPinned {+ thread_id: thread.id.clone(),+ pinned: thread.is_pinned,+ last_active_at: thread.last_active_at,+ });+ stamp_sent = true;+ }+ if known.name != thread.name {+ ops.push(codec::TreeOp::RenameThread {+ thread_id: thread.id.clone(),+ name: thread.name.clone(),+ last_active_at: thread.last_active_at,+ });+ stamp_sent = true;+ }+ if !stamp_sent && known.last_active_at != thread.last_active_at {+ ops.push(codec::TreeOp::TouchThread {+ thread_id: thread.id.clone(),+ at: thread.last_active_at,+ });+ }+ if known.planned_workspace_name != thread.planned_workspace_name+ || known.materialized_workspace_name != thread.materialized_workspace_name+ {+ ops.push(codec::TreeOp::SetThreadWorkspaceName {+ thread_id: thread.id.clone(),+ planned: thread.planned_workspace_name.clone(),+ materialized: thread.materialized_workspace_name.clone(),+ });+ }+ if known.is_unread != thread.is_unread {+ ops.push(codec::TreeOp::SetThreadUnread {+ thread_id: thread.id.clone(),+ unread: thread.is_unread,+ });+ }+ }+ }++ // Threads and projects first: deleting their Space would take them+ // with it, and we want the narrower removal when only a row went away.+ for project in &last_known.projects {+ for thread in &project.threads {+ if !live_threads.contains(thread.id.as_str()) {+ ops.push(codec::TreeOp::DeleteThread {+ thread_id: thread.id.clone(),+ });+ }+ }+ if !live_projects.contains(project.id.as_str()) {+ ops.push(codec::TreeOp::RemoveProject {+ project_id: project.id.clone(),+ });+ }+ }+ for space in &last_known.spaces {+ if !space_ids.contains(&space.id) {+ ops.push(codec::TreeOp::DeleteSpace {+ space_id: space.id.clone(),+ });+ }+ }++ ops+ }++ /// Rebuild this domain's Spaces/Projects/Threads from the server's tree.+ ///+ /// The server owns what exists, what it is called, its order and its pins.+ /// This device owns where it is looking (`active_*`), how it is displayed+ /// (`threads_collapsed`, font scales), its Vault/Note bindings, and the+ /// locally-derived agent work status. Those are carried across by id, so a+ /// push from another device cannot collapse your rows or move your cursor.+ ///+ /// Remote records keep being written to the local JSON file, but purely as+ /// a cache: it lets the sidebar draw something before the attach finishes,+ /// and this function overwrites it wholesale when the truth arrives.+ fn ingest_remote_tree(&mut self, domain_name: &str, tree: &codec::ThinkTermTree) -> bool {+ let owned_space_ids: std::collections::HashSet<SpaceId> = self+ .spaces+ .iter()+ .filter(|space| space.client_domain.as_deref() == Some(domain_name))+ .map(|space| space.id.clone())+ .chain(tree.spaces.iter().map(|space| space.id.clone()))+ .collect();++ let mut space_state: HashMap<SpaceId, (Option<ProjectId>, Option<SpaceVaultBinding>)> =+ HashMap::new();+ for space in &self.spaces {+ if space.client_domain.as_deref() == Some(domain_name) {+ space_state.insert(+ space.id.clone(),+ (space.active_project_id.clone(), space.note_vault.clone()),+ );+ }+ }++ struct ProjectViewState {+ active_thread_id: Option<WorkspaceThreadId>,+ threads_collapsed: bool,+ active_note_path: Option<String>,+ }+ struct ThreadViewState {+ remote_font_scales: HashMap<PaneId, f64>,+ work_is_running: bool,+ work_needs_attention: bool,+ work_finished_unseen: bool,+ }++ let mut project_state: HashMap<ProjectId, ProjectViewState> = HashMap::new();+ let mut thread_state: HashMap<WorkspaceThreadId, ThreadViewState> = HashMap::new();+ for project in &self.projects {+ if !owned_space_ids.contains(&project.space_id) {+ continue;+ }+ project_state.insert(+ project.id.clone(),+ ProjectViewState {+ active_thread_id: project.active_thread_id.clone(),+ threads_collapsed: project.threads_collapsed,+ active_note_path: project.active_note_path.clone(),+ },+ );+ for thread in &project.threads {+ thread_state.insert(+ thread.id.clone(),+ ThreadViewState {+ remote_font_scales: thread.remote_font_scales.clone(),+ work_is_running: thread.work_is_running,+ work_needs_attention: thread.work_needs_attention,+ work_finished_unseen: thread.work_finished_unseen,+ },+ );+ }+ }++ let new_spaces: Vec<Space> = tree+ .spaces+ .iter()+ .map(|space| {+ let (active_project_id, note_vault) =+ space_state.get(&space.id).cloned().unwrap_or((None, None));+ Space {+ id: space.id.clone(),+ name: space.name.clone(),+ active_project_id,+ note_vault,+ is_default: false,+ client_domain: Some(domain_name.to_string()),+ }+ })+ .collect();++ let new_projects: Vec<Project> = tree+ .projects+ .iter()+ .map(|project| {+ let view = project_state.get(&project.id);+ let threads: Vec<WorkspaceThread> = project+ .threads+ .iter()+ .map(|thread| {+ let state = thread_state.get(&thread.id);+ WorkspaceThread {+ id: thread.id.clone(),+ name: thread.name.clone(),+ project_id: thread.project_id.clone(),+ // A remote thread's layout belongs to the server;+ // the client never persists one for it.+ layout: None,+ remote_font_scales: state+ .map(|state| state.remote_font_scales.clone())+ .unwrap_or_default(),+ planned_workspace_name: thread.planned_workspace_name.clone(),+ materialized_workspace_name: thread.materialized_workspace_name.clone(),+ last_active_at: thread.last_active_at,+ is_pinned: thread.is_pinned,+ is_unread: thread.is_unread,+ work_is_running: state.map_or(false, |state| state.work_is_running),+ work_needs_attention: state+ .map_or(false, |state| state.work_needs_attention),+ work_finished_unseen: state+ .map_or(false, |state| state.work_finished_unseen),+ }+ })+ .collect();+ Project {+ id: project.id.clone(),+ space_id: project.space_id.clone(),+ name: project.name.clone(),+ path: PathBuf::from(&project.path),+ // Drop a remembered active thread that the server no+ // longer has, rather than pointing at a deleted row.+ active_thread_id: view.and_then(|view| {+ view.active_thread_id+ .clone()+ .filter(|id| threads.iter().any(|thread| &thread.id == id))+ }),+ threads,+ threads_collapsed: view.map_or(false, |view| view.threads_collapsed),+ active_note_path: view.and_then(|view| view.active_note_path.clone()),+ }+ })+ .collect();++ // Splice the rebuilt block in where the old one started so that the+ // Space menu and sidebar do not reshuffle on every push.+ let spaces = splice_in_place(&self.spaces, new_spaces, |space| {+ space.client_domain.as_deref() == Some(domain_name)+ });+ let projects = splice_in_place(&self.projects, new_projects, |project| {+ owned_space_ids.contains(&project.space_id)+ });++ if spaces == self.spaces && projects == self.projects {+ return false;+ }+ self.spaces = spaces;+ self.projects = projects;+ true+ }++ fn thread_record(&self, thread_id: &str) -> Option<&WorkspaceThread> {+ self.projects+ .iter()+ .flat_map(|project| project.threads.iter())+ .find(|thread| thread.id == thread_id)+ }+fn rename_project(&mut self, project_id: &str, name: String) -> bool {let name = name.trim();if name.is_empty() {@@ -4052,6 +5475,16 @@ pub fn remote_project_id_for_space(space_id: &str, host_id: &str) -> ProjectId {format!("{host_id}{REMOTE_PROJECT_SPACE_SEPARATOR}{space_id}")}+/// The Space a remote project id was minted for, if it carries one. Lets a+/// Space tell a sibling Space's rows on the same server apart from genuinely+/// orphaned ones.+fn space_id_from_remote_project_id(project_id: &str) -> Option<&str> {+ project_id+ .split_once(REMOTE_PROJECT_SPACE_SEPARATOR)+ .map(|(_host, space_id)| space_id)+ .filter(|space_id| !space_id.is_empty())+}+/// Prefix distinguishing mux-client-domain pseudo host ids from the ssh_hosts/// store's `ssh-`/`system-ssh-` ids, so none of the sidebar SSH machinery/// fires on them.@@ -4184,6 +5617,12 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {if workspace_known {continue;}+ // One server can host several Spaces. A workspace whose embedded Space+ // id names a sibling Space we already know about belongs to that+ // Space, which will show it; adopting it here would move a live+ // terminal out from under it.+ let belongs_to_sibling_space = space_id_from_remote_project_id(&project_id)+ .is_some_and(|sibling| sibling != space_id && store.has_space(sibling));match store.projects.iter_mut()@@ -4206,7 +5645,10 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {// Re-home it as a thread of THIS Space's mux-domain project; the// materialized workspace name keeps routing to the live remote// workspace.- None if project_id.contains(REMOTE_PROJECT_SPACE_SEPARATOR) => {+ //+ None if project_id.contains(REMOTE_PROJECT_SPACE_SEPARATOR)+ && !belongs_to_sibling_space =>+ {let thread_id_taken = store.projects.iter()@@ -4274,6 +5716,12 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {store.ensure_unique_thread_names();persist_locked(&store);}+ drop(store);+ if changed {+ // Rows rebuilt from live remote windows are new to the server too+ // whenever it was the server's tree that went missing.+ reconcile_remote_subtree(&domain_name);+ }changed}@@ -4287,9 +5735,19 @@ pub fn create_remote_project_from_path(space_id: &str, path: &str) -> Result<Wor"remote project path must be absolute or start with ~: {trimmed}");let mut store = THREAD_STORE.lock();+ let domain = tree_domain_for_space(&store, space_id)+ .with_context(|| format!("Space {space_id} is not a remote Space"))?;+ ensure!(+ remote_tree_mutation_allowed(Some(&domain)),+ "{domain} is disconnected"+ );store.normalize_after_load();let thread_id = store.create_project_from_path(space_id, PathBuf::from(trimmed));persist_locked(&store);+ drop(store);+ // create_project_from_path either adds a project and its first thread or+ // reuses an existing project for the same path; reconciling covers both.+ reconcile_remote_subtree(&domain);Ok(thread_id)}@@ -4307,63 +5765,70 @@ pub struct MuxDomainSpacePlan {/// same records.pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {let mut store = THREAD_STORE.lock();+ let plan = store.ensure_mux_domain_space(domain_name);+ persist_locked(&store);+ plan+}- let space_id = store- .spaces- .iter()- .find(|space| space.client_domain.as_deref() == Some(domain_name))- .map(|space| space.id.clone())- .unwrap_or_else(|| {- store.create_space_record_for_domain(- domain_name.to_string(),- Some(domain_name.to_string()),- )- });-- let host_id = mux_domain_host_id(domain_name);- let project_id = remote_project_id_for_space(&space_id, &host_id);- if !store.projects.iter().any(|p| p.id == project_id) {- store.projects.push(Project {- id: project_id.clone(),- space_id: space_id.clone(),- name: domain_name.to_string(),- path: PathBuf::from(format!("wezterm-mux://{domain_name}")),- threads: vec![],- active_thread_id: None,- threads_collapsed: false,- active_note_path: None,- });- }+impl WorkspaceThreadStore {+ fn ensure_mux_domain_space(&mut self, domain_name: &str) -> MuxDomainSpacePlan {+ let store = self;++ // A server can host several Spaces. Land on the one this device was last+ // using; failing that its first Space; and only create one when we have+ // never connected (or the server told us it has none).+ let space_id = store+ .preferred_space_for_domain(domain_name)+ .unwrap_or_else(|| {+ store.create_space_record_for_domain(+ domain_name.to_string(),+ Some(domain_name.to_string()),+ )+ });- let project = store- .projects- .iter_mut()- .find(|p| p.id == project_id)- .expect("mux domain project was just ensured");- if project.threads.is_empty() {- project.threads.push(WorkspaceThread::new(- project_id.clone(),- "main".to_string(),- None,- ));- }- let thread_id = project- .active_thread_id- .clone()- .filter(|id| project.threads.iter().any(|t| &t.id == id))- .unwrap_or_else(|| project.threads[0].id.clone());- project.active_thread_id = Some(thread_id.clone());+ let host_id = mux_domain_host_id(domain_name);+ let project_id = remote_project_id_for_space(&space_id, &host_id);+ if !store.projects.iter().any(|p| p.id == project_id) {+ store.projects.push(Project {+ id: project_id.clone(),+ space_id: space_id.clone(),+ name: domain_name.to_string(),+ path: PathBuf::from(format!("wezterm-mux://{domain_name}")),+ threads: vec![],+ active_thread_id: None,+ threads_collapsed: false,+ active_note_path: None,+ });+ }- if let Some(space) = store.spaces.iter_mut().find(|space| space.id == space_id) {- space.active_project_id = Some(project_id.clone());- }+ let project = store+ .projects+ .iter_mut()+ .find(|p| p.id == project_id)+ .expect("mux domain project was just ensured");+ if project.threads.is_empty() {+ project.threads.push(WorkspaceThread::new(+ project_id.clone(),+ "main".to_string(),+ None,+ ));+ }+ let thread_id = project+ .active_thread_id+ .clone()+ .filter(|id| project.threads.iter().any(|t| &t.id == id))+ .unwrap_or_else(|| project.threads[0].id.clone());+ project.active_thread_id = Some(thread_id.clone());- persist_locked(&store);+ if let Some(space) = store.spaces.iter_mut().find(|space| space.id == space_id) {+ space.active_project_id = Some(project_id.clone());+ }- MuxDomainSpacePlan {- space_id,- project_id,- thread_id,+ MuxDomainSpacePlan {+ space_id,+ project_id,+ thread_id,+ }}}@@ -4395,6 +5860,7 @@ pub fn ensure_mux_thread_workspace(plan: &MuxDomainSpacePlan) -> String {}}persist_locked(&store);+ submit_thread_state(&store, &plan.thread_id);name.unwrap_or_else(|| workspace_name_for_thread(&plan.project_id, &plan.thread_id))}@@ -4457,6 +5923,33 @@ fn unique_thread_name(}}+/// Replace every element matching `is_replaced` with `replacement`, as one+/// block positioned where the first match was. Used to swap a mux domain's+/// rows for the server's version without disturbing the ordering of anything+/// around them (other Spaces, local projects).+fn splice_in_place<T: Clone>(+ current: &[T],+ replacement: Vec<T>,+ is_replaced: impl Fn(&T) -> bool,+) -> Vec<T> {+ let mut out = Vec::with_capacity(current.len() + replacement.len());+ let mut spliced = false;+ for item in current {+ if is_replaced(item) {+ if !spliced {+ out.extend(replacement.iter().cloned());+ spliced = true;+ }+ continue;+ }+ out.push(item.clone());+ }+ if !spliced {+ out.extend(replacement);+ }+ out+}+fn new_id(prefix: &str) -> String {format!("{prefix}-{}-{:08x}",@@ -6284,4 +7777,762 @@ mod tests {assert!(store.move_thread_before("project-1", &ids[2], Some(&ids[1])));assert_eq!(order(&store), ["t1", "t3", "t2"]);}++ /// A store holding one remote Space for `domain`, plus one purely local+ /// project, so that ingestion can be checked for collateral damage.+ fn remote_test_store(domain: &str) -> WorkspaceThreadStore {+ let mut store = test_store();+ let local_space = store.spaces[0].id.clone();+ store.projects.push(test_project_in_space(+ &local_space,+ "local-1",+ "local",+ PathBuf::from("/tmp/local"),+ vec![],+ ));+ store.spaces.push(Space {+ id: "space-remote".to_string(),+ name: "syd".to_string(),+ active_project_id: None,+ note_vault: None,+ is_default: false,+ client_domain: Some(domain.to_string()),+ });+ store+ }++ fn tree_thread(id: &str, project_id: &str, name: &str) -> codec::TtThread {+ codec::TtThread {+ id: id.to_string(),+ project_id: project_id.to_string(),+ name: name.to_string(),+ planned_workspace_name: None,+ materialized_workspace_name: Some(format!("thinkterm:{project_id}:{id}")),+ last_active_at: 10,+ is_pinned: false,+ is_unread: false,+ }+ }++ fn sample_tree() -> codec::ThinkTermTree {+ codec::ThinkTermTree {+ spaces: vec![codec::TtSpace {+ id: "space-remote".to_string(),+ name: "syd".to_string(),+ }],+ projects: vec![codec::TtProject {+ id: "rp1".to_string(),+ space_id: "space-remote".to_string(),+ name: "thinkterm".to_string(),+ path: "/home/x/github/ThinkTerm".to_string(),+ threads: vec![+ tree_thread("rt1", "rp1", "main"),+ tree_thread("rt2", "rp1", "build"),+ ],+ }],+ revision: 1,+ }+ }++ #[test]+ fn ingesting_a_tree_adopts_shared_rows_and_leaves_local_spaces_alone() {+ let mut store = remote_test_store("syd");+ let local_projects_before = store.projects.clone();++ assert!(store.ingest_remote_tree("syd", &sample_tree()));++ let remote: Vec<&Project> = store+ .projects+ .iter()+ .filter(|project| project.space_id == "space-remote")+ .collect();+ assert_eq!(remote.len(), 1);+ assert_eq!(remote[0].id, "rp1");+ assert_eq!(remote[0].path, PathBuf::from("/home/x/github/ThinkTerm"));+ assert_eq!(+ remote[0]+ .threads+ .iter()+ .map(|thread| thread.name.as_str())+ .collect::<Vec<_>>(),+ ["main", "build"]+ );+ // The client's own client_domain tag is re-applied, not taken from the+ // wire: the tree describes rows, not which connection carries them.+ assert_eq!(+ store+ .spaces+ .iter()+ .find(|space| space.id == "space-remote")+ .and_then(|space| space.client_domain.clone()),+ Some("syd".to_string())+ );+ // The local project is untouched and still ahead of the remote block.+ assert_eq!(store.projects[0], local_projects_before[0]);++ // Ingesting the same tree twice reports no change, so no repaint and+ // no write.+ assert!(!store.ingest_remote_tree("syd", &sample_tree()));+ }++ #[test]+ fn ingesting_keeps_this_devices_own_view_state() {+ let mut store = remote_test_store("syd");+ assert!(store.ingest_remote_tree("syd", &sample_tree()));++ // Things this device decided for itself.+ let project = store+ .projects+ .iter_mut()+ .find(|project| project.id == "rp1")+ .unwrap();+ project.threads_collapsed = true;+ project.active_thread_id = Some("rt2".to_string());+ project.active_note_path = Some("notes/rp1.md".to_string());+ project.threads[0].remote_font_scales.insert(7, 1.5);+ project.threads[0].work_finished_unseen = true;+ let space = store+ .spaces+ .iter_mut()+ .find(|space| space.id == "space-remote")+ .unwrap();+ space.note_vault = Some(SpaceVaultBinding {+ root: PathBuf::from("/home/x/vault"),+ managed: false,+ });++ // Another device renames a thread; the push carries only shared state.+ let mut tree = sample_tree();+ tree.projects[0].threads[1].name = "release".to_string();+ assert!(store.ingest_remote_tree("syd", &tree));++ let project = store+ .projects+ .iter()+ .find(|project| project.id == "rp1")+ .unwrap();+ assert_eq!(project.threads[1].name, "release");+ assert!(project.threads_collapsed);+ assert_eq!(project.active_thread_id.as_deref(), Some("rt2"));+ assert_eq!(project.active_note_path.as_deref(), Some("notes/rp1.md"));+ assert_eq!(project.threads[0].remote_font_scales.get(&7), Some(&1.5));+ assert!(project.threads[0].work_finished_unseen);+ assert!(store+ .spaces+ .iter()+ .find(|space| space.id == "space-remote")+ .unwrap()+ .note_vault+ .is_some());+ }++ #[test]+ fn ingesting_drops_rows_the_server_no_longer_has() {+ let mut store = remote_test_store("syd");+ assert!(store.ingest_remote_tree("syd", &sample_tree()));++ // This device was looking at the thread another device just deleted.+ store+ .projects+ .iter_mut()+ .find(|project| project.id == "rp1")+ .unwrap()+ .active_thread_id = Some("rt2".to_string());++ let mut tree = sample_tree();+ tree.projects[0].threads.pop();+ assert!(store.ingest_remote_tree("syd", &tree));++ let project = store+ .projects+ .iter()+ .find(|project| project.id == "rp1")+ .unwrap();+ assert_eq!(project.threads.len(), 1);+ // Rather than leaving the sidebar pointing at a row that is gone.+ assert_eq!(project.active_thread_id, None);+ }++ #[test]+ fn a_reconcile_creates_what_is_new_and_deletes_only_what_it_knew_about() {+ let mut store = remote_test_store("syd");+ let last_known = sample_tree();+ assert!(store.ingest_remote_tree("syd", &last_known));++ // This device deleted one thread locally...+ assert!(store.delete_thread("rt2").is_some());+ // ...and another device added one we have not been told about yet.+ let ops = store.reconcile_ops_for_domain("syd", &last_known);++ assert!(ops.contains(&codec::TreeOp::DeleteThread {+ thread_id: "rt2".to_string()+ }));+ assert!(!ops.iter().any(|op| matches!(+ op,+ codec::TreeOp::DeleteThread { thread_id } if thread_id == "rt1"+ )));+ // Nothing outside this domain is ever mentioned.+ assert!(!ops.iter().any(|op| matches!(+ op,+ codec::TreeOp::CreateProject { project_id, .. } if project_id == "local-1"+ )));++ // Replaying the reconcile against the server's copy reproduces ours.+ let mut server = last_known.clone();+ for op in &ops {+ codec::apply_op(&mut server, op);+ }+ assert_eq!(+ server.project("rp1").unwrap().threads.len(),+ store+ .projects+ .iter()+ .find(|project| project.id == "rp1")+ .unwrap()+ .threads+ .len()+ );+ }++ /// A reconcile restates only what *this* device changed. Anything still+ /// matching the server's last word is left alone, so a compound path here+ /// cannot revert an edit another device made in the meantime.+ #[test]+ fn a_reconcile_does_not_revert_what_another_device_changed() {+ let mut store = remote_test_store("syd");+ let last_known = sample_tree();+ assert!(store.ingest_remote_tree("syd", &last_known));++ // Nothing has changed on either side: there is nothing to say.+ assert!(store+ .reconcile_ops_for_domain("syd", &last_known)+ .is_empty());++ // This device renames one thread.+ assert!(store.rename_thread("rt1", "shell".to_string()));+ let ops = store.reconcile_ops_for_domain("syd", &last_known);++ // Meanwhile another device renamed the Space and the *other* thread,+ // and we have not been told yet.+ let mut server = last_known.clone();+ assert!(codec::apply_op(+ &mut server,+ &codec::TreeOp::RenameSpace {+ space_id: "space-remote".to_string(),+ name: "sydney".to_string(),+ }+ ));+ assert!(codec::apply_op(+ &mut server,+ &codec::TreeOp::RenameThread {+ thread_id: "rt2".to_string(),+ name: "tests".to_string(),+ last_active_at: 99,+ }+ ));++ for op in &ops {+ codec::apply_op(&mut server, op);+ }++ assert_eq!(server.thread("rt1").unwrap().name, "shell");+ assert_eq!(server.space("space-remote").unwrap().name, "sydney");+ assert_eq!(server.thread("rt2").unwrap().name, "tests");+ assert_eq!(server.thread("rt2").unwrap().last_active_at, 99);+ }++ /// Disconnecting a remote Space leaves it on the server for the other+ /// devices, so every later push still carries it; this device filters it+ /// out until it connects to that server again.+ #[test]+ fn a_locally_disconnected_space_is_filtered_out_of_later_pushes() {+ let mut pushed = sample_tree();+ assert!(codec::apply_op(+ &mut pushed,+ &codec::TreeOp::CreateSpace {+ space_id: "space-remote-2".to_string(),+ name: "side".to_string(),+ }+ ));+ assert!(codec::apply_op(+ &mut pushed,+ &codec::TreeOp::CreateProject {+ project_id: "rp2".to_string(),+ space_id: "space-remote-2".to_string(),+ name: "side project".to_string(),+ path: "/srv/side".to_string(),+ }+ ));++ let mut hidden = std::collections::HashSet::new();+ hidden.insert("space-remote-2".to_string());+ strip_hidden_spaces(&mut pushed, &hidden);++ assert!(pushed.space("space-remote-2").is_none());+ // Its projects go with it, or they would be orphan rows pointing at a+ // Space this device cannot draw.+ assert!(pushed.project("rp2").is_none());+ assert!(pushed.space("space-remote").is_some());+ assert!(pushed.project("rp1").is_some());+ }++ /// A push cut just before an online RPC lands may carry the previous tree.+ /// The connection-scoped overlay avoids a visual rollback, but is retired+ /// as soon as the server response accounts for it.+ #[test]+ fn in_flight_ops_survive_an_overtaking_push_only_until_ack() {+ let domain = "in-flight-test-domain";+ take_in_flight_tree_ops(domain);++ queue_in_flight_tree_ops(+ domain,+ &[codec::TreeOp::CreateSpace {+ space_id: "space-offline".to_string(),+ name: "Space 2".to_string(),+ }],+ );+ queue_in_flight_tree_ops(+ domain,+ &[codec::TreeOp::RenameSpace {+ space_id: "space-offline".to_string(),+ name: "Frontend".to_string(),+ }],+ );++ let mut unacked = take_in_flight_tree_ops(domain);+ assert_eq!(unacked.len(), 2);+ // Taking them empties the queue: they must not be replayed twice.+ assert!(take_in_flight_tree_ops(domain).is_empty());++ // A tree cut before either op reached the server: both are replayed on+ // top of it, and both stay queued because it does not show them.+ let mut stale = sample_tree();+ assert!(stale.space("space-offline").is_none());+ unacked.retain(|op| codec::apply_op(&mut stale, op));+ assert_eq!(stale.space("space-offline").unwrap().name, "Frontend");+ assert_eq!(unacked.len(), 2);++ // The tree that comes back once the server has applied them retires+ // both: re-applying an op the server already has changes nothing, and+ // that is exactly what an acknowledgement looks like here.+ let mut acked = stale.clone();+ unacked.retain(|op| codec::apply_op(&mut acked, op));+ assert!(unacked.is_empty());+ assert_eq!(acked, stale);++ // An op the server answered differently — it deleted the Space rather+ // than accepting the rename — also retires, instead of being replayed+ // forever against a row that is gone.+ let mut rename_only = vec![codec::TreeOp::RenameSpace {+ space_id: "space-offline".to_string(),+ name: "Frontend".to_string(),+ }];+ let mut without_it = sample_tree();+ rename_only.retain(|op| codec::apply_op(&mut without_it, op));+ assert!(rename_only.is_empty());+ }++ #[test]+ fn shared_remote_mutations_require_a_healthy_attached_connection() {+ use mux::domain::DomainState;++ assert!(remote_tree_connection_can_mutate(+ DomainState::Attached,+ false,+ false,+ false+ ));+ assert!(!remote_tree_connection_can_mutate(+ DomainState::Detached,+ false,+ false,+ false+ ));+ assert!(!remote_tree_connection_can_mutate(+ DomainState::Attached,+ true,+ false,+ false+ ));+ assert!(!remote_tree_connection_can_mutate(+ DomainState::Attached,+ false,+ true,+ false+ ));+ assert!(!remote_tree_connection_can_mutate(+ DomainState::Attached,+ false,+ false,+ true+ ));+ }++ /// A tree that predates the one we hold is stale news, whichever route it+ /// took — an RPC answer is checked exactly as a broadcast is, or a reply+ /// cut before a push and delivered after it would undo the push.+ #[test]+ fn a_tree_that_predates_what_we_hold_is_ignored() {+ assert!(tree_is_stale(4, Some(5)));+ assert!(!tree_is_stale(5, Some(5)));+ assert!(!tree_is_stale(6, Some(5)));+ // Nothing held yet: the first word on the subject is not stale.+ assert!(!tree_is_stale(0, None));+ // Including revision 0, which would otherwise read as "never written+ // to" and send this device back round the seeding path.+ assert!(tree_is_stale(0, Some(9)));+ }++ /// Connecting is the one thing that clears the baseline, so a server that+ /// came back having lost or rolled back its own copy is re-adopted rather+ /// than ignored for the rest of the session. It also un-hides the Spaces+ /// this device disconnected from, which is what the menu promises.+ #[test]+ fn connecting_clears_the_baseline_a_restarted_server_would_be_measured_against() {+ let domain = "reconnect-test-domain";+ LAST_KNOWN_REMOTE_TREES.lock().insert(+ domain.to_string(),+ codec::ThinkTermTree {+ revision: 9,+ ..Default::default()+ },+ );+ let mut hidden = std::collections::HashSet::new();+ hidden.insert("space-hidden".to_string());+ LOCALLY_HIDDEN_SPACES+ .lock()+ .insert(domain.to_string(), hidden);+ queue_in_flight_tree_ops(+ domain,+ &[codec::TreeOp::RenameSpace {+ space_id: "space-old-generation".to_string(),+ name: "stale intent".to_string(),+ }],+ );++ // While that baseline stands, a server restarting at revision 1 is+ // rightly dismissed as stale.+ let known = LAST_KNOWN_REMOTE_TREES+ .lock()+ .get(domain)+ .map(|tree| tree.revision);+ assert!(tree_is_stale(1, known));++ note_remote_connected(domain);++ assert!(LAST_KNOWN_REMOTE_TREES.lock().get(domain).is_none());+ assert!(take_in_flight_tree_ops(domain).is_empty());+ assert!(LOCALLY_HIDDEN_SPACES.lock().get(domain).is_none());+ assert!(FIRST_TREE_PENDING.lock().contains(domain));+ let known = LAST_KNOWN_REMOTE_TREES+ .lock()+ .get(domain)+ .map(|tree| tree.revision);+ assert!(!tree_is_stale(1, known));++ // The catch-up is a one-shot and may mint a Space, but never flushes+ // an intent left over from the connection that just ended.+ assert!(FIRST_TREE_PENDING.lock().remove(domain));+ assert!(!FIRST_TREE_PENDING.lock().remove(domain));+ }++ /// A re-home is a notification the target window has yet to act on, so a+ /// window orphaned by one server is still parked on that server's dead+ /// Space when the next server speaks. Only the server that owned the Space+ /// may move it.+ #[test]+ fn one_servers_push_does_not_claim_another_servers_orphan() {+ let mut store = remote_test_store("syd");+ assert!(store.ingest_remote_tree("syd", &sample_tree()));+ store.spaces.push(Space {+ id: "space-ams".to_string(),+ name: "ams".to_string(),+ active_project_id: None,+ note_vault: None,+ is_default: false,+ client_domain: Some("ams".to_string()),+ });++ let owned_by_syd = store.space_ids_for_domain("syd");+ let owned_by_ams = store.space_ids_for_domain("ams");+ assert!(owned_by_syd.contains("space-remote"));+ assert!(owned_by_ams.contains("space-ams"));++ // A window is sitting on syd's Space, and syd has just dropped it.+ let owner_id = next_space_owner_id();+ WINDOW_SPACES+ .lock()+ .insert(owner_id, "space-remote".to_string());+ store.spaces.retain(|space| space.id != "space-remote");++ // ams speaking about its own rows must not touch it...+ let by_ams = orphaned_window_spaces(&store, "ams", &owned_by_ams);+ assert!(+ !by_ams.iter().any(|(owner, _)| *owner == owner_id),+ "ams claimed a window orphaned by syd: {:?}",+ by_ams+ );++ // ...but syd, whose Space it was, re-homes it onto a Space it has.+ let by_syd = orphaned_window_spaces(&store, "syd", &owned_by_syd);+ assert!(+ by_syd.iter().any(|(owner, _)| *owner == owner_id),+ "syd did not re-home the window it orphaned: {:?}",+ by_syd+ );++ WINDOW_SPACES.lock().remove(&owner_id);+ }++ /// Ending the sessions of one Space must not reach into its siblings on+ /// the same server, which the domain id alone cannot distinguish.+ #[test]+ fn a_spaces_workspaces_do_not_include_its_siblings_on_the_same_server() {+ let mut store = remote_test_store("syd");+ assert!(store.ingest_remote_tree("syd", &sample_tree()));+ store.spaces.push(Space {+ id: "space-remote-2".to_string(),+ name: "side".to_string(),+ active_project_id: None,+ note_vault: None,+ is_default: false,+ client_domain: Some("syd".to_string()),+ });+ store.projects.push(Project {+ id: "rp2".to_string(),+ space_id: "space-remote-2".to_string(),+ name: "side project".to_string(),+ path: PathBuf::from("/srv/side"),+ threads: vec![WorkspaceThread {+ materialized_workspace_name: Some("thinkterm:rp2:rt9".to_string()),+ ..WorkspaceThread::new("rp2".to_string(), "main".to_string(), None)+ }],+ active_thread_id: None,+ threads_collapsed: false,+ active_note_path: None,+ });++ let mine = store.materialized_workspaces_for_space("space-remote");+ assert_eq!(mine, ["thinkterm:rp1:rt1", "thinkterm:rp1:rt2"]);+ assert!(!mine.iter().any(|ws| ws == "thinkterm:rp2:rt9"));+ assert_eq!(+ store.materialized_workspaces_for_space("space-remote-2"),+ ["thinkterm:rp2:rt9"]+ );+ }++ #[test]+ fn a_server_can_host_several_spaces_and_reconnect_returns_to_the_last_one() {+ let mut store = remote_test_store("syd");+ store.spaces.push(Space {+ id: "space-remote-2".to_string(),+ name: "side".to_string(),+ active_project_id: None,+ note_vault: None,+ is_default: false,+ client_domain: Some("syd".to_string()),+ });++ // With nothing remembered, connecting lands on the server's first.+ assert_eq!(+ store.preferred_space_for_domain("syd").as_deref(),+ Some("space-remote")+ );++ assert!(store.remember_space_for_domain("space-remote-2"));+ assert_eq!(+ store.preferred_space_for_domain("syd").as_deref(),+ Some("space-remote-2")+ );+ // Recording the same Space twice is not a change worth persisting.+ assert!(!store.remember_space_for_domain("space-remote-2"));++ // A remembered Space the server has since dropped falls back rather+ // than stranding the connection.+ store.spaces.retain(|space| space.id != "space-remote-2");+ assert_eq!(+ store.preferred_space_for_domain("syd").as_deref(),+ Some("space-remote")+ );++ // Another server's Space is never offered for this one, and a domain+ // with no Spaces reports none.+ assert!(store.preferred_space_for_domain("other").is_none());+ // Local Spaces are not "remembered per domain" at all.+ let local = store.spaces[0].id.clone();+ assert!(!store.remember_space_for_domain(&local));+ }++ /// A live remote window belonging to a sibling Space on the same server+ /// must not be adopted by whichever Space happens to be active: that would+ /// move a running terminal out from under the Space that owns it.+ #[test]+ fn a_sibling_spaces_workspace_is_not_mistaken_for_an_orphan() {+ let host = mux_domain_host_id("syd");+ let mine = remote_project_id_for_space("space-remote", &host);+ let sibling = remote_project_id_for_space("space-remote-2", &host);++ assert_eq!(space_id_from_remote_project_id(&mine), Some("space-remote"));+ assert_eq!(+ space_id_from_remote_project_id(&sibling),+ Some("space-remote-2")+ );+ // A plain local project id carries no Space, so the orphan path still+ // applies to it.+ assert_eq!(space_id_from_remote_project_id("project-1"), None);++ let mut store = remote_test_store("syd");+ assert!(store.has_space("space-remote"));+ assert!(!store.has_space("space-remote-2"));+ // With the sibling Space unknown, its rows really are orphaned.+ assert!(!space_id_from_remote_project_id(&sibling)+ .is_some_and(|s| s != "space-remote" && store.has_space(s)));++ store.spaces.push(Space {+ id: "space-remote-2".to_string(),+ name: "side".to_string(),+ active_project_id: None,+ note_vault: None,+ is_default: false,+ client_domain: Some("syd".to_string()),+ });+ // Once it is known, they are hands off.+ assert!(space_id_from_remote_project_id(&sibling)+ .is_some_and(|s| s != "space-remote" && store.has_space(s)));+ // Our own Space's rows are never "a sibling's".+ assert!(!space_id_from_remote_project_id(&mine)+ .is_some_and(|s| s != "space-remote" && store.has_space(s)));+ }++ /// Two Spaces on one server must not collide: the mux-domain project id+ /// embeds the Space id, and the thread workspace name embeds the project.+ #[test]+ fn two_spaces_on_one_server_get_distinct_projects_and_workspaces() {+ let host = mux_domain_host_id("syd");+ let a = remote_project_id_for_space("space-remote", &host);+ let b = remote_project_id_for_space("space-remote-2", &host);+ assert_ne!(a, b);+ assert_eq!(remote_host_id_for_project_id(&a), host);+ assert_eq!(remote_host_id_for_project_id(&b), host);++ let ws_a = workspace_name_for_thread(&a, "thread-1");+ let ws_b = workspace_name_for_thread(&b, "thread-1");+ assert_ne!(ws_a, ws_b);+ assert_eq!(+ parse_thread_workspace_name(&ws_a),+ Some((a, "thread-1".to_string()))+ );+ }++ /// The local store and `codec::apply_op` implement the same row-ordering+ /// and pin rules in two different places. If they ever drift, a drag would+ /// look right until the server's push snapped it back.+ #[test]+ fn store_and_wire_ordering_rules_agree() {+ let mut store = remote_test_store("syd");+ let mut tree = sample_tree();+ tree.projects.push(codec::TtProject {+ id: "rp2".to_string(),+ space_id: "space-remote".to_string(),+ name: "notes".to_string(),+ path: "/srv/notes".to_string(),+ threads: vec![tree_thread("rt3", "rp2", "main")],+ });+ assert!(store.ingest_remote_tree("syd", &tree));++ let cases: Vec<codec::TreeOp> = vec![+ codec::TreeOp::MoveProjectBefore {+ space_id: "space-remote".to_string(),+ project_id: "rp2".to_string(),+ before: Some("rp1".to_string()),+ },+ codec::TreeOp::MoveProjectBefore {+ space_id: "space-remote".to_string(),+ project_id: "rp2".to_string(),+ before: None,+ },+ codec::TreeOp::MoveThreadBefore {+ project_id: "rp1".to_string(),+ thread_id: "rt2".to_string(),+ before: Some("rt1".to_string()),+ },+ codec::TreeOp::MoveThreadBefore {+ project_id: "rp1".to_string(),+ thread_id: "rt2".to_string(),+ before: None,+ },+ // A pinned row is refused as both subject and anchor on both sides.+ codec::TreeOp::SetThreadPinned {+ thread_id: "rt1".to_string(),+ pinned: true,+ last_active_at: 10,+ },+ codec::TreeOp::MoveThreadBefore {+ project_id: "rp1".to_string(),+ thread_id: "rt1".to_string(),+ before: None,+ },+ codec::TreeOp::MoveThreadBefore {+ project_id: "rp1".to_string(),+ thread_id: "rt2".to_string(),+ before: Some("rt1".to_string()),+ },+ ];++ for op in &cases {+ let wire_changed = codec::apply_op(&mut tree, op);+ let store_changed = match op {+ codec::TreeOp::MoveProjectBefore {+ space_id,+ project_id,+ before,+ } => store.move_project_before(space_id, project_id, before.as_deref()),+ codec::TreeOp::MoveThreadBefore {+ project_id,+ thread_id,+ before,+ } => store.move_thread_before(project_id, thread_id, before.as_deref()),+ codec::TreeOp::SetThreadPinned { thread_id, .. } => {+ store.toggle_thread_pinned(thread_id)+ }+ other => panic!("unhandled case {:?}", other),+ };+ assert_eq!(wire_changed, store_changed, "differing verdict on {op:?}");++ let wire_projects: Vec<&str> = tree+ .projects_in_space("space-remote")+ .map(|project| project.id.as_str())+ .collect();+ let store_projects: Vec<&str> = store+ .projects+ .iter()+ .filter(|project| project.space_id == "space-remote")+ .map(|project| project.id.as_str())+ .collect();+ assert_eq!(wire_projects, store_projects, "project order after {op:?}");++ for project_id in ["rp1", "rp2"] {+ let wire_threads: Vec<&str> = tree+ .project(project_id)+ .unwrap()+ .threads+ .iter()+ .map(|thread| thread.id.as_str())+ .collect();+ let store_threads: Vec<&str> = store+ .projects+ .iter()+ .find(|project| project.id == project_id)+ .unwrap()+ .threads+ .iter()+ .map(|thread| thread.id.as_str())+ .collect();+ assert_eq!(+ wire_threads, store_threads,+ "thread order in {project_id} after {op:?}"+ );+ }+ }+ }}diff --git a/wezterm-mux-server-impl/Cargo.toml b/wezterm-mux-server-impl/Cargo.tomlindex 44e871dc..f7be112f 100644--- a/wezterm-mux-server-impl/Cargo.toml+++ b/wezterm-mux-server-impl/Cargo.toml@@ -24,7 +24,9 @@ portable-pty = { workspace=true, features = ["serde_support"]}promise.workspace = truerangeset.workspace = truercgen.workspace = true+serde_json.workspace = truesmol.workspace = true+tempfile.workspace = truetermwiz = { workspace=true, features=["use_serde"] }url.workspace = truewezterm-client.workspace = truediff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rsindex c3728f1c..65e2a742 100644--- a/wezterm-mux-server-impl/src/dispatch.rs+++ b/wezterm-mux-server-impl/src/dispatch.rs@@ -202,6 +202,17 @@ where.await?;stream.flush().await.context("flushing PDU to client")?;}+ Ok(Item::Notif(MuxNotification::ThinkTermTreeChanged)) => {+ // The tree is small enough to resend whole; this is also the+ // path that tells the client which mutated it that the server+ // accepted the op.+ Pdu::ThinkTermTreeState(codec::ThinkTermTreeState {+ tree: crate::thinkterm_tree::snapshot(),+ })+ .encode_async(&mut stream, 0)+ .await?;+ stream.flush().await.context("flushing PDU to client")?;+ }Ok(Item::Notif(MuxNotification::ActiveWorkspaceChanged(_))) => {}Ok(Item::Notif(MuxNotification::Empty)) => {}Err(err) => {diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rsindex bc0b6968..5be3cb21 100644--- a/wezterm-mux-server-impl/src/lib.rs+++ b/wezterm-mux-server-impl/src/lib.rs@@ -9,6 +9,7 @@ pub mod dispatch;pub mod local;pub mod pki;pub mod sessionhandler;+pub mod thinkterm_tree;fn client_domains(config: &config::ConfigHandle) -> Vec<ClientDomainConfig> {let mut domains = vec![];diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 29f05af7..51242dbd 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -913,6 +913,22 @@ impl SessionHandler {.detach();}+ Pdu::GetThinkTermTree(_) => {+ send_response(Ok(Pdu::ThinkTermTreeState(ThinkTermTreeState {+ tree: crate::thinkterm_tree::snapshot(),+ })));+ }++ Pdu::MutateThinkTermTree(MutateThinkTermTree { ops }) => {+ // mutate() broadcasts to every connection when the batch+ // changed something; the direct response here is what lets the+ // caller reconcile even when it did not.+ send_response(+ crate::thinkterm_tree::mutate(&ops)+ .map(|tree| Pdu::ThinkTermTreeState(ThinkTermTreeState { tree })),+ );+ }+Pdu::MovePaneToNewTab(request) => {let client_id = self.client_id.clone();spawn_into_main_thread(async move {@@ -1188,6 +1204,7 @@ impl SessionHandler {| Pdu::MovePaneToNewTabResponse { .. }| Pdu::TabAddedToWindow { .. }| Pdu::GetPaneRenderableDimensionsResponse { .. }+ | Pdu::ThinkTermTreeState { .. }| Pdu::ErrorResponse { .. } => {send_response(Err(anyhow!("expected a request, got {:?}", decoded.pdu)))}diff --git a/wezterm-mux-server-impl/src/thinkterm_tree.rs b/wezterm-mux-server-impl/src/thinkterm_tree.rsnew file mode 100644index 00000000..0dc34fbe--- /dev/null+++ b/wezterm-mux-server-impl/src/thinkterm_tree.rs@@ -0,0 +1,287 @@+//! Server-side ownership of the ThinkTerm sidebar tree.+//!+//! The mux server is the single source of truth for Space/Project/Thread on a+//! remote host: any number of devices can attach and they all see the same+//! rows. Clients send one `TreeOp` at a time, the op is applied here with+//! `codec::apply_op` — the same function the client ran locally — and the+//! resulting tree is broadcast to every connection.+//!+//! Storage is a single JSON file. The server is one process, so all writes are+//! already serialized through this mutex; there is nothing a database would+//! buy at this size (tens of KB) that an atomic file replace does not.++use anyhow::{Context, Result};+use codec::{apply_op, ensure_unique_thread_names, ThinkTermTree, TreeOp};+use mux::{Mux, MuxNotification};+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::Mutex;++lazy_static::lazy_static! {+ static ref TREE: Mutex<ThinkTermTree> = Mutex::new(load_or_default());+}++pub fn tree_path() -> PathBuf {+ config::DATA_DIR.join("thinkterm_tree.json")+}++fn load_or_default() -> ThinkTermTree {+ let path = tree_path();+ match load_from_path(&path) {+ Ok(mut tree) => {+ if let Err(err) = repair_loaded_tree(&path, &mut tree) {+ log::error!(+ "failed to persist repaired ThinkTerm tree to {}: {err:#}",+ path.display()+ );+ }+ tree+ }+ Err(err) => {+ // A corrupt or unreadable tree must not stop the server from+ // serving terminals; the client will re-seed an empty one.+ log::warn!(+ "failed to load ThinkTerm tree from {}: {err:#}; starting empty",+ path.display()+ );+ ThinkTermTree::default()+ }+ }+}++#[cfg(test)]+fn load_repaired_from_path(path: &Path) -> Result<ThinkTermTree> {+ let mut tree = load_from_path(path)?;+ repair_loaded_tree(path, &mut tree)?;+ Ok(tree)+}++fn repair_loaded_tree(path: &Path, tree: &mut ThinkTermTree) -> Result<()> {+ if ensure_unique_thread_names(tree) {+ tree.revision = tree.revision.saturating_add(1);+ save_to_path(path, &tree)+ .with_context(|| format!("persist repaired ThinkTerm tree to {}", path.display()))?;+ }+ Ok(())+}++fn load_from_path(path: &Path) -> Result<ThinkTermTree> {+ if !path.exists() {+ return Ok(ThinkTermTree::default());+ }+ let file = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?;+ serde_json::from_reader(std::io::BufReader::new(file))+ .with_context(|| format!("parse {}", path.display()))+}++/// Replace the file atomically so that a crash mid-write can never leave a+/// half-serialized tree behind. Same shape as the GUI's own store writer.+fn save_to_path(path: &Path, tree: &ThinkTermTree) -> Result<()> {+ let parent = path+ .parent()+ .ok_or_else(|| anyhow::anyhow!("{} has no parent directory", path.display()))?;+ std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;++ let mut file = tempfile::NamedTempFile::new_in(parent)+ .with_context(|| format!("create temporary tree file in {}", parent.display()))?;+ serde_json::to_writer_pretty(&mut file, tree)+ .with_context(|| format!("write {}", path.display()))?;+ file.flush()+ .with_context(|| format!("flush {}", path.display()))?;+ file.as_file()+ .sync_all()+ .with_context(|| format!("sync {}", path.display()))?;+ file.persist(path)+ .with_context(|| format!("replace {}", path.display()))?;+ Ok(())+}++/// The tree as it stands right now.+pub fn snapshot() -> ThinkTermTree {+ TREE.lock().unwrap().clone()+}++fn apply_and_persist(+ current: &ThinkTermTree,+ ops: &[TreeOp],+ path: &Path,+) -> Result<(ThinkTermTree, bool)> {+ let mut candidate = current.clone();+ let mut changed = false;+ for op in ops {+ changed |= apply_op(&mut candidate, op);+ }+ if !changed {+ return Ok((candidate, false));+ }+ candidate.revision = candidate.revision.saturating_add(1);+ save_to_path(path, &candidate)+ .with_context(|| format!("persist authoritative ThinkTerm tree to {}", path.display()))?;+ Ok((candidate, true))+}++/// Apply `ops` in order and return the resulting tree.+///+/// When nothing changed (unknown ids, no-op moves, a racing delete from+/// another device, or a seed batch the server already has) neither the file+/// nor the other clients are touched; the caller still gets the current tree+/// so its own RPC can reconcile.+pub fn mutate(ops: &[TreeOp]) -> Result<ThinkTermTree> {+ // The file is written while the lock is still held. Dropping it first and+ // saving afterwards lets two connections race: the one that applied the+ // *older* revision can reach the disk last and leave the file behind what+ // every client has already been shown, so a delete or rename would come+ // back from the dead at the next server restart. The tree is tens of KB,+ // so serializing the writes costs nothing worth measuring.+ let (tree, changed) = {+ let mut guard = TREE.lock().unwrap();+ let path = tree_path();+ let (candidate, changed) = apply_and_persist(&guard, ops, &path)?;+ if changed {+ *guard = candidate;+ }+ (guard.clone(), changed)+ };++ if changed {+ Mux::notify_from_any_thread(MuxNotification::ThinkTermTreeChanged);+ }++ Ok(tree)+}++#[cfg(test)]+mod test {+ use super::*;+ use codec::TreeOp;++ fn sample() -> ThinkTermTree {+ let mut tree = ThinkTermTree::default();+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateSpace {+ space_id: "s1".into(),+ name: "Work".into()+ }+ ));+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateProject {+ project_id: "p1".into(),+ space_id: "s1".into(),+ name: "thinkterm".into(),+ path: "/home/x/github/ThinkTerm".into(),+ }+ ));+ assert!(apply_op(+ &mut tree,+ &TreeOp::CreateThread {+ thread_id: "t1".into(),+ project_id: "p1".into(),+ name: "main".into(),+ workspace: Some("thinkterm:p1:t1".into()),+ created_at: 42,+ }+ ));+ tree+ }++ #[test]+ fn a_saved_tree_reloads_identically() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("nested").join("thinkterm_tree.json");+ let tree = sample();++ save_to_path(&path, &tree).unwrap();+ assert_eq!(load_from_path(&path).unwrap(), tree);+ }++ /// The revision is what lets a client tell "never written to" from "the+ /// user deleted the last Space", so it has to outlive a server restart+ /// just as the rows do.+ #[test]+ fn the_revision_survives_a_reload() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("thinkterm_tree.json");+ let mut tree = sample();+ tree.revision = 12;+ save_to_path(&path, &tree).unwrap();++ let reloaded = load_from_path(&path).unwrap();+ assert_eq!(reloaded.revision, 12);+ assert!(!reloaded.is_uninitialized());+ }++ #[test]+ fn a_missing_file_loads_as_an_empty_tree() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("absent.json");+ assert_eq!(load_from_path(&path).unwrap(), ThinkTermTree::default());+ }++ #[test]+ fn a_corrupt_file_is_reported_rather_than_silently_emptied() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("corrupt.json");+ std::fs::write(&path, b"{ this is not json").unwrap();+ // load_from_path surfaces the error; load_or_default is what decides+ // to fall back, and it logs when it does.+ assert!(load_from_path(&path).is_err());+ }++ #[test]+ fn saving_replaces_rather_than_appends() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("thinkterm_tree.json");+ let mut tree = sample();+ save_to_path(&path, &tree).unwrap();++ assert!(apply_op(+ &mut tree,+ &TreeOp::DeleteThread {+ thread_id: "t1".into()+ }+ ));+ save_to_path(&path, &tree).unwrap();++ let reloaded = load_from_path(&path).unwrap();+ assert_eq!(reloaded, tree);+ assert!(reloaded.thread("t1").is_none());+ }++ #[test]+ fn loading_repairs_and_persists_duplicate_thread_names() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("thinkterm_tree.json");+ let mut tree = sample();+ let duplicate = tree.projects[0].threads[0].clone();+ let mut duplicate = duplicate;+ duplicate.id = "t2".into();+ tree.projects[0].threads.push(duplicate);+ tree.revision = 7;+ save_to_path(&path, &tree).unwrap();++ let repaired = load_repaired_from_path(&path).unwrap();+ assert_eq!(repaired.revision, 8);+ assert_eq!(repaired.projects[0].threads[0].name, "main");+ assert_eq!(repaired.projects[0].threads[1].name, "main 2");+ assert_eq!(load_from_path(&path).unwrap(), repaired);+ }++ #[test]+ fn failed_persistence_does_not_commit_the_candidate_tree() {+ let dir = tempfile::tempdir().unwrap();+ let blocker = dir.path().join("not-a-directory");+ std::fs::write(&blocker, b"file").unwrap();+ let path = blocker.join("thinkterm_tree.json");+ let current = sample();+ let op = TreeOp::RenameSpace {+ space_id: "s1".into(),+ name: "Renamed".into(),+ };++ assert!(apply_and_persist(¤t, &[op], &path).is_err());+ assert_eq!(current.space("s1").unwrap().name, "Work");+ assert_eq!(current.revision, 0);+ }+}