A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(settings): export and import ThinkTerm's state from a Backup page
RoversXa76ce9e9ca62
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex c409031c..e2c094b9 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -649,6 +649,26 @@ settings-agent-details-native-doc = Protokollreferenz: docs/agent-status.md im Tsettings-agent-details-pending = Für diesen Agent gibt es keine Bildschirmregeln; ein Lebenszyklus-Adapter ist geplant. Er läuft einwandfrei — nur der Status wird noch nicht angezeigt.# --- Software-Update -------------------------------------------------------settings-section-update = Software-Update+settings-section-backup = Sicherung+settings-backup-description = Sichern Sie Spaces, Projekte, Threads, SSH-Hosts und Snippets von ThinkTerm in einem Ordner Ihrer Wahl oder stellen Sie sie daraus wieder her. Gesichert wird nur, was Sie exportieren.+settings-backup-export = Exportieren+settings-backup-export-description = Legt einen Ordner „ThinkTerm Backup“ an. Gespeicherte SSH-Passwörter funktionieren nur auf diesem Computer; auf einem anderen geben Sie sie erneut ein.+settings-backup-export-button = Exportieren…+settings-backup-import = Importieren+settings-backup-import-description = Stellt eine Sicherung beim nächsten Start von ThinkTerm wieder her. Was sie ersetzt, bleibt daneben erhalten, und Spaces, die der Sitzungsserver dieses Computers noch hat, bleiben ebenfalls.+settings-backup-import-button = Importieren…+settings-backup-import-ready = Import bereit+settings-backup-import-ready-description = Beenden Sie ThinkTerm und öffnen Sie es erneut, um den Import abzuschließen.+settings-backup-quit-button = ThinkTerm beenden+settings-backup-export-picker-title = Speicherort für die Sicherung wählen+settings-backup-import-picker-title = Einen Ordner „ThinkTerm Backup“ wählen+settings-status-backup-exported = Exportiert nach { $path }+settings-status-backup-export-error = Export fehlgeschlagen: { $error }+settings-status-backup-import-staged = Import bereit: Beenden Sie ThinkTerm und öffnen Sie es erneut.+settings-status-backup-import-error = Import fehlgeschlagen: { $error }+settings-status-backup-exporting = Wird exportiert…+settings-status-backup-checking = Sicherung wird geprüft…+settings-backup-import-failed = Import fehlgeschlagensettings-update-current = ThinkTerm ist auf dem neuesten Stand.settings-update-current-detail = ThinkTerm { $version }settings-update-available = Ein Update ist verfügbar.diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 43870d78..e97a92e1 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -649,6 +649,26 @@ settings-agent-details-native-doc = Protocol reference: docs/agent-status.md insettings-agent-details-pending = No screen rules exist for this agent; a lifecycle adapter is planned. It runs fine — status just isn't shown yet.# --- Software Update -------------------------------------------------------settings-section-update = Software Update+settings-section-backup = Backup+settings-backup-description = Save ThinkTerm's Spaces, projects, threads, SSH hosts and snippets to a folder you choose, or bring them back from one. Nothing is backed up unless you export it.+settings-backup-export = Export+settings-backup-export-description = Writes a "ThinkTerm Backup" folder. Saved SSH passwords only work on this computer; on another one, enter them again.+settings-backup-export-button = Export…+settings-backup-import = Import+settings-backup-import-description = Restores a backup the next time ThinkTerm starts. What it replaces is kept beside it, and Spaces still on this computer's session server stay as well.+settings-backup-import-button = Import…+settings-backup-import-ready = Import ready+settings-backup-import-ready-description = Quit ThinkTerm and open it again to finish the import.+settings-backup-quit-button = Quit ThinkTerm+settings-backup-export-picker-title = Choose where to save the backup+settings-backup-import-picker-title = Choose a ThinkTerm Backup folder+settings-status-backup-exported = Exported to { $path }+settings-status-backup-export-error = Export failed: { $error }+settings-status-backup-import-staged = Import ready: quit ThinkTerm and open it again to finish.+settings-status-backup-import-error = Import failed: { $error }+settings-status-backup-exporting = Exporting…+settings-status-backup-checking = Checking the backup…+settings-backup-import-failed = Import failedsettings-update-current = ThinkTerm is up to date.settings-update-current-detail = ThinkTerm { $version }settings-update-available = An update is available.diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex ecae4cd2..9c82b02d 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -646,6 +646,26 @@ settings-agent-details-native-doc = Référence du protocole : docs/agent-statussettings-agent-details-pending = Pas encore de règles d'écran pour cet agent ; un adaptateur est prévu. Il fonctionne normalement, seul l'état n'est pas affiché.# --- Mise à jour logicielle ------------------------------------------------settings-section-update = Mise à jour+settings-section-backup = Sauvegarde+settings-backup-description = Enregistrez les espaces, projets, fils, hôtes SSH et extraits de ThinkTerm dans le dossier de votre choix, ou restaurez-les depuis celui-ci. Rien n'est sauvegardé sans export.+settings-backup-export = Exporter+settings-backup-export-description = Crée un dossier « ThinkTerm Backup ». Les mots de passe SSH enregistrés ne fonctionnent que sur cet ordinateur ; sur un autre, saisissez-les à nouveau.+settings-backup-export-button = Exporter…+settings-backup-import = Importer+settings-backup-import-description = Restaure une sauvegarde au prochain démarrage de ThinkTerm. Ce qu'elle remplace est conservé à côté, et les espaces encore présents sur le serveur de sessions de cet ordinateur restent aussi.+settings-backup-import-button = Importer…+settings-backup-import-ready = Import prêt+settings-backup-import-ready-description = Quittez ThinkTerm puis rouvrez-le pour terminer l'import.+settings-backup-quit-button = Quitter ThinkTerm+settings-backup-export-picker-title = Choisir où enregistrer la sauvegarde+settings-backup-import-picker-title = Choisir un dossier « ThinkTerm Backup »+settings-status-backup-exported = Exporté vers { $path }+settings-status-backup-export-error = Échec de l'export : { $error }+settings-status-backup-import-staged = Import prêt : quittez ThinkTerm puis rouvrez-le.+settings-status-backup-import-error = Échec de l'import : { $error }+settings-status-backup-exporting = Export en cours…+settings-status-backup-checking = Vérification de la sauvegarde…+settings-backup-import-failed = Échec de l'importsettings-update-current = ThinkTerm est à jour.settings-update-current-detail = ThinkTerm { $version }settings-update-available = Une mise à jour est disponible.diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 9d37a1b8..5ed2d3e5 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -634,6 +634,26 @@ settings-agent-details-native-doc = プロトコル資料: ThinkTerm リポジsettings-agent-details-pending = このエージェントにはまだスクリーンルールがありません。アダプターを計画中です。動作には問題なく、状態表示だけ未対応です。# --- ソフトウェアアップデート ----------------------------------------------settings-section-update = ソフトウェアアップデート+settings-section-backup = バックアップ+settings-backup-description = ThinkTerm のスペース、プロジェクト、スレッド、SSH ホスト、スニペットを選んだフォルダに保存したり、そこから戻したりします。書き出さない限り何もバックアップされません。+settings-backup-export = 書き出す+settings-backup-export-description = 「ThinkTerm Backup」フォルダを作成します。保存済みの SSH パスワードはこのコンピュータでのみ使えます。別のコンピュータでは入力し直してください。+settings-backup-export-button = 書き出す…+settings-backup-import = 読み込む+settings-backup-import-description = 次に ThinkTerm を起動したときにバックアップを復元します。置き換えられるデータは横に保存され、このコンピュータのセッションサーバーに残っているスペースもそのまま残ります。+settings-backup-import-button = 読み込む…+settings-backup-import-ready = 読み込みの準備完了+settings-backup-import-ready-description = ThinkTerm を終了してもう一度開くと、読み込みが完了します。+settings-backup-quit-button = ThinkTerm を終了+settings-backup-export-picker-title = バックアップの保存先を選択+settings-backup-import-picker-title = 「ThinkTerm Backup」フォルダを選択+settings-status-backup-exported = { $path } に書き出しました+settings-status-backup-export-error = 書き出しに失敗しました: { $error }+settings-status-backup-import-staged = 読み込みの準備ができました。ThinkTerm を終了してもう一度開いてください。+settings-status-backup-import-error = 読み込みに失敗しました: { $error }+settings-status-backup-exporting = 書き出し中…+settings-status-backup-checking = バックアップを確認中…+settings-backup-import-failed = 読み込みに失敗しましたsettings-update-current = ThinkTerm は最新です。settings-update-current-detail = ThinkTerm { $version }settings-update-available = アップデートがあります。diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex 98ad46f9..c779bca3 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -634,6 +634,26 @@ settings-agent-details-native-doc = 协议文档:ThinkTerm 仓库的 docs/agent-settings-agent-details-pending = 该 agent 暂无屏幕规则;生命周期 adapter 在计划中。它可以正常运行,只是暂不显示状态。# --- 软件更新 --------------------------------------------------------------settings-section-update = 软件更新+settings-section-backup = 备份+settings-backup-description = 把 ThinkTerm 的 Space、项目、线程、SSH 主机和代码片段保存到你选的文件夹,或从中恢复。不导出就不会有任何备份。+settings-backup-export = 导出+settings-backup-export-description = 生成一个“ThinkTerm Backup”文件夹。已保存的 SSH 密码只能在这台电脑上使用,换电脑后需要重新输入。+settings-backup-export-button = 导出…+settings-backup-import = 导入+settings-backup-import-description = 下次启动 ThinkTerm 时恢复备份。被替换的数据会另存在旁边,本机会话服务器上还在的 Space 也会保留。+settings-backup-import-button = 导入…+settings-backup-import-ready = 导入已就绪+settings-backup-import-ready-description = 退出 ThinkTerm 再重新打开即可完成导入。+settings-backup-quit-button = 退出 ThinkTerm+settings-backup-export-picker-title = 选择备份保存位置+settings-backup-import-picker-title = 选择一个“ThinkTerm Backup”文件夹+settings-status-backup-exported = 已导出到 { $path }+settings-status-backup-export-error = 导出失败:{ $error }+settings-status-backup-import-staged = 导入已就绪:退出 ThinkTerm 再重新打开即可完成。+settings-status-backup-import-error = 导入失败:{ $error }+settings-status-backup-exporting = 正在导出…+settings-status-backup-checking = 正在检查备份…+settings-backup-import-failed = 导入失败settings-update-current = ThinkTerm 已是最新版本。settings-update-current-detail = ThinkTerm { $version }settings-update-available = 有可用更新。diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 7e25a1be..6c998adb 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -69,6 +69,7 @@ mod shell_catalog;mod snippets;mod spawn;mod ssh_hosts;+mod state_backup;mod stats;mod tabbar;mod termwindow;@@ -201,6 +202,7 @@ async fn async_run_ssh(opts: SshCommand) -> anyhow::Result<()> {}fn run_ssh(opts: SshCommand) -> anyhow::Result<()> {+ crate::state_backup::enter_gui();if let Some(cls) = opts.class.as_ref() {crate::set_window_class(cls);}@@ -254,6 +256,7 @@ async fn async_run_serial(opts: SerialCommand) -> anyhow::Result<()> {}fn run_serial(config: config::ConfigHandle, opts: SerialCommand) -> anyhow::Result<()> {+ crate::state_backup::enter_gui();if let Some(cls) = opts.class.as_ref() {crate::set_window_class(cls);}@@ -1345,6 +1348,8 @@ fn build_initial_mux(}fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) -> anyhow::Result<()> {+ // Before anything reads the state: an import staged from Settings.+ crate::state_backup::enter_gui();if let Some(cls) = opts.class.as_ref() {crate::set_window_class(cls);}diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex b5c9e2d2..82c314ca 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -343,6 +343,7 @@ enum SettingsSection {Developer,UiKit,Memory,+ Backup,Update,About,}@@ -360,6 +361,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[SettingsSection::CommandPalette,SettingsSection::Compatibility,SettingsSection::Developer,+ SettingsSection::Backup,SettingsSection::Update,SettingsSection::About,];@@ -425,6 +427,7 @@ fn initial_section() -> SettingsSection {"developer" => SettingsSection::Developer,"uikit" => SettingsSection::UiKit,"memory" => SettingsSection::Memory,+ "backup" => SettingsSection::Backup,"update" => SettingsSection::Update,"about" => SettingsSection::About,_ => SettingsSection::Appearance,@@ -452,6 +455,7 @@ impl SettingsSection {Self::Developer => crate::i18n::tr("settings-section-developer"),Self::UiKit => "UI Kit".to_string(),Self::Memory => "Memory".to_string(),+ Self::Backup => crate::i18n::tr("settings-section-backup"),Self::Update => crate::i18n::tr("settings-section-update"),Self::About => crate::i18n::tr("settings-section-about"),}@@ -473,6 +477,7 @@ impl SettingsSection {Self::Developer => SettingsIcon::Developer,Self::UiKit => SettingsIcon::UiKit,Self::Memory => SettingsIcon::Memory,+ Self::Backup => SettingsIcon::Backup,Self::Update => SettingsIcon::Update,Self::About => SettingsIcon::About,}@@ -648,6 +653,15 @@ impl SettingsSection {"Agent Panel","Right Sidebar",],+ Self::Backup => &[+ "Backup",+ "Export",+ "Import",+ "Restore",+ "Spaces",+ "SSH Hosts",+ "Snippets",+ ],Self::Update => &["Update","Software Update",@@ -898,6 +912,8 @@ enum SettingsAction {OpenThirdPartyNotices,OpenPrivacyPolicy,OpenDataFolder,+ ExportBackup,+ ImportBackup,CopyVersionInfo,ToggleThemeModeMenu,SetThemeMode(NativeThemeMode),@@ -3251,6 +3267,91 @@ impl SettingsWindow {}}+ /// Pick where to export a backup to, or which backup to import.+ fn choose_backup_folder(&mut self, import: bool) {+ self.ui.open_dropdown = None;+ let Some(window) = self.window.clone() else {+ return;+ };+ let instance_id = self.instance_id;+ let notify = window.clone();+ let title = if import {+ "settings-backup-import-picker-title"+ } else {+ "settings-backup-export-picker-title"+ };+ window.pick_folder_async_with_options(+ FolderPickerOptions {+ title: crate::i18n::tr(title),+ prompt: crate::i18n::tr("common-choose"),+ ..Default::default()+ },+ Box::new(move |path| {+ let Some(path) = path else {+ return;+ };+ promise::spawn::spawn_into_main_thread(async move {+ if let Some(settings) = settings_window_for_instance(instance_id) {+ settings.borrow_mut().finish_backup(import, path);+ notify.invalidate();+ }+ })+ .detach();+ }),+ );+ }++ /// Export to, or stage an import from, the folder picked. The copies can+ /// be slow on a network or synced folder, so they run off the UI thread+ /// and report back through the status line.+ fn finish_backup(&mut self, import: bool, path: PathBuf) {+ self.status = crate::i18n::tr(if import {+ "settings-status-backup-checking"+ } else {+ "settings-status-backup-exporting"+ });+ let instance_id = self.instance_id;+ let window = self.window.clone();+ promise::spawn::spawn(async move {+ let done = promise::spawn::spawn_into_new_thread(move || {+ Ok::<_, anyhow::Error>(if import {+ crate::state_backup::stage_import(&path).map(|()| None)+ } else {+ crate::state_backup::export(&path).map(Some)+ })+ })+ .await+ .and_then(|done| done);+ let status = match (import, done) {+ (true, Ok(_)) => crate::i18n::tr("settings-status-backup-import-staged"),+ (true, Err(err)) => settings_tr(+ "settings-status-backup-import-error",+ &[("error", format!("{err:#}"))],+ ),+ (false, Ok(folder)) => settings_tr(+ "settings-status-backup-exported",+ &[(+ "path",+ folder+ .map(|folder| folder.display().to_string())+ .unwrap_or_default(),+ )],+ ),+ (false, Err(err)) => settings_tr(+ "settings-status-backup-export-error",+ &[("error", format!("{err:#}"))],+ ),+ };+ if let Some(settings) = settings_window_for_instance(instance_id) {+ settings.borrow_mut().status = status;+ }+ if let Some(window) = window {+ window.invalidate();+ }+ })+ .detach();+ }+fn choose_remote_download_directory(&mut self) {self.ui.open_dropdown = None;let Some(window) = self.window.clone() else {@@ -4720,6 +4821,8 @@ impl SettingsWindow {self.ui.open_dropdown = None;Self::open_path(config::DATA_DIR.clone());}+ SettingsAction::ExportBackup => self.choose_backup_folder(false),+ SettingsAction::ImportBackup => self.choose_backup_folder(true),SettingsAction::CopyVersionInfo => {self.ui.open_dropdown = None;window.set_clipboard(Clipboard::Clipboard, self.version_info_for_clipboard());@@ -5722,6 +5825,7 @@ impl SettingsWindow {SettingsSection::UiKit => self.paint_ui_kit(layers, x, max_width)?,SettingsSection::Memory => self.paint_memory_diagnostics(layers, x, max_width)?,SettingsSection::Sidebar => self.paint_sidebar_settings(layers, x, max_width)?,+ SettingsSection::Backup => self.paint_backup(layers, x, max_width)?,SettingsSection::Update => self.paint_update(layers, x, max_width)?,SettingsSection::About => self.paint_about(layers, x, max_width)?,}@@ -8460,6 +8564,91 @@ impl SettingsWindow {Ok(())}+ fn paint_backup(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ max_width: f32,+ ) -> anyhow::Result<()> {+ let palette = self.palette();+ let body_font = Rc::clone(&self.body_font);+ let scroll = self.ui.content_scroll.offset;+ let row_step = self.settings_row_step();+ let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;+ let staged = crate::state_backup::import_staged();+ let failed = crate::state_backup::last_import_error();+ let row_count = 2 + usize::from(staged) + usize::from(failed.is_some());+ 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.draw_text(+ layers,+ &body_font,+ x,+ section_y,+ &crate::i18n::tr("settings-backup-description"),+ palette.secondary_text,+ max_width,+ )?;+ let card_padding = self.ui_px(36.0);+ let row_x = x + card_padding;+ let row_width = max_width - card_padding * 2.0;+ self.paint_group_card(layers, x, card_y, max_width, card_height)?;+ self.paint_action_setting_row(+ layers,+ row_x,+ first_row_y,+ row_width,+ &crate::i18n::tr("settings-backup-export"),+ &crate::i18n::tr("settings-backup-export-description"),+ &crate::i18n::tr("settings-backup-export-button"),+ SettingsAction::ExportBackup,+ false,+ )?;+ self.paint_action_setting_row(+ layers,+ row_x,+ first_row_y + row_step,+ row_width,+ &crate::i18n::tr("settings-backup-import"),+ &crate::i18n::tr("settings-backup-import-description"),+ &crate::i18n::tr("settings-backup-import-button"),+ SettingsAction::ImportBackup,+ true,+ )?;+ let mut next_row_y = first_row_y + row_step * 2.0;+ if staged {+ self.paint_action_setting_row(+ layers,+ row_x,+ next_row_y,+ row_width,+ &crate::i18n::tr("settings-backup-import-ready"),+ &crate::i18n::tr("settings-backup-import-ready-description"),+ &crate::i18n::tr("settings-backup-quit-button"),+ SettingsAction::QuitApplication,+ true,+ )?;+ next_row_y += row_step;+ }+ if let Some(error) = failed {+ self.paint_setting_row(+ layers,+ row_x,+ next_row_y,+ row_width,+ &crate::i18n::tr("settings-backup-import-failed"),+ &error,+ "",+ true,+ )?;+ }+ Ok(())+ }+fn paint_compatibility(&mut self,layers: &mut TripleLayerQuadAllocator<'_>,diff --git a/wezterm-gui/src/snippets.rs b/wezterm-gui/src/snippets.rsindex 7efbfd2b..96a52d94 100644--- a/wezterm-gui/src/snippets.rs+++ b/wezterm-gui/src/snippets.rs@@ -81,6 +81,11 @@ fn load_snippet_store() -> Result<SnippetStore> {load_snippet_store_from_path(&snippets_store_path())}+/// Whether `path` reads as a snippet store, as an imported backup must.+pub(crate) fn check_snippet_store(path: &Path) -> Result<()> {+ load_snippet_store_from_path(path).map(drop)+}+fn load_snippet_store_from_path(path: &Path) -> Result<SnippetStore> {if !path.exists() {return Ok(SnippetStore::default());diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rsindex df4106bf..9abf3e07 100644--- a/wezterm-gui/src/ssh_hosts.rs+++ b/wezterm-gui/src/ssh_hosts.rs@@ -84,6 +84,11 @@ fn load_ssh_host_store() -> Result<SshHostStore> {load_ssh_host_store_from_path(&ssh_hosts_store_path()?)}+/// Whether `path` reads as a host catalog, as an imported backup must.+pub(crate) fn check_ssh_host_store(path: &Path) -> Result<()> {+ load_ssh_host_store_from_path(path).map(drop)+}+fn load_ssh_host_store_from_path(path: &Path) -> Result<SshHostStore> {if !path.exists() {return Ok(SshHostStore::default());diff --git a/wezterm-gui/src/state_backup.rs b/wezterm-gui/src/state_backup.rsnew file mode 100644index 00000000..5130e78c--- /dev/null+++ b/wezterm-gui/src/state_backup.rs@@ -0,0 +1,529 @@+//! Export and import of ThinkTerm's own state, by hand from Settings.+//!+//! Nothing here runs unasked. An export writes the Spaces, projects and+//! threads, the saved SSH hosts, the snippets and the recent commands into a+//! folder the user picks. An import cannot swap those files under a running+//! window, which holds them in memory and writes them back, so it is staged+//! beside the state and applied by the next launch that finds no other window+//! running, before anything reads the state. What it replaces is kept beside+//! it first.+//!+//! The Spaces this app shares with its local session server are merged on the+//! next connection: the server adds back the Spaces it still has, and its+//! names win where both have one. An import brings back what the backup+//! holds; it does not remove what the server kept.+//!+//! `secret.key` is never exported: saved host passwords stay encrypted with+//! this machine's key, so on another machine they have to be entered again.++use anyhow::{bail, Context, Result};+use serde::{Deserialize, Serialize};+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::time::{Duration, Instant};++/// Names the files in a backup folder; its presence is what makes a folder+/// one.+const MANIFEST: &str = "thinkterm-backup.json";+const FORMAT: u32 = 1;+const STORE: &str = "workspace_threads.json";++/// The staged import, in the state folder.+const PENDING: &str = ".import-pending";+/// Held shared by every running window for its whole life. An import is+/// applied only by a launch that can hold it alone, so never under a window+/// that has the old state in memory.+const RUNNING_LOCK: &str = ".windows-running.lock";+/// How long a launch with an import waiting gives the windows still running+/// to exit: long enough for a restart's old process, short enough not to+/// stall a launch that is only handing a request to a running window.+const WAIT_FOR_OTHERS: Duration = Duration::from_secs(5);++#[derive(Serialize, Deserialize)]+struct Manifest {+ format: u32,+ created: String,+ files: Vec<String>,+}++static IMPORT_STAGED: AtomicBool = AtomicBool::new(false);+static LAST_IMPORT_ERROR: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);++/// Whether an import waits for this window to quit.+pub(crate) fn import_staged() -> bool {+ IMPORT_STAGED.load(Ordering::Relaxed)+}++/// Why the import staged last session could not be applied, if it could not.+pub(crate) fn last_import_error() -> Option<String> {+ LAST_IMPORT_ERROR+ .lock()+ .unwrap_or_else(|err| err.into_inner())+ .clone()+}++/// Each file a backup may hold, by its name in the backup, and where it+/// lives.+fn state_files() -> Vec<(&'static str, Option<PathBuf>)> {+ vec![+ (+ STORE,+ Some(crate::workspace_threads::workspace_thread_store_path()),+ ),+ (+ "ssh_hosts.json",+ thinkterm_core::ssh_hosts::saved_hosts_path().ok(),+ ),+ (+ "snippets.json",+ Some(crate::snippets::snippets_store_path()),+ ),+ (+ "recent-commands.json",+ Some(config::DATA_DIR.join("recent-commands.json")),+ ),+ ]+}++/// Read a backup's file the way the app would, without the migrations its+/// loaders run on the live state.+fn check_file(name: &str, path: &Path) -> Result<()> {+ match name {+ STORE => {+ serde_json::from_slice::<crate::workspace_threads::WorkspaceThreadStore>(&fs::read(+ path,+ )?)?;+ }+ "ssh_hosts.json" => {+ crate::ssh_hosts::check_ssh_host_store(path)?;+ }+ "snippets.json" => {+ crate::snippets::check_snippet_store(path)?;+ }+ _ => {+ serde_json::from_slice::<serde_json::Value>(&fs::read(path)?)?;+ }+ }+ Ok(())+}++#[cfg(unix)]+fn make_private(path: &Path) -> Result<()> {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(path, fs::Permissions::from_mode(0o600))+ .with_context(|| format!("make {} private", path.display()))+}++#[cfg(not(unix))]+fn make_private(_path: &Path) -> Result<()> {+ Ok(())+}++/// Write the current state into a new folder inside `into` and return it.+/// The Spaces come from memory, so the export has what is on screen even if+/// the last save is still on its way to disk. Blocking: call it off the UI+/// thread.+pub(crate) fn export(into: &Path) -> Result<PathBuf> {+ if crate::workspace_threads::workspace_thread_store_is_unreadable() {+ bail!("ThinkTerm could not read its Spaces when it started, so there are none to export");+ }+ let store = crate::workspace_threads::workspace_thread_store_snapshot();+ let files: Vec<(&str, PathBuf)> = state_files()+ .into_iter()+ .filter(|(name, _)| *name != STORE)+ .filter_map(|(name, path)| Some((name, path?)))+ .collect();+ export_to(into, &store, &files)+}++fn export_to(+ into: &Path,+ store: &crate::workspace_threads::WorkspaceThreadStore,+ files: &[(&str, PathBuf)],+) -> Result<PathBuf> {+ let stamp = chrono::Local::now().format("%Y-%m-%d %H%M%S").to_string();+ let mut target = into.join(format!("ThinkTerm Backup {stamp}"));+ let mut serial = 1;+ while target.exists() {+ serial += 1;+ target = into.join(format!("ThinkTerm Backup {stamp} {serial}"));+ }+ // Built beside the target and renamed into place, so a folder with the+ // backup's name is always a whole one.+ let staging = tempfile::Builder::new()+ .prefix(".thinkterm-backup-")+ .tempdir_in(into)+ .with_context(|| format!("create a folder in {}", into.display()))?;+ let mut written = vec![STORE.to_string()];+ crate::workspace_threads::save_workspace_thread_store_to_path(+ &staging.path().join(STORE),+ store,+ )?;+ for (name, from) in files {+ if from.is_file() {+ let to = staging.path().join(name);+ fs::copy(from, &to).with_context(|| format!("copy {name}"))?;+ make_private(&to)?;+ written.push(name.to_string());+ }+ }+ let manifest = Manifest {+ format: FORMAT,+ created: chrono::Local::now().to_rfc3339(),+ files: written,+ };+ fs::write(+ staging.path().join(MANIFEST),+ serde_json::to_vec_pretty(&manifest)?,+ )?;+ let staged = staging.keep();+ if let Err(err) = fs::rename(&staged, &target) {+ let _ = fs::remove_dir_all(&staged);+ return Err(err).with_context(|| format!("create {}", target.display()));+ }+ Ok(target)+}++/// Check `from` is a backup and stage it to be applied once this window has+/// quit. Blocking: call it off the UI thread.+pub(crate) fn stage_import(from: &Path) -> Result<()> {+ stage_import_into(from, &crate::native_paths::data_dir())?;+ IMPORT_STAGED.store(true, Ordering::Relaxed);+ Ok(())+}++fn stage_import_into(from: &Path, data: &Path) -> Result<()> {+ let manifest: Manifest = serde_json::from_slice(+ &fs::read(from.join(MANIFEST))+ .with_context(|| format!("{} is not a ThinkTerm backup", from.display()))?,+ )+ .context("read the backup's manifest")?;+ if manifest.format != FORMAT {+ bail!("this backup was made by a different version of ThinkTerm");+ }+ let known: Vec<&str> = state_files().iter().map(|(name, _)| *name).collect();+ let names: Vec<&String> = manifest+ .files+ .iter()+ .filter(|name| known.contains(&name.as_str()))+ .collect();+ if !names.iter().any(|name| *name == STORE) {+ bail!("the backup has no Spaces to import");+ }+ // Every file must read back before anything is staged.+ for name in &names {+ check_file(name, &from.join(name))+ .with_context(|| format!("{name} in the backup cannot be read"))?;+ }++ config::create_user_owned_dirs(data)?;+ let staging = tempfile::Builder::new()+ .prefix(".import-staging-")+ .tempdir_in(data)?;+ for name in &names {+ let to = staging.path().join(name);+ fs::copy(from.join(name), &to).with_context(|| format!("copy {name}"))?;+ make_private(&to)?;+ }+ let pending = data.join(PENDING);+ let _ = fs::remove_dir_all(&pending);+ let staged = staging.keep();+ if let Err(err) = fs::rename(&staged, &pending) {+ let _ = fs::remove_dir_all(&staged);+ return Err(err).context("stage the import");+ }+ Ok(())+}++/// Called first by every way the GUI starts, before anything reads the+/// state: apply an import waiting from last session if no other window is+/// running, then join the running windows for the rest of this process.+pub(crate) fn enter_gui() {+ let data = crate::native_paths::data_dir();+ if let Err(err) = config::create_user_owned_dirs(&data) {+ log::warn!("cannot create {}: {err:#}", data.display());+ return;+ }+ let lock = match fs::OpenOptions::new()+ .create(true)+ .write(true)+ .truncate(false)+ .open(data.join(RUNNING_LOCK))+ {+ Ok(lock) => lock,+ Err(err) => {+ log::warn!("cannot open the window lock: {err:#}");+ return;+ }+ };+ if data.join(PENDING).is_dir() {+ let alone = match wait_for(|| lock.try_lock()) {+ Ok(alone) => alone,+ Err(err) => {+ // A folder that cannot lock cannot say whether a window runs;+ // the import is what was asked for, so it goes ahead.+ log::warn!("cannot lock {}: {err}; importing unchecked", data.display());+ true+ }+ };+ if alone {+ let targets: Vec<(&str, PathBuf)> = state_files()+ .into_iter()+ .filter_map(|(name, path)| Some((name, path?)))+ .collect();+ match apply_pending_into(&data, &targets) {+ Ok(()) => log::warn!("imported the ThinkTerm backup staged last session"),+ Err(err) => {+ log::error!("cannot import the staged ThinkTerm backup: {err:#}");+ *LAST_IMPORT_ERROR+ .lock()+ .unwrap_or_else(|err| err.into_inner()) = Some(format!("{err:#}"));+ }+ }+ let _ = lock.unlock();+ } else {+ log::warn!("another ThinkTerm window still runs; the import waits for a later launch");+ }+ }+ IMPORT_STAGED.store(data.join(PENDING).is_dir(), Ordering::Relaxed);+ // Joined for good; waits only while another launch is mid-import.+ if let Ok(false) | Err(_) = wait_for(|| lock.try_lock_shared()) {+ log::warn!("cannot hold the window lock; an import could apply under this window");+ }+ static HELD: std::sync::OnceLock<fs::File> = std::sync::OnceLock::new();+ let _ = HELD.set(lock);+}++/// Try `lock` until it succeeds or `WAIT_FOR_OTHERS` passes: `Ok(false)` if+/// it is still held elsewhere, `Err` if the folder cannot lock at all.+fn wait_for(lock: impl Fn() -> Result<(), fs::TryLockError>) -> std::io::Result<bool> {+ let deadline = Instant::now() + WAIT_FOR_OTHERS;+ loop {+ match lock() {+ Ok(()) => return Ok(true),+ Err(fs::TryLockError::WouldBlock) if Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(100));+ }+ Err(fs::TryLockError::WouldBlock) => return Ok(false),+ Err(fs::TryLockError::Error(err)) => return Err(err),+ }+ }+}++/// Put the staged files in place. Every file is first copied beside its+/// target, and what it replaces kept, before any target is touched; if that+/// fails the copies are removed and nothing changes. Then each is renamed+/// over its target. The staged import is cleared either way, so a failure is+/// reported once rather than retried at every launch.+fn apply_pending_into(data: &Path, targets: &[(&str, PathBuf)]) -> Result<()> {+ let pending = data.join(PENDING);+ let result = prepare_and_replace(&pending, targets);+ let cleared = fs::remove_dir_all(&pending).context("clear the staged import");+ result.and(cleared)+}++fn prepare_and_replace(pending: &Path, targets: &[(&str, PathBuf)]) -> Result<()> {+ let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();+ let mut prepared: Vec<(PathBuf, &PathBuf)> = vec![];+ let mut kept: Vec<PathBuf> = vec![];+ let prepare = (|| -> Result<()> {+ for (name, target) in targets {+ let from = pending.join(name);+ if !from.is_file() {+ continue;+ }+ if let Some(parent) = target.parent() {+ config::create_user_owned_dirs(parent)?;+ }+ if target.is_file() {+ let stem = Path::new(name)+ .file_stem()+ .and_then(|stem| stem.to_str())+ .unwrap_or(name);+ let keep = target.with_file_name(format!("{stem}.before-import-{stamp}.json"));+ fs::copy(target, &keep).with_context(|| format!("keep the current {name}"))?;+ kept.push(keep);+ }+ let temp = target.with_file_name(format!(".{name}.importing"));+ fs::copy(&from, &temp).with_context(|| format!("copy {name}"))?;+ prepared.push((temp.clone(), target));+ make_private(&temp)?;+ }+ Ok(())+ })();+ if let Err(err) = prepare {+ for (temp, _) in &prepared {+ let _ = fs::remove_file(temp);+ }+ for keep in &kept {+ let _ = fs::remove_file(keep);+ }+ return Err(err);+ }+ let mut failed = None;+ for (temp, target) in &prepared {+ if let Err(err) = fs::rename(temp, target) {+ let _ = fs::remove_file(temp);+ failed.get_or_insert_with(|| {+ anyhow::Error::new(err).context(format!("replace {}", target.display()))+ });+ }+ }+ match failed {+ Some(err) => Err(err),+ None => Ok(()),+ }+}++#[cfg(test)]+mod test {+ use super::*;++ fn write(dir: &Path, name: &str, body: &str) {+ fs::create_dir_all(dir).unwrap();+ fs::write(dir.join(name), body).unwrap();+ }++ fn exported(base: &Path) -> PathBuf {+ let state = base.join("state");+ write(&state, "ssh_hosts.json", "{\"version\":1,\"hosts\":[]}");+ write(&state, "secret.key", "key");+ let into = base.join("exports");+ fs::create_dir_all(&into).unwrap();+ export_to(+ &into,+ &crate::workspace_threads::WorkspaceThreadStore::default(),+ &[+ ("ssh_hosts.json", state.join("ssh_hosts.json")),+ ("snippets.json", state.join("snippets.json")),+ ],+ )+ .unwrap()+ }++ fn names_in(dir: &Path) -> Vec<String> {+ let mut names: Vec<String> = fs::read_dir(dir)+ .unwrap()+ .flatten()+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .collect();+ names.sort();+ names+ }++ #[test]+ fn an_export_is_one_whole_folder_without_the_key() {+ let base = tempfile::tempdir().unwrap();+ let backup = exported(base.path());+ assert!(backup+ .file_name()+ .unwrap()+ .to_string_lossy()+ .starts_with("ThinkTerm Backup "));+ assert!(backup.join(STORE).is_file());+ assert!(backup.join("ssh_hosts.json").is_file());+ // Not there to copy, so not listed either.+ assert!(!backup.join("snippets.json").exists());+ assert!(!backup.join("secret.key").exists());+ let manifest: Manifest =+ serde_json::from_slice(&fs::read(backup.join(MANIFEST)).unwrap()).unwrap();+ assert_eq!(manifest.files, vec![STORE, "ssh_hosts.json"]);+ // No staging folder is left behind.+ assert_eq!(names_in(&base.path().join("exports")).len(), 1);+ }++ #[test]+ fn an_import_is_staged_then_applied_keeping_what_it_replaces() {+ let base = tempfile::tempdir().unwrap();+ let backup = exported(base.path());+ let data = base.path().join("data");+ let store = data.join(STORE);+ write(&data, STORE, "{\"current\":true}");+ stage_import_into(&backup, &data).unwrap();+ // Staging changes nothing yet.+ assert_eq!(fs::read_to_string(&store).unwrap(), "{\"current\":true}");++ let hosts = base.path().join("elsewhere/ssh_hosts.json");+ let targets = [(STORE, store.clone()), ("ssh_hosts.json", hosts.clone())];+ apply_pending_into(&data, &targets).unwrap();+ assert_eq!(+ fs::read(&store).unwrap(),+ fs::read(backup.join(STORE)).unwrap()+ );+ assert!(hosts.is_file());+ let kept: Vec<String> = names_in(&data)+ .into_iter()+ .filter(|name| name.starts_with("workspace_threads.before-import-"))+ .collect();+ assert_eq!(kept.len(), 1);+ assert_eq!(+ fs::read_to_string(data.join(&kept[0])).unwrap(),+ "{\"current\":true}"+ );+ // Applied once only, and nothing half-done is left.+ assert!(!data.join(PENDING).exists());+ assert!(!names_in(&data)+ .iter()+ .any(|name| name.ends_with(".importing")));+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = fs::metadata(&hosts).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600);+ }+ }++ #[test]+ fn a_failed_import_changes_nothing_and_is_not_retried() {+ let base = tempfile::tempdir().unwrap();+ let backup = exported(base.path());+ let data = base.path().join("data");+ let store = data.join(STORE);+ write(&data, STORE, "{\"current\":true}");+ stage_import_into(&backup, &data).unwrap();+ // A target whose folder cannot be made (a file is in the way) fails+ // while the files are being prepared, after the store was.+ fs::write(base.path().join("blocked"), "x").unwrap();+ let blocked = base.path().join("blocked/ssh_hosts.json");+ let targets = [(STORE, store.clone()), ("ssh_hosts.json", blocked)];+ assert!(apply_pending_into(&data, &targets).is_err());+ assert_eq!(fs::read_to_string(&store).unwrap(), "{\"current\":true}");+ assert!(!data.join(PENDING).exists());+ // Nothing prepared or kept is left behind.+ assert_eq!(names_in(&data), vec![STORE.to_string()]);+ }++ #[test]+ fn a_folder_that_is_not_a_backup_is_refused() {+ let base = tempfile::tempdir().unwrap();+ let data = base.path().join("data");+ let stranger = base.path().join("stranger");+ write(&stranger, STORE, "{}");+ assert!(stage_import_into(&stranger, &data).is_err());+ // Valid JSON of the wrong shape is refused too.+ let backup = exported(base.path());+ fs::write(backup.join("ssh_hosts.json"), "{\"hosts\":\"x\"}").unwrap();+ assert!(stage_import_into(&backup, &data).is_err());+ assert!(!data.join(PENDING).exists());+ }++ #[test]+ fn only_a_lock_held_elsewhere_makes_a_launch_wait() {+ let base = tempfile::tempdir().unwrap();+ let path = base.path().join(RUNNING_LOCK);+ let running = fs::File::create(&path).unwrap();+ running.try_lock_shared().unwrap();+ // Another window running: the exclusive lock an import needs waits,+ // then gives up; joining the running windows does not wait.+ let starting = fs::File::create(&path).unwrap();+ assert!(matches!(+ starting.try_lock(),+ Err(fs::TryLockError::WouldBlock)+ ));+ assert!(wait_for(|| starting.try_lock_shared()).unwrap());+ drop(running);+ starting.unlock().unwrap();+ assert!(wait_for(|| starting.try_lock()).unwrap());+ }+}diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rsindex c49d29cf..27009a45 100644--- a/wezterm-gui/src/ui/icons.rs+++ b/wezterm-gui/src/ui/icons.rs@@ -16,6 +16,7 @@ pub(crate) enum SettingsIcon {Update,About,Archived,+ Backup,Web,CommandPalette,Search,@@ -40,6 +41,7 @@ impl SettingsIcon {Self::Update => SvgIcon::RefreshCw,Self::About => SvgIcon::Info,Self::Archived => SvgIcon::Archive,+ Self::Backup => SvgIcon::Save,Self::Web => SvgIcon::Globe,Self::CommandPalette => SvgIcon::SquareTerminal,Self::Search => SvgIcon::Search,diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex de5b22f7..95ff97be 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -769,6 +769,19 @@ pub fn workspace_thread_store_path() -> PathBuf {crate::native_paths::data_file("workspace_threads.json")}+/// The store as the app holds it now, which a save may not have reached yet.+pub fn workspace_thread_store_snapshot() -> WorkspaceThreadStore {+ THREAD_STORE.lock().clone()+}++/// Whether the store on disk could not be read at start, so the one in+/// memory is an empty stand-in (see `STORE_IS_UNREADABLE`).+pub fn workspace_thread_store_is_unreadable() -> bool {+ // Reading the store is what sets the flag.+ drop(THREAD_STORE.lock());+ STORE_IS_UNREADABLE.load(Ordering::Acquire)+}+pub fn load_workspace_thread_store() -> Result<WorkspaceThreadStore> {load_workspace_thread_store_from_path(&workspace_thread_store_path())}