Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

Archive whole projects out of the sidebar

RoversXd7b31dcc004a
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index 1c6725f4..7ee8ff3d 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -11,13 +11,13 @@
#![allow(dead_code)]
#![allow(clippy::range_plus_one)]
-use anyhow::{Context as _, Error, bail};
+use anyhow::{bail, Context as _, Error};
+use rangeset::*;
+use serde::{Deserialize, Serialize};
use thinkterm_proto::{
ClientId, ClientInfo, CommandSpec, PaneDirection, PaneId, PaneNode, RenderableDimensions,
ScrollbackEraseMode, SerdeUrl, SplitRequest, StableCursorPosition, TabId, WindowId,
};
-use rangeset::*;
-use serde::{Deserialize, Serialize};
// smol's io/prelude are pure re-exports of these futures-lite modules, so
// this is the same set of traits -- minus smol's runtime (async-io, polling),
// which does not build for wasm and which nothing in this crate uses.
@@ -38,8 +38,8 @@ use wezterm_term::{Alert, ClipboardSelection, StableRowIndex, TerminalSize};
pub mod thinkterm_tree;
pub use thinkterm_tree::{
- ThinkTermTree, TreeOp, TtProject, TtProjectId, TtSpace, TtSpaceId, TtThread, TtThreadId,
- apply_op, ensure_unique_thread_names,
+ apply_op, ensure_unique_thread_names, ThinkTermTree, TreeOp, TtProject, TtProjectId, TtSpace,
+ TtSpaceId, TtThread, TtThreadId,
};
#[derive(Error, Debug)]
@@ -485,7 +485,9 @@ macro_rules! pdu {
/// 61: Agent status is classified by the mux that owns the pane and pushed
/// to clients (AgentStatusChanged), with a request/response pair for
/// cold-start delivery and for `thinkterm cli agent list`.
-pub const CODEC_VERSION: usize = 61;
+/// 62: Projects carry an archived state in the shared ThinkTerm tree
+/// (TtProject.archived_at, TreeOp::SetProjectArchived).
+pub const CODEC_VERSION: usize = 62;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
@@ -1717,17 +1719,17 @@ mod golden {
116, 0, 0, 0, 1, 125, 0, 0, 1, 12, 47, 100, 101, 118, 47, 116, 116, 121, 115, 48, 48, 49,
3, 0, 1, 1, 2, 4, 7, 115, 116, 97, 99, 107, 101, 100, 24, 80, 128, 5, 128, 3, 96, 1, 13,
102, 105, 108, 101, 58, 47, 47, 47, 116, 109, 112, 47, 120, 1, 0, 1, 7, 100, 101, 102, 97,
- 117, 108, 116, 0, 0, 0, 1, 125, 0, 0, 1, 12, 47, 100, 101, 118, 47, 116, 116, 121, 115,
- 48, 48, 49, 1, 7, 0, 24, 40, 192, 2, 128, 3, 96, 24, 39, 184, 2, 128, 3, 96, 1, 4, 109,
- 97, 105, 110, 1, 1, 3, 119, 105, 110,
+ 117, 108, 116, 0, 0, 0, 1, 125, 0, 0, 1, 12, 47, 100, 101, 118, 47, 116, 116, 121, 115, 48,
+ 48, 49, 1, 7, 0, 24, 40, 192, 2, 128, 3, 96, 24, 39, 184, 2, 128, 3, 96, 1, 4, 109, 97,
+ 105, 110, 1, 1, 3, 119, 105, 110,
];
const SPLIT_PANE: &[u8] = &[
5, 1, 1, 0, 1, 30, 0, 1, 5, 47, 104, 111, 109, 101, 2, 3, 100, 111, 109, 1, 2,
];
const SEARCH: &[u8] = &[3, 2, 2, 97, 43, 123, 10, 1, 100];
const CLIENT_LIST: &[u8] = &[
- 1, 4, 104, 111, 115, 116, 4, 117, 115, 101, 114, 100, 2, 3, 0, 128, 226, 207, 170, 6, 1,
- 7, 100, 101, 102, 97, 117, 108, 116, 128, 226, 207, 170, 6, 1, 4,
+ 1, 4, 104, 111, 115, 116, 4, 117, 115, 101, 114, 100, 2, 3, 0, 128, 226, 207, 170, 6, 1, 7,
+ 100, 101, 102, 97, 117, 108, 116, 128, 226, 207, 170, 6, 1, 4,
];
const RENDER_CHANGES: &[u8] = &[
1, 0, 1, 0, 0, 0, 1, 80, 24, 100, 121, 180, 127, 96, 128, 5, 128, 3, 0, 2, 0, 2, 5, 6, 5,
@@ -1761,8 +1763,8 @@ mod golden {
// introduced. The other literals guard against changing an old format;
// this one guards against accidentally changing the new one.
const COMMAND_SPEC: &[u8] = &[
- 2, 4, 112, 114, 111, 103, 3, 102, 128, 111, 2, 4, 80, 65, 84, 72, 8, 47, 117, 115, 114,
- 47, 98, 105, 110, 1, 3, 70, 79, 79, 3, 98, 97, 114, 0, 1, 4, 47, 116, 109, 112, 1, 18, 0,
+ 2, 4, 112, 114, 111, 103, 3, 102, 128, 111, 2, 4, 80, 65, 84, 72, 8, 47, 117, 115, 114, 47,
+ 98, 105, 110, 1, 3, 70, 79, 79, 3, 98, 97, 114, 0, 1, 4, 47, 116, 109, 112, 1, 18, 0,
];
#[test]
@@ -2001,6 +2003,18 @@ mod test {
pinned: true,
last_active_at: 1_700_000_001,
},
+ // A second live project so archiving p1 passes the Space's
+ // last-live-project guard.
+ TreeOp::CreateProject {
+ project_id: "p2".into(),
+ space_id: "s1".into(),
+ name: "notes".into(),
+ path: "/srv/projects/notes".into(),
+ },
+ TreeOp::SetProjectArchived {
+ project_id: "p1".into(),
+ archived_at: Some(1_700_000_002),
+ },
] {
assert!(apply_op(&mut tree, &op));
}
@@ -2024,6 +2038,10 @@ mod test {
thread_id: "t2".into(),
before: None,
},
+ TreeOp::SetProjectArchived {
+ project_id: "p1".into(),
+ archived_at: None,
+ },
TreeOp::DeleteSpace {
space_id: "s1".into(),
},
@@ -2043,7 +2061,11 @@ mod test {
#[test]
fn agent_status_protocol_round_trip_at_version_61() {
- assert_eq!(CODEC_VERSION, 61);
+ // The agent-status protocol arrived at 61 and is unchanged since.
+ // The exact assertion is the tripwire: whoever bumps the codec must
+ // come here, confirm the round-trips still cover the new version,
+ // and advance it deliberately.
+ assert_eq!(CODEC_VERSION, 62);
use thinkterm_proto::{AgentEvidence, AgentState, AgentStatus};
fn round_trip(pdu: Pdu) {
diff --git a/codec/src/thinkterm_tree.rs b/codec/src/thinkterm_tree.rs
index 6c309eed..9d6bb929 100644
--- a/codec/src/thinkterm_tree.rs
+++ b/codec/src/thinkterm_tree.rs
@@ -41,6 +41,13 @@ pub struct TtProject {
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)]
@@ -164,6 +171,17 @@ pub enum TreeOp {
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 {
@@ -264,6 +282,7 @@ pub fn ensure_unique_thread_names(tree: &mut ThinkTermTree) -> bool {
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);
@@ -335,6 +354,7 @@ pub fn apply_op(tree: &mut ThinkTermTree, op: &TreeOp) -> bool {
name: name.clone(),
path: path.clone(),
threads: vec![],
+ archived_at: None,
});
true
}
@@ -578,6 +598,48 @@ pub fn apply_op(tree: &mut ThinkTermTree, op: &TreeOp) -> bool {
_ => 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;
@@ -976,6 +1038,10 @@ mod test {
TreeOp::DeleteThread {
thread_id: "t2".into(),
},
+ TreeOp::SetProjectArchived {
+ project_id: "p3".into(),
+ archived_at: Some(9),
+ },
];
let mut client = seeded();
@@ -990,4 +1056,95 @@ mod test {
}
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,
+ }
+ ));
+ }
}
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs
index 2dd71865..915df809 100644
--- a/config/src/keyassignment.rs
+++ b/config/src/keyassignment.rs
@@ -554,6 +554,15 @@ pub enum KeyAssignment {
CreateWorkspaceThread(String),
ToggleWorkspaceThreadsCollapsed(String),
RemoveProject(String),
+ /// Archive a project: close its panes, keep its rows and layouts, hide
+ /// it from the sidebar until unarchived.
+ ArchiveProject(String),
+ UnarchiveProject(String),
+ /// Palette entries cannot carry a project id; this archives the active
+ /// Space's active project.
+ ArchiveActiveProject,
+ /// Transiently reveal archived projects at the tail of the sidebar.
+ ToggleShowArchivedProjects,
ConnectWorkspaceThread(String),
DisconnectWorkspaceThread(String),
ToggleWorkspaceThreadPinned(String),
diff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftl
index a303d2ba..a9e9ec57 100644
--- a/wezterm-gui/i18n/en-US.ftl
+++ b/wezterm-gui/i18n/en-US.ftl
@@ -29,6 +29,21 @@ settings-section-general = General
settings-section-appearance = Appearance
settings-section-terminal = Terminal
settings-section-workspaces = Workspaces
+settings-section-archived = Archived
+settings-archived-heading = Hidden from the sidebar
+settings-archived-empty = Nothing archived. Right-click a workspace in the sidebar and choose "Archive Project…" to put it away.
+settings-archived-meta = { $space } · { $threads ->
+ [one] 1 thread
+ *[other] { $threads } threads
+ } · archived { $when }
+settings-archived-when-today = today
+settings-archived-when-yesterday = yesterday
+settings-archived-unarchive = Unarchive
+settings-archived-delete = Delete
+settings-archived-delete-confirm = Confirm
+settings-archived-unarchived = Restored "{ $name }" to the sidebar
+settings-archived-deleted = Deleted "{ $name }" permanently
+settings-archived-remote-offline = That workspace lives on a disconnected server; reconnect first
settings-section-keymap = Keymap
settings-section-compatibility = Import from WezTerm
settings-section-developer = Developer
@@ -196,6 +211,25 @@ menu-rename-project = Rename Project…
menu-new-thread = New Thread
menu-toggle-threads = Collapse / Expand Threads
menu-remove-project = Remove Project
+menu-archive-project = Archive Project…
+menu-archive-project-quiet = Archive Project
+menu-archive-project-explain = Closes { $panes ->
+ [one] 1 running pane
+ *[other] { $panes } running panes
+ }; layouts are kept
+menu-archive-project-confirm = Archive and Close Panes
+menu-unarchive-project = Unarchive Project
+menu-delete-project-permanently = Delete Permanently…
+menu-delete-project-permanently-explain = Deletes { $threads ->
+ [one] 1 thread
+ *[other] { $threads } threads
+ } for good; this cannot be undone
+menu-delete-project-permanently-confirm = Delete Project and Threads
+menu-show-archived = Archived
+menu-show-archived-count = Archived ({ $count })
+archive-project-last-live-project = The Space needs at least one live project; unarchive or add another first
+archive-project-server-rejected = The server rejected archiving this project
+archive-project-teardown-incomplete = Archived, but some remote sessions could not be closed. Reconnect, then unarchive and archive again to finish the cleanup
menu-space-occupied = { $name } (occupied)
menu-space-remote = { $name } (Remote)
menu-new-space = New Space
diff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftl
index fe8b25ce..a59f6f69 100644
--- a/wezterm-gui/i18n/fr-FR.ftl
+++ b/wezterm-gui/i18n/fr-FR.ftl
@@ -29,6 +29,21 @@ settings-section-general = Général
settings-section-appearance = Apparence
settings-section-terminal = Terminal
settings-section-workspaces = Espaces de travail
+settings-section-archived = Archivés
+settings-archived-heading = Masqués de la barre latérale
+settings-archived-empty = Rien d'archivé. Clic droit sur un projet dans la barre latérale puis « Archiver le projet… ».
+settings-archived-meta = { $space } · { $threads ->
+ [one] 1 session
+ *[other] { $threads } sessions
+ } · archivé { $when }
+settings-archived-when-today = aujourd'hui
+settings-archived-when-yesterday = hier
+settings-archived-unarchive = Désarchiver
+settings-archived-delete = Supprimer
+settings-archived-delete-confirm = Confirmer
+settings-archived-unarchived = « { $name } » restauré dans la barre latérale
+settings-archived-deleted = « { $name } » supprimé définitivement
+settings-archived-remote-offline = Ce projet vit sur un serveur déconnecté ; reconnectez-vous d'abord
settings-section-keymap = Raccourcis clavier
settings-section-compatibility = Importer depuis WezTerm
settings-section-developer = Développeur
@@ -196,6 +211,25 @@ menu-rename-project = Renommer le projet…
menu-new-thread = Nouvelle session
menu-toggle-threads = Réduire / développer les sessions
menu-remove-project = Supprimer le projet
+menu-archive-project = Archiver le projet…
+menu-archive-project-quiet = Archiver le projet
+menu-archive-project-explain = Ferme { $panes ->
+ [one] 1 panneau actif
+ *[other] { $panes } panneaux actifs
+ } ; les dispositions sont conservées
+menu-archive-project-confirm = Archiver et fermer les panneaux
+menu-unarchive-project = Désarchiver le projet
+menu-delete-project-permanently = Supprimer définitivement…
+menu-delete-project-permanently-explain = Supprime { $threads ->
+ [one] 1 session
+ *[other] { $threads } sessions
+ } définitivement ; action irréversible
+menu-delete-project-permanently-confirm = Supprimer le projet et ses sessions
+menu-show-archived = Archivés
+menu-show-archived-count = Archivés ({ $count })
+archive-project-last-live-project = L'espace doit garder au moins un projet actif ; désarchivez ou ajoutez-en un d'abord
+archive-project-server-rejected = Le serveur a refusé l'archivage de ce projet
+archive-project-teardown-incomplete = Archivé, mais certaines sessions distantes n'ont pas pu être fermées. Reconnectez-vous, puis désarchivez et archivez de nouveau pour terminer le nettoyage
menu-space-occupied = { $name } (occupé)
menu-space-remote = { $name } (distant)
menu-new-space = Nouvel espace
diff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftl
index 1b382413..b1d973e0 100644
--- a/wezterm-gui/i18n/ja-JP.ftl
+++ b/wezterm-gui/i18n/ja-JP.ftl
@@ -29,6 +29,18 @@ settings-section-general = 一般
settings-section-appearance = 外観
settings-section-terminal = ターミナル
settings-section-workspaces = ワークスペース
+settings-section-archived = アーカイブ
+settings-archived-heading = サイドバーから非表示
+settings-archived-empty = アーカイブはありません。サイドバーのワークスペースを右クリックし「プロジェクトをアーカイブ…」を選んでください。
+settings-archived-meta = { $space } · セッション { $threads } 件 · { $when }にアーカイブ
+settings-archived-when-today = 今日
+settings-archived-when-yesterday = 昨日
+settings-archived-unarchive = アーカイブ解除
+settings-archived-delete = 削除
+settings-archived-delete-confirm = 確認
+settings-archived-unarchived = 「{ $name }」をサイドバーに復元しました
+settings-archived-deleted = 「{ $name }」を完全に削除しました
+settings-archived-remote-offline = このワークスペースは切断中のサーバー上にあります。先に再接続してください
settings-section-keymap = キーマップ
settings-section-compatibility = WezTerm からインポート
settings-section-developer = 開発者
@@ -196,6 +208,19 @@ menu-rename-project = プロジェクト名を変更…
menu-new-thread = 新しいセッション
menu-toggle-threads = セッションを折りたたむ/展開
menu-remove-project = プロジェクトを削除
+menu-archive-project = プロジェクトをアーカイブ…
+menu-archive-project-quiet = プロジェクトをアーカイブ
+menu-archive-project-explain = 実行中のペイン { $panes } 件を閉じます。レイアウトは保持されます
+menu-archive-project-confirm = アーカイブしてペインを閉じる
+menu-unarchive-project = アーカイブを解除
+menu-delete-project-permanently = 完全に削除…
+menu-delete-project-permanently-explain = { $threads } 件のセッションを完全に削除します。元に戻せません
+menu-delete-project-permanently-confirm = プロジェクトとセッションを削除
+menu-show-archived = アーカイブ済み
+menu-show-archived-count = アーカイブ済み({ $count })
+archive-project-last-live-project = スペースには稼働中のプロジェクトが少なくとも 1 つ必要です。先に別のプロジェクトを復元または追加してください
+archive-project-server-rejected = サーバーがこのプロジェクトのアーカイブを拒否しました
+archive-project-teardown-incomplete = アーカイブしましたが、一部のリモートセッションを閉じられませんでした。再接続後、アーカイブを解除してもう一度アーカイブすると後始末が完了します
menu-space-occupied = { $name }(使用中)
menu-space-remote = { $name }(リモート)
menu-new-space = 新しいスペース
diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftl
index 083fff9f..ef28866b 100644
--- a/wezterm-gui/i18n/zh-CN.ftl
+++ b/wezterm-gui/i18n/zh-CN.ftl
@@ -29,6 +29,18 @@ settings-section-general = 通用
settings-section-appearance = 外观
settings-section-terminal = 终端
settings-section-workspaces = 工作区
+settings-section-archived = 已归档
+settings-archived-heading = 已从侧边栏隐藏
+settings-archived-empty = 暂无归档。在侧边栏右键某个工作区,选择「归档项目…」即可收纳。
+settings-archived-meta = { $space } · { $threads } 个会话 · { $when }归档
+settings-archived-when-today = 今天
+settings-archived-when-yesterday = 昨天
+settings-archived-unarchive = 取消归档
+settings-archived-delete = 删除
+settings-archived-delete-confirm = 确认删除
+settings-archived-unarchived = 已将「{ $name }」恢复到侧边栏
+settings-archived-deleted = 已永久删除「{ $name }」
+settings-archived-remote-offline = 该工作区在已断开的服务器上,请先重新连接
settings-section-keymap = 快捷键
settings-section-compatibility = 从 WezTerm 导入
settings-section-developer = 开发者
@@ -196,6 +208,19 @@ menu-rename-project = 重命名项目…
menu-new-thread = 新建会话
menu-toggle-threads = 折叠 / 展开会话
menu-remove-project = 移除项目
+menu-archive-project = 归档项目…
+menu-archive-project-quiet = 归档项目
+menu-archive-project-explain = 将关闭 { $panes } 个运行中的面板;布局会保留
+menu-archive-project-confirm = 归档并关闭面板
+menu-unarchive-project = 取消归档
+menu-delete-project-permanently = 永久删除…
+menu-delete-project-permanently-explain = 将永久删除 { $threads } 个会话;此操作无法撤销
+menu-delete-project-permanently-confirm = 删除项目及会话
+menu-show-archived = 已归档
+menu-show-archived-count = 已归档({ $count })
+archive-project-last-live-project = 空间至少需要保留一个未归档的项目;请先恢复或新建一个
+archive-project-server-rejected = 服务器拒绝了归档该项目的请求
+archive-project-teardown-incomplete = 已归档,但部分远程会话未能关闭。重新连接后,取消归档再归档一次即可完成清理
menu-space-occupied = { $name }(已被占用)
menu-space-remote = { $name }(远程)
menu-new-space = 新建空间
diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs
index 08ef7af7..b84a56b4 100644
--- a/wezterm-gui/src/commands.rs
+++ b/wezterm-gui/src/commands.rs
@@ -1020,6 +1020,44 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
menubar: &[],
icon: Some("md_delete"),
},
+ ArchiveProject(_) => CommandDef {
+ brief: "Archive Workspace".into(),
+ doc: "Closes the workspace's panes and hides it from the sidebar; \
+ its threads and layouts are kept for unarchiving"
+ .into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
+ UnarchiveProject(_) => CommandDef {
+ brief: "Unarchive Workspace".into(),
+ doc: "Restores an archived workspace to the sidebar".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
+ ArchiveActiveProject => CommandDef {
+ brief: "Archive Active Workspace".into(),
+ doc: "Closes the active workspace's panes and hides it from the \
+ sidebar; its threads and layouts are kept for unarchiving"
+ .into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
+ ToggleShowArchivedProjects => CommandDef {
+ brief: "Show Archived Workspaces".into(),
+ doc: "Reveals archived workspaces at the bottom of the sidebar \
+ until toggled off or the window closes"
+ .into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &[],
+ icon: None,
+ },
ConnectWorkspaceThread(_) => CommandDef {
brief: "Connect Thread".into(),
doc: "Connects or reconnects the ThinkTerm remote thread".into(),
@@ -2275,6 +2313,8 @@ fn compute_default_actions() -> Vec<KeyAssignment> {
// ----------------- Shell
ToggleLiveOverview,
OpenSshHosts,
+ ArchiveActiveProject,
+ ToggleShowArchivedProjects,
SpawnTab(SpawnTabDomain::CurrentPaneDomain),
SpawnWindow,
SplitVertical(SpawnCommand {
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index e9038483..2ad5bf87 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -155,6 +155,22 @@ fn settings_window_pixel_size(
(width, height)
}
+/// "today" / "yesterday" / a local date, for the Archived list's second
+/// line. Recency is what the user reasons about there, so the two recent
+/// cases get words instead of a date they have to decode.
+fn format_archived_when(archived_at: i64) -> String {
+ let Some(when) = chrono::DateTime::from_timestamp(archived_at, 0) else {
+ return String::new();
+ };
+ let when = when.with_timezone(&chrono::Local).date_naive();
+ let today = chrono::Local::now().date_naive();
+ match (today - when).num_days() {
+ 0 => crate::i18n::tr("settings-archived-when-today"),
+ 1 => crate::i18n::tr("settings-archived-when-yesterday"),
+ _ => when.format("%Y-%m-%d").to_string(),
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SettingsSection {
General,
@@ -162,6 +178,7 @@ enum SettingsSection {
Terminal,
Workspaces,
Agents,
+ Archived,
Keymap,
Compatibility,
Developer,
@@ -176,6 +193,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[
SettingsSection::Terminal,
SettingsSection::Workspaces,
SettingsSection::Agents,
+ SettingsSection::Archived,
SettingsSection::Keymap,
SettingsSection::Compatibility,
SettingsSection::Developer,
@@ -185,10 +203,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[
const DEVELOPER_SECTIONS: &[SettingsSection] = &[SettingsSection::UiKit, SettingsSection::Memory];
/// The expandable per-agent explanation in the Integrations list.
-fn agent_detail_lines(
- agent_id: &str,
- kind: crate::agent_status::IntegrationKind,
-) -> Vec<String> {
+fn agent_detail_lines(agent_id: &str, kind: crate::agent_status::IntegrationKind) -> Vec<String> {
use crate::agent_status::IntegrationKind;
match kind {
IntegrationKind::ScreenRules => vec![
@@ -206,9 +221,7 @@ fn agent_detail_lines(
crate::i18n::tr("settings-agent-details-native"),
crate::i18n::tr("settings-agent-details-native-doc"),
],
- IntegrationKind::Pending => vec![
- crate::i18n::tr("settings-agent-details-pending"),
- ],
+ IntegrationKind::Pending => vec![crate::i18n::tr("settings-agent-details-pending")],
}
}
@@ -236,6 +249,7 @@ fn initial_section() -> SettingsSection {
"terminal" => SettingsSection::Terminal,
"workspaces" => SettingsSection::Workspaces,
"agents" => SettingsSection::Agents,
+ "archived" => SettingsSection::Archived,
"keymap" => SettingsSection::Keymap,
"compatibility" => SettingsSection::Compatibility,
"developer" => SettingsSection::Developer,
@@ -256,6 +270,7 @@ impl SettingsSection {
Self::Terminal => crate::i18n::tr("settings-section-terminal"),
Self::Workspaces => crate::i18n::tr("settings-section-workspaces"),
Self::Agents => crate::i18n::tr("settings-section-agents"),
+ Self::Archived => crate::i18n::tr("settings-section-archived"),
Self::Keymap => crate::i18n::tr("settings-section-keymap"),
Self::Compatibility => crate::i18n::tr("settings-section-compatibility"),
Self::Developer => crate::i18n::tr("settings-section-developer"),
@@ -272,6 +287,7 @@ impl SettingsSection {
Self::Terminal => SettingsIcon::Terminal,
Self::Workspaces => SettingsIcon::Workspaces,
Self::Agents => SettingsIcon::Agents,
+ Self::Archived => SettingsIcon::Archived,
Self::Keymap => SettingsIcon::Keymap,
Self::Compatibility => SettingsIcon::Sync,
Self::Developer => SettingsIcon::Developer,
@@ -350,6 +366,14 @@ impl SettingsSection {
"Cursor",
"Detection Rules",
],
+ Self::Archived => &[
+ "Archive",
+ "Archived",
+ "Unarchive",
+ "Restore",
+ "Hidden",
+ "Archived Workspaces",
+ ],
Self::Keymap => &["Keymap", "Keyboard", "Shortcut", "Command Palette"],
Self::Compatibility => &[
"ThinkTerm Config",
@@ -487,6 +511,9 @@ enum SettingsAction {
ToggleNotificationSounds,
ToggleAgentPanel,
ToggleAgentDetails(&'static str),
+ /// Index into the archived rows cached at paint time.
+ UnarchiveArchivedRow(usize),
+ DeleteArchivedRow(usize),
ToggleDeveloperMode,
ToggleFallbackContextMenu,
ShowOnboardingNow,
@@ -962,6 +989,12 @@ struct SettingsUiState {
memory_snapshot: Option<MemorySnapshot>,
main_window_resource_lines: Vec<String>,
memory_snapshot_copied_until: Option<Instant>,
+ /// The archived rows as last painted; row-action indices resolve here
+ /// so a click acts on exactly what the user saw.
+ archived_rows: Vec<crate::workspace_threads::ArchivedProjectRow>,
+ /// Two-step delete: the project id whose Delete button was clicked
+ /// once. A second click executes; any other action clears it.
+ confirm_delete_archived: Option<String>,
input_diagnostics_copied_until: Option<Instant>,
sidebar_scrollbar_visible_until: Option<Instant>,
content_scrollbar_visible_until: Option<Instant>,
@@ -993,6 +1026,8 @@ impl SettingsUiState {
memory_snapshot: None,
main_window_resource_lines: Vec::new(),
memory_snapshot_copied_until: None,
+ archived_rows: Vec::new(),
+ confirm_delete_archived: None,
input_diagnostics_copied_until: None,
sidebar_scrollbar_visible_until: None,
content_scrollbar_visible_until: None,
@@ -3345,6 +3380,48 @@ impl SettingsWindow {
}
}
}
+ SettingsAction::UnarchiveArchivedRow(index) => {
+ self.ui.open_dropdown = None;
+ self.ui.confirm_delete_archived = None;
+ if let Some(row) = self.ui.archived_rows.get(index).cloned() {
+ if crate::workspace_threads::unarchive_project(&row.id) {
+ let mut args = FluentArgs::new();
+ args.set("name", row.name.clone());
+ self.status = crate::i18n::tr_args("settings-archived-unarchived", &args);
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ front_end.invalidate_all_windows();
+ }
+ } else {
+ // The only refusal for a row that still exists is a
+ // detached remote domain.
+ self.status = crate::i18n::tr("settings-archived-remote-offline");
+ }
+ }
+ window.invalidate();
+ }
+ SettingsAction::DeleteArchivedRow(index) => {
+ self.ui.open_dropdown = None;
+ if let Some(row) = self.ui.archived_rows.get(index).cloned() {
+ if self.ui.confirm_delete_archived.as_deref() == Some(&row.id) {
+ self.ui.confirm_delete_archived = None;
+ if crate::workspace_threads::remove_project(&row.id).is_some() {
+ let mut args = FluentArgs::new();
+ args.set("name", row.name.clone());
+ self.status = crate::i18n::tr_args("settings-archived-deleted", &args);
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ front_end.invalidate_all_windows();
+ }
+ } else {
+ self.status = crate::i18n::tr("settings-archived-remote-offline");
+ }
+ } else {
+ // First click arms; the second one, on the relabeled
+ // button, deletes for good.
+ self.ui.confirm_delete_archived = Some(row.id.clone());
+ }
+ }
+ window.invalidate();
+ }
SettingsAction::ToggleAgentPanel => {
self.ui.open_dropdown = None;
self.native_settings.chrome.agent_panel_enabled =
@@ -4244,6 +4321,7 @@ impl SettingsWindow {
SettingsSection::Terminal => self.paint_terminal(layers, x, max_width)?,
SettingsSection::Workspaces => self.paint_workspaces(layers, x, max_width)?,
SettingsSection::Agents => self.paint_agents(layers, x, max_width)?,
+ SettingsSection::Archived => self.paint_archived(layers, x, max_width)?,
SettingsSection::Keymap => self.paint_placeholder(
layers,
&ui_font,
@@ -4522,6 +4600,200 @@ impl SettingsWindow {
Ok(())
}
+ fn paint_archived(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let scroll = self.ui.content_scroll.offset;
+ let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
+
+ // Snapshot the rows once per paint; the row-action indices the
+ // buttons register resolve against exactly this list.
+ let rows = crate::workspace_threads::archived_projects_overview();
+ if self
+ .ui
+ .confirm_delete_archived
+ .as_ref()
+ .is_some_and(|id| !rows.iter().any(|row| &row.id == id))
+ {
+ self.ui.confirm_delete_archived = None;
+ }
+ self.ui.archived_rows = rows.clone();
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ section_y,
+ &crate::i18n::tr("settings-archived-heading"),
+ palette.muted_text,
+ max_width,
+ )?;
+
+ let row_count = rows.len().max(1);
+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
+ let card_height = self.settings_card_height(row_count);
+ self.ui.content_scroll.set_extents(
+ self.content_viewport_extent(),
+ self.settings_content_extent(card_y + scroll + card_height),
+ );
+ self.paint_group_card(layers, x, card_y, max_width, card_height)?;
+
+ let padding = 36.0;
+ let row_x = x + padding;
+ let row_width = max_width - padding * 2.0;
+ let row_step = self.settings_row_step();
+
+ if rows.is_empty() {
+ let tile = self.settings_row_description_y(first_row_y) - first_row_y
+ + self.metrics.cell_size.height as f32;
+ let icon_gap = self.ui_px(12.0);
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ row_x,
+ first_row_y,
+ tile,
+ tile,
+ palette.control_bg,
+ palette.rule,
+ self.ui_px(8.0),
+ )?;
+ let mark = tile * 0.62;
+ self.draw_svg_icon(
+ layers,
+ SvgIcon::Archive,
+ row_x + (tile - mark) / 2.0,
+ first_row_y + (tile - mark) / 2.0,
+ mark,
+ palette.muted_text,
+ )?;
+ self.draw_text(
+ layers,
+ &ui_font,
+ row_x + tile + icon_gap,
+ first_row_y,
+ &crate::i18n::tr("settings-archived-empty"),
+ palette.muted_text,
+ row_width - tile - icon_gap,
+ )?;
+ return Ok(());
+ }
+
+ let delete_label = crate::i18n::tr("settings-archived-delete");
+ let confirm_label = crate::i18n::tr("settings-archived-delete-confirm");
+ let unarchive_label = crate::i18n::tr("settings-archived-unarchive");
+ // Wider than the usual control gap: these two do opposite things,
+ // and the destructive one must not read as adjacent-by-accident.
+ let button_gap = self.ui_px(18.0);
+ let unarchive_width = self.button_width_for_label(&unarchive_label, 0.0);
+
+ for (index, row) in rows.iter().enumerate() {
+ let y = first_row_y + row_step * index as f32;
+ // Same two-line shape as every other settings row: name on top,
+ // muted provenance underneath, controls right-aligned.
+ if index > 0 {
+ self.paint_separator(layers, row_x, y - self.ui_px(28.0), row_width)?;
+ }
+ // Each button is only as wide as the words it is showing --
+ // reserving room for the confirm label would leave "Delete"
+ // rattling around in an oversized frame. The group is anchored
+ // by its right edge, so arming grows the button leftward and
+ // that movement is itself the state feedback.
+ let delete_is_armed = self.ui.confirm_delete_archived.as_deref() == Some(&row.id);
+ let delete_label = if delete_is_armed {
+ &confirm_label
+ } else {
+ &delete_label
+ };
+ let delete_width = self.button_width_for_label(delete_label, 0.0);
+ let controls_x = row_x + row_width - (unarchive_width + button_gap + delete_width);
+ // Same leading-mark treatment as the Integrations rows: a
+ // rounded tile spanning the two-line block with the glyph
+ // centered at 62%. A bare icon sized to one text line reads as
+ // a speck beside a row this tall.
+ let tile =
+ self.settings_row_description_y(y) - y + self.metrics.cell_size.height as f32;
+ let icon_gap = self.ui_px(12.0);
+ self.draw_rounded_frame(
+ layers,
+ 0,
+ row_x,
+ y,
+ tile,
+ tile,
+ palette.control_bg,
+ palette.rule,
+ self.ui_px(8.0),
+ )?;
+ let mark = tile * 0.62;
+ self.draw_svg_icon(
+ layers,
+ if row.is_remote {
+ SvgIcon::Server
+ } else {
+ SvgIcon::Archive
+ },
+ row_x + (tile - mark) / 2.0,
+ y + (tile - mark) / 2.0,
+ mark,
+ palette.text,
+ )?;
+ let text_x = row_x + tile + icon_gap;
+ let text_width = (controls_x - text_x - self.ui_px(24.0)).max(row_width * 0.3);
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ text_x,
+ y,
+ &row.name,
+ palette.text,
+ text_width,
+ )?;
+
+ let mut meta_args = FluentArgs::new();
+ meta_args.set("space", row.space_name.clone());
+ meta_args.set("threads", row.thread_count as i64);
+ meta_args.set("when", format_archived_when(row.archived_at));
+ self.draw_text(
+ layers,
+ &ui_font,
+ text_x,
+ self.settings_row_description_y(y),
+ &crate::i18n::tr_args("settings-archived-meta", &meta_args),
+ palette.secondary_text,
+ text_width,
+ )?;
+
+ // Centered on the two-line block, not top-aligned to the first
+ // line: the tile defines the row's visual height here, and a
+ // top-biased control reads as misaligned against it.
+ let control_y = y + (tile - self.ui_px(CONTROL_HEIGHT)) / 2.0;
+ self.draw_button(
+ layers,
+ controls_x,
+ control_y,
+ unarchive_width,
+ &unarchive_label,
+ SettingsAction::UnarchiveArchivedRow(index),
+ )?;
+ self.draw_button(
+ layers,
+ controls_x + unarchive_width + button_gap,
+ control_y,
+ delete_width,
+ delete_label,
+ SettingsAction::DeleteArchivedRow(index),
+ )?;
+ }
+ Ok(())
+ }
+
fn paint_workspaces(
&mut self,
layers: &mut TripleLayerQuadAllocator<'_>,
@@ -4701,8 +4973,7 @@ impl SettingsWindow {
})
.unwrap_or(0.0);
let integrations_title_y = card_y + card_height + self.settings_section_card_gap();
- let integrations_card_y =
- integrations_title_y + self.settings_section_card_gap().min(54.0);
+ let integrations_card_y = integrations_title_y + self.settings_section_card_gap().min(54.0);
let integrations_first_row_y = integrations_card_y + self.settings_card_top_padding();
let mut integrations_card_height =
self.settings_card_height(integrations_row_count) + expanded_extra;
@@ -4778,18 +5049,11 @@ impl SettingsWindow {
for (agent_id, _names, kind) in crate::agent_status::SUPPORTED_AGENTS {
let expanded = self.agents_expanded == Some(*agent_id);
let arrow = if expanded { "\u{25be}" } else { "\u{25b8}" };
- let label = format!(
- "{arrow} {}",
- crate::agent_status::display_name(agent_id)
- );
+ let label = format!("{arrow} {}", crate::agent_status::display_name(agent_id));
let on_path = crate::agent_status::agent_on_path(agent_id);
let description = match kind {
- IntegrationKind::Native => {
- crate::i18n::tr("settings-integration-native")
- }
- IntegrationKind::Pending => {
- crate::i18n::tr("settings-integration-pending")
- }
+ IntegrationKind::Native => crate::i18n::tr("settings-integration-native"),
+ IntegrationKind::Pending => crate::i18n::tr("settings-integration-pending"),
IntegrationKind::ScreenRules if on_path => {
crate::i18n::tr("settings-integration-screen-active")
}
@@ -4801,12 +5065,7 @@ impl SettingsWindow {
// the detail block, so the rule would cut across its card; the
// frame itself already separates.
if draw_top_rule && !prev_expanded {
- self.paint_separator(
- layers,
- row_x,
- row_y - self.ui_px(28.0),
- row_width,
- )?;
+ self.paint_separator(layers, row_x, row_y - self.ui_px(28.0), row_width)?;
}
// The brand mark leads the row; agents without a logo (and the
// expand arrow) still line up because the text column starts
@@ -4847,14 +5106,9 @@ impl SettingsWindow {
Some(crate::agent_status::AgentIcon::Mono(icon)) => {
self.draw_svg_icon(layers, icon, mark_x, mark_y, mark, palette.text)?
}
- None => self.draw_svg_icon(
- layers,
- SvgIcon::Bot,
- mark_x,
- mark_y,
- mark,
- palette.text,
- )?,
+ None => {
+ self.draw_svg_icon(layers, SvgIcon::Bot, mark_x, mark_y, mark, palette.text)?
+ }
}
self.draw_text(
layers,
@@ -4875,12 +5129,7 @@ impl SettingsWindow {
text_width,
)?;
self.ui_context.push(
- rect(
- row_x,
- row_y - self.ui_px(6.0),
- row_width,
- self.ui_px(56.0),
- ),
+ rect(row_x, row_y - self.ui_px(6.0), row_width, self.ui_px(56.0)),
crate::ui::WidgetKind::Button,
SettingsAction::ToggleAgentDetails(agent_id),
);
@@ -7890,14 +8139,21 @@ impl SettingsWindow {
border,
self.ui_px(CONTROL_RADIUS),
)?;
+ // Center the label in the frame. A fixed left inset left every
+ // button's text biased toward the left edge -- button_width_for_label
+ // adds 44px of padding, so a 14px inset left 30px on the right --
+ // which is most visible on short labels in a wide frame.
+ let font = Rc::clone(&self.ui_font);
+ let label_width = self.measure_text_width(&font, button.label);
+ let text_x = x + ((width - label_width) / 2.0).max(self.ui_px(12.0));
self.draw_text(
layers,
- &Rc::clone(&self.ui_font),
- x + self.ui_px(14.0),
+ &font,
+ text_x,
self.control_text_y(y, self.ui_px(CONTROL_HEIGHT)),
button.label,
palette.text,
- width - self.ui_px(36.0),
+ (x + width - self.ui_px(12.0) - text_x).max(0.0),
)?;
Ok(())
}
@@ -8343,12 +8599,7 @@ impl SettingsWindow {
/// Greedy word wrap against the shaped width; falls back to char-level
/// breaking for unspaced (CJK) text or overlong tokens.
- fn wrap_settings_text(
- &self,
- font: &Rc<LoadedFont>,
- text: &str,
- max_width: f32,
- ) -> Vec<String> {
+ fn wrap_settings_text(&self, font: &Rc<LoadedFont>, text: &str, max_width: f32) -> Vec<String> {
let mut lines = Vec::new();
let mut current = String::new();
let push_wrapped_word = |word: &str, current: &mut String, lines: &mut Vec<String>| {
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index d9547d95..e3429e90 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -446,6 +446,8 @@ pub(crate) enum ContextMenuApplicationAction {
},
/// Sidebar view-options: show/hide threads with this work status.
ToggleWorkspaceStatusFilter(crate::workspace_threads::WorkspaceThreadWorkStatus),
+ /// Sidebar view-options: transiently reveal archived projects.
+ ToggleWorkspaceShowArchived,
/// Add a thread reference to a Space (local, non-home, not already
/// holding it — the menu only offers eligible targets).
AddThreadToCollection {
@@ -549,6 +551,10 @@ pub enum UIItemType {
/// the current Space. Payload is the group key (origin project id).
ThreadRefGroupNewThread(String),
Project(String),
+ /// A revealed archived project row: inert except for its context menu,
+ /// so it stays invisible to the drag, rename and reorder paths that
+ /// match on `Project`.
+ ArchivedProject(String),
WorkspaceThread(String),
WorkspaceThreadPin(String),
WorkspaceThreadDelete(String),
@@ -1940,6 +1946,10 @@ pub struct TermWindow {
/// collapse state resets
/// with the window, like a disclosure and unlike project collapse.
thread_ref_groups_collapsed: std::collections::HashSet<String>,
+ /// Transient reveal of archived projects in the sidebar. Deliberately
+ /// NOT persisted: "archived" means hidden, and a setting left on would
+ /// quietly un-implement the feature. Resets with the window.
+ pub(crate) workspace_sidebar_show_archived: bool,
/// A native (AppKit) context menu is open. The fallback menu tracks
/// itself in `context_menu`; the native path otherwise leaves no trace,
/// and the hover machine must not retreat the panel a menu is anchored
@@ -2907,6 +2917,7 @@ impl TermWindow {
workspace_sidebar_hover: sidebar_hover::SidebarHoverReveal::default(),
titlebar_sidebar_button_hovered: false,
thread_ref_groups_collapsed: std::collections::HashSet::new(),
+ workspace_sidebar_show_archived: false,
native_context_menu_open: false,
workspace_notification_snapshot: None,
workspace_notification_pulse_started_at: None,
@@ -4516,6 +4527,112 @@ impl TermWindow {
self.start_delete_space(space_id, removal, false);
}
+ /// Archive a project off the sidebar: snapshot the on-screen layout,
+ /// close the project's panes (remote ones die on the server first), and
+ /// land the window on the next live project. Async because the remote
+ /// path must await pane kills and the server's verdict.
+ pub(crate) fn start_archive_project(&mut self, project_id: &str) {
+ // The workspace currently on screen deserves a fresh snapshot so
+ // unarchiving restores what the user last saw, not an older save.
+ self.snapshot_active_workspace_thread_layout();
+ let project_id = project_id.to_string();
+ let gui_window = self.window.clone();
+ promise::spawn::spawn_into_main_thread(async move {
+ let result = crate::workspace_threads::archive_project(&project_id).await;
+ if let Some(gui_window) = gui_window {
+ gui_window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.finish_archive_project(result);
+ })));
+ }
+ })
+ .detach();
+ }
+
+ fn finish_archive_project(
+ &mut self,
+ result: Result<
+ crate::workspace_threads::ArchivedProject,
+ crate::workspace_threads::ArchiveProjectError,
+ >,
+ ) {
+ let window = self.window.clone();
+ match result {
+ Ok(archived) => {
+ let cleanup_workspaces = archived.materialized_workspace_names;
+ if archived.was_active {
+ if let (Some(next_thread_id), Some(window)) =
+ (archived.next_thread_id.clone(), window.as_ref())
+ {
+ // The successor may still need materializing, in
+ // which case adoption is deferred -- killing the
+ // workspaces synchronously here would take down this
+ // window's own mux window. Route the cleanup through
+ // the activation, like finish_removed_project does.
+ self.activate_workspace_thread_with_cleanup(
+ next_thread_id,
+ window,
+ cleanup_workspaces,
+ );
+ return;
+ }
+ }
+ // Local mirrors of the archived workspaces; remote panes are
+ // already gone by the time the store call returns, so any
+ // mirror still present must not send a duplicate KillPane
+ // while its window is torn down.
+ let mux = Mux::get();
+ for workspace in cleanup_workspaces {
+ 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>()
+ {
+ client.ignore_next_kill();
+ }
+ }
+ mux.kill_window(window_id);
+ }
+ }
+ }
+ Err(err) => {
+ let text = match err {
+ crate::workspace_threads::ArchiveProjectError::LastLiveProject => {
+ crate::i18n::tr("archive-project-last-live-project")
+ }
+ crate::workspace_threads::ArchiveProjectError::ServerRejected => {
+ crate::i18n::tr("archive-project-server-rejected")
+ }
+ crate::workspace_threads::ArchiveProjectError::TeardownIncomplete => {
+ crate::i18n::tr("archive-project-teardown-incomplete")
+ }
+ // RemoteUnavailable already raised its own toast via
+ // notify_remote_tree_mutation_unavailable; the rest are
+ // benign races (row already gone / already archived).
+ _ => {
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ return;
+ }
+ };
+ log::error!("archive project failed: {text}");
+ wezterm_toast_notification::persistent_toast_notification("ThinkTerm", &text);
+ }
+ }
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
+
pub(crate) fn start_delete_space(
&mut self,
space_id: &str,
@@ -7276,6 +7393,28 @@ impl TermWindow {
}
}
}
+ ArchiveProject(project_id) => {
+ self.start_archive_project(project_id);
+ }
+ UnarchiveProject(project_id) => {
+ crate::workspace_threads::unarchive_project(project_id);
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
+ ArchiveActiveProject => {
+ if let Some(project_id) = crate::workspace_threads::active_project_id_for_space(
+ self.workspace_sidebar_space_id(),
+ ) {
+ self.start_archive_project(&project_id);
+ }
+ }
+ ToggleShowArchivedProjects => {
+ self.workspace_sidebar_show_archived = !self.workspace_sidebar_show_archived;
+ if let Some(window) = window.as_ref() {
+ window.invalidate();
+ }
+ }
ConnectWorkspaceThread(thread_id) => {
if let Some(window) = window.as_ref() {
self.connect_remote_thread(thread_id.clone(), window);
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index d6a99bf2..75fa704f 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1400,6 +1400,7 @@ impl super::TermWindow {
| UIItemType::ThreadRefGroupToggle { .. }
| UIItemType::ThreadRefGroupNewThread(_)
| UIItemType::Project(_)
+ | UIItemType::ArchivedProject(_)
| UIItemType::WorkspaceThread(_)
| UIItemType::WorkspaceThreadPin(_)
| UIItemType::WorkspaceThreadDelete(_)
@@ -1513,6 +1514,7 @@ impl super::TermWindow {
| UIItemType::ThreadRefGroupToggle { .. }
| UIItemType::ThreadRefGroupNewThread(_)
| UIItemType::Project(_)
+ | UIItemType::ArchivedProject(_)
| UIItemType::WorkspaceThread(_)
| UIItemType::WorkspaceThreadPin(_)
| UIItemType::WorkspaceThreadDelete(_)
@@ -3487,6 +3489,10 @@ impl super::TermWindow {
let project_id = project_id.clone();
self.mouse_event_project(item, project_id, event, context);
}
+ UIItemType::ArchivedProject(ref project_id) => {
+ let project_id = project_id.clone();
+ self.mouse_event_archived_project(project_id, event, context);
+ }
UIItemType::WorkspaceThread(ref thread_id) => {
let thread_id = thread_id.clone();
self.mouse_event_workspace_thread(item, thread_id, event, context);
@@ -4010,6 +4016,10 @@ impl super::TermWindow {
let project_id = project_id.clone();
self.mouse_event_project(item, project_id, event, context);
}
+ UIItemType::ArchivedProject(ref project_id) => {
+ let project_id = project_id.clone();
+ self.mouse_event_archived_project(project_id, event, context);
+ }
UIItemType::WorkspaceThread(ref thread_id) => {
let thread_id = thread_id.clone();
self.mouse_event_workspace_thread(item, thread_id, event, context);
@@ -4871,6 +4881,21 @@ impl super::TermWindow {
}
}
+ /// A revealed archived row is inert on purpose: the only ways out are
+ /// the explicit menu items, so a stray click cannot half-restore it.
+ pub fn mouse_event_archived_project(
+ &mut self,
+ project_id: String,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::Arrow));
+ if let WMEK::Press(MousePress::Right) = event.kind {
+ let items = self.archived_project_context_menu_items(&project_id);
+ self.show_term_context_menu(context, event.coords, items);
+ }
+ }
+
pub fn mouse_event_project(
&mut self,
item: UIItem,
@@ -5162,6 +5187,50 @@ impl super::TermWindow {
KeyAssignment::ToggleWorkspaceThreadsCollapsed(project_id.clone()),
),
ContextMenuItem::Separator,
+ {
+ // The only unrecoverable part of archiving is killing live
+ // panes, so the second-gesture gate (the submenu standing in
+ // for a confirm dialog, like Space delete's) appears only
+ // when panes would actually die. A quiet project archives in
+ // one click -- unarchiving is lossless.
+ let mux = Mux::get();
+ let live_panes: usize =
+ crate::workspace_threads::materialized_workspace_names_for_project(&project_id)
+ .iter()
+ .flat_map(|workspace| mux.iter_windows_in_workspace(workspace))
+ .filter_map(|window_id| mux.get_window(window_id))
+ .flat_map(|window| {
+ window
+ .iter()
+ .map(|tab| tab.iter_all_panes().len())
+ .collect::<Vec<_>>()
+ })
+ .sum();
+ if live_panes == 0 {
+ ContextMenuItem::item_with_icon(
+ crate::i18n::tr("menu-archive-project-quiet"),
+ ContextMenuIcon::Archive,
+ KeyAssignment::ArchiveProject(project_id.clone()),
+ )
+ } else {
+ ContextMenuItem::submenu_with_icon(
+ crate::i18n::tr("menu-archive-project"),
+ ContextMenuIcon::Archive,
+ vec![
+ ContextMenuItem::section_header({
+ let mut args = FluentArgs::new();
+ args.set("panes", live_panes as i64);
+ crate::i18n::tr_args("menu-archive-project-explain", &args)
+ }),
+ ContextMenuItem::item_with_icon(
+ crate::i18n::tr("menu-archive-project-confirm"),
+ ContextMenuIcon::Archive,
+ KeyAssignment::ArchiveProject(project_id.clone()),
+ ),
+ ],
+ )
+ }
+ },
ContextMenuItem::item_with_icon(
crate::i18n::tr("menu-remove-project"),
ContextMenuIcon::FolderRemove,
@@ -5170,6 +5239,39 @@ impl super::TermWindow {
]
}
+ /// The menu for a revealed archived row: restore it, or delete it for
+ /// good through the same second-gesture gate the live menu uses.
+ fn archived_project_context_menu_items(&self, project_id: &str) -> Vec<ContextMenuItem> {
+ let project_id = project_id.to_string();
+ vec![
+ ContextMenuItem::item_with_icon(
+ crate::i18n::tr("menu-unarchive-project"),
+ ContextMenuIcon::ArchiveRestore,
+ KeyAssignment::UnarchiveProject(project_id.clone()),
+ ),
+ ContextMenuItem::Separator,
+ ContextMenuItem::submenu_with_icon(
+ crate::i18n::tr("menu-delete-project-permanently"),
+ ContextMenuIcon::Delete,
+ vec![
+ ContextMenuItem::section_header({
+ let mut args = FluentArgs::new();
+ args.set(
+ "threads",
+ crate::workspace_threads::ordered_thread_ids(&project_id).len() as i64,
+ );
+ crate::i18n::tr_args("menu-delete-project-permanently-explain", &args)
+ }),
+ ContextMenuItem::item_with_icon(
+ crate::i18n::tr("menu-delete-project-permanently-confirm"),
+ ContextMenuIcon::Delete,
+ KeyAssignment::RemoveProject(project_id),
+ ),
+ ],
+ ),
+ ]
+ }
+
/// One row per Space, grouped by the server hosting it.
///
/// A remote server is a *connection*, not a Space: it can host several, and
@@ -5391,6 +5493,28 @@ impl super::TermWindow {
ContextMenuIcon::Check,
status_items,
),
+ {
+ let archived_count = crate::workspace_threads::archived_project_count(
+ self.workspace_sidebar_space_id(),
+ );
+ let label = if archived_count > 0 {
+ let mut args = FluentArgs::new();
+ args.set("count", archived_count as i64);
+ crate::i18n::tr_args("menu-show-archived-count", &args)
+ } else {
+ crate::i18n::tr("menu-show-archived")
+ };
+ // Disabled at zero -- an inert toggle would look broken --
+ // but never while the reveal is on, or the flag could latch
+ // with no way to untoggle it.
+ self.context_menu_application_item_with_icon(
+ label,
+ ContextMenuIcon::Archive,
+ crate::termwindow::ContextMenuApplicationAction::ToggleWorkspaceShowArchived,
+ archived_count > 0 || self.workspace_sidebar_show_archived,
+ )
+ .checked(self.workspace_sidebar_show_archived)
+ },
]
}
@@ -5732,7 +5856,7 @@ impl super::TermWindow {
self.activate_workspace_thread_impl(thread_id, context, None, Vec::new());
}
- fn activate_workspace_thread_with_cleanup(
+ pub(crate) fn activate_workspace_thread_with_cleanup(
&mut self,
thread_id: String,
context: &dyn WindowOps,
@@ -6130,10 +6254,7 @@ impl super::TermWindow {
if via_thread_ref {
// Remember the choice so switching back to this Space restores
// the reference, like a normal Space restores its active thread.
- crate::workspace_threads::note_thread_active_ref(
- &self.active_space_id,
- &thread_id,
- );
+ crate::workspace_threads::note_thread_active_ref(&self.active_space_id, &thread_id);
} else {
// Activating one of the Space's own threads means the next
// switch back should follow the normal pointers, not jump to a
diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rs
index 34a8df79..ce8180e3 100644
--- a/wezterm-gui/src/termwindow/ui/context_menu.rs
+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs
@@ -255,6 +255,10 @@ impl crate::TermWindow {
) => {
self.toggle_workspace_sidebar_status_filter(status);
}
+ crate::termwindow::ContextMenuApplicationAction::ToggleWorkspaceShowArchived => {
+ self.workspace_sidebar_show_archived = !self.workspace_sidebar_show_archived;
+ self.invalidate_window();
+ }
crate::termwindow::ContextMenuApplicationAction::AddThreadToCollection {
collection_space_id,
thread_id,
@@ -295,11 +299,9 @@ impl crate::TermWindow {
if let Some(window) = self.window.clone() {
match outcome.next_thread_id {
Some(next) => {
- if !self
- .open_remote_workspace_thread_without_connecting(
- &next, &window,
- )
- {
+ if !self.open_remote_workspace_thread_without_connecting(
+ &next, &window,
+ ) {
self.activate_workspace_thread(next, &window);
}
}
@@ -1094,6 +1096,8 @@ fn context_menu_palette(appearance: Appearance) -> UiPalette {
fn menu_icon(icon: &ContextMenuIcon) -> Option<SvgIcon> {
match icon {
ContextMenuIcon::Application | ContextMenuIcon::ExternalLink => Some(SvgIcon::ExternalLink),
+ ContextMenuIcon::Archive => Some(SvgIcon::Archive),
+ ContextMenuIcon::ArchiveRestore => Some(SvgIcon::ArchiveRestore),
ContextMenuIcon::Back | ContextMenuIcon::MoveLeft => Some(SvgIcon::ArrowLeft),
ContextMenuIcon::Check => Some(SvgIcon::CircleCheck),
ContextMenuIcon::Close => Some(SvgIcon::X),
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index 665ed58b..4b194bab 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -5,6 +5,7 @@ use window::Image;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SvgIcon {
Archive,
+ ArchiveRestore,
ArrowLeft,
ArrowRight,
Bell,
@@ -95,6 +96,9 @@ impl SvgIcon {
pub fn bytes(self) -> &'static [u8] {
match self {
Self::Archive => include_bytes!("../../../../third_party/lucide/icons/archive.svg"),
+ Self::ArchiveRestore => {
+ include_bytes!("../../../../third_party/lucide/icons/archive-restore.svg")
+ }
Self::ArrowLeft => {
include_bytes!("../../../../third_party/lucide/icons/arrow-left.svg")
}
@@ -566,6 +570,7 @@ mod tests {
fn svg_icons_rasterize() {
for icon in [
SvgIcon::Archive,
+ SvgIcon::ArchiveRestore,
SvgIcon::ArrowLeft,
SvgIcon::Bell,
SvgIcon::Braces,
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index 9eabf4a4..83808ffc 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -35,12 +35,11 @@ use crate::termwindow::ui::tokens::{
use crate::termwindow::{
NoteEditorCommand, PendingLocalCopy, PendingRemoteConfirm, RightSidebarFileCharBag,
RightSidebarFileDirCache, RightSidebarFileDirEntry, RightSidebarFileField,
- RightSidebarFileIndex, RightSidebarFileIndexEntry,
- RightSidebarFileIndexStatus, RightSidebarFilePreviewImage, RightSidebarFilePreviewLine,
- RightSidebarFilePreviewSelection, RightSidebarFilePreviewSelectionPoint,
- RightSidebarFilePreviewSliceCacheKey, RightSidebarFilePreviewSliceCacheValue,
- RightSidebarFilePreviewSpan, RightSidebarFileTreeRow, RightSidebarFileView,
- RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,
+ RightSidebarFileIndex, RightSidebarFileIndexEntry, RightSidebarFileIndexStatus,
+ RightSidebarFilePreviewImage, RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,
+ RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSliceCacheKey,
+ RightSidebarFilePreviewSliceCacheValue, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,
+ RightSidebarFileView, RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,
RightSidebarNoteImageSource, RightSidebarNoteTableLayout, RightSidebarNoteView,
RightSidebarOpenWithCacheEntry, RightSidebarSnippetField, RightSidebarSnippetView,
TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup,
@@ -51,6 +50,7 @@ use crate::workspace_threads;
use anyhow::Context;
use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource, KeyAssignment};
use fluent_bundle::FluentArgs;
+use ignore::{DirEntry as IgnoreDirEntry, WalkBuilder};
use mux::pane::{Pane, PaneId};
use mux::Mux;
use std::borrow::Cow;
@@ -68,7 +68,6 @@ use termwiz::image::{ImageData, ImageDataType};
use termwiz::input::{KeyCode as TermKeyCode, Modifiers as TermModifiers};
use thinkterm_syntax::{HighlightKind, HighlightResult, HighlightSpan, LanguageId};
use unicode_segmentation::UnicodeSegmentation;
-use ignore::{DirEntry as IgnoreDirEntry, WalkBuilder};
use wezterm_font::LoadedFont;
use window::color::LinearRgba;
use window::{
@@ -3051,7 +3050,10 @@ impl crate::TermWindow {
fn spawn_right_sidebar_dir_reads(&mut self, dirs: Vec<PathBuf>) {
let dirs: Vec<PathBuf> = dirs
.into_iter()
- .filter(|dir| self.right_sidebar_file_dir_loads_in_flight.insert(dir.clone()))
+ .filter(|dir| {
+ self.right_sidebar_file_dir_loads_in_flight
+ .insert(dir.clone())
+ })
.collect();
if dirs.is_empty() {
return;
@@ -4691,12 +4693,15 @@ impl crate::TermWindow {
visual: &Arc<VisualDocument>,
fonts: NotePrewarmFonts,
) {
- let same_target = self.right_sidebar_note_prewarm.as_ref().is_some_and(|state| {
- state.visual.as_ptr() == Arc::as_ptr(visual)
+ let same_target = self
+ .right_sidebar_note_prewarm
+ .as_ref()
+ .is_some_and(|state| {
+ state.visual.as_ptr() == Arc::as_ptr(visual)
// A config/appearance change mints new LoadedFonts (new ids,
// new cache keys); restart so the warm entries match paint.
&& Rc::ptr_eq(&state.fonts.ui.0, &fonts.ui.0)
- });
+ });
if !same_target {
self.right_sidebar_note_prewarm = Some(NotePrewarmState {
visual: Arc::downgrade(visual),
@@ -4748,7 +4753,12 @@ impl crate::TermWindow {
self.right_sidebar_note_prewarm = None;
return;
};
- (visual, state.fonts.clone(), state.next_line, state.shaped_runs)
+ (
+ visual,
+ state.fonts.clone(),
+ state.next_line,
+ state.shaped_runs,
+ )
};
if self.render_state.is_none() {
// No GPU state to rasterize into yet; the next paint re-arms us.
@@ -10157,8 +10167,12 @@ impl crate::TermWindow {
.current_mux_workspace()
.unwrap_or_else(|| mux.active_workspace());
let workspaces = mux.iter_workspaces();
- let view =
- workspace_threads::view_for_current_project(&space_id, &active_workspace, &workspaces);
+ let view = workspace_threads::view_for_current_project(
+ &space_id,
+ &active_workspace,
+ &workspaces,
+ false,
+ );
let project = view
.projects
.iter()
@@ -13365,8 +13379,12 @@ impl crate::TermWindow {
.current_mux_workspace()
.unwrap_or_else(|| mux.active_workspace());
let workspaces = mux.iter_workspaces();
- let view =
- workspace_threads::view_for_current_project(&space_id, &active_workspace, &workspaces);
+ let view = workspace_threads::view_for_current_project(
+ &space_id,
+ &active_workspace,
+ &workspaces,
+ false,
+ );
let project = view
.projects
.iter()
@@ -13584,8 +13602,7 @@ impl crate::TermWindow {
// Whether anything below the list needs protecting from overflow.
// Decides both the bottom mask and how far row chrome may extend:
// unprotected, rows run to the window edge and are cut there.
- let masked_below =
- strip_rows > 0 || (self.show_tab_bar && self.config.tab_bar_at_bottom);
+ let masked_below = strip_rows > 0 || (self.show_tab_bar && self.config.tab_bar_at_bottom);
let row_clip_bottom = if masked_below {
viewport_bottom
} else {
@@ -16711,7 +16728,9 @@ fn preview_visible_line_range(
start..end
}
-pub(crate) fn right_sidebar_file_row_metrics(ui_metrics: RenderMetrics) -> RightSidebarFileRowMetrics {
+pub(crate) fn right_sidebar_file_row_metrics(
+ ui_metrics: RenderMetrics,
+) -> RightSidebarFileRowMetrics {
// Font metrics already follow the window DPI. Derive the row chrome from
// those metrics so the file tree keeps the same logical size across
// displays instead of being pinned by physical-pixel clamps.
@@ -18710,20 +18729,20 @@ mod tests {
copy_entries_blocking, copy_file_chunked, download_name_candidates,
encode_pasted_image_png, failed_folder_download, file_preview_close_requires_reflow,
file_release_action, file_row_placement, full_line_colors_by_byte,
- sidebar_row_element_visible,
- image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,
- naturalish_cmp, note_code_highlight_key, note_code_highlight_lines, note_code_row_height,
- note_image_display_size, note_open_pending_for_vault, note_release_action,
- open_with_candidate_allowed, pasted_image_file_name, path_key, pick_free_remote_name,
- preflight_local_copy, preview_line_count, preview_lines_from_text,
- preview_plain_lines_from_text, preview_text_range, preview_visible_colored,
- preview_visible_line_range, remote_lease_failure_disposition, resolve_drop_destination,
- load_dir_cache_for_test, rescan_plan, resolve_local_drop_target, resolve_remote_drop_target,
+ image_pixels_within_preview_budget, load_dir_cache_for_test, load_file_preview,
+ load_file_preview_image, naturalish_cmp, note_code_highlight_key,
+ note_code_highlight_lines, note_code_row_height, note_image_display_size,
+ note_open_pending_for_vault, note_release_action, open_with_candidate_allowed,
+ pasted_image_file_name, path_key, pick_free_remote_name, preflight_local_copy,
+ preview_line_count, preview_lines_from_text, preview_plain_lines_from_text,
+ preview_text_range, preview_visible_colored, preview_visible_line_range,
+ remote_lease_failure_disposition, rescan_plan, resolve_drop_destination,
+ resolve_local_drop_target, resolve_remote_drop_target,
right_sidebar_file_browse_rows_from_dir_cache, right_sidebar_file_row_metrics,
right_sidebar_open_with_cache_key, sanitize_preview_text, scrollable_note_table_columns,
- search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,
- sorted_open_with_candidates, spawn_pasted_image_staging, stage_pasted_image,
- terminal_paste_snapshot_mismatch, virtual_note_line_range,
+ search_right_sidebar_file_index, sidebar_row_element_visible, snippet_cursor_visible,
+ snippet_run_buffer, sorted_open_with_candidates, spawn_pasted_image_staging,
+ stage_pasted_image, terminal_paste_snapshot_mismatch, virtual_note_line_range,
visible_code_block_rounded_edges, visible_file_row_range, wrap_snippet_text_for_width,
FileReleaseAction, FileRowPlacement, NoteApproximateTextMetrics, NoteCodeHighlightEntry,
NoteCodeHighlightState, NoteReleaseAction, RemoteLeaseFailureDisposition,
@@ -20146,11 +20165,17 @@ mod tests {
// mask). Elements are 30 tall.
let vis = |y| sidebar_row_element_visible(y, 30, 100, 160, 440);
assert!(vis(160), "fully inside");
- assert!(vis(140), "half out of the top -- drawn, then cut by the mask");
+ assert!(
+ vis(140),
+ "half out of the top -- drawn, then cut by the mask"
+ );
assert!(vis(131), "one pixel of it still below list_top");
assert!(!vis(130), "entirely above the list: nothing to show");
assert!(vis(399), "half out of the bottom -- drawn, then cut");
- assert!(vis(410), "wholly inside the bottom mask, still safe to draw");
+ assert!(
+ vis(410),
+ "wholly inside the bottom mask, still safe to draw"
+ );
assert!(!vis(411), "would cross the panel edge and escape the mask");
assert!(!vis(99), "would escape above the top mask");
}
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index 431bc265..3870502b 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -869,6 +869,7 @@ impl crate::TermWindow {
self.workspace_sidebar_space_id(),
&active_workspace,
&workspaces,
+ self.workspace_sidebar_show_archived,
));
let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
let total_height = Self::workspace_sidebar_scroll_height(
@@ -929,6 +930,7 @@ impl crate::TermWindow {
self.workspace_sidebar_space_id(),
&active_workspace,
&workspaces,
+ self.workspace_sidebar_show_archived,
));
let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
let total_height = Self::workspace_sidebar_scroll_height(
@@ -1165,6 +1167,7 @@ impl crate::TermWindow {
self.workspace_sidebar_space_id(),
&active_workspace,
&workspaces,
+ self.workspace_sidebar_show_archived,
));
// A ref row is showing its workspace: the Space's own rows must not
// paint a second active highlight from their stale pointer.
@@ -1927,6 +1930,45 @@ impl crate::TermWindow {
.saturating_sub(project_action_size + self.ui_px(SIDEBAR_INSET));
let project_text_right = project_action_x;
+ if project.is_archived {
+ // A revealed archived row: dimmed, inert, no chevron and
+ // no "+" button. Its own UIItemType keeps it invisible
+ // to drag targeting, inline rename and folder reorder.
+ if row_is_visible {
+ self.ui_items.push(UIItem {
+ x: item_x,
+ y: hit_y,
+ width: item_width,
+ height: hit_height,
+ item_type: UIItemType::ArchivedProject(project.id.clone()),
+ });
+ let icon_y = y + ((session_row_height.saturating_sub(icon_size)) / 2);
+ let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::Archive,
+ project_icon_x,
+ icon_y,
+ icon_size,
+ muted_fg,
+ )?;
+ let project_title = self.sidebar_project_title(&project.id, &project.name);
+ self.paint_sidebar_text(
+ layers,
+ &ui_font,
+ ui_metrics,
+ &project_title,
+ project_text_x,
+ text_y,
+ project_text_right
+ .saturating_sub(project_text_x + self.ui_px(SIDEBAR_INSET)),
+ muted_fg,
+ )?;
+ }
+ virtual_y += session_row_height + row_gap;
+ continue;
+ }
+
if row_is_visible {
self.ui_items.push(UIItem {
x: item_x,
diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rs
index 6564eca1..4206d891 100644
--- a/wezterm-gui/src/ui/icons.rs
+++ b/wezterm-gui/src/ui/icons.rs
@@ -13,6 +13,7 @@ pub(crate) enum SettingsIcon {
UiKit,
Memory,
About,
+ Archived,
Search,
Clear,
External,
@@ -32,6 +33,7 @@ impl SettingsIcon {
Self::UiKit => SvgIcon::SlidersVertical,
Self::Memory => SvgIcon::MemoryStick,
Self::About => SvgIcon::Info,
+ Self::Archived => SvgIcon::Archive,
Self::Search => SvgIcon::Search,
Self::Clear => SvgIcon::X,
Self::External => SvgIcon::ExternalLink,
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index ad93fb6e..0946e4ec 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -151,6 +151,12 @@ pub struct Project {
/// active notes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active_note_path: Option<String>,
+ /// When this project was archived, or `None` while it is live. A
+ /// timestamp, not a bool: it sorts the archived list, and it can never
+ /// be confused with the retired thread-level `archived` flag that
+ /// `drop_legacy_archived_threads` still deletes on load.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub archived_at: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -285,6 +291,27 @@ impl WorkspaceThreadsView {
self.display_order = merged_display_order(folder_order, &project_keys, &group_keys);
}
+ /// Move archived projects to the tail of `display_order`, newest
+ /// archive first, keeping every other folder in place. The Space's
+ /// persisted `folder_order` predates archiving and would otherwise
+ /// interleave archived rows back among the live ones.
+ pub fn partition_archived_last(&mut self) {
+ let order = std::mem::take(&mut self.display_order);
+ let (live, mut archived): (Vec<SidebarFolder>, Vec<SidebarFolder>) =
+ order.into_iter().partition(|folder| match folder {
+ SidebarFolder::Project(index) => !self.projects[*index].is_archived,
+ SidebarFolder::RefGroup(_) => true,
+ });
+ archived.sort_by_key(|folder| match folder {
+ SidebarFolder::Project(index) => {
+ std::cmp::Reverse(self.projects[*index].archived_at.unwrap_or(0))
+ }
+ SidebarFolder::RefGroup(_) => std::cmp::Reverse(0),
+ });
+ self.display_order = live;
+ self.display_order.extend(archived);
+ }
+
/// True when the workspace on screen is one of this Space's thread
/// references. Activating a ref never repoints the Space's own
/// active-thread pointer, so while this holds, the own rows' `is_active`
@@ -344,6 +371,11 @@ pub struct ProjectView {
pub is_remote: bool,
/// Detected `/etc/os-release` `ID` for remote hosts, used to pick an OS icon.
pub distro: Option<String>,
+ /// Painted dimmed with no thread rows; only present when the sidebar's
+ /// transient reveal is on.
+ pub is_archived: bool,
+ /// Sort key for the archived tail of the sidebar (newest first).
+ pub archived_at: Option<i64>,
}
#[derive(Debug, Clone)]
@@ -536,6 +568,28 @@ pub enum DeleteSpaceError {
ServerRejected,
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ArchivedProject {
+ pub was_active: bool,
+ pub next_thread_id: Option<WorkspaceThreadId>,
+ pub materialized_workspace_names: Vec<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ArchiveProjectError {
+ NotFound,
+ AlreadyArchived,
+ /// Archiving would leave the Space with no live project to land on.
+ LastLiveProject,
+ RemoteUnavailable,
+ ServerRejected,
+ /// The archive flag landed but some remote panes could not be killed
+ /// (usually the connection died mid-teardown). Rolling the flag back
+ /// over the same dead connection cannot work; the recovery is to
+ /// unarchive and archive again, whose retry path finishes the kills.
+ TeardownIncomplete,
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpaceView {
pub id: SpaceId,
@@ -1331,8 +1385,7 @@ pub fn move_host_candidates(thread_id: &str) -> Vec<(SpaceId, String)> {
// Same test the move itself applies: a Space holding
// only direct-SSH projects has nowhere local to put
// the thread, and offering it would no-op silently.
- candidate.space_id == space.id
- && !is_remote_project(candidate, &store.spaces)
+ candidate.space_id == space.id && !is_remote_project(candidate, &store.spaces)
})
})
.map(|space| (space.id.clone(), space.name.clone()))
@@ -1434,6 +1487,7 @@ pub fn create_space_on_domain(domain_name: &str, name: Option<String>) -> Result
active_thread_id: Some(thread_id),
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
if let Some(space) = store.spaces.iter_mut().find(|space| space.id == space_id) {
space.active_project_id = Some(project_id);
@@ -1911,6 +1965,7 @@ pub fn default_project_for_space(space_id: &str) -> Project {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
}
}
@@ -1930,6 +1985,7 @@ pub fn view_for_current_project(
space_id: &str,
active_workspace: &str,
live_workspaces: &[String],
+ include_archived: bool,
) -> WorkspaceThreadsView {
let mut store = THREAD_STORE.lock();
if store.normalize_after_load() {
@@ -1952,7 +2008,7 @@ pub fn view_for_current_project(
let has_own_projects = store
.projects
.iter()
- .any(|project| project.space_id == space_id);
+ .any(|project| project.space_id == space_id && !project.is_archived());
if !has_own_projects && !ref_groups.is_empty() {
let mut view = WorkspaceThreadsView {
pinned_threads: Vec::new(),
@@ -1973,9 +2029,11 @@ pub fn view_for_current_project(
.any(|project| project.space_id == space_id && &project.id == project_id)
})
{
- let mut view = store.view_for_project(space_id, &project_id, live_workspaces);
+ let mut view =
+ store.view_for_project(space_id, &project_id, live_workspaces, include_archived);
view.ref_groups = ref_groups;
view.rebuild_display_order(&folder_order);
+ view.partition_archived_last();
return view;
}
@@ -2083,7 +2141,12 @@ pub fn thread_to_recover_after_window_death(space_id: &str) -> Option<WorkspaceT
.and_then(|project| project.active_thread_id.clone());
let mut best: Option<(i64, WorkspaceThreadId)> = None;
- for project in store.projects.iter().filter(|p| p.space_id == space_id) {
+ // A dying window must never resurrect an archived project.
+ for project in store
+ .projects
+ .iter()
+ .filter(|p| p.space_id == space_id && !p.is_archived())
+ {
for thread in &project.threads {
if dead_thread_id.as_deref() == Some(thread.id.as_str()) {
continue;
@@ -2105,13 +2168,13 @@ pub fn thread_to_recover_after_window_death(space_id: &str) -> Option<WorkspaceT
store
.projects
.iter()
- .any(|p| p.space_id == space_id && &p.id == project_id)
+ .any(|p| p.space_id == space_id && &p.id == project_id && !p.is_archived())
})
.or_else(|| {
store
.projects
.iter()
- .find(|p| p.space_id == space_id)
+ .find(|p| p.space_id == space_id && !p.is_archived())
.map(|p| p.id.clone())
})?;
let thread_id = store.create_thread(&project_id, None);
@@ -2881,7 +2944,7 @@ pub fn ordered_project_ids(space_id: &str) -> Vec<ProjectId> {
store
.projects
.iter()
- .filter(|project| project.space_id == space_id)
+ .filter(|project| project.space_id == space_id && !project.is_archived())
.map(|project| project.id.clone())
.collect()
}
@@ -2913,7 +2976,7 @@ pub fn unpinned_thread_ids(project_id: &str) -> Vec<WorkspaceThreadId> {
store
.projects
.iter()
- .find(|project| project.id == project_id)
+ .find(|project| project.id == project_id && !project.is_archived())
.map(|project| {
project
.threads
@@ -3143,6 +3206,253 @@ pub fn remove_project(project_id: &str) -> Option<RemovedProject> {
removed
}
+/// Archive a project, killing its remote panes first when it lives on a mux
+/// server. Local projects resolve synchronously inside; the caller kills the
+/// returned materialized workspaces' local (mirror) windows afterwards, the
+/// same division of labor `remove_project` uses.
+pub async fn archive_project(project_id: &str) -> Result<ArchivedProject, ArchiveProjectError> {
+ let domain_name = {
+ let store = THREAD_STORE.lock();
+ tree_domain_for_project(&store, project_id)
+ };
+
+ let Some(domain_name) = domain_name else {
+ // Local: no server involved, commit directly.
+ let mut store = THREAD_STORE.lock();
+ let archived = store.archive_project(project_id, now_ts())?;
+ persist_locked(&store);
+ return Ok(archived);
+ };
+
+ // Stage against a clone: validate the guards and capture the workspace
+ // names while nothing has been destroyed yet. AlreadyArchived is not an
+ // error here but a cleanup retry: the flag landed on a previous attempt
+ // whose pane teardown did not finish, so skip the mutate and finish the
+ // teardown below.
+ let (archived_at, materialized_workspace_names, is_retry) = {
+ let store = THREAD_STORE.lock();
+ let mut staged = store.clone();
+ let archived_at = now_ts();
+ match staged.archive_project(project_id, archived_at) {
+ Ok(archived) => (archived_at, archived.materialized_workspace_names, false),
+ Err(ArchiveProjectError::AlreadyArchived) => {
+ let names = store
+ .projects
+ .iter()
+ .find(|project| project.id == project_id)
+ .map(|project| {
+ project
+ .threads
+ .iter()
+ .filter_map(|session| session.materialized_workspace_name.clone())
+ .collect::<Vec<_>>()
+ })
+ .ok_or(ArchiveProjectError::NotFound)?;
+ (archived_at, names, true)
+ }
+ Err(err) => return Err(err),
+ }
+ };
+
+ if !remote_tree_domain_is_attached(&domain_name) {
+ notify_remote_tree_mutation_unavailable(&domain_name);
+ return Err(ArchiveProjectError::RemoteUnavailable);
+ }
+ let domain = Mux::get()
+ .get_domain_by_name(&domain_name)
+ .ok_or(ArchiveProjectError::RemoteUnavailable)?;
+ let client = domain
+ .downcast_ref::<wezterm_client::domain::ClientDomain>()
+ .ok_or(ArchiveProjectError::RemoteUnavailable)?;
+ // Keep empty mirror windows from being pruned while the remote panes
+ // die; without this the last KillPane notification can detach the
+ // domain mid-teardown.
+ let _archive_activity = mux::activity::Activity::new();
+
+ // The flag must land BEFORE any pane dies: the server freezes an
+ // archived project's stored layouts, and its snapshotter would
+ // otherwise prune them the moment the workspaces go pane-less. A
+ // mutate that succeeds but whose teardown fails below leaves an
+ // archived project with leftover panes; re-running the archive takes
+ // the retry path above and finishes the job.
+ if !is_retry {
+ let tree = match client
+ .mutate_thinkterm_tree(vec![codec::TreeOp::SetProjectArchived {
+ project_id: project_id.to_string(),
+ archived_at: Some(archived_at),
+ }])
+ .await
+ {
+ Ok(tree) => tree,
+ Err(err) => {
+ log::error!("failed to archive project {project_id} on {domain_name}: {err:#}");
+ notify_remote_tree_mutation_unavailable(&domain_name);
+ return Err(ArchiveProjectError::RemoteUnavailable);
+ }
+ };
+ if tree
+ .project(project_id)
+ .map_or(false, |project| project.archived_at.is_none())
+ {
+ log::error!("{domain_name} rejected archiving ThinkTerm project {project_id}");
+ return Err(ArchiveProjectError::ServerRejected);
+ }
+ }
+
+ let mut panes = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ for workspace in &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 archiving project {project_id} on {domain_name}: {err:#}",
+ pane.pane_id()
+ );
+ // The flag already landed; this is a half-finished teardown,
+ // not an unreachable server per se, and the caller's toast
+ // explains the unarchive-then-archive cleanup.
+ return Err(ArchiveProjectError::TeardownIncomplete);
+ }
+ }
+
+ // The mutate reply already flowed through ingest_remote_tree, so the
+ // shared flag is in the local cache. Commit only per-device state, and
+ // do the pointer landing against the REAL store: the staged run's
+ // choice may have minted its landing thread only inside the discarded
+ // clone.
+ {
+ let mut store = THREAD_STORE.lock();
+ let space_id = store
+ .projects
+ .iter()
+ .find(|project| project.id == project_id)
+ .map(|project| project.space_id.clone());
+ let mut landed = None;
+ if let Some(space_id) = space_id {
+ let still_active =
+ store.active_project_id_for_space(&space_id).as_deref() == Some(project_id);
+ if still_active {
+ landed = store.land_active_off_project(&space_id, project_id);
+ }
+ }
+ persist_locked(&store);
+ Ok(ArchivedProject {
+ was_active: landed.is_some(),
+ next_thread_id: landed,
+ materialized_workspace_names,
+ })
+ }
+}
+
+/// Restore an archived project. Nothing was destroyed, so nothing needs
+/// staging or verification: remote domains take the ordinary optimistic op
+/// path, and a failure is put right by the next authoritative push.
+pub fn unarchive_project(project_id: &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.unarchive_project(project_id);
+ if changed {
+ if let Some(domain) = domain {
+ submit_tree_op(
+ domain,
+ codec::TreeOp::SetProjectArchived {
+ project_id: project_id.to_string(),
+ archived_at: None,
+ },
+ );
+ }
+ persist_locked(&store);
+ }
+ changed
+}
+
+/// The materialized workspace names of a project's threads, for callers
+/// that need to count live panes before offering a destructive action.
+pub fn materialized_workspace_names_for_project(project_id: &str) -> Vec<String> {
+ let store = THREAD_STORE.lock();
+ store
+ .projects
+ .iter()
+ .find(|project| project.id == project_id)
+ .map(|project| {
+ project
+ .threads
+ .iter()
+ .filter_map(|session| session.materialized_workspace_name.clone())
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// One row of the Settings window's Archived page.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ArchivedProjectRow {
+ pub id: ProjectId,
+ pub name: String,
+ pub space_name: String,
+ pub thread_count: usize,
+ pub archived_at: i64,
+ pub is_remote: bool,
+}
+
+/// Every archived project across every Space, newest archive first --
+/// the Settings window's Archived page.
+pub fn archived_projects_overview() -> Vec<ArchivedProjectRow> {
+ let store = THREAD_STORE.lock();
+ let mut rows: Vec<ArchivedProjectRow> = store
+ .projects
+ .iter()
+ .filter(|project| project.is_archived())
+ .map(|project| ArchivedProjectRow {
+ id: project.id.clone(),
+ name: project.name.clone(),
+ space_name: store
+ .spaces
+ .iter()
+ .find(|space| space.id == project.space_id)
+ .map(|space| space.name.clone())
+ .unwrap_or_default(),
+ thread_count: project.threads.len(),
+ archived_at: project.archived_at.unwrap_or(0),
+ is_remote: is_remote_project(project, &store.spaces),
+ })
+ .collect();
+ rows.sort_by_key(|row| std::cmp::Reverse(row.archived_at));
+ rows
+}
+
+/// Sorted ids+names of the current Space's archived projects, for the
+/// view-options row's count and the disabled state.
+pub fn archived_project_count(space_id: &str) -> usize {
+ let store = THREAD_STORE.lock();
+ store
+ .projects
+ .iter()
+ .filter(|project| project.space_id == space_id && project.is_archived())
+ .count()
+}
+
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);
@@ -3846,7 +4156,7 @@ fn ordered_folder_keys_locked(store: &WorkspaceThreadStore, space_id: &str) -> V
let project_keys: Vec<String> = store
.projects
.iter()
- .filter(|project| project.space_id == space_id)
+ .filter(|project| project.space_id == space_id && !project.is_archived())
.map(|project| project.id.clone())
.collect();
let group_keys: Vec<String> =
@@ -4061,11 +4371,14 @@ impl WorkspaceThreadStore {
}
// Mirror the projects' relative order back into the store's Vec.
+ // Must mirror ordered_folder_keys_locked's archived filter, or the
+ // len-equality guard below never holds and reorders stop syncing
+ // into the projects Vec.
let project_positions: Vec<usize> = store
.projects
.iter()
.enumerate()
- .filter(|(_, project)| project.space_id == space_id)
+ .filter(|(_, project)| project.space_id == space_id && !project.is_archived())
.map(|(index, _)| index)
.collect();
let mut wanted_project_order: Vec<usize> = Vec::new();
@@ -4180,6 +4493,10 @@ fn thread_views_for_project(
}
impl Project {
+ pub fn is_archived(&self) -> bool {
+ self.archived_at.is_some()
+ }
+
fn view(&self, live_workspaces: &[String], is_remote: bool) -> WorkspaceThreadsView {
WorkspaceThreadsView {
pinned_threads: vec![],
@@ -4191,6 +4508,8 @@ impl Project {
threads: thread_views_for_project(self, Some(&self.id), live_workspaces),
is_remote,
distro: None,
+ is_archived: false,
+ archived_at: None,
}],
ref_groups: Vec::new(),
display_order: vec![SidebarFolder::Project(0)],
@@ -4261,17 +4580,29 @@ impl WorkspaceThreadStore {
for index in 0..self.spaces.len() {
let space_id = self.spaces[index].id.clone();
let active_project_id = self.spaces[index].active_project_id.clone();
+ // An archived project cannot stay the Space's active pointer:
+ // the sidebar would open onto a hidden row.
let active_is_valid = active_project_id.as_ref().is_some_and(|project_id| {
- self.projects
- .iter()
- .any(|project| project.space_id == space_id && &project.id == project_id)
+ self.projects.iter().any(|project| {
+ project.space_id == space_id
+ && &project.id == project_id
+ && !project.is_archived()
+ })
});
if !active_is_valid {
let next_active_project_id = self
.projects
.iter()
- .find(|project| project.space_id == space_id)
- .map(|project| project.id.clone());
+ .find(|project| project.space_id == space_id && !project.is_archived())
+ .map(|project| project.id.clone())
+ .or_else(|| {
+ // Every project archived: keep any pointer rather
+ // than none, so the Space still resolves.
+ self.projects
+ .iter()
+ .find(|project| project.space_id == space_id)
+ .map(|project| project.id.clone())
+ });
if self.spaces[index].active_project_id != next_active_project_id {
self.spaces[index].active_project_id = next_active_project_id;
changed = true;
@@ -4566,10 +4897,12 @@ impl WorkspaceThreadStore {
let space = self.spaces.iter().find(|space| space.id == space_id)?;
// A dangling ref (origin rows not in the local cache) cannot be
// activated, so it cannot be a restore target either.
+ // A ref whose origin project is archived is hidden from the view,
+ // so restoring it would activate a thread with no visible row.
let resolvable = |id: &String| {
- self.projects
- .iter()
- .any(|project| project.threads.iter().any(|thread| &thread.id == id))
+ self.projects.iter().any(|project| {
+ !project.is_archived() && project.threads.iter().any(|thread| &thread.id == id)
+ })
};
let last_opened = space
.active_thread_ref
@@ -4734,6 +5067,12 @@ impl WorkspaceThreadStore {
dangling: true,
});
};
+ // A ref into an archived project is hidden, not pruned:
+ // the row (and groom's resolution above it) survives, so
+ // unarchiving brings the ref back verbatim.
+ if project.is_archived() {
+ return None;
+ }
let origin = self.spaces.iter().find(|s| s.id == project.space_id)?;
let session = project.threads.iter().find(|t| &t.id == thread_id)?;
let workspace_name = session
@@ -4909,6 +5248,14 @@ impl WorkspaceThreadStore {
.iter()
.find(|p| p.space_id == space_id && p.path == current.path)
{
+ if project.is_archived() {
+ // This is a background sync fallback, not an open-folder
+ // gesture: it must neither resurrect the archived project
+ // nor point the Space at a hidden row. (Explicitly opening
+ // the folder goes through create_project_from_path, which
+ // does unarchive.)
+ return (project.id.clone(), false);
+ }
(project.id.clone(), false)
} else {
let mut project = current;
@@ -4932,14 +5279,18 @@ impl WorkspaceThreadStore {
space_id: &str,
project_id: &str,
live_workspaces: &[String],
+ include_archived: bool,
) -> WorkspaceThreadsView {
let active_project_id = self
.active_project_id_for_space(space_id)
.unwrap_or_else(|| project_id.to_string());
+ // An archived project's pinned threads never surface in Pinned --
+ // unconditionally, even while the transient reveal is showing the
+ // archived rows themselves.
let pinned_threads = self
.projects
.iter()
- .filter(|project| project.space_id == space_id)
+ .filter(|project| project.space_id == space_id && !project.is_archived())
.flat_map(|project| {
thread_views_for_project(project, Some(&active_project_id), live_workspaces)
.into_iter()
@@ -4949,22 +5300,28 @@ impl WorkspaceThreadStore {
let projects: Vec<ProjectView> = self
.projects
.iter()
- .filter(|project| project.space_id == space_id)
+ .filter(|project| {
+ project.space_id == space_id && (include_archived || !project.is_archived())
+ })
.map(|project| {
let is_remote = is_remote_project(project, &self.spaces);
+ let is_archived = project.is_archived();
ProjectView {
id: project.id.clone(),
name: project.name.clone(),
- is_active: project.id == active_project_id,
- threads_collapsed: project.threads_collapsed,
- threads: thread_views_for_project(
- project,
- Some(&active_project_id),
- live_workspaces,
- )
- .into_iter()
- .filter(|session| !session.is_pinned)
- .collect(),
+ is_active: !is_archived && project.id == active_project_id,
+ // Archived rows paint as a single collapsed line: no
+ // thread rows means every downstream height/scroll walk
+ // is already correct with no edits.
+ threads_collapsed: is_archived || project.threads_collapsed,
+ threads: if is_archived {
+ Vec::new()
+ } else {
+ thread_views_for_project(project, Some(&active_project_id), live_workspaces)
+ .into_iter()
+ .filter(|session| !session.is_pinned)
+ .collect()
+ },
is_remote,
distro: if is_remote {
crate::ssh_hosts::host_spec(remote_host_id_for_project_id(&project.id))
@@ -4972,6 +5329,8 @@ impl WorkspaceThreadStore {
} else {
None
},
+ is_archived,
+ archived_at: project.archived_at,
}
})
.collect();
@@ -5054,31 +5413,42 @@ impl WorkspaceThreadStore {
if self.workspace_belongs_to_other_space(space_id, active_workspace) {
return changed;
}
- let (project_id, project_changed) =
- if let Some(project_id) = self.project_id_for_workspace(space_id, active_workspace) {
- if self.set_active_project_for_space(space_id, project_id.clone()) {
- (project_id, true)
- } else {
- (project_id, false)
- }
- } else if self.is_client_domain_space(space_id) {
- // A mux-domain Space's connect window lives in the default
- // mux workspace, which is not bound to any thread. Resolve to
- // the Space's mux project instead of manufacturing a local
- // Home project.
- let Some(project_id) = self
- .projects
- .iter()
- .find(|p| p.space_id == space_id && is_mux_domain_project_id(&p.id))
- .map(|p| p.id.clone())
- else {
- return changed;
- };
- let set = self.set_active_project_for_space(space_id, project_id.clone());
- (project_id, set)
+ let (project_id, project_changed) = if let Some(project_id) =
+ self.project_id_for_workspace(space_id, active_workspace)
+ {
+ // A window can outlive its project's archiving (e.g. the
+ // archive ran on another device). Never point the Space at
+ // the hidden row: normalize would repoint it right back,
+ // and the two would churn the store on every notification.
+ let archived = self
+ .projects
+ .iter()
+ .any(|project| project.id == project_id && project.is_archived());
+ if !archived && self.set_active_project_for_space(space_id, project_id.clone()) {
+ (project_id, true)
} else {
- self.ensure_current_project(space_id, active_workspace)
+ (project_id, false)
+ }
+ } else if self.is_client_domain_space(space_id) {
+ // A mux-domain Space's connect window lives in the default
+ // mux workspace, which is not bound to any thread. Resolve to
+ // the Space's mux project instead of manufacturing a local
+ // Home project.
+ let Some(project_id) = self
+ .projects
+ .iter()
+ .find(|p| {
+ p.space_id == space_id && is_mux_domain_project_id(&p.id) && !p.is_archived()
+ })
+ .map(|p| p.id.clone())
+ else {
+ return changed;
};
+ let set = self.set_active_project_for_space(space_id, project_id.clone());
+ (project_id, set)
+ } else {
+ self.ensure_current_project(space_id, active_workspace)
+ };
changed |= project_changed;
changed |= self.sync_active_workspace(space_id, &project_id, active_workspace);
changed
@@ -5219,6 +5589,9 @@ impl WorkspaceThreadStore {
project.space_id = space_id.to_string();
project.name = label.to_string();
project.path = path.clone();
+ // Connecting to the host is an explicit gesture; it revives an
+ // archived project rather than landing threads in a hidden row.
+ project.archived_at = None;
} else {
self.projects.push(Project {
id: project_id.clone(),
@@ -5229,6 +5602,7 @@ impl WorkspaceThreadStore {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
}
@@ -5259,9 +5633,15 @@ impl WorkspaceThreadStore {
let project_id = project_id_for_path(space_id, &path);
if let Some(existing_project_id) = self
.projects
- .iter()
+ .iter_mut()
.find(|project| project.space_id == space_id && project.path == path)
- .map(|project| project.id.clone())
+ .map(|project| {
+ // Opening the folder again is an unambiguous intent to
+ // un-hide it; a duplicate row on the same path would break
+ // the path->id reuse contract.
+ project.archived_at = None;
+ project.id.clone()
+ })
{
if let Some(thread_id) = self.active_thread_for_project(&existing_project_id) {
return thread_id;
@@ -5283,6 +5663,7 @@ impl WorkspaceThreadStore {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
};
let session = WorkspaceThread::new(project_id.clone(), "main".to_string(), None);
let thread_id = session.id.clone();
@@ -5357,7 +5738,9 @@ impl WorkspaceThreadStore {
.active_project_id_for_space(space_id)
.and_then(|active_project_id| {
self.projects.iter().position(|project| {
- project.space_id == space_id && project.id == active_project_id
+ project.space_id == space_id
+ && project.id == active_project_id
+ && !project.is_archived()
})
})
.into_iter()
@@ -5365,7 +5748,9 @@ impl WorkspaceThreadStore {
self.projects
.iter()
.enumerate()
- .filter_map(|(index, project)| (project.space_id == space_id).then_some(index)),
+ .filter_map(|(index, project)| {
+ (project.space_id == space_id && !project.is_archived()).then_some(index)
+ }),
)
.collect::<Vec<_>>();
@@ -5390,7 +5775,7 @@ impl WorkspaceThreadStore {
fn restorable_thread_id_for_project(&self, project_index: usize) -> Option<WorkspaceThreadId> {
let project = self.projects.get(project_index)?;
- if self.is_client_domain_space(&project.space_id) {
+ if project.is_archived() || self.is_client_domain_space(&project.space_id) {
return None;
}
project
@@ -5702,19 +6087,34 @@ impl WorkspaceThreadStore {
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 {
+ 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(),
+ });
+ if project.archived_at.is_some() {
+ ops.push(codec::TreeOp::SetProjectArchived {
+ project_id: project.id.clone(),
+ archived_at: project.archived_at,
+ });
+ }
+ }
+ Some(known) => {
+ if known.name != project.name {
+ ops.push(codec::TreeOp::RenameProject {
+ project_id: project.id.clone(),
+ name: project.name.clone(),
+ });
+ }
+ if known.archived_at != project.archived_at {
+ ops.push(codec::TreeOp::SetProjectArchived {
+ project_id: project.id.clone(),
+ archived_at: project.archived_at,
+ });
+ }
}
- Some(_) => {}
}
for thread in &project.threads {
live_threads.insert(thread.id.as_str());
@@ -5972,6 +6372,9 @@ impl WorkspaceThreadStore {
threads,
threads_collapsed: view.map_or(false, |view| view.threads_collapsed),
active_note_path: view.and_then(|view| view.active_note_path.clone()),
+ // Server-owned, never carried over from the previous
+ // local rows: archived state lives in the shared tree.
+ archived_at: project.archived_at,
}
})
.collect();
@@ -6285,7 +6688,7 @@ impl WorkspaceThreadStore {
let project_count = self
.projects
.iter()
- .filter(|project| project.space_id == space_id)
+ .filter(|project| project.space_id == space_id && !project.is_archived())
.count();
if project_count <= 1 {
@@ -6393,12 +6796,15 @@ impl WorkspaceThreadStore {
.iter()
.position(|project| project.id == project_id)?;
let space_id = self.projects[index].space_id.clone();
- if self
- .projects
- .iter()
- .filter(|project| project.space_id == space_id)
- .count()
- <= 1
+ // Count live projects only: archived rows must not prop up a Space
+ // that has no usable project left.
+ if !self.projects[index].is_archived()
+ && self
+ .projects
+ .iter()
+ .filter(|project| project.space_id == space_id && !project.is_archived())
+ .count()
+ <= 1
{
return None;
}
@@ -6415,7 +6821,7 @@ impl WorkspaceThreadStore {
.projects
.iter()
.enumerate()
- .filter(|(_, project)| project.space_id == space_id)
+ .filter(|(_, project)| project.space_id == space_id && !project.is_archived())
.map(|(idx, _)| idx)
.find(|idx| *idx >= index)
.or_else(|| {
@@ -6423,7 +6829,7 @@ impl WorkspaceThreadStore {
.iter()
.enumerate()
.rev()
- .find(|(_, project)| project.space_id == space_id)
+ .find(|(_, project)| project.space_id == space_id && !project.is_archived())
.map(|(idx, _)| idx)
})
else {
@@ -6463,6 +6869,136 @@ impl WorkspaceThreadStore {
})
}
+ /// Repoint the Space's active project/thread away from `project_id`,
+ /// landing on the next live project down (wrapping like
+ /// `remove_project`), minting a "main" thread when the target has none.
+ /// Returns None when the Space has no other live project.
+ fn land_active_off_project(
+ &mut self,
+ space_id: &str,
+ project_id: &str,
+ ) -> Option<WorkspaceThreadId> {
+ let index = self
+ .projects
+ .iter()
+ .position(|project| project.id == project_id)?;
+ let next_index = self
+ .projects
+ .iter()
+ .enumerate()
+ .filter(|(idx, project)| {
+ *idx != index && project.space_id == space_id && !project.is_archived()
+ })
+ .map(|(idx, _)| idx)
+ .find(|idx| *idx > index)
+ .or_else(|| {
+ self.projects
+ .iter()
+ .enumerate()
+ .rev()
+ .find(|(idx, project)| {
+ *idx != index && project.space_id == space_id && !project.is_archived()
+ })
+ .map(|(idx, _)| idx)
+ })?;
+ let next_project_id = self.projects[next_index].id.clone();
+ let picked = self.projects[next_index]
+ .active_thread_id
+ .clone()
+ .filter(|id| {
+ self.projects[next_index]
+ .threads
+ .iter()
+ .any(|session| &session.id == id)
+ })
+ .or_else(|| {
+ self.projects[next_index]
+ .threads
+ .first()
+ .map(|session| session.id.clone())
+ });
+ let thread_id = match picked {
+ Some(id) => id,
+ None => {
+ let project = &mut self.projects[next_index];
+ let session = WorkspaceThread::new(project.id.clone(), "main".to_string(), None);
+ let id = session.id.clone();
+ project.threads.push(session);
+ id
+ }
+ };
+ self.projects[next_index].active_thread_id = Some(thread_id.clone());
+ self.set_active_project_for_space(space_id, next_project_id);
+ Some(thread_id)
+ }
+
+ /// Archive a project in place: rows, layouts, pins and workspace
+ /// bindings all stay so unarchiving can rebuild the shells. The caller
+ /// kills the materialized windows afterwards, exactly like
+ /// `remove_project`'s caller does.
+ fn archive_project(
+ &mut self,
+ project_id: &str,
+ archived_at: i64,
+ ) -> Result<ArchivedProject, ArchiveProjectError> {
+ let index = self
+ .projects
+ .iter()
+ .position(|project| project.id == project_id)
+ .ok_or(ArchiveProjectError::NotFound)?;
+ if self.projects[index].is_archived() {
+ return Err(ArchiveProjectError::AlreadyArchived);
+ }
+ let space_id = self.projects[index].space_id.clone();
+ if self
+ .projects
+ .iter()
+ .filter(|project| project.space_id == space_id && !project.is_archived())
+ .count()
+ <= 1
+ {
+ return Err(ArchiveProjectError::LastLiveProject);
+ }
+ let was_active = self.active_project_id_for_space(&space_id).as_deref() == Some(project_id);
+ let materialized_workspace_names = self.projects[index]
+ .threads
+ .iter()
+ .filter_map(|session| session.materialized_workspace_name.clone())
+ .collect::<Vec<_>>();
+
+ // Land on another live project, preferring the next one down like
+ // remove_project does; the guard above proved one exists.
+ let next_thread_id = if was_active {
+ let landed = self
+ .land_active_off_project(&space_id, project_id)
+ .ok_or(ArchiveProjectError::LastLiveProject)?;
+ Some(landed)
+ } else {
+ None
+ };
+
+ self.projects[index].archived_at = Some(archived_at);
+ Ok(ArchivedProject {
+ was_active,
+ next_thread_id,
+ materialized_workspace_names,
+ })
+ }
+
+ fn unarchive_project(&mut self, project_id: &str) -> bool {
+ match self
+ .projects
+ .iter_mut()
+ .find(|project| project.id == project_id)
+ {
+ Some(project) if project.is_archived() => {
+ project.archived_at = None;
+ true
+ }
+ _ => false,
+ }
+ }
+
fn toggle_project_threads_collapsed(&mut self, project_id: &str) -> bool {
let Some(project) = self
.projects
@@ -7305,9 +7841,7 @@ fn scan_workspace_work_status(workspace: &str) -> (WorkspaceThreadWorkStatus, Ve
.flatten()
.unwrap_or_else(|| native_pane_work_status(pane.as_ref()));
match observed {
- WorkspaceThreadWorkStatus::NeedsAttention => {
- waiting_panes.push(pane.pane_id())
- }
+ WorkspaceThreadWorkStatus::NeedsAttention => waiting_panes.push(pane.pane_id()),
WorkspaceThreadWorkStatus::Running => running = true,
_ => {}
}
@@ -7604,6 +8138,10 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {
if project.space_id != space_id {
continue;
}
+ // A live remote session proves the project is in use; a
+ // hidden row must not swallow it unreachably. The reconcile
+ // that follows adoption propagates the un-archive.
+ project.archived_at = None;
let mut thread =
WorkspaceThread::new(project_id, "main".to_string(), Some(workspace));
thread.id = thread_id;
@@ -7639,6 +8177,7 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
}
let project = store
@@ -7679,6 +8218,7 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {
active_thread_id: Some(thread_id),
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
changed = true;
}
@@ -7770,6 +8310,7 @@ impl WorkspaceThreadStore {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
}
@@ -7778,6 +8319,10 @@ impl WorkspaceThreadStore {
.iter_mut()
.find(|p| p.id == project_id)
.expect("mux domain project was just ensured");
+ // Connecting to the server is an explicit gesture: a hidden project
+ // must not swallow the attach. The reconcile that follows a connect
+ // propagates the un-archive to the server.
+ project.archived_at = None;
if project.threads.is_empty() {
project.threads.push(WorkspaceThread::new(
project_id.clone(),
@@ -8573,6 +9118,7 @@ mod tests {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
}
}
@@ -9028,6 +9574,7 @@ mod tests {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
let state = store
@@ -9083,7 +9630,7 @@ mod tests {
requested_root: dir.path().to_string_lossy().into_owned(),
}
);
- let view = store.view_for_project(&space_id, "project-path", &[]);
+ let view = store.view_for_project(&space_id, "project-path", &[], false);
assert!(view.projects[0].is_remote);
assert!(store.project_reveal_path("project-path").is_none());
assert!(!store.snapshot_active_space_thread_layout(
@@ -9128,6 +9675,7 @@ mod tests {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
let plan = store
@@ -9292,11 +9840,7 @@ mod tests {
);
let change = store
- .observe_thread_work_for_workspace(
- "workspace-1",
- WorkspaceThreadWorkStatus::Idle,
- &[],
- )
+ .observe_thread_work_for_workspace("workspace-1", WorkspaceThreadWorkStatus::Idle, &[])
.unwrap();
assert!(change.changed);
assert!(change.should_persist);
@@ -9566,6 +10110,8 @@ mod tests {
],
is_remote: false,
distro: None,
+ is_archived: false,
+ archived_at: None,
}],
ref_groups: Vec::new(),
display_order: Vec::new(),
@@ -10064,7 +10610,7 @@ mod tests {
store.projects.push(second_project);
store.set_active_project_for_space(&space_id, "project-2".to_string());
- let view = store.view_for_project(&space_id, "project-2", &[]);
+ let view = store.view_for_project(&space_id, "project-2", &[], false);
assert!(!view.projects[0].is_active);
assert!(!view.projects[0].threads[0].is_active);
assert!(view.projects[1].is_active);
@@ -10194,6 +10740,52 @@ mod tests {
assert!(!store.move_sidebar_folder_before("space-remote", "rp1", None));
}
+ #[test]
+ fn tmp_probe_archived_breaks_mirror_and_folder_order() {
+ let mut store = remote_test_store("syd");
+ assert!(store.ingest_remote_tree("syd", &sample_tree()));
+ let local_space = store.spaces[0].id.clone();
+ store.projects.push(test_project_in_space(
+ &local_space,
+ "local-2",
+ "beta",
+ PathBuf::from("/tmp/beta"),
+ vec![],
+ ));
+ store.projects.push(test_project_in_space(
+ &local_space,
+ "local-3",
+ "gamma",
+ PathBuf::from("/tmp/gamma"),
+ vec![],
+ ));
+ store.archive_project("local-3", 100).unwrap();
+ eprintln!(
+ "PROBE keys before = {:?}",
+ ordered_folder_keys_locked(&store, &local_space)
+ );
+ assert!(store.move_sidebar_folder_before(&local_space, "local-1", None));
+ eprintln!(
+ "PROBE keys after = {:?}",
+ ordered_folder_keys_locked(&store, &local_space)
+ );
+ let vec_order: Vec<&str> = store
+ .projects
+ .iter()
+ .filter(|project| project.space_id == local_space)
+ .map(|project| project.id.as_str())
+ .collect();
+ eprintln!("PROBE vec order = {:?}", vec_order);
+ let fo = store
+ .spaces
+ .iter()
+ .find(|s| s.id == local_space)
+ .unwrap()
+ .folder_order
+ .clone();
+ eprintln!("PROBE folder_order= {:?}", fo);
+ }
+
/// A move is a re-home: the thread leaves its project, joins the target
/// Space's project, keeps its identity (refs elsewhere still resolve),
/// and a ref held by the TARGET Space dissolves — a Space never
@@ -10357,6 +10949,8 @@ mod tests {
threads: vec![make("own-active", true), make("own-idle", false)],
is_remote: false,
distro: None,
+ is_archived: false,
+ archived_at: None,
}],
ref_groups: Vec::new(),
display_order: Vec::new(),
@@ -10783,7 +11377,7 @@ mod tests {
assert!(updated.is_pinned);
assert!(updated.is_unread);
- let view = store.view_for_project(&space_id, "project-1", &[]);
+ let view = store.view_for_project(&space_id, "project-1", &[], false);
assert_eq!(view.pinned_threads.len(), 1);
assert_eq!(view.pinned_threads[0].id, second_id);
assert_eq!(view.projects[0].threads.len(), 1);
@@ -10960,6 +11554,7 @@ mod tests {
tree_thread("rt1", "rp1", "main"),
tree_thread("rt2", "rp1", "build"),
],
+ archived_at: None,
}],
revision: 1,
}
@@ -11503,6 +12098,7 @@ mod tests {
active_thread_id: None,
threads_collapsed: false,
active_note_path: None,
+ archived_at: None,
});
let mine = store.materialized_workspaces_for_space("space-remote");
@@ -11640,6 +12236,7 @@ mod tests {
name: "notes".to_string(),
path: "/srv/notes".to_string(),
threads: vec![tree_thread("rt3", "rp2", "main")],
+ archived_at: None,
});
assert!(store.ingest_remote_tree("syd", &tree));
@@ -11738,4 +12335,265 @@ mod tests {
}
}
}
+
+ /// Two local projects, the first active with a pinned thread and a
+ /// materialized workspace -- the archive fixture.
+ fn store_with_two_projects() -> (WorkspaceThreadStore, String, String) {
+ let mut store = test_store();
+ let mut alpha = default_project_for_space(DEFAULT_SPACE_ID);
+ alpha.id = "proj-alpha".to_string();
+ alpha.path = PathBuf::from("/tmp/alpha");
+ let mut t1 = WorkspaceThread::new(alpha.id.clone(), "main".to_string(), None);
+ t1.materialized_workspace_name = Some("ws-alpha".to_string());
+ t1.is_pinned = true;
+ let mut t2 = WorkspaceThread::new(alpha.id.clone(), "side".to_string(), None);
+ t2.layout = Some(WorkspaceThreadLayoutSnapshot {
+ active_tab: 0,
+ tabs: vec![],
+ terminal_specs: vec![],
+ });
+ alpha.active_thread_id = Some(t1.id.clone());
+ alpha.threads.push(t1);
+ alpha.threads.push(t2);
+ let mut beta = default_project_for_space(DEFAULT_SPACE_ID);
+ beta.id = "proj-beta".to_string();
+ beta.path = PathBuf::from("/tmp/beta");
+ let bt = WorkspaceThread::new(beta.id.clone(), "main".to_string(), None);
+ beta.active_thread_id = Some(bt.id.clone());
+ beta.threads.push(bt);
+ let (alpha_id, beta_id) = (alpha.id.clone(), beta.id.clone());
+ store.projects.push(alpha);
+ store.projects.push(beta);
+ store.set_active_project_for_space(DEFAULT_SPACE_ID, alpha_id.clone());
+ (store, alpha_id, beta_id)
+ }
+
+ #[test]
+ fn archiving_a_project_hides_it_and_moves_the_active_pointer() {
+ let (mut store, alpha, beta) = store_with_two_projects();
+ let archived = store.archive_project(&alpha, 100).unwrap();
+ assert!(archived.was_active);
+ assert_eq!(
+ archived.materialized_workspace_names,
+ vec!["ws-alpha".to_string()]
+ );
+ assert_eq!(
+ store
+ .active_project_id_for_space(DEFAULT_SPACE_ID)
+ .as_deref(),
+ Some(beta.as_str())
+ );
+ // Hidden from the ordinary view...
+ let view = store.view_for_project(DEFAULT_SPACE_ID, &beta, &[], false);
+ assert!(view.projects.iter().all(|project| project.id != alpha));
+ // ...but every row, pin and layout stays in the store.
+ let row = store.projects.iter().find(|p| p.id == alpha).unwrap();
+ assert_eq!(row.archived_at, Some(100));
+ assert_eq!(row.threads.len(), 2);
+ assert!(row.threads[0].is_pinned);
+ assert!(row.threads[1].layout.is_some());
+ assert!(row.threads[0].materialized_workspace_name.is_some());
+ }
+
+ #[test]
+ fn archiving_refuses_the_spaces_last_live_project() {
+ let (mut store, alpha, beta) = store_with_two_projects();
+ // test_store's normalize seeds a Home project too; archive
+ // everything but one and the last one must be refused.
+ let others: Vec<String> = store
+ .projects
+ .iter()
+ .filter(|p| p.space_id == DEFAULT_SPACE_ID && p.id != alpha)
+ .map(|p| p.id.clone())
+ .collect();
+ for id in &others {
+ store.archive_project(id, 50).unwrap();
+ }
+ assert_eq!(
+ store.archive_project(&alpha, 60),
+ Err(ArchiveProjectError::LastLiveProject)
+ );
+ assert_eq!(
+ store.archive_project(&beta, 61),
+ Err(ArchiveProjectError::AlreadyArchived)
+ );
+ }
+
+ #[test]
+ fn archived_projects_pinned_threads_leave_the_pinned_section() {
+ let (mut store, alpha, beta) = store_with_two_projects();
+ let pinned_before = store.view_for_project(DEFAULT_SPACE_ID, &beta, &[], false);
+ assert!(!pinned_before.pinned_threads.is_empty());
+ store.archive_project(&alpha, 100).unwrap();
+ // Unconditionally out of Pinned, reveal on or off.
+ for include_archived in [false, true] {
+ let view = store.view_for_project(DEFAULT_SPACE_ID, &beta, &[], include_archived);
+ assert!(view.pinned_threads.is_empty());
+ }
+ }
+
+ #[test]
+ fn revealing_archived_projects_puts_them_last_with_no_thread_rows() {
+ let (mut store, alpha, beta) = store_with_two_projects();
+ store.archive_project(&alpha, 100).unwrap();
+ let mut view = store.view_for_project(DEFAULT_SPACE_ID, &beta, &[], true);
+ // A persisted folder_order listing alpha first must not pull the
+ // archived row back up.
+ view.rebuild_display_order(&[alpha.clone()]);
+ view.partition_archived_last();
+ let last = view.display_order.last().unwrap();
+ match last {
+ SidebarFolder::Project(index) => {
+ let project = &view.projects[*index];
+ assert_eq!(project.id, alpha);
+ assert!(project.is_archived);
+ assert!(project.threads.is_empty());
+ assert!(project.threads_collapsed);
+ assert!(!project.is_active);
+ }
+ SidebarFolder::RefGroup(_) => panic!("expected the archived project last"),
+ }
+ }
+
+ #[test]
+ fn unarchiving_restores_the_project_and_its_threads() {
+ let (mut store, alpha, beta) = store_with_two_projects();
+ store.archive_project(&alpha, 100).unwrap();
+ assert!(store.unarchive_project(&alpha));
+ assert!(
+ !store.unarchive_project(&alpha),
+ "second restore is a no-op"
+ );
+ let view = store.view_for_project(DEFAULT_SPACE_ID, &beta, &[], false);
+ let row = view.projects.iter().find(|p| p.id == alpha).unwrap();
+ assert!(!row.is_archived);
+ assert!(!view.pinned_threads.is_empty(), "the pin came back");
+ let record = store.projects.iter().find(|p| p.id == alpha).unwrap();
+ assert!(record.threads[1].layout.is_some(), "layout survived");
+ }
+
+ #[test]
+ fn archived_state_survives_an_ingest_and_is_not_carried_over() {
+ // The server is authoritative: a locally-archived remote project
+ // whose tree says live comes back live, and vice versa.
+ let mut store = remote_test_store("syd");
+ assert!(store.ingest_remote_tree("syd", &sample_tree()));
+ store
+ .projects
+ .iter_mut()
+ .find(|p| p.id == "rp1")
+ .unwrap()
+ .archived_at = Some(7);
+ assert!(store.ingest_remote_tree("syd", &sample_tree()));
+ assert_eq!(
+ store
+ .projects
+ .iter()
+ .find(|p| p.id == "rp1")
+ .unwrap()
+ .archived_at,
+ None
+ );
+
+ let mut archived_tree = sample_tree();
+ archived_tree.projects[0].archived_at = Some(9);
+ archived_tree.revision = 2;
+ assert!(store.ingest_remote_tree("syd", &archived_tree));
+ assert_eq!(
+ store
+ .projects
+ .iter()
+ .find(|p| p.id == "rp1")
+ .unwrap()
+ .archived_at,
+ Some(9)
+ );
+ }
+
+ #[test]
+ fn reconcile_emits_a_set_project_archived_when_only_the_flag_moved() {
+ let mut store = remote_test_store("syd");
+ assert!(store.ingest_remote_tree("syd", &sample_tree()));
+ store
+ .projects
+ .iter_mut()
+ .find(|p| p.id == "rp1")
+ .unwrap()
+ .archived_at = Some(11);
+ let ops = store.reconcile_ops_for_domain("syd", &sample_tree());
+ assert_eq!(
+ ops,
+ vec![codec::TreeOp::SetProjectArchived {
+ project_id: "rp1".to_string(),
+ archived_at: Some(11),
+ }]
+ );
+ }
+
+ #[test]
+ fn reopening_an_archived_projects_path_unarchives_it() {
+ let (mut store, alpha, _beta) = store_with_two_projects();
+ store.archive_project(&alpha, 100).unwrap();
+ let thread_id =
+ store.create_project_from_path(DEFAULT_SPACE_ID, PathBuf::from("/tmp/alpha"));
+ let row = store.projects.iter().find(|p| p.id == alpha).unwrap();
+ assert_eq!(row.archived_at, None, "reopening the folder revives it");
+ assert!(
+ row.threads.iter().any(|t| t.id == thread_id),
+ "the existing project was reused, not duplicated"
+ );
+ assert_eq!(
+ store
+ .projects
+ .iter()
+ .filter(|p| p.path == PathBuf::from("/tmp/alpha"))
+ .count(),
+ 1
+ );
+ }
+
+ #[test]
+ fn an_archived_projects_refs_are_hidden_but_never_pruned() {
+ let (mut store, coll, t1, _) = store_with_collection();
+ assert!(store.add_thread_ref(&coll, &t1));
+ store.normalize_after_load();
+ let origin_project_id = store
+ .projects
+ .iter()
+ .find(|p| p.threads.iter().any(|t| t.id == t1))
+ .unwrap()
+ .id
+ .clone();
+ // Guard needs a second live project in the origin Space.
+ let mut extra = default_project_for_space(DEFAULT_SPACE_ID);
+ extra.id = "proj-extra".to_string();
+ extra.path = PathBuf::from("/tmp/extra");
+ extra.threads.push(WorkspaceThread::new(
+ extra.id.clone(),
+ "main".to_string(),
+ None,
+ ));
+ store.projects.push(extra);
+
+ store.archive_project(&origin_project_id, 100).unwrap();
+ assert!(
+ store.view_for_thread_refs(&coll, &[], None).is_empty(),
+ "refs into an archived project are hidden"
+ );
+ assert!(!store.groom_thread_refs(), "and groom must not prune them");
+ assert!(store
+ .spaces
+ .iter()
+ .find(|s| s.id == coll)
+ .unwrap()
+ .thread_refs
+ .contains(&t1));
+
+ store.unarchive_project(&origin_project_id);
+ assert_eq!(
+ store.view_for_thread_refs(&coll, &[], None).len(),
+ 1,
+ "unarchiving brings the ref row back verbatim"
+ );
+ }
}
diff --git a/wezterm-mux-server-impl/src/thinkterm_layout.rs b/wezterm-mux-server-impl/src/thinkterm_layout.rs
index 4ab60496..b06f9ed9 100644
--- a/wezterm-mux-server-impl/src/thinkterm_layout.rs
+++ b/wezterm-mux-server-impl/src/thinkterm_layout.rs
@@ -255,6 +255,16 @@ fn thread_records(tree: &codec::ThinkTermTree) -> Vec<(String, String)> {
fn snapshot_live_layouts(_generation: u64) -> Result<()> {
let tree = crate::thinkterm_tree::snapshot();
let records = thread_records(&tree);
+ // An archived project's stored layouts are frozen: archiving kills its
+ // panes on purpose, and the stored layout is exactly what unarchiving
+ // restores from. Neither the live-empty prune nor a mid-teardown
+ // partial snapshot may touch them.
+ let archived_thread_ids: HashSet<String> = tree
+ .projects
+ .iter()
+ .filter(|project| project.archived_at.is_some())
+ .flat_map(|project| project.threads.iter().map(|thread| thread.id.clone()))
+ .collect();
let valid_thread_ids = records
.iter()
.map(|(thread_id, _)| thread_id.clone())
@@ -285,6 +295,9 @@ fn snapshot_live_layouts(_generation: u64) -> Result<()> {
let mut candidate = prune_orphaned_layouts(&store.stored, &valid_thread_ids);
for (thread_id, workspace) in &records {
+ if archived_thread_ids.contains(thread_id) {
+ continue;
+ }
if store.restoring_workspaces.contains(workspace) {
continue;
}
@@ -417,6 +430,9 @@ fn working_dir_from_entry(entry: &PaneEntry) -> Option<String> {
}
pub(crate) fn reconcile_with_tree(tree: &codec::ThinkTermTree) -> Result<()> {
+ // Archived projects deliberately keep their layouts: their threads stay
+ // in the tree, so `valid` still covers them and unarchiving can rebuild
+ // the shells from what is stored here.
let valid = tree
.projects
.iter()
diff --git a/wezterm-mux-server-impl/src/thinkterm_session.rs b/wezterm-mux-server-impl/src/thinkterm_session.rs
index d7bfe142..5d69d9ce 100644
--- a/wezterm-mux-server-impl/src/thinkterm_session.rs
+++ b/wezterm-mux-server-impl/src/thinkterm_session.rs
@@ -32,6 +32,10 @@ pub fn snapshot() -> anyhow::Result<ThinkTermSessionState> {
let projects = tree
.projects
.iter()
+ // Archived projects are hidden everywhere; the session projection
+ // (TUI sidebar, CLI listings, attach pickers) must not resurface
+ // them. Their panes are gone, so nothing live is lost.
+ .filter(|project| project.archived_at.is_none())
.map(|project| ThinkTermSessionProject {
id: project.id.clone(),
space_id: project.space_id.clone(),
diff --git a/wezterm-mux-server-impl/src/thinkterm_tree.rs b/wezterm-mux-server-impl/src/thinkterm_tree.rs
index abf8edd1..74529210 100644
--- a/wezterm-mux-server-impl/src/thinkterm_tree.rs
+++ b/wezterm-mux-server-impl/src/thinkterm_tree.rs
@@ -128,11 +128,15 @@ fn ensure_landing_in_tree(
preferred_thread_id: Option<&str>,
) -> (LandingRecord, bool) {
let mut changed = false;
+ // Archived projects never serve as a landing target: a fresh attach
+ // must not silently resurrect a project the user put away. When every
+ // project is archived the None branch below mints a live Home instead.
let selected = preferred_thread_id
.and_then(|preferred| {
tree.projects
.iter()
.enumerate()
+ .filter(|(_, project)| project.archived_at.is_none())
.find_map(|(project_index, project)| {
project
.threads
@@ -145,6 +149,7 @@ fn ensure_landing_in_tree(
tree.projects
.iter()
.enumerate()
+ .filter(|(_, project)| project.archived_at.is_none())
.find_map(|(project_index, project)| {
(!project.threads.is_empty()).then_some((project_index, 0))
})
@@ -160,10 +165,10 @@ fn ensure_landing_in_tree(
});
}
- let project_index = tree
- .projects
- .iter()
- .position(|project| tree.spaces.iter().any(|space| space.id == project.space_id));
+ let project_index = tree.projects.iter().position(|project| {
+ project.archived_at.is_none()
+ && tree.spaces.iter().any(|space| space.id == project.space_id)
+ });
let project_index = match project_index {
Some(index) => index,
None => {
@@ -174,6 +179,7 @@ fn ensure_landing_in_tree(
name: "Home".to_string(),
path: "~".to_string(),
threads: vec![],
+ archived_at: None,
});
tree.projects.len() - 1
}
@@ -277,6 +283,25 @@ fn apply_and_persist(
/// 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> {
+ // Archiving freezes the project's stored layouts, so capture the live
+ // topology while its panes are still running -- the client tears them
+ // down only after this mutation returns. Without this, a change still
+ // inside the snapshot debounce would never be persisted and unarchiving
+ // would restore a stale arrangement. Must run before the TREE lock:
+ // the snapshot reads the tree itself.
+ if ops.iter().any(|op| {
+ matches!(
+ op,
+ TreeOp::SetProjectArchived {
+ archived_at: Some(_),
+ ..
+ }
+ )
+ }) {
+ if let Err(err) = crate::thinkterm_layout::flush_now() {
+ log::error!("flushing layouts before archiving a project: {err:#}");
+ }
+ }
// 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
@@ -483,4 +508,66 @@ mod test {
assert!(tree.spaces[0].id.starts_with("space-"));
assert!(tree.projects[0].id.starts_with("project-"));
}
+
+ #[test]
+ fn landing_skips_archived_projects() {
+ // An archived first project must not host the landing, even when it
+ // is the preferred thread's home.
+ let mut tree = sample();
+ assert!(apply_op(
+ &mut tree,
+ &TreeOp::CreateProject {
+ project_id: "p2".into(),
+ space_id: "s1".into(),
+ name: "second".into(),
+ path: "/srv/projects/second".into(),
+ }
+ ));
+ assert!(apply_op(
+ &mut tree,
+ &TreeOp::CreateThread {
+ thread_id: "t2".into(),
+ project_id: "p2".into(),
+ name: "main".into(),
+ workspace: Some("thinkterm:p2:t2".into()),
+ created_at: 43,
+ }
+ ));
+ assert!(apply_op(
+ &mut tree,
+ &TreeOp::SetProjectArchived {
+ project_id: "p1".into(),
+ archived_at: Some(100),
+ }
+ ));
+
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("t1"));
+ assert!(!changed);
+ assert_eq!(
+ landing.thread_id, "t2",
+ "preferred thread lives in an archived project"
+ );
+
+ // With every project archived, a fresh live Home is minted rather
+ // than landing inside an archived one. apply_op refuses to archive
+ // the last live project, so force the state directly -- external
+ // edits and older writers can still produce it.
+ tree.projects
+ .iter_mut()
+ .find(|project| project.id == "p2")
+ .unwrap()
+ .archived_at = Some(101);
+ let (landing, changed) = ensure_landing_in_tree(&mut tree, None);
+ assert!(changed);
+ let host = tree
+ .projects
+ .iter()
+ .find(|project| project.threads.iter().any(|t| t.id == landing.thread_id))
+ .unwrap();
+ assert_eq!(host.archived_at, None);
+ assert_eq!(host.name, "Home");
+ // The archived projects themselves are untouched.
+ assert!(tree.project("p1").unwrap().archived_at.is_some());
+ assert!(tree.project("p2").unwrap().archived_at.is_some());
+ }
}
diff --git a/window/src/lib.rs b/window/src/lib.rs
index 7d1fb068..e38e1490 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -211,6 +211,8 @@ pub enum ContextMenuItem {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ContextMenuIcon {
Application,
+ Archive,
+ ArchiveRestore,
Back,
Check,
Close,
@@ -274,6 +276,10 @@ impl ContextMenuIcon {
pub fn sf_symbol_name(self) -> &'static str {
match self {
Self::Application => "app",
+ Self::Archive => "archivebox",
+ // The oldest widely-available "take back out of the bin" glyph;
+ // newer restore symbols are too recent to rely on.
+ Self::ArchiveRestore => "tray.and.arrow.up",
Self::Back => "chevron.left",
Self::Check => "checkmark.circle",
Self::Close => "xmark",
@@ -325,6 +331,10 @@ impl ContextMenuIcon {
pub fn lucide_svg(self) -> &'static [u8] {
match self {
Self::Application => include_bytes!("../../third_party/lucide/icons/app-window.svg"),
+ Self::Archive => include_bytes!("../../third_party/lucide/icons/archive.svg"),
+ Self::ArchiveRestore => {
+ include_bytes!("../../third_party/lucide/icons/archive-restore.svg")
+ }
Self::Back | Self::MoveLeft => {
include_bytes!("../../third_party/lucide/icons/arrow-left.svg")
}