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
//! 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>,
/// When this project was archived, or `None` while it is live. A
/// timestamp rather than a bool so the archived list can sort
/// most-recent-first without a second field, and so it can never be
/// confused with the retired thread-level `archived` flag that
/// `drop_legacy_archived_threads` still cleans up.
#[serde(default)]
pub archived_at: Option<i64>,
}
#[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,
},
/// Archive or restore a whole project. Threads, their names, order,
/// pins and workspace bindings all stay in the tree: archiving is a
/// visibility and lifecycle state, not a deletion, and unarchiving
/// must be able to rebuild the shells from the layouts the server
/// still holds.
SetProjectArchived {
project_id: TtProjectId,
/// The archive time, or `None` to restore. Timestamps travel in
/// the op like `RenameThread`'s; the server does not mint them.
archived_at: Option<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()),
archived_at: project.archived_at,
};
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![],
archived_at: None,
});
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::SetProjectArchived {
project_id,
archived_at,
} => {
// A Space must keep at least one live project. Each client
// checks this before sending, but two clients can archive the
// last two live projects concurrently -- only this check,
// against the authoritative tree, is atomic. The refusal
// converges like every other one here: the optimistic local
// apply refuses by the same rule, and where the caches
// disagreed the server's next push corrects the loser.
if archived_at.is_some() {
let Some(space_id) = tree
.project(project_id)
.map(|project| project.space_id.clone())
else {
return false;
};
let another_live = tree.projects.iter().any(|project| {
project.space_id == space_id
&& project.id != *project_id
&& project.archived_at.is_none()
});
if !another_live {
return false;
}
}
match tree
.projects
.iter_mut()
.find(|project| project.id == *project_id)
{
// A re-archive with a fresh timestamp is a legitimate
// touch; only the exact same state is a no-op.
Some(project) if project.archived_at != *archived_at => {
project.archived_at = *archived_at;
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(),
},
TreeOp::SetProjectArchived {
project_id: "p3".into(),
archived_at: Some(9),
},
];
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);
}
#[test]
fn archiving_a_project_is_idempotent_and_keeps_its_threads() {
let mut tree = seeded();
let threads_before = thread_ids(&tree, "p1");
// Archive, re-archive with the same stamp, re-archive with a fresh
// stamp, restore. Only the exact-same-state applications are no-ops.
assert!(apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p1".into(),
archived_at: Some(100),
}
));
assert_eq!(tree.project("p1").unwrap().archived_at, Some(100));
assert!(!apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p1".into(),
archived_at: Some(100),
}
));
assert!(apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p1".into(),
archived_at: Some(200),
}
));
// Archiving is a visibility state: every thread survives it.
assert_eq!(thread_ids(&tree, "p1"), threads_before);
assert!(apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p1".into(),
archived_at: None,
}
));
assert_eq!(tree.project("p1").unwrap().archived_at, None);
assert_eq!(thread_ids(&tree, "p1"), threads_before);
// Unknown ids race concurrent deletes and must not error.
assert!(!apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "nope".into(),
archived_at: Some(1),
}
));
}
#[test]
fn the_spaces_last_live_project_cannot_be_archived() {
// Two clients can pass their local guards concurrently; the
// authoritative tree is where the invariant actually holds.
let mut tree = seeded();
assert!(apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p1".into(),
archived_at: Some(1),
}
));
assert!(apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p2".into(),
archived_at: Some(2),
}
));
// p3 is the last live project in s1: refused, tree unchanged.
assert!(!apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p3".into(),
archived_at: Some(3),
}
));
assert_eq!(tree.project("p3").unwrap().archived_at, None);
// Restoring is never gated.
assert!(apply_op(
&mut tree,
&TreeOp::SetProjectArchived {
project_id: "p1".into(),
archived_at: None,
}
));
}
}