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(restore): keep pane contents across quit, logout and shutdown
RoversXeb951c93580b
diff --git a/Cargo.lock b/Cargo.lockindex c2936ac4..e07de5e7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5428,6 +5428,7 @@ dependencies = ["serial2","shell-words","smol",+ "tempfile","terminfo","termwiz 0.24.0","termwiz-funcs",@@ -5441,6 +5442,7 @@ dependencies = ["wezterm-term","wezterm-uds","winapi",+ "zstd",][[package]]@@ -12057,6 +12059,7 @@ dependencies = ["sha2 0.10.9","shared_library","shlex 1.3.0",+ "signal-hook","smol","sys-locale","tabout",diff --git a/lua-api-crates/termwiz-funcs/src/lib.rs b/lua-api-crates/termwiz-funcs/src/lib.rsindex e0433e61..e455eb03 100644--- a/lua-api-crates/termwiz-funcs/src/lib.rs+++ b/lua-api-crates/termwiz-funcs/src/lib.rs@@ -276,6 +276,11 @@ pub fn lines_to_escapes(lines: Vec<Line>) -> anyhow::Result<String> {}}changes.push(Change::AllAttributes(CellAttributes::blank()));+ changes_to_escapes(&changes)+}++/// `changes` as the escape sequences a terminal would be sent for them.+pub fn changes_to_escapes(changes: &[Change]) -> anyhow::Result<String> {let mut renderer = new_wezterm_terminfo_renderer();struct Target {@@ -298,6 +303,6 @@ pub fn lines_to_escapes(lines: Vec<Line>) -> anyhow::Result<String> {}let mut target = Target { target: vec![] };- renderer.render_to(&changes, &mut target)?;+ renderer.render_to(changes, &mut target)?;Ok(String::from_utf8(target.target)?)}diff --git a/mux/Cargo.toml b/mux/Cargo.tomlindex 7f56c5d6..0336630d 100644--- a/mux/Cargo.toml+++ b/mux/Cargo.toml@@ -13,7 +13,8 @@ async-trait.workspace = truebase64.workspace = truebintree.workspace = truebitflags.workspace = true-chrono.workspace = true+# The local time a restored pane's separator line shows.+chrono = { workspace = true, features = ["clock"] }config.workspace = truecrossbeam.workspace = truedowncast-rs.workspace = true@@ -51,6 +52,7 @@ url.workspace = truewezterm-dynamic.workspace = truewezterm-ssh.workspace = truewezterm-term = { workspace=true, features=["use_serde"] }+zstd.workspace = true[target."cfg(windows)".dependencies]ntapi.workspace = true@@ -71,3 +73,4 @@ winapi = { workspace=true, features = [[dev-dependencies]k9.workspace = true+tempfile.workspace = truediff --git a/mux/src/domain.rs b/mux/src/domain.rsindex a9a08e90..446fa41d 100644--- a/mux/src/domain.rs+++ b/mux/src/domain.rs@@ -735,10 +735,12 @@ impl Domain for LocalDomain {async fn spawn_pane(&self,size: TerminalSize,- command: Option<CommandBuilder>,+ mut command: Option<CommandBuilder>,command_dir: Option<String>,) -> anyhow::Result<Arc<dyn Pane>> {let pane_id = alloc_pane_id();+ // A pane a restored layout spawns starts with what it showed.+ let kept = crate::kept_output::take_seed(&mut command);let cmd = self.build_command(command, command_dir, pane_id).await@@ -773,6 +775,10 @@ impl Domain for LocalDomain {if self.is_conpty() {terminal.enable_conpty_quirks();}+ // Before the reader starts, so the shell's first output lands below.+ if let Some(kept) = &kept {+ terminal.advance_bytes(kept.bytes(size.rows, self.is_conpty()));+ }let pane_writer = terminal.writer_handle();let pane: Arc<dyn Pane> = match child_result {@@ -806,6 +812,11 @@ impl Domain for LocalDomain {let mux = Mux::get();mux.add_pane(&pane)?;+ // Kept until here: a spawn that failed on the way leaves the record+ // for the next try.+ if let Some(kept) = kept {+ kept.spend();+ }Ok(pane)}diff --git a/mux/src/kept_output.rs b/mux/src/kept_output.rsnew file mode 100644index 00000000..83ac0f71--- /dev/null+++ b/mux/src/kept_output.rs@@ -0,0 +1,900 @@+//! What a pane showed when the process holding it stopped, kept on disk+//! until its Thread's layout is restored and then put back above the new+//! shell. Off unless Settings turns it on.+//!+//! Only a controlled exit keeps anything: a shutdown or logout, the session+//! server being stopped, ThinkTerm quitting with its terminals inside it. A+//! crash brings the layout back without it. A record is read once, by the+//! local domain spawning the pane that takes its place, and removed; nothing+//! is held in memory in between.+//!+//! Whoever restores a layout -- the session server for its own Threads, the+//! app for the ones it rebuilds, here or in the local session server -- says+//! in the spawn command which record a pane starts with, and the process that+//! spawns it reads that from this machine's disk.+//!+//! Kept: the primary screen and its scrollback, as text and colors. Not+//! kept: a full-screen program's frame, pictures, and whatever looks like a+//! password or token -- masked before anything is written, so the original+//! never reaches the disk.++use crate::domain::LocalDomain;+use crate::localpane::LocalPane;+use crate::pane::{Pane, PaneId};+use crate::Mux;+use anyhow::Context;+use portable_pty::CommandBuilder;+use regex::{Regex, RegexSet};+use std::collections::HashSet;+use std::io::{Read, Write};+use std::ops::Range;+use std::path::{Path, PathBuf};+use std::sync::{Arc, OnceLock};+use std::time::{Duration, SystemTime, UNIX_EPOCH};+use termwiz::cell::{Cell, CellAttributes};+use termwiz::surface::{Change, Line, SEQ_ZERO};++/// Whose records: the session server's or the app's, each keyed by+/// workspace name and by the pane ids that process gave its panes.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Owner {+ Server,+ App,+}++impl Owner {+ fn dir_name(self) -> &'static str {+ match self {+ Self::Server => "server",+ Self::App => "app",+ }+ }+}++/// How long a Thread nobody reopens keeps its record.+const MAX_AGE: Duration = Duration::from_secs(15 * 24 * 60 * 60);+/// The most rows a pane keeps: past the default scrollback, and short+/// enough that a huge one cannot outlast the time a shutdown allows.+const MAX_LINES: usize = 10_000;+/// More than any scrollback is not a record of ours.+const MAX_RECORD_BYTES: u64 = 64 * 1024 * 1024;+const HEADER: &str = "ThinkTerm kept output 1";+/// Names a restoring spawn's record, `owner:pane:workspace`, for+/// `LocalDomain::spawn_pane`, which takes it out of the environment before+/// it builds the command.+const SEED_ENV: &str = "THINKTERM_KEPT_OUTPUT";+/// The same, on a command made only to carry the name for a spawn that gave+/// none. The spawn makes it none again: a local domain fills in no command+/// with defaults of its own, a WSL domain's directory for one.+const BARE_SEED_ENV: &str = "THINKTERM_KEPT_OUTPUT_BARE";++/// The switch, for this machine alone: a small file beside the desktop's+/// settings that Settings, `thinkterm cli restore-output` and the session+/// server all go by. Not a key in settings.json: a command line tool+/// rewriting that file would reorder it, and one creating it would make the+/// desktop take a fresh install for an old one.+fn switch_path() -> PathBuf {+ config::native_settings_path().with_file_name("restore-pane-output")+}++/// Whether this machine keeps pane output, read when it matters: at an exit+/// and at a restore.+pub fn enabled() -> bool {+ enabled_at(&switch_path())+}++fn enabled_at(switch: &Path) -> bool {+ std::fs::read_to_string(switch).is_ok_and(|text| text.trim() == "on")+}++/// Turn it on or off for this machine. Off removes what was kept, too.+pub fn set_enabled(on: bool) -> anyhow::Result<()> {+ set_enabled_at(&switch_path(), on)?;+ if !on {+ discard_all();+ }+ Ok(())+}++fn set_enabled_at(switch: &Path, on: bool) -> anyhow::Result<()> {+ if on {+ if let Some(dir) = switch.parent() {+ std::fs::create_dir_all(dir)?;+ }+ let partial = switch.with_extension("partial");+ std::fs::write(&partial, "on\n")?;+ std::fs::rename(&partial, switch)?;+ return Ok(());+ }+ match std::fs::remove_file(switch) {+ Ok(()) => Ok(()),+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(err) => Err(err.into()),+ }+}++fn root() -> PathBuf {+ config::DATA_DIR.join("kept-output")+}++/// Before a controlled exit: replace what `key` kept with what `panes` show+/// now, under the pane ids its saved layout records them by. When none of+/// them has anything to keep, the old record stays: a Thread whose panes+/// were never restored still has what it had.+pub fn save(owner: Owner, key: &str, panes: &[(PaneId, Arc<dyn Pane>)]) {+ let kept: Vec<(PaneId, String)> = panes+ .iter()+ .filter_map(|(id, pane)| Some((*id, capture(&**pane)?)))+ .collect();+ if let Err(err) = write_records(&root(), owner, key, &kept, now()) {+ log::warn!("keeping the pane output of {key}: {err:#}");+ }+}++/// Remove what nobody will restore: the records of keys `keep` does not+/// name, and any older than [`MAX_AGE`] whoever kept them -- the other+/// process may never run here again to clear its own.+pub fn prune(owner: Owner, keep: &HashSet<String>) {+ prune_at(&root(), owner, keep, SystemTime::now());+ prune_stale();+}++/// Remove records older than [`MAX_AGE`], whoever kept them.+pub fn prune_stale() {+ prune_stale_at(&root(), SystemTime::now());+}++/// Everything `owner` kept, as when the setting is turned off.+pub fn discard(owner: Owner) {+ remove_tree(&root().join(owner.dir_name()));+}++/// Everything kept, by any owner.+pub fn discard_all() {+ remove_tree(&root());+}++/// `command`, made to start its terminal with what the pane `saved` in+/// `key`'s layout showed, when that was kept. For a spawn in a local domain,+/// in this process or the local session server: the one that spawns it+/// reads the record from this machine's disk. Unchanged otherwise.+pub fn with_seed(+ owner: Owner,+ key: &str,+ saved: PaneId,+ command: Option<CommandBuilder>,+) -> Option<CommandBuilder> {+ if !enabled() {+ return command;+ }+ with_seed_at(&root(), owner, key, saved, command)+}++fn with_seed_at(+ root: &Path,+ owner: Owner,+ key: &str,+ saved: PaneId,+ command: Option<CommandBuilder>,+) -> Option<CommandBuilder> {+ if !key_dir(root, owner, key).join(saved.to_string()).is_file() {+ return command;+ }+ let (mut command, name) = match command {+ Some(command) => (command, SEED_ENV),+ None => (CommandBuilder::new_default_prog(), BARE_SEED_ENV),+ };+ command.env(name, format!("{}:{saved}:{key}", owner.dir_name()));+ Some(command)+}++/// `command`, made to start with `key`'s record when it kept exactly one:+/// for a Thread that comes back without a recorded layout, which is a+/// Thread that only ever had the one pane. With more there is no telling+/// which pane was which, and none is used.+pub fn with_lone_seed(key: &str, command: Option<CommandBuilder>) -> Option<CommandBuilder> {+ if !enabled() {+ return command;+ }+ with_lone_seed_at(&root(), key, command)+}++fn with_lone_seed_at(+ root: &Path,+ key: &str,+ command: Option<CommandBuilder>,+) -> Option<CommandBuilder> {+ let mut kept = vec![];+ for owner in [Owner::Server, Owner::App] {+ let Ok(entries) = std::fs::read_dir(key_dir(root, owner, key)) else {+ continue;+ };+ for entry in entries.flatten() {+ if let Some(pane) = entry+ .file_name()+ .to_str()+ .and_then(|name| name.parse::<PaneId>().ok())+ {+ kept.push((owner, pane));+ }+ }+ }+ match kept.as_slice() {+ [(owner, pane)] => with_seed_at(root, *owner, key, *pane, command),+ _ => command,+ }+}++/// `key`'s layout is back: what was kept for it is spent, and a record no+/// pane took would only meet the wrong pane later, once ids come round again.+pub fn finish(key: &str) {+ finish_at(&root(), key);+}++fn finish_at(root: &Path, key: &str) {+ for owner in [Owner::Server, Owner::App] {+ remove_tree(&key_dir(root, owner, key));+ }+}++/// One pane's record: when it was kept, and the text with its colors.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct Seed {+ closed: i64,+ text: String,+}++impl Seed {+ /// What the new terminal starts with: the kept text, a dim line saying+ /// when it stopped and came back, and the start of a fresh line for+ /// the shell. A pseudo console paints from the top of what it takes to+ /// be an empty screen, so there all of it goes up into the scrollback+ /// first and the shell starts at the top.+ pub(crate) fn bytes(&self, rows: usize, conpty: bool) -> Vec<u8> {+ let mut out = self.text.clone();+ out.push_str(&format!(+ "\r\n\x1b[2m── closed {} · restored {} ──\x1b[0m\r\n",+ local_time(self.closed),+ local_time(now())+ ));+ if conpty {+ // From any row, one fewer than the screen holds scrolls the+ // cursor's row to the top and everything above it off it.+ for _ in 1..rows {+ out.push_str("\r\n");+ }+ out.push_str("\x1b[H");+ }+ out.into_bytes()+ }+}++/// The record a restoring spawn names, taken out of its command before that+/// is built, so the shell never sees the variable, and moved aside so no+/// other pane gets it.+pub(crate) fn take_seed(command: &mut Option<CommandBuilder>) -> Option<Claim> {+ let named = take_named(command)?;+ if !enabled() {+ return None;+ }+ take_seed_at(&root(), &named)+}++/// A record taken for a pane being made: gone once the pane exists, back in+/// place if making it fails, so the next try -- in another folder after the+/// Project's was refused, say -- still starts with it.+pub(crate) struct Claim {+ seed: Seed,+ path: PathBuf,+ aside: PathBuf,+ spent: bool,+}++impl Claim {+ pub(crate) fn bytes(&self, rows: usize, conpty: bool) -> Vec<u8> {+ self.seed.bytes(rows, conpty)+ }++ /// The pane exists and starts with the record: it has done its work.+ pub(crate) fn spend(mut self) {+ self.spent = true;+ std::fs::remove_file(&self.aside).ok();+ }+}++impl Drop for Claim {+ fn drop(&mut self) {+ if !self.spent {+ std::fs::rename(&self.aside, &self.path).ok();+ }+ }+}++/// `command`, made only to carry a record's name for a spawn that gave none,+/// has been filled in by a client -- with the shell chosen in Settings, which+/// the session server does not know -- and is now one to run as it is.+pub fn filled_in(command: &mut CommandBuilder) {+ if let Some(named) = command+ .get_env(BARE_SEED_ENV)+ .map(|value| value.to_os_string())+ {+ command.env_remove(BARE_SEED_ENV);+ command.env(SEED_ENV, named);+ }+}++/// What `command` names, out of its environment whether or not it is of+/// use; a command that was only carrying the name is none again.+fn take_named(command: &mut Option<CommandBuilder>) -> Option<String> {+ let cmd = command.as_mut()?;+ let named = cmd.get_env(SEED_ENV).map(|value| value.to_os_string());+ let bare = cmd.get_env(BARE_SEED_ENV).map(|value| value.to_os_string());+ cmd.env_remove(SEED_ENV);+ cmd.env_remove(BARE_SEED_ENV);+ if bare.is_some() {+ *command = None;+ }+ named.or(bare)?.into_string().ok()+}++fn take_seed_at(root: &Path, named: &str) -> Option<Claim> {+ let mut parts = named.splitn(3, ':');+ let owner = match parts.next()? {+ "server" => Owner::Server,+ "app" => Owner::App,+ _ => return None,+ };+ let pane: PaneId = parts.next()?.parse().ok()?;+ let path = key_dir(root, owner, parts.next()?).join(pane.to_string());+ // Moved before it is read: of two spawns naming it, one gets it.+ let aside = path.with_extension("taken");+ std::fs::rename(&path, &aside).ok()?;+ match read_record(&aside) {+ Ok(seed) => Some(Claim {+ seed,+ path,+ aside,+ spent: false,+ }),+ Err(err) => {+ log::warn!("reading kept pane output {}: {err:#}", path.display());+ std::fs::remove_file(&aside).ok();+ None+ }+ }+}++/// The text a local pane's primary screen holds, masked, or None when it+/// holds nothing or is not a terminal on this machine: an ssh or tmux pane+/// is a `LocalPane` too, but its domain is not local and no restore of it+/// would read a record.+fn capture(pane: &dyn Pane) -> Option<String> {+ let local = Mux::try_get()?+ .get_domain(pane.domain_id())?+ .downcast_ref::<LocalDomain>()+ .is_some();+ if !local {+ return None;+ }+ keep(+ pane.downcast_ref::<LocalPane>()?+ .primary_screen_lines(MAX_LINES),+ )+}++fn keep(mut lines: Vec<Line>) -> Option<String> {+ while lines.last().is_some_and(Line::is_whitespace) {+ lines.pop();+ }+ if lines.is_empty() {+ return None;+ }+ mask_secrets(&mut lines);+ match render(&lines) {+ Ok(text) => Some(text),+ Err(err) => {+ log::warn!("rendering pane output to keep: {err:#}");+ None+ }+ }+}++/// `lines` as escape sequences. A row that wrapped runs on into the next+/// one, so the restored pane wraps the text again at its own width.+fn render(lines: &[Line]) -> anyhow::Result<String> {+ let mut changes = vec![];+ // The pen as the escapes leave it: what a row's changes last set, not its+ // last cell. A row of plain spaces sets nothing, and taking its last cell+ // would leave the next row in the colours of the one before. A clear to+ // the end of the row leaves the pen in its background alone: a row that+ // is only a background is nothing else.+ let mut attr = CellAttributes::blank();+ for (index, line) in lines.iter().enumerate() {+ let row = line.changes(&attr);+ if let Some(set) = row.iter().rev().find_map(|change| match change {+ Change::AllAttributes(set) => Some(set.clone()),+ Change::ClearToEndOfLine(background) => {+ Some(CellAttributes::blank().set_background(*background).clone())+ }+ _ => None,+ }) {+ attr = set;+ }+ changes.extend(row);+ if index + 1 < lines.len() && !line.last_cell_was_wrapped() {+ // A line feed that scrolls fills the new row with the pen's+ // background: plain, or a row ending in a colour paints the next.+ if attr != CellAttributes::blank() {+ attr = CellAttributes::blank();+ changes.push(Change::AllAttributes(attr.clone()));+ }+ changes.push(Change::Text("\r\n".to_string()));+ }+ }+ changes.push(Change::AllAttributes(CellAttributes::blank()));+ termwiz_funcs::changes_to_escapes(&changes)+}++/// What a value only its name vouches for must look like. Code says+/// `token = …` and `password: …` too; a secret is data, not an expression.+#[derive(Clone, Copy, PartialEq)]+enum Check {+ None,+ /// Not code: no substitution, call, index or structure.+ Literal,+ /// A literal with a digit in it, as generated tokens and keys have.+ Generated,+}++/// Where a private key's rows are, line by line, and the margin a listing+/// put before each of them (`margin_pattern`).+#[derive(Clone)]+enum KeyRows {+ Outside,+ /// After the BEGIN line: header lines, and the blank line that ends them.+ Header(Option<Regex>),+ Body(Option<Regex>),+}++struct Pattern {+ regex: Regex,+ /// The capture group that is the secret: 0 for the whole match. A value+ /// that may stand in quotes has a group for each form, and the one that+ /// took part is the secret.+ group: usize,+ check: Check,+}++struct Patterns {+ any: RegexSet,+ each: Vec<Pattern>,+ /// A key's BEGIN line: the marker ends it, as in a file. One that says+ /// more after it quotes the marker and starts no key.+ key_begin: Regex,+ /// A header line an encrypted PEM key or a PGP key has before its body.+ key_header: Regex,+ /// A row of a PEM key's body: base64 and nothing else.+ key_body: Regex,+ /// A value that starts as a call, an index or a generic type does.+ code: Regex,+}++fn patterns() -> &'static Patterns {+ static PATTERNS: OnceLock<Patterns> = OnceLock::new();+ PATTERNS.get_or_init(|| {+ let each: &[(&str, usize, Check)] = &[+ // A value named for a password: `PASSWORD=…`, `db_pass: …`,+ // `"pwd": "…"`. Passwords can be short and plain words. One in+ // quotes runs to the closing quote: a passphrase has spaces, and+ // a generated password `,` and `;`.+ (+ r#"(?i)\b(?:[a-z0-9_.-]*[_.-])?(?:password|passwd|passphrase|pass|pwd)["']?\s*[:=]\s*(?:"([^"]{4,})"|'([^']{4,})'|["']?([^\s"',;]{4,}))"#,+ 1,+ Check::Literal,+ ),+ // The variables tools read one from, the word run on from a+ // prefix: `PGPASSWORD=…`, `SSHPASS=…`. Capitals and `=` only, as+ // an environment has them, so prose and code that say "bypass"+ // are left alone.+ (+ r#"\b[A-Z][A-Z0-9]*(?:PASSWORD|PASSWD|PASSPHRASE|PASS)=(?:"([^"]{4,})"|'([^']{4,})'|["']?([^\s"',;]{4,}))"#,+ 1,+ Check::Literal,+ ),+ // A command's option: `--password …`, `--token=…`.+ (+ r#"(?i)(?:^|\s)--?(?:password|passwd|pass|pwd|token|secret|api-?key|auth-token)(?:=|\s+)(?:"([^"]{4,})"|'([^']{4,})'|["']?([^\s"']{4,}))"#,+ 1,+ Check::Literal,+ ),+ // A value named for a token or key: `API_TOKEN=…`, `SECRET_KEY=…`,+ // `"client_secret": "…"`. A count or a type name is no secret.+ (+ r#"(?i)\b[a-z0-9_.-]*(?:secret|token|key|credentials?)["']?\s*[:=]\s*["']?([^\s"',;]{8,})"#,+ 1,+ Check::Generated,+ ),+ (+ r"(?i)\bauthorization:\s*(?:basic|bearer|token)\s+([A-Za-z0-9._~+/=-]{8,})",+ 1,+ Check::None,+ ),+ (r"(?i)\bbearer\s+([A-Za-z0-9._~+/=-]{16,})", 1, Check::None),+ // The password in `scheme://user:password@host`.+ (+ r"\b[A-Za-z][A-Za-z0-9+.-]*://[^\s:/@]+:([^\s@/]+)@",+ 1,+ Check::None,+ ),+ // A private key on one line, as a JSON key file holds it.+ (+ r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(.+?)-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----",+ 1,+ Check::None,+ ),+ // A PEM block in base64, as a Kubernetes secret holds one.+ (r"\bLS0tLS1CRUdJTi[A-Za-z0-9+/=]{16,}", 0, Check::None),+ // The formats services hand their keys out in.+ (r"\bsk-[A-Za-z0-9_-]{20,}", 0, Check::None),+ (r"\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}", 0, Check::None),+ (r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}", 0, Check::None),+ (r"\bgithub_pat_[A-Za-z0-9_]{30,}", 0, Check::None),+ (r"\bglpat-[A-Za-z0-9_-]{20,}", 0, Check::None),+ (r"\bxox[abprs]-[A-Za-z0-9-]{10,}", 0, Check::None),+ (r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b", 0, Check::None),+ (r"\bAIza[0-9A-Za-z_-]{35}", 0, Check::None),+ (+ r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}",+ 0,+ Check::None,+ ),+ ];+ Patterns {+ any: RegexSet::new(each.iter().map(|(pattern, _, _)| *pattern))+ .expect("secret patterns compile"),+ each: each+ .iter()+ .map(|(pattern, group, check)| Pattern {+ regex: Regex::new(pattern).expect("secret pattern"),+ group: *group,+ check: *check,+ })+ .collect(),+ key_begin: Regex::new(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----\s*$")+ .expect("key pattern"),+ key_header: Regex::new(+ r"^\s*(?:Proc-Type|DEK-Info|Version|Comment|Hash|Charset|MessageID):",+ )+ .expect("key pattern"),+ key_body: Regex::new(r"^\s*[A-Za-z0-9+/=]+\s*$").expect("key pattern"),+ code: Regex::new(r"^[A-Za-z_][A-Za-z0-9_]+(?:(?:\.|::)[A-Za-z_][A-Za-z0-9_]*)*[(\[<]")+ .expect("code pattern"),+ }+ })+}++/// `value`, which stood in the quote `quote` names if any, against what+/// `check` asks of it.+fn passes(check: Check, value: &str, quote: Option<char>, patterns: &Patterns) -> bool {+ let literal = || !looks_like_code(value, quote, patterns);+ match check {+ Check::None => true,+ Check::Literal => literal(),+ Check::Generated => literal() && value.chars().any(|c| c.is_ascii_digit()),+ }+}++/// Whether `value` reads as an expression rather than data: a substitution,+/// a call, an index, a generic type or a structure. Generated passwords have+/// brackets and `&`, `*`, `$` in them too, so only the shape counts, and a+/// quoted value is a string unless a shell would still expand it: nothing+/// expands in single quotes.+fn looks_like_code(value: &str, quote: Option<char>, patterns: &Patterns) -> bool {+ if quote == Some('\'') {+ return false;+ }+ if value.starts_with('$') || value.contains("${") || value.contains("$(") {+ return true;+ }+ if quote.is_some() {+ return false;+ }+ value.starts_with(['(', '[', '{', '<', '&', '*']) || patterns.code.is_match(value)+}++/// A pattern for the margin `before` a key's BEGIN marker, which a listing+/// puts before every row: a line number, a diff's sign, a search hit's file+/// name. Numbers and runs of spaces may change from row to row, and a search+/// marks its hit with `:` and the rows around it with `-`. None when it is+/// only indentation, which the rows' own check allows for.+fn margin_pattern(before: &str) -> Option<Regex> {+ if before.trim().is_empty() {+ return None;+ }+ let mut pattern = String::from("^");+ let mut chars = before.chars().peekable();+ while let Some(c) = chars.next() {+ if c.is_ascii_digit() {+ while chars.next_if(char::is_ascii_digit).is_some() {}+ pattern.push_str(r"\d+");+ } else if c.is_whitespace() {+ while chars.next_if(|c| c.is_whitespace()).is_some() {}+ pattern.push_str(r"\s*");+ } else if c == ':' || c == '-' {+ pattern.push_str("[:-]");+ } else {+ pattern.push_str(®ex::escape(c.encode_utf8(&mut [0; 4])));+ }+ }+ Regex::new(&pattern).ok()+}++/// `text` past the margin `margin` matches at its start, or all of it.+fn after_margin<'a>(text: &'a str, margin: &Option<Regex>) -> &'a str {+ match margin.as_ref().and_then(|margin| margin.find(text)) {+ Some(found) => &text[found.end()..],+ None => text,+ }+}++/// Replace what looks like a password, token or private key with `•`, cell+/// by cell, keeping the colors, and drop links whose address holds one. A+/// logical line is matched whole, so a token that wrapped is found across+/// the break.+fn mask_secrets(lines: &mut [Line]) {+ let patterns = patterns();+ let mut key = KeyRows::Outside;+ let mut start = 0;+ while start < lines.len() {+ let mut end = start + 1;+ while end < lines.len() && lines[end - 1].last_cell_was_wrapped() {+ end += 1;+ }+ mask_logical_line(&mut lines[start..end], patterns, &mut key);+ start = end;+ }+}++fn mask_logical_line(rows: &mut [Line], patterns: &Patterns, key: &mut KeyRows) {+ let mut text = String::new();+ // Where each cell's text starts in `text`, and which cell it is.+ let mut cells = vec![];+ for (row, line) in rows.iter().enumerate() {+ for cell in line.visible_cells() {+ cells.push((text.len(), row, cell.cell_index(), cell.width()));+ text.push_str(cell.str());+ }+ }++ let mut secret: Vec<Range<usize>> = vec![];+ // A key's body runs from its BEGIN line to its END line, and is base64+ // throughout, after the header lines an encrypted PEM key or a PGP key+ // starts with and the blank line that ends them: any other line ends+ // it, so a search hit or a diff that shows only the BEGIN line masks+ // nothing after it. Each row is read past the margin the BEGIN line had.+ let (in_header, margin) = match std::mem::replace(key, KeyRows::Outside) {+ KeyRows::Outside => (false, None),+ KeyRows::Header(margin) => (true, Some(margin)),+ KeyRows::Body(margin) => (false, Some(margin)),+ };+ if let Some(margin) = margin {+ let rest = after_margin(&text, &margin);+ *key = if in_header && patterns.key_header.is_match(rest) {+ KeyRows::Header(margin)+ } else if in_header && rest.trim().is_empty() {+ KeyRows::Body(margin)+ } else if patterns.key_body.is_match(rest) {+ secret.push(text.len() - rest.len()..text.len());+ KeyRows::Body(margin)+ } else {+ KeyRows::Outside+ };+ }+ if matches!(*key, KeyRows::Outside) {+ if let Some(begin) = patterns.key_begin.find(&text) {+ *key = KeyRows::Header(margin_pattern(&text[..begin.start()]));+ }+ }+ if patterns.any.is_match(&text) {+ for pattern in &patterns.each {+ for captures in pattern.regex.captures_iter(&text) {+ if let Some(found) = captures.iter().skip(pattern.group).flatten().next() {+ let quote = text[..found.start()]+ .chars()+ .next_back()+ .filter(|c| matches!(c, '"' | '\''));+ if passes(pattern.check, found.as_str(), quote, patterns) {+ secret.push(found.range());+ }+ }+ }+ }+ }++ let masked: HashSet<(usize, usize)> = cells+ .into_iter()+ .filter(|(offset, _, _, width)| {+ *width == 1+ && !text[*offset..].starts_with(' ')+ && secret.iter().any(|range| range.contains(offset))+ })+ .map(|(_, row, index, _)| (row, index))+ .collect();+ for (row, line) in rows.iter_mut().enumerate() {+ let replacements: Vec<(usize, Cell)> = line+ .visible_cells()+ .filter_map(|cell| {+ let masked = masked.contains(&(row, cell.cell_index()));+ let secret_link = cell+ .attrs()+ .hyperlink()+ .is_some_and(|link| masked || patterns.any.is_match(link.uri()));+ if !masked && !secret_link {+ return None;+ }+ let mut attrs = cell.attrs().clone();+ if secret_link {+ attrs.set_hyperlink(None);+ }+ let replacement = if masked {+ Cell::new('•', attrs)+ } else {+ Cell::new_grapheme_with_width(cell.str(), cell.width(), attrs)+ };+ Some((cell.cell_index(), replacement))+ })+ .collect();+ for (index, cell) in replacements {+ line.set_cell(index, cell, SEQ_ZERO);+ }+ }+}++fn write_records(+ root: &Path,+ owner: Owner,+ key: &str,+ kept: &[(PaneId, String)],+ closed: i64,+) -> anyhow::Result<()> {+ if kept.is_empty() {+ return Ok(());+ }+ let dir = key_dir(root, owner, key);+ remove_tree(&dir);+ create_private_dir(&dir).with_context(|| format!("creating {}", dir.display()))?;+ for (id, text) in kept {+ let plain = format!("{HEADER}\n{closed}\n{text}");+ let packed = zstd::encode_all(plain.as_bytes(), 3)?;+ let path = dir.join(id.to_string());+ write_private(&path, &packed).with_context(|| format!("writing {}", path.display()))?;+ }+ Ok(())+}++fn read_record(path: &Path) -> anyhow::Result<Seed> {+ let mut plain = vec![];+ zstd::stream::read::Decoder::new(std::fs::File::open(path)?)?+ .take(MAX_RECORD_BYTES + 1)+ .read_to_end(&mut plain)?;+ anyhow::ensure!(+ plain.len() as u64 <= MAX_RECORD_BYTES,+ "kept output exceeds the size limit"+ );+ let plain = String::from_utf8(plain)?;+ let mut parts = plain.splitn(3, '\n');+ anyhow::ensure!(parts.next() == Some(HEADER), "not a kept output record");+ let closed = parts.next().context("record has no time")?.parse()?;+ Ok(Seed {+ closed,+ text: parts.next().unwrap_or_default().to_string(),+ })+}++/// A key as a folder name: Thread ids and workspace names are made of+/// these characters already, apart from a workspace name's colons.+fn key_dir(root: &Path, owner: Owner, key: &str) -> PathBuf {+ let name: String = key+ .chars()+ .take(200)+ .map(|c| {+ if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {+ c+ } else {+ '_'+ }+ })+ .collect();+ let name = if name.chars().all(|c| c == '.') {+ "_".to_string()+ } else {+ name+ };+ root.join(owner.dir_name()).join(name)+}++fn prune_at(root: &Path, owner: Owner, keep: &HashSet<String>, now: SystemTime) {+ let keep: HashSet<PathBuf> = keep.iter().map(|key| key_dir(root, owner, key)).collect();+ let Ok(entries) = std::fs::read_dir(root.join(owner.dir_name())) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if is_stale(&entry, now) || !keep.contains(&path) {+ remove_tree(&path);+ }+ }+}++fn prune_stale_at(root: &Path, now: SystemTime) {+ for owner in [Owner::Server, Owner::App] {+ let Ok(entries) = std::fs::read_dir(root.join(owner.dir_name())) else {+ continue;+ };+ for entry in entries.flatten() {+ if is_stale(&entry, now) {+ remove_tree(&entry.path());+ }+ }+ }+}++fn is_stale(entry: &std::fs::DirEntry, now: SystemTime) -> bool {+ entry+ .metadata()+ .and_then(|metadata| metadata.modified())+ .ok()+ .and_then(|modified| now.duration_since(modified).ok())+ .is_some_and(|age| age > MAX_AGE)+}++fn create_private_dir(dir: &Path) -> std::io::Result<()> {+ let mut builder = std::fs::DirBuilder::new();+ builder.recursive(true);+ #[cfg(unix)]+ std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);+ builder.create(dir)+}++/// Written whole or not at all, readable by this user alone on unix. On+/// Windows it takes the data directory's ACL, as the other private files+/// there do.+fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ let partial = path.with_extension("partial");+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create(true).truncate(true);+ #[cfg(unix)]+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);+ let mut file = options.open(&partial)?;+ file.write_all(bytes)?;+ file.sync_all()?;+ drop(file);+ std::fs::rename(&partial, path)+}++fn remove_tree(path: &Path) {+ match std::fs::remove_dir_all(path) {+ Ok(()) => {}+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}+ Err(err) => log::warn!("removing kept pane output {}: {err:#}", path.display()),+ }+}++fn now() -> i64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|elapsed| elapsed.as_secs() as i64)+ .unwrap_or_default()+}++fn local_time(secs: i64) -> String {+ use chrono::TimeZone;+ chrono::Local+ .timestamp_opt(secs, 0)+ .single()+ .map(|time| time.format("%m-%d %H:%M").to_string())+ .unwrap_or_default()+}++#[cfg(test)]+mod tests;diff --git a/mux/src/kept_output/tests.rs b/mux/src/kept_output/tests.rsnew file mode 100644index 00000000..7c2f19c1--- /dev/null+++ b/mux/src/kept_output/tests.rs@@ -0,0 +1,741 @@+use super::*;+use termwiz::color::ColorAttribute;+use wezterm_term::{Terminal, TerminalSize};++const GREEN: ColorAttribute = ColorAttribute::PaletteIndex(2);++fn line(text: &str) -> Line {+ Line::from_text(text, &CellAttributes::default(), SEQ_ZERO, None)+}++fn text_of(line: &Line) -> String {+ line.visible_cells()+ .map(|cell| cell.str().to_string())+ .collect()+}++fn masked(lines: Vec<Line>) -> Vec<String> {+ let mut lines = lines;+ mask_secrets(&mut lines);+ lines.iter().map(text_of).collect()+}++fn dots(count: usize) -> String {+ "•".repeat(count)+}++#[test]+fn secrets_are_masked_and_the_rest_is_left_alone() {+ let key = format!("sk-{}", "a".repeat(24));+ let texts = masked(vec![+ line(&format!("export EXAMPLE_API_KEY={key}")),+ line("API_TOKEN=abcdefgh12345678"),+ line(r#"{"client_secret": "0123456789abcdef"}"#),+ line("git clone https://user:[email protected]/repo.git"),+ line("Authorization: Bearer abcdefghijklmnopqrstuvwxyz"),+ line("max_tokens = 4096"),+ line(" Finished `dev` profile in 4.21s"),+ ]);+ assert_eq!(+ texts[0],+ format!("export EXAMPLE_API_KEY={}", dots(key.len()))+ );+ assert_eq!(texts[1], format!("API_TOKEN={}", dots(16)));+ assert_eq!(texts[2], format!(r#"{{"client_secret": "{}"}}"#, dots(16)));+ assert_eq!(+ texts[3],+ format!("git clone https://user:{}@example.com/repo.git", dots(12))+ );+ assert_eq!(texts[4], format!("Authorization: Bearer {}", dots(26)));+ assert_eq!(texts[5], "max_tokens = 4096");+ assert_eq!(texts[6], " Finished `dev` profile in 4.21s");+}++#[test]+fn a_token_that_wrapped_is_masked_on_both_rows() {+ let token = format!("ghp_{}", "b".repeat(36));+ let mut first = line(&format!("token is {}", &token[..20]));+ first.set_last_cell_was_wrapped(true, SEQ_ZERO);+ let texts = masked(vec![first, line(&token[20..])]);+ assert_eq!(texts, vec![format!("token is {}", dots(20)), dots(20)]);+}++#[test]+fn a_private_key_is_masked_between_its_markers() {+ let texts = masked(vec![+ line("-----BEGIN OPENSSH PRIVATE KEY-----"),+ line("b3BlbnNzaC1rZXktdjEAAAAA"),+ line("QyNTUxOQAAACDx+8KxZ/ab=="),+ line("-----END OPENSSH PRIVATE KEY-----"),+ line("after"),+ ]);+ assert_eq!(+ texts,+ vec![+ "-----BEGIN OPENSSH PRIVATE KEY-----".to_string(),+ dots(24),+ dots(24),+ "-----END OPENSSH PRIVATE KEY-----".to_string(),+ "after".to_string(),+ ]+ );+}++/// A search hit or a diff shows the BEGIN line alone: nothing after it is+/// a key's body. Nor after code that quotes the marker.+#[test]+fn a_begin_line_without_its_body_masks_nothing_after_it() {+ let rows = vec![+ "id_rsa:-----BEGIN OPENSSH PRIVATE KEY-----",+ "notes.txt: nothing to see here",+ "$ ls",+ r#"let pem = "-----BEGIN RSA PRIVATE KEY-----";"#,+ "Finished",+ ];+ let texts = masked(rows.iter().map(|row| line(row)).collect());+ assert_eq!(texts, rows);+}++/// A listing that numbers its lines, a diff and a search with context put+/// a margin before each row of a key; the body past it is masked, the+/// margin kept.+#[test]+fn a_private_key_shown_with_a_margin_is_masked() {+ let body = "MIIEowIBAAKCAQEAx+8KxZab";+ let listings = [+ // bat+ vec![+ " 1 │ -----BEGIN OPENSSH PRIVATE KEY-----".to_string(),+ format!(" 2 │ {body}"),+ format!(" 3 │ {body}"),+ " 4 │ -----END OPENSSH PRIVATE KEY-----".to_string(),+ ],+ // cat -n, its tab put on screen as spaces+ vec![+ " 1 -----BEGIN RSA PRIVATE KEY-----".to_string(),+ format!(" 2 {body}"),+ format!(" 3 {body}"),+ " 4 -----END RSA PRIVATE KEY-----".to_string(),+ ],+ // A diff that removes it.+ vec![+ "------BEGIN RSA PRIVATE KEY-----".to_string(),+ format!("-{body}"),+ format!("-{body}"),+ "------END RSA PRIVATE KEY-----".to_string(),+ ],+ // grep -n -A, past line 9.+ vec![+ "key.pem:8:-----BEGIN RSA PRIVATE KEY-----".to_string(),+ format!("key.pem-9-{body}"),+ format!("key.pem-10-{body}"),+ "key.pem-11------END RSA PRIVATE KEY-----".to_string(),+ ],+ ];+ for rows in listings {+ let texts = masked(rows.iter().map(|row| line(row)).collect());+ for row in [1, 2] {+ let margin = rows[row].strip_suffix(body).unwrap();+ assert_eq!(texts[row], format!("{margin}{}", dots(body.len())));+ }+ assert_eq!(texts[0], rows[0]);+ assert_eq!(texts[3], rows[3]);+ }++ // A PGP key's header and blank line behind the margin too.+ let texts = masked(vec![+ line(" 1 │ -----BEGIN PGP PRIVATE KEY BLOCK-----"),+ line(" 2 │ Version: GnuPG v2"),+ line(" 3 │"),+ line(&format!(" 4 │ {body}")),+ line(" 5 │ -----END PGP PRIVATE KEY BLOCK-----"),+ ]);+ assert_eq!(texts[1], " 2 │ Version: GnuPG v2");+ assert_eq!(texts[3], format!(" 4 │ {}", dots(body.len())));+}++#[test]+fn common_secret_formats_are_masked() {+ let one_line_key = r"\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n";+ let stripe = format!("sk_live_{}", "a1".repeat(12));+ let cases = [+ ("DB_PASS=hunter22", format!("DB_PASS={}", dots(8))),+ ("MYSQL_PWD=abcd", format!("MYSQL_PWD={}", dots(4))),+ ("PASSWORD=hunter2", format!("PASSWORD={}", dots(7))),+ (+ "mysql --password Sup3rS3cretPw",+ format!("mysql --password {}", dots(13)),+ ),+ (+ &*format!("STRIPE_KEY={}", stripe),+ format!("STRIPE_KEY={}", dots(stripe.len())),+ ),+ (+ &*format!(+ r#" "private_key": "-----BEGIN PRIVATE KEY-----{}-----END PRIVATE KEY-----","#,+ one_line_key+ ),+ format!(+ r#" "private_key": "-----BEGIN PRIVATE KEY-----{}-----END PRIVATE KEY-----","#,+ dots(one_line_key.len())+ ),+ ),+ (+ "tls.key: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0t",+ format!("tls.key: {}", dots(36)),+ ),+ (+ "Authorization: Basic dXNlcjpwYXNzd29yZA==",+ format!("Authorization: Basic {}", dots(20)),+ ),+ ];+ for (text, expected) in cases {+ assert_eq!(masked(vec![line(text)]), vec![expected], "{}", text);+ }+}++/// The names tools read a password from, with no separator before the+/// word, and passwords with the symbols generated ones have.+#[test]+fn passwords_by_those_names_and_with_symbols_are_masked() {+ let cases = [+ (+ "export PGPASSWORD=hunter22",+ format!("export PGPASSWORD={}", dots(8)),+ ),+ ("SSHPASS=correcthorse", format!("SSHPASS={}", dots(12))),+ ("DBPASS=s3cr3t", format!("DBPASS={}", dots(6))),+ (+ "DB_PASSWORD=Tr0ub4dor&3",+ format!("DB_PASSWORD={}", dots(11)),+ ),+ (+ "export DB_PASS=p@ss$word",+ format!("export DB_PASS={}", dots(9)),+ ),+ (+ "mysql --password 'p@ss(w)rd'",+ format!("mysql --password '{}'", dots(9)),+ ),+ (+ r#" "password": "x(9]Kq*Lz","#,+ format!(r#" "password": "{}","#, dots(9)),+ ),+ // In quotes, all of it: `,`, `;` and spaces too, and a `$` that+ // single quotes keep from being expanded.+ (+ "DB_PASSWORD='ab;Xk9!q2'",+ format!("DB_PASSWORD='{}'", dots(9)),+ ),+ (+ r#" "password": "Tr0ub,4dor","#,+ format!(r#" "password": "{}","#, dots(10)),+ ),+ (+ r#"export PASSPHRASE="correct horse battery""#,+ format!(r#"export PASSPHRASE="{} {} {}""#, dots(7), dots(5), dots(7)),+ ),+ (+ "sshpass -p x --password 'ab cd;ef'",+ format!("sshpass -p x --password '{} {}'", dots(2), dots(5)),+ ),+ ("PASSWORD='$ecr3tPw'", format!("PASSWORD='{}'", dots(8))),+ ];+ for (text, expected) in cases {+ assert_eq!(masked(vec![line(text)]), vec![expected], "{}", text);+ }+}++/// A client that fills in a command made only to carry the name -- with+/// the shell chosen in Settings, which the session server does not know --+/// has the spawn run it as it is.+#[test]+fn a_bare_command_a_client_filled_in_is_run_as_it_is() {+ let root = tempfile::tempdir().unwrap();+ let key = "thinkterm:project-1:thread-2";+ write_records(root.path(), Owner::Server, key, &[(3, "old".into())], 7).unwrap();+ let mut command = with_seed_at(root.path(), Owner::Server, key, 3, None);+ let given = command.as_mut().unwrap();+ given.env("SHELL", "/usr/local/bin/fish");+ filled_in(given);+ assert_eq!(+ take_named(&mut command).unwrap(),+ format!("server:3:{}", key)+ );+ let command = command.unwrap();+ assert!(command.is_default_prog());+ assert_eq!(command.get_env("SHELL").unwrap(), "/usr/local/bin/fish");+ assert!(command.get_env(SEED_ENV).is_none());+ assert!(command.get_env(BARE_SEED_ENV).is_none());+}++/// An encrypted PEM key and a PGP one carry header lines, and a blank line+/// before the body; the body is masked all the same.+#[test]+fn a_private_key_with_headers_is_masked() {+ let texts = masked(vec![+ line("-----BEGIN RSA PRIVATE KEY-----"),+ line("Proc-Type: 4,ENCRYPTED"),+ line("DEK-Info: AES-128-CBC,0123456789ABCDEF"),+ line(""),+ line("MIIEowIBAAKCAQEAx+8KxZab"),+ line("-----END RSA PRIVATE KEY-----"),+ line("-----BEGIN PGP PRIVATE KEY BLOCK-----"),+ line("Version: GnuPG v2"),+ line(""),+ line("lQOYBGT4Kx0BCAC7v9QeWcU1"),+ line("=Ab12"),+ line("-----END PGP PRIVATE KEY BLOCK-----"),+ line("after"),+ ]);+ assert_eq!(texts[4], dots(24));+ assert_eq!(texts[9], dots(24));+ assert_eq!(texts[10], dots(5));+ assert_eq!(texts[1], "Proc-Type: 4,ENCRYPTED");+ assert_eq!(texts[11], "-----END PGP PRIVATE KEY BLOCK-----");+ assert_eq!(texts[12], "after");+}++/// Code names things token and password too.+#[test]+fn code_that_mentions_secrets_is_left_alone() {+ let rows = vec![+ "let token = generate_token();",+ "fn parse(tokens: Vec<Token>) -> Result<()>",+ "pub secret_store: SecretStore,",+ "tokenizer.json: 100%|######| 2.11M/2.11M",+ "password: ${DB_PASSWORD}",+ "max_tokens = 4096",+ "password = getpass()",+ "PGPASSWORD=$PGPASS psql",+ "export DB_PASSWORD=$(cat secret.txt)",+ "let token = sha256(data);",+ "access_token = response.json()[0]",+ r#"PGPASSWORD="$DB_PASS" psql"#,+ "password = os.environ['DB_PASSWORD']",+ r#"log("password: %s, user: %s", p, u)"#,+ ];+ let texts = masked(rows.iter().map(|row| line(row)).collect());+ assert_eq!(texts, rows);+}++/// A link's address would put the secret back on disk however its text+/// was masked.+#[test]+fn links_that_carry_a_secret_are_dropped() {+ let url = "http://localhost:8888/lab?token=4f3a9c0d1e2f3a4b";+ let mut attrs = CellAttributes::default();+ attrs.set_hyperlink(Some(Arc::new(termwiz::hyperlink::Hyperlink::new(url))));+ let mut lines = vec![Line::from_text(url, &attrs, SEQ_ZERO, None)];+ mask_secrets(&mut lines);+ assert_eq!(+ text_of(&lines[0]),+ format!("http://localhost:8888/lab?token={}", dots(16))+ );+ assert!(lines[0]+ .visible_cells()+ .all(|cell| cell.attrs().hyperlink().is_none()));+ assert!(!render(&lines).unwrap().contains("4f3a9c0d"));+}++#[test]+fn masking_keeps_the_colors() {+ let mut attrs = CellAttributes::default();+ attrs.set_foreground(GREEN);+ let mut lines = vec![Line::from_text(+ "PASSWORD=correcthorse",+ &attrs,+ SEQ_ZERO,+ None,+ )];+ mask_secrets(&mut lines);+ assert_eq!(text_of(&lines[0]), format!("PASSWORD={}", dots(12)));+ assert!(lines[0].visible_cells().all(|cell| *cell.attrs() == attrs));+}++/// `text` without its colors.+fn plain(text: &str) -> String {+ Regex::new("\x1b\\[[0-9;:]*m")+ .unwrap()+ .replace_all(text, "")+ .into_owned()+}++#[test]+fn trailing_blank_rows_go_and_an_empty_screen_keeps_nothing() {+ assert_eq!(keep(vec![line(""), line(" ")]), None);+ let kept = keep(vec![line("$ ls"), line("README.md"), line(""), line(" ")]).unwrap();+ assert_eq!(plain(&kept), "$ ls\r\nREADME.md");+}++fn terminal(rows: usize, cols: usize) -> Terminal {+ Terminal::new(+ TerminalSize {+ rows,+ cols,+ ..TerminalSize::default()+ },+ Arc::new(config::TermConfig::new()),+ "ThinkTerm",+ "test",+ Box::new(std::io::sink()),+ )+}++fn screen_text(term: &Terminal) -> Vec<String> {+ let screen = term.screen_for_alt(false);+ screen+ .lines_in_phys_range(0..screen.scrollback_rows())+ .iter()+ .map(|line| text_of(line).trim_end().to_string())+ .collect()+}++/// After a row of plain spaces, as `git diff` prints for an empty context+/// line, the next row is plain again, not in the colour before.+#[test]+fn colours_end_where_they_ended() {+ let mut wide = terminal(4, 20);+ wide.advance_bytes("\x1b[31m-foo\x1b[0m\r\n \r\n bar");+ let kept = keep(wide.screen_for_alt(false).lines_in_phys_range(0..4)).unwrap();+ let mut back = terminal(4, 20);+ back.advance_bytes(&kept);+ let lines = back.screen_for_alt(false).lines_in_phys_range(0..3);+ let first = |row: usize| {+ lines[row]+ .visible_cells()+ .next()+ .unwrap()+ .attrs()+ .foreground()+ };+ assert_eq!(first(0), ColorAttribute::PaletteIndex(1));+ assert_eq!(text_of(&lines[2]).trim_end(), " bar");+ assert_eq!(first(2), ColorAttribute::Default);+}++#[test]+fn kept_text_reads_back_and_rewraps_at_the_new_width() {+ let mut wide = terminal(4, 20);+ wide.advance_bytes("\x1b[32mgreen\x1b[0m plain\r\n0123456789abcdefghijKLMN");+ let kept = keep(wide.screen_for_alt(false).lines_in_phys_range(0..4)).unwrap();++ let mut narrow = terminal(6, 10);+ narrow.advance_bytes(&kept);+ assert_eq!(+ screen_text(&narrow),+ vec!["green plai", "n", "0123456789", "abcdefghij", "KLMN", ""]+ );+ let green = narrow.screen_for_alt(false).lines_in_phys_range(0..1)[0]+ .visible_cells()+ .next()+ .unwrap()+ .attrs()+ .foreground();+ assert_eq!(green, GREEN);+}++/// A row that ends in a background, as `git diff` marks trailing+/// whitespace, paints only itself: the row put back after it scrolls in+/// plain, and is plain past its text.+#[test]+fn a_row_ending_in_a_background_does_not_paint_the_next() {+ let mut wide = terminal(4, 20);+ wide.advance_bytes("+foo\x1b[41m \x1b[0m\r\nnext");+ let kept = keep(wide.screen_for_alt(false).lines_in_phys_range(0..4)).unwrap();+ // One row tall, so every line feed scrolls and fills the new row with+ // the pen of the moment.+ let mut back = terminal(1, 20);+ back.advance_bytes(&kept);+ let screen = back.screen_for_alt(false);+ let lines = screen.lines_in_phys_range(0..screen.scrollback_rows());+ let next = lines+ .iter()+ .find(|line| text_of(line).starts_with("next"))+ .unwrap();+ assert!(next+ .visible_cells()+ .all(|cell| cell.attrs().background() == ColorAttribute::Default));+}++/// A row that is only a background, as a diff viewer paints an empty added+/// line, leaves the row after it plain too.+#[test]+fn a_row_of_only_a_background_does_not_paint_the_next() {+ let mut wide = terminal(4, 20);+ wide.advance_bytes("\x1b[42m\x1b[K\x1b[0m\r\nnext");+ let kept = keep(wide.screen_for_alt(false).lines_in_phys_range(0..4)).unwrap();+ let mut back = terminal(1, 20);+ back.advance_bytes(&kept);+ let screen = back.screen_for_alt(false);+ let lines = screen.lines_in_phys_range(0..screen.scrollback_rows());+ let next = lines+ .iter()+ .find(|line| text_of(line).starts_with("next"))+ .unwrap();+ assert!(next+ .visible_cells()+ .all(|cell| cell.attrs().background() == ColorAttribute::Default));+ let filled = lines+ .iter()+ .find(|line| line.visible_cells().next().is_some())+ .unwrap();+ assert_eq!(+ filled.visible_cells().next().unwrap().attrs().background(),+ GREEN+ );+}++/// Where a long line wrapped on a space, the space is part of the text.+#[test]+fn a_space_where_a_line_wrapped_is_kept() {+ let mut narrow = terminal(4, 5);+ narrow.advance_bytes("aaaa bbbb cccc");+ let kept = keep(narrow.screen_for_alt(false).lines_in_phys_range(0..4)).unwrap();+ let mut wide = terminal(2, 20);+ wide.advance_bytes(&kept);+ assert_eq!(screen_text(&wide)[0], "aaaa bbbb cccc");+}++/// A wide character that did not fit at the end of a row went to the next+/// one; the cell it left empty is not text.+#[test]+fn the_cell_a_wide_character_left_at_a_wrap_is_not_kept() {+ let mut narrow = terminal(4, 5);+ narrow.advance_bytes("abcd漢字");+ let kept = keep(narrow.screen_for_alt(false).lines_in_phys_range(0..4)).unwrap();+ let mut wide = terminal(2, 20);+ wide.advance_bytes(&kept);+ assert_eq!(screen_text(&wide)[0], "abcd漢字");+}++#[test]+fn a_seed_ends_with_the_separator_and_under_a_pseudo_console_moves_up() {+ let seed = Seed {+ closed: now(),+ text: "old".into(),+ };+ let plain = String::from_utf8(seed.bytes(3, false)).unwrap();+ assert!(+ plain.starts_with("old\r\n\u{1b}[2m── closed "),+ "{:?}",+ plain+ );+ assert!(plain.ends_with(" ──\u{1b}[0m\r\n"), "{:?}", plain);++ let conpty = String::from_utf8(seed.bytes(3, true)).unwrap();+ assert!(+ conpty.ends_with(" ──\u{1b}[0m\r\n\r\n\r\n\u{1b}[H"),+ "{:?}",+ conpty+ );+ // The separator is the last row above the screen; the screen is empty+ // and the shell starts at its top.+ let mut term = terminal(3, 60);+ term.advance_bytes(&conpty);+ let text = screen_text(&term);+ assert_eq!(&text[text.len() - 3..], &["", "", ""]);+ assert!(text[text.len() - 4].starts_with("── closed "), "{:?}", text);+ assert_eq!(term.cursor_pos().y, 0);+}++#[test]+fn a_spawn_names_its_record_and_takes_it_off_the_disk() {+ let root = tempfile::tempdir().unwrap();+ let key = "thinkterm:project-1:thread-2";+ write_records(root.path(), Owner::Server, key, &[(3, "old".into())], 7).unwrap();+ // Nothing kept for pane 4: its command stays as it was.+ assert!(with_seed_at(root.path(), Owner::Server, key, 4, None).is_none());++ let mut command = with_seed_at(root.path(), Owner::Server, key, 3, None);+ let named = take_named(&mut command).unwrap();+ assert_eq!(named, format!("server:3:{}", key));+ // It gave no command, and is spawned as giving none.+ assert!(command.is_none());+ // One that gave a command keeps it, without the name.+ let mut command = with_seed_at(+ root.path(),+ Owner::Server,+ key,+ 3,+ Some(CommandBuilder::new("htop")),+ );+ assert_eq!(take_named(&mut command).unwrap(), named);+ let command = command.unwrap();+ assert_eq!(command.get_argv(), &vec![std::ffi::OsString::from("htop")]);+ assert!(command.get_env(SEED_ENV).is_none());+ assert!(command.get_env(BARE_SEED_ENV).is_none());+ let claim = take_seed_at(root.path(), &named).unwrap();+ assert_eq!(+ claim.seed,+ Seed {+ closed: 7,+ text: "old".into()+ }+ );+ // While its pane is being made, no other pane gets it.+ assert!(take_seed_at(root.path(), &named).is_none());+ // A spawn that failed leaves it for the next try.+ drop(claim);+ let claim = take_seed_at(root.path(), &named).unwrap();+ // Spent once the pane exists: the next pane with that id gets nothing.+ claim.spend();+ assert!(take_seed_at(root.path(), &named).is_none());+ let dir = key_dir(root.path(), Owner::Server, key);+ assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0);+ for nonsense in ["", "other:3:key", "server:three:key", "server:3"] {+ assert!(+ take_seed_at(root.path(), nonsense).is_none(),+ "{}",+ nonsense+ );+ }+}++#[test]+fn a_thread_without_a_layout_takes_only_a_lone_record() {+ let root = tempfile::tempdir().unwrap();+ assert!(with_lone_seed_at(root.path(), "default", None).is_none());++ write_records(+ root.path(),+ Owner::Server,+ "default",+ &[(5, "one".into())],+ 1,+ )+ .unwrap();+ let mut command = with_lone_seed_at(root.path(), "default", None);+ assert_eq!(take_named(&mut command).unwrap(), "server:5:default");++ // Two panes kept: no telling which one the lone new pane was.+ write_records(+ root.path(),+ Owner::Server,+ "default",+ &[(5, "one".into()), (6, "two".into())],+ 2,+ )+ .unwrap();+ assert!(with_lone_seed_at(root.path(), "default", None).is_none());+}++#[test]+fn a_restored_layout_spends_what_was_kept_for_it() {+ let root = tempfile::tempdir().unwrap();+ let kept = vec![(3, "one".to_string()), (7, "two\r\nlines".to_string())];+ for owner in [Owner::Server, Owner::App] {+ write_records(root.path(), owner, "default", &kept, 1_700_000_000).unwrap();+ }+ write_records(root.path(), Owner::Server, "other", &kept, 1).unwrap();+ assert_eq!(+ take_seed_at(root.path(), "app:7:default")+ .unwrap()+ .seed+ .text,+ "two\r\nlines"+ );+ finish_at(root.path(), "default");+ for owner in [Owner::Server, Owner::App] {+ assert!(!key_dir(root.path(), owner, "default").exists());+ }+ assert!(key_dir(root.path(), Owner::Server, "other").exists());+}++#[test]+fn nothing_to_keep_leaves_the_last_record_and_new_ones_replace_it() {+ let root = tempfile::tempdir().unwrap();+ let dir = key_dir(root.path(), Owner::App, "thinkterm:project-1:thread-2");+ assert!(dir.ends_with("app/thinkterm_project-1_thread-2"));++ write_records(+ root.path(),+ Owner::App,+ "thinkterm:project-1:thread-2",+ &[(1, "old".into())],+ 1,+ )+ .unwrap();+ write_records(+ root.path(),+ Owner::App,+ "thinkterm:project-1:thread-2",+ &[],+ 2,+ )+ .unwrap();+ assert!(dir.join("1").exists());++ write_records(+ root.path(),+ Owner::App,+ "thinkterm:project-1:thread-2",+ &[(2, "new".into())],+ 3,+ )+ .unwrap();+ assert!(!dir.join("1").exists());+ assert_eq!(+ take_seed_at(root.path(), "app:2:thinkterm:project-1:thread-2")+ .unwrap()+ .seed+ .text,+ "new"+ );+}++#[test]+fn keys_cannot_leave_the_owners_folder() {+ let root = Path::new("/home/user/kept");+ for key in ["..", ".", "", "../other", "a/b", "C:x"] {+ let dir = key_dir(root, Owner::Server, key);+ assert_eq!(dir.parent(), Some(root.join("server").as_path()), "{key}");+ assert!(!dir+ .file_name()+ .unwrap()+ .to_str()+ .unwrap()+ .chars()+ .all(|c| c == '.'));+ }+}++#[test]+fn prune_removes_unknown_and_old_records() {+ let root = tempfile::tempdir().unwrap();+ for key in ["keep", "gone"] {+ write_records(root.path(), Owner::Server, key, &[(1, "x".into())], 1).unwrap();+ }+ let keep: HashSet<String> = ["keep".to_string()].into();+ prune_at(root.path(), Owner::Server, &keep, SystemTime::now());+ assert!(key_dir(root.path(), Owner::Server, "keep").exists());+ assert!(!key_dir(root.path(), Owner::Server, "gone").exists());++ let later = SystemTime::now() + MAX_AGE + Duration::from_secs(24 * 60 * 60);+ prune_at(root.path(), Owner::Server, &keep, later);+ assert!(!key_dir(root.path(), Owner::Server, "keep").exists());++ // Old records go whoever kept them: the other process may never run+ // here again to clear its own.+ write_records(root.path(), Owner::App, "elsewhere", &[(1, "x".into())], 1).unwrap();+ prune_stale_at(root.path(), SystemTime::now());+ assert!(key_dir(root.path(), Owner::App, "elsewhere").exists());+ prune_stale_at(root.path(), later);+ assert!(!key_dir(root.path(), Owner::App, "elsewhere").exists());+}++#[test]+fn the_switch_is_a_file_that_says_on() {+ let dir = tempfile::tempdir().unwrap();+ let switch = dir.path().join("thinkterm").join("restore-pane-output");+ assert!(!enabled_at(&switch));+ set_enabled_at(&switch, true).unwrap();+ assert!(enabled_at(&switch));+ assert_eq!(std::fs::read_to_string(&switch).unwrap(), "on\n");+ set_enabled_at(&switch, false).unwrap();+ assert!(!switch.exists());+ // Off twice is still off; anything but "on" is off.+ set_enabled_at(&switch, false).unwrap();+ std::fs::write(&switch, "yes").unwrap();+ assert!(!enabled_at(&switch));+}diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 65e372db..ece03df6 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -46,6 +46,7 @@ pub mod default_prog;pub mod domain;pub mod foreground_program;pub mod geometrytrace;+pub mod kept_output;pub mod localpane;pub mod pane;mod parse_watchdog;diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex 984d23fa..90155f7a 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -1661,6 +1661,16 @@ impl LocalPane {)}+ /// The last `max` rows of the primary screen with its scrollback,+ /// oldest first, whichever screen is showing: what the shell printed,+ /// not a full-screen program's frame.+ pub fn primary_screen_lines(&self, max: usize) -> Vec<Line> {+ let term = self.terminal.lock();+ let screen = term.screen_for_alt(false);+ let rows = screen.scrollback_rows();+ screen.lines_in_phys_range(rows.saturating_sub(max)..rows)+ }+pub fn new(pane_id: PaneId,mut terminal: Terminal,diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 773f88b2..bdb53d7b 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -198,6 +198,8 @@ settings-update-download-source-direct = GitHub (direkt)settings-update-download-source-auto = Automatischsettings-local-sessions-via-mux = Lokale Terminals in einem Hintergrund-Sitzungsserver haltensettings-local-sessions-via-mux-description = Lokale Terminals laufen in einem Mux-Server auf diesem Rechner und überstehen das Beenden, Abstürzen oder Aktualisieren von ThinkTerm. Wird beim nächsten Start von ThinkTerm wirksam.+settings-restore-pane-output = Pane-Inhalte beim erneuten Öffnen wiederherstellen+settings-restore-pane-output-description = Nur für die Terminals dieses Computers: Wenn ThinkTerm beendet wird, der Computer herunterfährt oder der Sitzungsserver stoppt, wird die Ausgabe jedes Panes auf diesem Computer gespeichert und beim nächsten Mal in sein Pane zurückgelegt. Passwörter und Tokens werden vor dem Speichern unkenntlich gemacht; bei einem Absturz oder Stromausfall bleibt keine Zeit zum Speichern. Für einen anderen Rechner, etwa einen Remote-Host, führen Sie dort in einem Terminal `thinkterm cli restore-output on` aus.settings-terminal-heading = Terminal-Konfigurationsettings-terminal-font-heading = Schriftsettings-terminal-display-heading = Anzeige@@ -781,6 +783,9 @@ settings-status-remote-update-keep-sessions-error = Die Einstellung für Remote-settings-status-local-sessions-via-mux-on = Lokale Terminals laufen ab dem nächsten Start in einem Hintergrund-Sitzungsserver.settings-status-local-sessions-via-mux-off = Lokale Terminals laufen ab dem nächsten Start innerhalb von ThinkTerm.settings-status-local-sessions-via-mux-error = Die Einstellung für lokale Sitzungen konnte nicht gespeichert werden: { $error }+settings-status-restore-pane-output-on = Pane-Inhalte werden beim Stoppen der Terminals gespeichert und beim nächsten Mal zurückgelegt.+settings-status-restore-pane-output-off = Pane-Inhalte werden nicht mehr gespeichert; Gespeichertes wurde gelöscht.+settings-status-restore-pane-output-error = Die Einstellung für Pane-Inhalte konnte nicht gespeichert werden: { $error }settings-stop-session-server = Sitzungsserver stoppensettings-stop-session-server-description = Beendet jetzt alle Terminals im Sitzungsserver im Hintergrund. Die Fenster, die sie zeigen, schließen sich; er startet wieder, sobald ThinkTerm ihn das nächste Mal braucht.settings-stop-session-server-now = Stoppen…diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex c9ea98b7..ca5e7e65 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -198,6 +198,8 @@ settings-update-download-source-direct = GitHub (direct)settings-update-download-source-auto = Automaticsettings-local-sessions-via-mux = Keep local terminals in a background session serversettings-local-sessions-via-mux-description = Local terminals run in a mux server on this machine and survive quitting, crashing or updating ThinkTerm. Takes effect the next time ThinkTerm starts.+settings-restore-pane-output = Restore pane contents+settings-restore-pane-output-description = Only for this computer's terminals: when ThinkTerm quits, the computer shuts down or the session server stops, each pane's output is kept on this computer and put back in its pane next time. Passwords and tokens are masked before saving; a crash or power loss leaves no time to save. To turn it on for another machine, such as a remote host, run `thinkterm cli restore-output on` in a terminal on that machine.settings-terminal-heading = Terminal configurationsettings-terminal-font-heading = Fontsettings-terminal-display-heading = Display@@ -781,6 +783,9 @@ settings-status-remote-update-keep-sessions-error = Could not save the remote upsettings-status-local-sessions-via-mux-on = Local terminals will run in a background session server from the next launch.settings-status-local-sessions-via-mux-off = Local terminals will run inside ThinkTerm from the next launch.settings-status-local-sessions-via-mux-error = Could not save the local sessions setting: { $error }+settings-status-restore-pane-output-on = Pane contents will be kept when terminals stop and put back next time.+settings-status-restore-pane-output-off = Pane contents are no longer kept; what was kept has been deleted.+settings-status-restore-pane-output-error = Could not save the pane contents setting: { $error }settings-stop-session-server = Stop the session serversettings-stop-session-server-description = Ends every terminal running in the background session server now. The windows showing them close; it starts again the next time ThinkTerm needs it.settings-stop-session-server-now = Stop…diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 42aee0d4..0306ffb7 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -198,6 +198,8 @@ settings-update-download-source-direct = GitHub (direct)settings-update-download-source-auto = Automatiquesettings-local-sessions-via-mux = Garder les terminaux locaux dans un serveur de sessions en arrière-plansettings-local-sessions-via-mux-description = Les terminaux locaux tournent dans un serveur mux sur cette machine et survivent à la fermeture, au plantage ou à la mise à jour de ThinkTerm. Prend effet au prochain lancement.+settings-restore-pane-output = Restaurer le contenu des volets à la réouverture+settings-restore-pane-output-description = Seulement pour les terminaux de cet ordinateur : quand ThinkTerm se ferme, que l’ordinateur s’éteint ou que le serveur de session s’arrête, la sortie de chaque volet est gardée sur cet ordinateur et remise dans son volet la fois suivante. Les mots de passe et jetons sont masqués avant l’enregistrement ; un plantage ou une coupure de courant ne laisse pas le temps d’enregistrer. Pour une autre machine, comme un hôte distant, lancez `thinkterm cli restore-output on` dans un terminal de cette machine.settings-terminal-heading = Configuration du terminalsettings-terminal-font-heading = Policesettings-terminal-display-heading = Affichage@@ -781,6 +783,9 @@ settings-status-remote-update-keep-sessions-error = Impossible d’enregistrer lsettings-status-local-sessions-via-mux-on = Les terminaux locaux tourneront dans un serveur de sessions dès le prochain lancement.settings-status-local-sessions-via-mux-off = Les terminaux locaux tourneront dans ThinkTerm dès le prochain lancement.settings-status-local-sessions-via-mux-error = Impossible d’enregistrer le réglage des sessions locales : { $error }+settings-status-restore-pane-output-on = Le contenu des volets sera gardé à l’arrêt des terminaux et remis la fois suivante.+settings-status-restore-pane-output-off = Le contenu des volets n’est plus gardé ; ce qui avait été gardé a été supprimé.+settings-status-restore-pane-output-error = Impossible d’enregistrer le réglage du contenu des volets : { $error }settings-stop-session-server = Arrêter le serveur de sessionsettings-stop-session-server-description = Met fin maintenant à tous les terminaux du serveur de session en arrière-plan. Les fenêtres qui les affichent se ferment ; il redémarrera la prochaine fois que ThinkTerm en aura besoin.settings-stop-session-server-now = Arrêter…diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 3e52a0ea..e450814b 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -195,6 +195,8 @@ settings-update-download-source-direct = GitHub(直接)settings-update-download-source-auto = 自動settings-local-sessions-via-mux = ローカル端末をバックグラウンドのセッションサーバーに置くsettings-local-sessions-via-mux-description = ローカル端末はこのマシンの mux サーバーで動作し、ThinkTerm の終了・クラッシュ・更新後も残ります。次回起動時に有効になります。+settings-restore-pane-output = 開き直したときにペインの内容を戻す+settings-restore-pane-output-description = このコンピューターのターミナルだけが対象です。ThinkTerm の終了、シャットダウン、セッションサーバーの停止のときに、各ペインの出力をこのコンピューターに保存し、次回元のペインに戻します。パスワードやトークンは保存前に伏せ字にします。クラッシュや停電のときは保存できません。リモートホストなど別のマシンで有効にするには、そのマシンのターミナルで `thinkterm cli restore-output on` を実行します。settings-terminal-heading = ターミナル設定settings-terminal-font-heading = フォントsettings-terminal-display-heading = 表示@@ -772,6 +774,9 @@ settings-status-remote-update-keep-sessions-error = リモート更新の設定settings-status-local-sessions-via-mux-on = 次回起動からローカル端末はバックグラウンドのセッションサーバーで動作します。settings-status-local-sessions-via-mux-off = 次回起動からローカル端末は ThinkTerm 内で動作します。settings-status-local-sessions-via-mux-error = ローカルセッションの設定を保存できませんでした: { $error }+settings-status-restore-pane-output-on = 有効:ターミナルが止まるときにペインの内容を保存し、次回戻します。+settings-status-restore-pane-output-off = 無効:ペインの内容は保存しません。保存済みの内容は削除しました。+settings-status-restore-pane-output-error = ペインの内容の設定を保存できませんでした: { $error }settings-stop-session-server = セッションサーバーを停止settings-stop-session-server-description = バックグラウンドのセッションサーバーで動いているターミナルをすべて今すぐ終了します。それらを表示していたウィンドウも閉じます。次に ThinkTerm が必要とするときに再び起動します。settings-stop-session-server-now = 停止…diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex c49df027..ce8f33f3 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -195,6 +195,8 @@ settings-update-download-source-direct = 直连 GitHubsettings-update-download-source-auto = 自动settings-local-sessions-via-mux = 本地终端放在后台会话 server 里settings-local-sessions-via-mux-description = 本地终端跑在本机的 mux server 中,ThinkTerm 退出、崩溃或更新后会话仍在。下次启动 ThinkTerm 时生效。+settings-restore-pane-output = 重新打开时恢复窗格内容+settings-restore-pane-output-description = 只管这台电脑上的终端:ThinkTerm 退出、电脑关机或停止会话服务器时,把每个窗格的输出存在这台电脑上,下次打开时放回原来的窗格。密码和 token 会先遮住再存;崩溃或断电时来不及保存。要在别的机器(比如远程主机)上打开,在那台机器的终端里运行 `thinkterm cli restore-output on`。settings-terminal-heading = 终端配置settings-terminal-font-heading = 字体settings-terminal-display-heading = 显示@@ -772,6 +774,9 @@ settings-status-remote-update-keep-sessions-error = 无法保存远端更新设settings-status-local-sessions-via-mux-on = 已开启:下次启动起本地终端跑在后台会话 server 里。settings-status-local-sessions-via-mux-off = 已关闭:下次启动起本地终端跑在 ThinkTerm 进程内。settings-status-local-sessions-via-mux-error = 无法保存本地会话设置:{ $error }+settings-status-restore-pane-output-on = 已开启:终端停止时会保存窗格内容,下次打开时放回。+settings-status-restore-pane-output-off = 已关闭:不再保存窗格内容,已保存的已删除。+settings-status-restore-pane-output-error = 无法保存窗格内容设置:{ $error }settings-stop-session-server = 停止会话服务器settings-stop-session-server-description = 立即结束后台会话服务器里的全部终端。显示它们的窗口会随之关闭;下次 ThinkTerm 需要时会重新启动它。settings-stop-session-server-now = 停止…diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex 325d51d5..699019e5 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -2521,6 +2521,9 @@ impl ClientDomain {}None => {}}+ // A restored pane's command made only to carry the name of what it+ // showed carries the choice now too, which the server must keep.+ mux::kept_output::filled_in(&mut cmd);Some(CommandSpec::from_command_builder(&cmd))}diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex 1fb53178..56eff058 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -158,6 +158,9 @@ window.workspace = true[target.'cfg(target_os = "macos")'.dependencies]+[target.'cfg(unix)'.dependencies]+signal-hook.workspace = true+[target.'cfg(windows)'.dependencies]shared_library.workspace = truewinapi = { workspace=true, features = [diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex ca83bf6b..f9fd0a20 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -537,6 +537,10 @@ impl GuiFrontEnd {}).detach();}+ ApplicationEvent::WillTerminate => {+ crate::local_sessions::note_app_ending();+ crate::workspace_threads::keep_pane_output();+ }ApplicationEvent::PerformKeyAssignment(action) => {// We should only get here when there are no windows open// and the user picks an action from the menubar.@@ -1027,8 +1031,10 @@ impl GuiFrontEnd {mux_window_id: MuxWindowId,recovery_slot: FrontendRecoverySlot,) {- // A GUI window exists again: any pending last-window cleanup is moot.+ // A GUI window exists again: any pending last-window cleanup is moot,+ // and the app goes on past what the last window closing kept.self.detach_when_windowless.set(false);+ crate::workspace_threads::keep_pane_output_again();self.any_window_recorded.set(true);// Mark this mux window as having a GUI window so the additive reconcile// never re-creates a window for it (e.g. after the user closes it whilediff --git a/wezterm-gui/src/local_sessions.rs b/wezterm-gui/src/local_sessions.rsindex 13b35f0c..4819c61b 100644--- a/wezterm-gui/src/local_sessions.rs+++ b/wezterm-gui/src/local_sessions.rs@@ -200,6 +200,15 @@ pub(crate) fn stop_server_at_exit() {STOP_AT_EXIT.store(true, std::sync::atomic::Ordering::SeqCst);}+/// The system is ending the app (a logout, a shutdown). A session server+/// that goes away now goes with it, and rebuilding its Threads into a new+/// one would spend what it kept on terminals about to end as well.+static ENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++pub(crate) fn note_app_ending() {+ ENDING.store(true, std::sync::atomic::Ordering::SeqCst);+}+pub(crate) fn finish_stop_at_exit(config: &ConfigHandle) {if !STOP_AT_EXIT.swap(false, std::sync::atomic::Ordering::SeqCst) {return;@@ -302,6 +311,9 @@ pub(crate) fn fall_back_to_in_process(mux: &Mux, why: &anyhow::Error) {/// adopted. An activity guard keeps the GUI from quitting while the mux/// is briefly empty.pub(crate) fn on_host_replaced(domain_id: mux::domain::DomainId) {+ if ENDING.load(std::sync::atomic::Ordering::SeqCst) {+ return;+ }promise::spawn::spawn_into_main_thread(async move {let _activity = mux::activity::Activity::new();let mux = Mux::get();diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 31ea661a..53556681 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -390,6 +390,7 @@ async fn spawn_tab_in_domain_if_mux_is_empty() -> anyhow::Result<()> {let mux = Mux::get();+ let named_domain = domain.is_some();let domain = domain.unwrap_or_else(|| mux.default_domain());// The local session host was attached before this ran and its windows@@ -459,6 +460,26 @@ async fn spawn_tab_in_domain_if_mux_is_empty(true});+ // A Thread living in the startup workspace takes this tab as its pane+ // rather than being rebuilt, so on a plain launch of a shell in this+ // machine's own terminals the tab starts with what that pane showed+ // when they last stopped, if that was kept: as a Thread rebuilt without+ // a recorded layout does. A program asked for by name is left alone,+ // and the record with it.+ let kept_key = if !named_domain+ && cmd.is_none()+ && crate::workspace_threads::reads_kept_output(&*domain)+ {+ mux.get_window(window_id)+ .map(|window| window.get_workspace().to_string())+ } else {+ None+ };+ let cmd = match &kept_key {+ Some(key) => mux::kept_output::with_lone_seed(key, cmd),+ None => cmd,+ };+let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi());let spawned = domain.spawn(@@ -470,6 +491,9 @@ async fn spawn_tab_in_domain_if_mux_is_empty(.await;drop(held_window);spawned?;+ if let Some(key) = &kept_key {+ mux::kept_output::finish(key);+ }trigger_and_log_gui_attached(MuxDomain(domain.domain_id())).await;Ok(())}@@ -1622,7 +1646,46 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->.detach();}- gui.run_forever()+ #[cfg(unix)]+ install_session_end_handler();+ let outcome = gui.run_forever();+ crate::local_sessions::finish_stop_at_exit(&config::configuration());+ outcome+}++/// A logout or shutdown ends the session with SIGTERM. With the terminals in+/// this process and Settings keeping their output, that is a quit like any+/// other: the loop ends and `main` keeps what they show. Otherwise, or when+/// the app does not get out in time, the signal does what it always did.+#[cfg(unix)]+fn install_session_end_handler() {+ use signal_hook::consts::signal::SIGTERM;+ let mut signals = match signal_hook::iterator::Signals::new([SIGTERM]) {+ Ok(signals) => signals,+ Err(err) => {+ log::warn!("not watching for SIGTERM: {err:#}");+ return;+ }+ };+ std::thread::spawn(move || {+ for signal in signals.forever() {+ if crate::local_sessions::host_domain_name().is_none()+ && mux::kept_output::enabled()+ {+ promise::spawn::spawn_into_main_thread(async {+ if let Some(conn) = Connection::get() {+ conn.terminate_message_loop();+ }+ })+ .detach();+ std::thread::sleep(std::time::Duration::from_secs(5));+ }+ if let Err(err) = signal_hook::low_level::emulate_default_handler(signal) {+ log::error!("ending on signal {signal}: {err:#}");+ std::process::exit(1);+ }+ }+ });}fn fatal_toast_notification(title: &str, message: &str) {@@ -1689,8 +1752,13 @@ fn main() {notify_on_panic();i18n::install();if let Err(e) = run() {+ // The display going away, as at a logout, ends the loop with an+ // error: what the terminals inside showed is kept all the same.+ crate::workspace_threads::keep_pane_output();terminate_with_error(e);}+ // Before the terminals inside this process end with it.+ crate::workspace_threads::keep_pane_output();Mux::shutdown();frontend::shutdown();}@@ -2054,6 +2122,17 @@ fn run() -> anyhow::Result<()> {};env_bootstrap::bootstrap();+ // Ended by a logoff or shutdown ahead of the session server (whose+ // `SHUTDOWN_LEVEL` this is one above) and of the shells in this+ // process's own terminals: what those show is kept while they are still+ // there, and the server is not started again as it goes.+ #[cfg(windows)]+ if unsafe { winapi::um::processthreadsapi::SetProcessShutdownParameters(0x301, 0) } == 0 {+ log::warn!(+ "setting the shutdown level: {}",+ std::io::Error::last_os_error()+ );+ }// window_funcs is not set up by env_bootstrap as window_funcs is// GUI environment specific and env_bootstrap is used to setup the// headless mux server.diff --git a/wezterm-gui/src/overlay/confirm_close_pane.rs b/wezterm-gui/src/overlay/confirm_close_pane.rsindex c069079a..93041ff0 100644--- a/wezterm-gui/src/overlay/confirm_close_pane.rs+++ b/wezterm-gui/src/overlay/confirm_close_pane.rs@@ -103,10 +103,14 @@ pub fn confirm_quit_program(mut term: TermWizTerminal,window: ::window::Window,tab_id: TabId,+ stop_server: bool,) -> anyhow::Result<()> {if confirm::run_confirmation("🛑 Really Quit ThinkTerm?", &mut term)? {promise::spawn::spawn_into_main_thread(async move {use ::window::{Connection, ConnectionOps};+ if stop_server {+ crate::local_sessions::stop_server_at_exit();+ }let con = Connection::get().expect("call on gui thread");con.terminate_message_loop();})diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex bf9d8dc5..94353f36 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -1079,6 +1079,8 @@ impl SettingsSection {"Window Size","Window Position","Configuration",+ "Restore Pane Contents",+ "Scrollback",],Self::Web => &["Web",@@ -1321,9 +1323,9 @@ impl SettingsSection {.iter().any(|term| term.to_lowercase().contains(query))|| (self == Self::General- && crate::i18n::tr("settings-language")- .to_lowercase()- .contains(query))+ && ["settings-language", "settings-restore-pane-output"]+ .iter()+ .any(|key| crate::i18n::tr(key).to_lowercase().contains(query)))|| (self == Self::Appearance&& ["settings-window-opacity",@@ -1830,6 +1832,7 @@ enum SettingsAction {ToggleAgentStatusPart(AgentStatusPart),ToggleRemoteUpdateKeepsSessions,ToggleLocalSessionsViaMux,+ ToggleRestorePaneOutput,StopSessionServer,/// The ⓘ after a label; hovering it shows the text under this i18n key.Hint(&'static str),@@ -2490,6 +2493,9 @@ impl ChromeFontArea {#[derive(Debug, Clone)]struct SettingsUiState {+ /// This machine's switch for keeping pane output, which lives outside+ /// the native settings (see `mux::kept_output`); read as the window opens.+ restore_pane_output: bool,import_source: ImportSource,import_step: ImportStep,import_result: Option<String>,@@ -2619,6 +2625,7 @@ impl SettingsUiState {fn new(dpi: usize) -> Self {let tokens = UiTokens::for_dpi(dpi);Self {+ restore_pane_output: mux::kept_output::enabled(),session_import: session_import::ImportUi::default(),import_source: ImportSource::initial(),import_step: if session_import::remembered_source().is_some() {@@ -6102,6 +6109,27 @@ impl SettingsWindow {}}}+ SettingsAction::ToggleRestorePaneOutput => {+ self.ui.open_dropdown = None;+ let enabled = !self.ui.restore_pane_output;+ // Turning it off removes what was kept, too.+ match mux::kept_output::set_enabled(enabled) {+ Ok(()) => {+ self.ui.restore_pane_output = enabled;+ self.status = crate::i18n::tr(if enabled {+ "settings-status-restore-pane-output-on"+ } else {+ "settings-status-restore-pane-output-off"+ });+ }+ Err(err) => {+ self.status = settings_tr(+ "settings-status-restore-pane-output-error",+ &[("error", format!("{err:#}"))],+ );+ }+ }+ }SettingsAction::ToggleMacGlassMenu => {self.ui.open_dropdown = if self.ui.open_dropdown == Some(SettingsDropdown::MacGlass){@@ -8474,6 +8502,27 @@ impl SettingsWindow {SettingsAction::ToggleLocalSessionsViaMux,)?;let mut end = y + band;+ let (tx, tw) = this.paint_band_tile(+ layers,+ row_x,+ end,+ band,+ row_width,+ SvgIcon::ArchiveRestore,+ TileColor::Slate,+ )?;+ this.paint_toggle_setting_row_with_hint(+ layers,+ tx,+ end,+ tw,+ band,+ &crate::i18n::tr("settings-restore-pane-output"),+ "settings-restore-pane-output-description",+ this.ui.restore_pane_output,+ SettingsAction::ToggleRestorePaneOutput,+ )?;+ end += band;if server_running {let button = crate::i18n::tr(if this.ui.confirm_stop_server {"settings-stop-session-server-confirm"@@ -20343,7 +20392,13 @@ return configif let Ok(cwd) = std::env::current_dir() {command.current_dir(cwd);}- command.spawn().context("spawn replacement ThinkTerm")?;+ // Before the replacement starts: it restores what this one keeps.+ crate::workspace_threads::keep_pane_output();+ if let Err(err) = command.spawn() {+ // Still running after all: its own exit keeps what it shows then.+ crate::workspace_threads::keep_pane_output_again();+ return Err(err).context("spawn replacement ThinkTerm");+ }if let Some(conn) = Connection::get() {conn.terminate_message_loop();}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 0616f209..12efbc63 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -3900,6 +3900,12 @@ impl TermWindow {fn close_gui_window_now(&self, window: &Window, preserve_mux_window: bool) {if !preserve_mux_window {+ // The last window going takes the app with it, and its terminals+ // end right here: what they show is kept first.+ if self.config.quit_when_all_windows_are_closed && front_end().gui_windows().len() <= 1+ {+ crate::workspace_threads::keep_pane_output();+ }// Local windows retain the established destructive close behavior.Mux::get().kill_window(self.mux_window_id);}@@ -11094,13 +11100,19 @@ impl TermWindow {let con = Connection::get().expect("call on gui thread");con.hide_application();}- QuitApplication => {+ QuitApplication | QuitAndStopSessionServer => {let mux = Mux::get();let config = &self.config;log::info!("QuitApplication over here (window)");+ // The server is stopped after the loop ends, and only if the+ // quit goes ahead: one called off stops nothing later.+ let stop_server = matches!(assignment, QuitAndStopSessionServer);match config.window_close_confirmation {WindowCloseConfirmation::NeverPrompt => {+ if stop_server {+ crate::local_sessions::stop_server_at_exit();+ }let con = Connection::get().expect("call on gui thread");con.terminate_message_loop();}@@ -11112,7 +11124,7 @@ impl TermWindow {let window = self.window.clone().unwrap();let (overlay, future) = start_overlay(self, &tab, move |tab_id, term| {- confirm_quit_program(term, window, tab_id)+ confirm_quit_program(term, window, tab_id, stop_server)});self.assign_overlay(tab.tab_id(), overlay);promise::spawn::spawn(future).detach();@@ -11544,12 +11556,6 @@ impl TermWindow {crate::settings_window::show_from(self.mux_window_id, &self.active_space_id);}FocusPluginPanel(plugin) => self.focus_plugin_panel(plugin),- QuitAndStopSessionServer => {- // The stop happens after the loop ends; the quit itself- // goes through the same confirmation as any quit.- crate::local_sessions::stop_server_at_exit();- return self.perform_key_assignment(pane, &QuitApplication);- }CheckForUpdates => {crate::settings_window::show_update_page_from(self.mux_window_id,diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 6ee804e1..4494c4de 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -4,7 +4,8 @@ use config::keyassignment::{SpawnCommand, SpawnTabDomain};use fluent_bundle::FluentArgs;use futures::future::LocalBoxFuture;use mux::domain::SplitSource;-use mux::pane::PaneId;+use mux::kept_output::Owner;+use mux::pane::{Pane, PaneId};use mux::tab::{PaneEntry, PaneNode, PaneStackEntry, SplitDirection, SplitRequest, SplitSize};use mux::window::WindowId as MuxWindowId;use mux::Mux;@@ -65,7 +66,6 @@ pub struct ImportedSession {}/// The most imports remembered; the oldest go first.-#[cfg(unix)]const MAX_IMPORTED_SESSIONS: usize = 64;#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]@@ -248,6 +248,10 @@ pub struct TerminalSpawnSpec {/// The label the pane was given; the pane that replaces it gets it.#[serde(default, skip_serializing_if = "Option::is_none")]pub label: Option<String>,+ /// The pane's id in the local session server, when it ran there: what+ /// that server keeps its output under (`mux::kept_output`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub host_pane_id: Option<PaneId>,}#[derive(Debug, Clone)]@@ -1443,7 +1447,6 @@ pub fn create_space(name: Option<String>) -> SpaceId {id}-#[cfg(unix)]pub(crate) fn persist_session_import(tree: &codec::ThinkTermTree,add: bool,@@ -1467,7 +1470,6 @@ pub(crate) fn persist_session_import(Ok(())}-#[cfg(unix)]fn store_with_session_import(store: &WorkspaceThreadStore,tree: &codec::ThinkTermTree,@@ -1511,6 +1513,7 @@ fn store_with_session_import(domain: Some("local".into()),title: entry.title.clone(),label: None,+ host_pane_id: None,},font_scale: None,})@@ -1909,7 +1912,6 @@ pub fn remote_space_domains() -> Vec<String> {/// Remember that `session` of `source`, imported on `host`, became/// `space_id`.-#[cfg(unix)]pub fn note_imported_session(source: &str, session: &str, host: Option<&str>, space_id: &str) {let mut store = THREAD_STORE.lock();store.note_imported_session(ImportedSession {@@ -1923,7 +1925,6 @@ pub fn note_imported_session(source: &str, session: &str, host: Option<&str>, sp/// The name of the Space `session` of `source` on `host` was imported/// into, while that Space is still here.-#[cfg(unix)]pub fn imported_session_space(source: &str, session: &str, host: Option<&str>) -> Option<String> {THREAD_STORE.lock()@@ -3486,7 +3487,6 @@ pub(crate) async fn materialize_thread(// *from* this materialization, and no window is worse than the wrong cwd.strict_project_cwd: bool,) -> Result<ThreadMaterializationOutcome> {- #[cfg(unix)]wezterm_mux_server_impl::session_import::wait_for_workspace(&workspace_name).await?;let mux = Mux::get();if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {@@ -3611,10 +3611,10 @@ pub(crate) async fn materialize_thread(Some((layout, tabs))});if let Some((layout, tabs)) = layout {- let _guard = MaterializeThreadLayoutGuard::new(workspace_name.clone());+ let guard = MaterializeThreadLayoutGuard::new(workspace_name.clone());materialize_layout(mux,- workspace_name,+ workspace_name.clone(),layout,tabs,initial_cwd,@@ -3622,6 +3622,8 @@ pub(crate) async fn materialize_thread(term_config,).await?;+ drop(guard);+ rekey_restored_layout(&workspace_name);Ok(ThreadMaterializationOutcome::RestoredLayout)} else {// A thread whose Space lives on a mux server needs its window tagged@@ -3673,6 +3675,14 @@ pub(crate) async fn materialize_thread(command.set_require_cwd(true);command});+ // A Thread back without a recorded layout only ever had one pane:+ // it starts with what that pane showed when it stopped, if kept.+ let command = if spawns_locally(&mux, &default_domain, None) {+ mux::kept_output::with_lone_seed(&workspace_name, command)+ } else {+ command+ };+ let kept_key = workspace_name.clone();let spawned = mux.spawn_tab_or_window(@@ -3690,6 +3700,7 @@ pub(crate) async fn materialize_thread(let (_tab, pane, _window_id) = spawned.context("spawn default thread window")?;pane.set_config(term_config);+ mux::kept_output::finish(&kept_key);let _ = src_window_id;Ok(ThreadMaterializationOutcome::SpawnedFresh)}@@ -3701,7 +3712,6 @@ pub async fn materialize_thread_spawn(size: TerminalSize,term_config: Arc<dyn TerminalConfiguration>,) -> Result<()> {- #[cfg(unix)]wezterm_mux_server_impl::session_import::wait_for_workspace(&workspace_name).await?;let mux = Mux::get();if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {@@ -6452,7 +6462,6 @@ impl WorkspaceThreadStore {/// The newest import of a session replaces older ones. A local entry/// whose Space is gone was deleted with it; a remote one may only be/// missing until its host connects again, so it waits for the cap.- #[cfg(unix)]fn note_imported_session(&mut self, imported: ImportedSession) {let spaces = &self.spaces;self.imported_sessions.retain(|known| {@@ -6469,7 +6478,6 @@ impl WorkspaceThreadStore {self.imported_sessions.drain(..excess);}- #[cfg(unix)]fn imported_session_space(&self,source: &str,@@ -7240,6 +7248,25 @@ impl WorkspaceThreadStore {true}+ /// The layout of the Thread that restores into `workspace`, under the+ /// name `keep_pane_output` keeps its panes' output by.+ fn thread_layout_for_workspace_mut(+ &mut self,+ workspace: &str,+ ) -> Option<&mut WorkspaceThreadLayoutSnapshot> {+ self.projects+ .iter_mut()+ .flat_map(|project| project.threads.iter_mut())+ .find(|thread| {+ thread+ .materialized_workspace_name+ .as_deref()+ .or(thread.planned_workspace_name.as_deref())+ == Some(workspace)+ })+ .and_then(|thread| thread.layout.as_mut())+ }+fn workspace_pane_font_scales(&self,workspace: &str,@@ -9030,6 +9057,257 @@ fn schedule_workspace_thread_store_persist() {});}+/// Set by the way out that kept the panes' output. See [`keep_pane_output`].+static PANE_OUTPUT_KEPT: AtomicBool = AtomicBool::new(false);++/// Before the app exits with its terminals inside it, rather than in the+/// session server: what each Thread's panes show, kept until its layout is+/// restored, when Settings has that on. See `mux::kept_output`.+pub(crate) fn keep_pane_output() {+ if crate::local_sessions::host_domain_name().is_some() {+ // The session server keeps its own; its terminals outlive this.+ mux::kept_output::prune_stale();+ return;+ }+ let Some(mux) = Mux::try_get() else {+ return;+ };+ if !mux::kept_output::enabled() {+ mux::kept_output::discard(Owner::App);+ return;+ }+ // The first way out to get here keeps (the last window closing, a+ // restart, the system ending the app); a second in the same exit would+ // write back what the next process may already have taken.+ if PANE_OUTPUT_KEPT.swap(true, Ordering::SeqCst) {+ return;+ }+ // The workspaces Threads restore into, named as the server names them,+ // and the layout each restores from.+ let threads: HashMap<String, Option<WorkspaceThreadLayoutSnapshot>> = THREAD_STORE+ .lock()+ .projects+ .iter()+ .flat_map(|project| &project.threads)+ .filter_map(|thread| {+ let workspace = thread+ .materialized_workspace_name+ .clone()+ .or_else(|| thread.planned_workspace_name.clone())?;+ Some((workspace, thread.layout.clone()))+ })+ .collect();+ for workspace in mux.iter_workspaces() {+ let Some(layout) = threads.get(&workspace) else {+ continue;+ };+ // Mid-restore its panes are not all there, and what was kept for+ // the rest has not been taken yet: that stays as it is.+ if is_materializing_thread_layout(&workspace) {+ continue;+ }+ let panes = panes_under_saved_ids(&mux, &workspace, layout.as_ref());+ mux::kept_output::save(Owner::App, &workspace, &panes);+ }+ if threads.is_empty() {+ // Nothing known of any Thread, as when the app stopped before it+ // read them: what was kept waits for a run that knows.+ mux::kept_output::prune_stale();+ } else {+ mux::kept_output::prune(Owner::App, &threads.into_keys().collect());+ }+}++/// The app goes on after a way out kept its panes' output: a restart whose+/// new process did not start, a window opened again after the last one+/// closed. Its own exit keeps what they show then.+pub(crate) fn keep_pane_output_again() {+ PANE_OUTPUT_KEPT.store(false, Ordering::SeqCst);+}++/// The panes of `workspace`, each under the id that `layout` -- what the+/// Thread restores from -- has for its place, which is the id the restore+/// asks for. A pane in a place the layout does not have is not kept: no+/// restore would ask for it. With no layout, or one of another shape+/// altogether -- the startup Thread comes back as its one pane whatever its+/// layout says -- each is kept under its own id, and a Thread that comes+/// back as one pane takes a lone record whatever its id.+fn panes_under_saved_ids(+ mux: &Mux,+ workspace: &str,+ layout: Option<&WorkspaceThreadLayoutSnapshot>,+) -> Vec<(PaneId, Arc<dyn Pane>)> {+ let saved: Option<Vec<PaneNode>> = layout+ .filter(|layout| !layout.tabs.is_empty())+ .and_then(|layout| {+ layout+ .tabs+ .iter()+ .map(|tab| serde_json::from_value(tab.clone()).ok())+ .collect()+ });+ let mut pairs = HashMap::new();+ if let (Some(saved), Some(live)) = (saved, live_tabs(mux, workspace)) {+ for (saved, live) in saved.iter().zip(&live) {+ pair_panes_by_place(saved, live, &mut pairs);+ }+ }+ if pairs.is_empty() {+ return mux+ .iter_windows_in_workspace(workspace)+ .into_iter()+ .filter_map(|window_id| {+ let window = mux.get_window(window_id)?;+ Some(window.iter().flat_map(|tab| tab.iter_all_panes()).collect::<Vec<_>>())+ })+ .flatten()+ .map(|pane| (pane.pane_id(), pane))+ .collect();+ }+ pairs+ .into_iter()+ .filter_map(|(saved, live)| Some((saved, mux.get_pane(live)?)))+ .collect()+}++/// The tabs of the window `workspace` shows in, as trees.+fn live_tabs(mux: &Mux, workspace: &str) -> Option<Vec<PaneNode>> {+ let window_id = mux.iter_windows_in_workspace(workspace).into_iter().next()?;+ let window = mux.get_window(window_id)?;+ Some(window.iter().map(|tab| tab.codec_pane_tree()).collect())+}++/// Pair each pane of `saved`, a tab of a saved layout, with the one standing+/// in its place in `live`. Where the two differ in shape nothing is paired:+/// a place there names no particular pane.+fn pair_panes_by_place(saved: &PaneNode, live: &PaneNode, pairs: &mut HashMap<PaneId, PaneId>) {+ match (saved, live) {+ (PaneNode::Leaf(saved), PaneNode::Leaf(live)) => {+ pairs.insert(saved.pane_id, live.pane_id);+ }+ (PaneNode::Stack(saved), PaneNode::Stack(live)) if saved.panes.len() == live.panes.len() => {+ for (saved, live) in saved.panes.iter().zip(&live.panes) {+ pairs.insert(saved.pane_id, live.pane_id);+ }+ }+ (+ PaneNode::Split {+ left: saved_left,+ right: saved_right,+ node: saved_node,+ },+ PaneNode::Split {+ left: live_left,+ right: live_right,+ node: live_node,+ },+ ) if saved_node.direction == live_node.direction => {+ pair_panes_by_place(saved_left, live_left, pairs);+ pair_panes_by_place(saved_right, live_right, pairs);+ }+ _ => {}+ }+}++/// The layout `workspace` was just restored from, made to name the panes now+/// standing in it -- by their ids here, and in the local session server for+/// the ones that run there -- with everything else it records left as it+/// was. An exit keeps each pane's output under those ids; a layout still+/// naming the panes it was restored from, as a Thread brought back at+/// startup and not changed since does, would have the next restore ask for+/// the run before's, and could hand one pane's output to another.+fn rekey_restored_layout(workspace: &str) {+ let mux = Mux::get();+ let Some(live) = live_tabs(&mux, workspace) else {+ return;+ };+ let mut ids = vec![];+ for tab in &live {+ collect_pane_ids(tab, &mut ids);+ }+ let host_panes: HashMap<PaneId, PaneId> = ids+ .into_iter()+ .filter_map(|id| {+ let pane = mux.get_pane(id)?;+ if !crate::local_sessions::is_host_domain_id(pane.domain_id()) {+ return None;+ }+ let client = pane.downcast_ref::<wezterm_client::pane::ClientPane>()?;+ Some((id, client.remote_pane_id))+ })+ .collect();+ let changed = THREAD_STORE+ .lock()+ .thread_layout_for_workspace_mut(workspace)+ .is_some_and(|layout| rekey_layout(layout, &live, &host_panes));+ if changed {+ schedule_workspace_thread_store_persist();+ }+}++/// `layout` naming, for each of its panes, the one standing in that place in+/// `live`, and that pane's id in the local session server from `host_panes`.+/// Whether that changed it. A layout with a tab this build cannot read is+/// left alone.+fn rekey_layout(+ layout: &mut WorkspaceThreadLayoutSnapshot,+ live: &[PaneNode],+ host_panes: &HashMap<PaneId, PaneId>,+) -> bool {+ let mut pairs = HashMap::new();+ let mut saved = vec![];+ for (tab, live) in layout.tabs.iter().zip(live) {+ let Ok(tab) = serde_json::from_value::<PaneNode>(tab.clone()) else {+ return false;+ };+ pair_panes_by_place(&tab, live, &mut pairs);+ saved.push(tab);+ }+ let before = layout.clone();+ for (value, mut tab) in layout.tabs.iter_mut().zip(saved) {+ rename_panes(&mut tab, &pairs);+ if let Ok(renamed) = serde_json::to_value(&tab) {+ *value = renamed;+ }+ }+ for entry in &mut layout.terminal_specs {+ if let Some(&live) = pairs.get(&entry.pane_id) {+ entry.pane_id = live;+ entry.spec.host_pane_id = host_panes.get(&live).copied();+ }+ }+ *layout != before+}++fn rename_panes(node: &mut PaneNode, pairs: &HashMap<PaneId, PaneId>) {+ let rename = |entry: &mut PaneEntry| {+ if let Some(&live) = pairs.get(&entry.pane_id) {+ entry.pane_id = live;+ }+ };+ match node {+ PaneNode::Empty => {}+ PaneNode::Leaf(entry) => rename(entry),+ PaneNode::Stack(stack) => stack.panes.iter_mut().for_each(rename),+ PaneNode::Split { left, right, .. } => {+ rename_panes(left, pairs);+ rename_panes(right, pairs);+ }+ }+}++fn collect_pane_ids(node: &PaneNode, ids: &mut Vec<PaneId>) {+ match node {+ PaneNode::Empty => {}+ PaneNode::Leaf(entry) => ids.push(entry.pane_id),+ PaneNode::Stack(stack) => ids.extend(stack.panes.iter().map(|entry| entry.pane_id)),+ PaneNode::Split { left, right, .. } => {+ collect_pane_ids(left, ids);+ collect_pane_ids(right, ids);+ }+ }+}+fn snapshot_window_layout<F>(window_id: MuxWindowId,pane_font_scale: &F,@@ -9290,6 +9568,19 @@ async fn materialize_layout(let domain = first_entry.map(|entry| spawn_domain_for_entry(&mux, entry, &terminal_specs, true)).unwrap_or(SpawnTabDomain::DefaultDomain);+ // What the pane showed when its terminals last stopped, if kept.+ let command = match first_entry {+ Some(entry) => kept_command(+ &mux,+ &workspace_name,+ entry,+ &terminal_specs,+ &domain,+ None,+ command,+ ),+ None => command,+ };let (_tab, pane, win_id) = mux.spawn_tab_or_window(window_id,@@ -9313,6 +9604,7 @@ async fn materialize_layout(&terminal_specs,heal_root,Arc::clone(&term_config),+ &workspace_name,).await?;spawned_tabs += 1;@@ -9327,6 +9619,7 @@ async fn materialize_layout(}rollback.commit();+ mux::kept_output::finish(&workspace_name);Ok(())}@@ -9337,6 +9630,7 @@ fn restore_node<'a>(terminal_specs: &'a HashMap<PaneId, TerminalSpawnSpec>,project_root: Option<&'a str>,term_config: Arc<dyn TerminalConfiguration>,+ workspace: &'a str,) -> LocalBoxFuture<'a, Result<()>> {Box::pin(async move {match node {@@ -9350,6 +9644,7 @@ fn restore_node<'a>(terminal_specs,project_root,term_config,+ workspace,).await?;}@@ -9365,12 +9660,26 @@ fn restore_node<'a>(node.second,)),};+ let domain = right_entry+ .map(|entry| spawn_domain_for_entry(&mux, entry, terminal_specs, false))+ .unwrap_or(SpawnTabDomain::CurrentPaneDomain);+ let command = right_entry.and_then(|entry| {+ kept_command(+ &mux,+ workspace,+ entry,+ terminal_specs,+ &domain,+ Some(base_pane_id),+ None,+ )+ });let (right_pane, _size) = mux.split_pane(base_pane_id,request,SplitSource::Spawn {- command: None,+ command,command_dir: heal_fallback_cwd(right_entry.and_then(|entry| {working_dir_for_entry(entry, terminal_specs)@@ -9378,9 +9687,7 @@ fn restore_node<'a>(project_root,),},- right_entry- .map(|entry| spawn_domain_for_entry(&mux, entry, terminal_specs, false))- .unwrap_or(SpawnTabDomain::CurrentPaneDomain),+ domain,).await.context("restore split pane")?;@@ -9392,6 +9699,7 @@ fn restore_node<'a>(terminal_specs,project_root,Arc::clone(&term_config),+ workspace,).await?;restore_node(@@ -9401,6 +9709,7 @@ fn restore_node<'a>(terminal_specs,project_root,term_config,+ workspace,).await?;}@@ -9416,14 +9725,25 @@ async fn restore_stack(terminal_specs: &HashMap<PaneId, TerminalSpawnSpec>,project_root: Option<&str>,term_config: Arc<dyn TerminalConfiguration>,+ workspace: &str,) -> Result<()> {let mut pane_ids = vec![base_pane_id];for entry in stack.panes.iter().skip(1) {+ let domain = spawn_domain_for_entry(&mux, entry, terminal_specs, false);+ let command = kept_command(+ &mux,+ workspace,+ entry,+ terminal_specs,+ &domain,+ Some(base_pane_id),+ None,+ );let pane = mux.spawn_pane_in_stack(base_pane_id,- spawn_domain_for_entry(&mux, entry, terminal_specs, false),- None,+ domain,+ command,heal_fallback_cwd(working_dir_for_entry(entry, terminal_specs), project_root),entry.size,)@@ -9442,6 +9762,48 @@ async fn restore_stack(Ok(())}+/// `command` for the pane standing in for `entry`, made to start with what+/// `entry` showed when its terminals last stopped, if that was kept+/// (`mux::kept_output`): the session server's record when the pane ran+/// there, this app's when it ran in here. Only a local domain, here or in+/// the local session server, reads the record.+fn kept_command(+ mux: &Mux,+ workspace: &str,+ entry: &PaneEntry,+ terminal_specs: &HashMap<PaneId, TerminalSpawnSpec>,+ domain: &SpawnTabDomain,+ current: Option<PaneId>,+ command: Option<CommandBuilder>,+) -> Option<CommandBuilder> {+ if !spawns_locally(mux, domain, current) {+ return command;+ }+ match terminal_specs+ .get(&entry.pane_id)+ .and_then(|spec| spec.host_pane_id)+ {+ Some(host_pane) => {+ mux::kept_output::with_seed(Owner::Server, workspace, host_pane, command)+ }+ None => mux::kept_output::with_seed(Owner::App, workspace, entry.pane_id, command),+ }+}++/// Whether a spawn in `domain` lands in a local domain, here or in the local+/// session server: the ones that read a kept record.+fn spawns_locally(mux: &Mux, domain: &SpawnTabDomain, current: Option<PaneId>) -> bool {+ mux.resolve_spawn_tab_domain(current, domain)+ .is_ok_and(|domain| reads_kept_output(&*domain))+}++/// Whether panes spawned in `domain` read a kept record: a local domain,+/// here or in the local session server.+pub(crate) fn reads_kept_output(domain: &dyn mux::domain::Domain) -> bool {+ domain.downcast_ref::<mux::domain::LocalDomain>().is_some()+ || crate::local_sessions::is_host_domain_id(domain.domain_id())+}+/// Give `pane_id` the label the pane it stands in for had.fn restore_label(mux: &Mux,@@ -9551,6 +9913,13 @@ fn collect_terminal_spec<F>(domain.domain_name().to_string()}});+ let host_pane_id = mux+ .get_pane(entry.pane_id)+ .filter(|pane| crate::local_sessions::is_host_domain_id(pane.domain_id()))+ .and_then(|pane| {+ pane.downcast_ref::<wezterm_client::pane::ClientPane>()+ .map(|client| client.remote_pane_id)+ });terminal_specs.push(TerminalSpecEntry {pane_id: entry.pane_id,spec: TerminalSpawnSpec {@@ -9558,6 +9927,7 @@ fn collect_terminal_spec<F>(domain,title: entry.title.clone(),label: mux.pane_label(entry.pane_id),+ host_pane_id,},font_scale: valid_font_scale(pane_font_scale(entry.pane_id)),});@@ -13753,7 +14123,6 @@ mod tests {store}- #[cfg(unix)]fn imported(source: &str, session: &str, host: Option<&str>, space: &str) -> ImportedSession {ImportedSession {source: source.to_string(),@@ -13763,7 +14132,6 @@ mod tests {}}- #[cfg(unix)]#[test]fn an_imported_session_is_known_only_while_its_space_is_on_that_connection() {let mut store = remote_test_store("server-a");@@ -13803,7 +14171,6 @@ mod tests {assert_eq!(name(&store, "work", Some("server-a")), None);}- #[cfg(unix)]#[test]fn imported_sessions_keep_the_newest_and_stay_bounded() {let mut store = remote_test_store("server-a");@@ -14393,7 +14760,6 @@ mod tests {tree}- #[cfg(unix)]fn import_layout_fixture() -> (codec::ThinkTermTree,Vec<wezterm_mux_server_impl::session_import::ImportedThreadLayout>,@@ -14485,7 +14851,6 @@ mod tests {(tree, layouts)}- #[cfg(unix)]#[test]fn imported_import_appends_and_rolls_back_only_its_own_rows() {let store = host_test_store();@@ -14499,7 +14864,6 @@ mod tests {assert_eq!(rolled_back, store);}- #[cfg(unix)]#[test]fn unopened_imported_threads_keep_every_layout_after_reload() {let (tree, layouts) = import_layout_fixture();@@ -15999,3 +16363,186 @@ mod tests {assert_eq!(ids, before_ids);}}++#[cfg(test)]+mod kept_output_layout_tests {+ use super::*;++ fn entry(pane_id: PaneId) -> PaneEntry {+ PaneEntry {+ window_id: 0,+ tab_id: 0,+ pane_id,+ title: format!("shell-{pane_id}"),+ size: TerminalSize::default(),+ working_dir: None,+ is_active_pane: false,+ is_zoomed_pane: false,+ alt_screen: false,+ workspace: "thinkterm:project-1:thread-2".into(),+ cursor_pos: Default::default(),+ physical_top: 0,+ top_row: 0,+ left_col: 0,+ tty_name: None,+ }+ }++ fn split(direction: SplitDirection, left: PaneNode, right: PaneNode) -> PaneNode {+ PaneNode::Split {+ left: Box::new(left),+ right: Box::new(right),+ node: mux::tab::SplitDirectionAndSize {+ direction,+ first: TerminalSize::default(),+ second: TerminalSize::default(),+ },+ }+ }++ fn stack(ids: &[PaneId]) -> PaneNode {+ PaneNode::Stack(PaneStackEntry {+ panes: ids.iter().map(|id| entry(*id)).collect(),+ active: 0,+ pane_stack_id: None,+ })+ }++ fn spec(pane_id: PaneId) -> TerminalSpecEntry {+ TerminalSpecEntry {+ pane_id,+ spec: TerminalSpawnSpec {+ cwd: Some(format!("/home/user/project/pane-{pane_id}")),+ domain: Some("local".into()),+ title: format!("shell-{pane_id}"),+ label: Some(format!("label-{pane_id}")),+ host_pane_id: Some(90 + pane_id),+ },+ font_scale: Some(1.25),+ }+ }++ fn layout(tabs: Vec<PaneNode>, specs: &[PaneId]) -> WorkspaceThreadLayoutSnapshot {+ WorkspaceThreadLayoutSnapshot {+ active_tab: 0,+ tabs: tabs+ .iter()+ .map(|tab| serde_json::to_value(tab).unwrap())+ .collect(),+ terminal_specs: specs.iter().map(|id| spec(*id)).collect(),+ strict_cwd_spawns: true,+ }+ }++ fn pairs(saved: &PaneNode, live: &PaneNode) -> Vec<(PaneId, PaneId)> {+ let mut pairs = HashMap::new();+ pair_panes_by_place(saved, live, &mut pairs);+ let mut pairs: Vec<_> = pairs.into_iter().collect();+ pairs.sort();+ pairs+ }++ #[test]+ fn panes_pair_only_where_the_shapes_match() {+ use SplitDirection::{Horizontal, Vertical};+ let saved = split(Horizontal, PaneNode::Leaf(entry(0)), PaneNode::Leaf(entry(1)));+ let live = split(Horizontal, PaneNode::Leaf(entry(5)), PaneNode::Leaf(entry(6)));+ assert_eq!(pairs(&saved, &live), [(0, 5), (1, 6)]);+ // Another shape names no particular pane.+ assert_eq!(pairs(&saved, &PaneNode::Leaf(entry(5))), []);+ let turned = split(Vertical, PaneNode::Leaf(entry(5)), PaneNode::Leaf(entry(6)));+ assert_eq!(pairs(&saved, &turned), []);+ assert_eq!(pairs(&stack(&[0, 1]), &stack(&[5])), []);+ // Where one side of a split still matches, that side pairs.+ let saved = split(+ Horizontal,+ PaneNode::Leaf(entry(0)),+ split(Vertical, PaneNode::Leaf(entry(1)), PaneNode::Leaf(entry(2))),+ );+ let live = split(Horizontal, PaneNode::Leaf(entry(7)), PaneNode::Leaf(entry(8)));+ assert_eq!(pairs(&saved, &live), [(0, 7)]);+ }++ /// A Thread restored at startup gets new ids, which may overlap the ones+ /// its layout names: left was 0 and right 1, now left is 1 and right 2.+ #[test]+ fn a_restored_layout_names_the_panes_now_in_it() {+ let saved = vec![+ split(+ SplitDirection::Horizontal,+ PaneNode::Leaf(entry(0)),+ PaneNode::Leaf(entry(1)),+ ),+ stack(&[2, 3]),+ ];+ let mut layout = layout(saved, &[0, 1, 2, 3]);+ let live = vec![+ split(+ SplitDirection::Horizontal,+ PaneNode::Leaf(entry(1)),+ PaneNode::Leaf(entry(2)),+ ),+ stack(&[3, 4]),+ ];+ let host_panes: HashMap<PaneId, PaneId> = [(1, 41), (2, 42)].into();+ assert!(rekey_layout(&mut layout, &live, &host_panes));++ let tabs: Vec<PaneNode> = layout+ .tabs+ .iter()+ .map(|tab| serde_json::from_value(tab.clone()).unwrap())+ .collect();+ let ids = |tab: &PaneNode| {+ let mut ids = vec![];+ collect_pane_ids(tab, &mut ids);+ ids+ };+ assert_eq!(ids(&tabs[0]), [1, 2]);+ assert_eq!(ids(&tabs[1]), [3, 4]);+ // Only the ids change: what the tree recorded of each pane stays.+ let PaneNode::Split { left, .. } = &tabs[0] else {+ panic!("the split is still a split");+ };+ let PaneNode::Leaf(left) = &**left else {+ panic!("its left is still a pane");+ };+ assert_eq!(left.title, "shell-0");+ let specs: Vec<(PaneId, Option<PaneId>, String)> = layout+ .terminal_specs+ .iter()+ .map(|entry| {+ (+ entry.pane_id,+ entry.spec.host_pane_id,+ entry.spec.cwd.clone().unwrap(),+ )+ })+ .collect();+ // Each keeps what it recorded -- the cwd says which pane it was --+ // under the id now standing in its place.+ assert_eq!(+ specs,+ [+ (1, Some(41), "/home/user/project/pane-0".to_string()),+ (2, Some(42), "/home/user/project/pane-1".to_string()),+ (3, None, "/home/user/project/pane-2".to_string()),+ (4, None, "/home/user/project/pane-3".to_string()),+ ]+ );+ assert!(layout+ .terminal_specs+ .iter()+ .all(|entry| entry.font_scale == Some(1.25) && entry.spec.label.is_some()));+ // Already naming them: nothing to change.+ assert!(!rekey_layout(&mut layout, &live, &host_panes));+ }++ #[test]+ fn a_layout_this_build_cannot_read_is_left_alone() {+ let mut layout = layout(vec![PaneNode::Leaf(entry(0))], &[0]);+ layout.tabs[0] = serde_json::json!({"not": "a pane tree"});+ let before = layout.clone();+ assert!(!rekey_layout(&mut layout, &[PaneNode::Leaf(entry(5))], &HashMap::new()));+ assert_eq!(layout, before);+ }+}diff --git a/wezterm-mux-server-impl/src/thinkterm_layout.rs b/wezterm-mux-server-impl/src/thinkterm_layout.rsindex c0a9a438..22ba5c9e 100644--- a/wezterm-mux-server-impl/src/thinkterm_layout.rs+++ b/wezterm-mux-server-impl/src/thinkterm_layout.rs@@ -8,8 +8,9 @@use anyhow::{Context, Result};use config::keyassignment::SpawnTabDomain;use futures::future::LocalBoxFuture;-use mux::domain::SplitSource;-use mux::pane::PaneId;+use mux::domain::{LocalDomain, SplitSource};+use mux::kept_output::{self, Owner};+use mux::pane::{Pane, PaneId};use mux::tab::{PaneEntry, PaneNode, SplitDirection, SplitRequest, SplitSize};use mux::window::WindowId;use mux::{Mux, MuxNotification};@@ -369,6 +370,67 @@ pub fn flush_now() -> Result<()> {snapshot_live_layouts(generation, false)}+/// Before a controlled exit, after `flush_now`: what each Thread's panes+/// show, kept by workspace until its layout is restored, when this machine+/// has that on. Only the panes the saved layout records, under its ids.+pub fn keep_pane_output() {+ if !kept_output::enabled() {+ kept_output::discard(Owner::Server);+ return;+ }+ let Some(mux) = Mux::try_get() else {+ return;+ };+ let records = thread_records(&crate::thinkterm_tree::snapshot());+ let recorded: Vec<(String, HashSet<PaneId>)> = {+ let store = STORE.lock().unwrap();+ records+ .iter()+ // A restore in flight has not replaced the saved layout yet, and+ // one that failed is kept as it was: in both the saved ids are+ // not the live panes', and a record under them would land in+ // the wrong pane.+ .filter(|(_, workspace)| {+ !store.restoring_workspaces.contains(workspace)+ && !store.protected_failed_layouts.contains_key(workspace)+ })+ .filter_map(|(thread_id, workspace)| {+ let layout = store.stored.layouts.get(thread_id)?;+ let ids = layout+ .terminal_specs+ .iter()+ .map(|spec| spec.pane_id)+ .collect();+ Some((workspace.clone(), ids))+ })+ .collect()+ };+ for (workspace, ids) in recorded {+ let panes: Vec<(PaneId, Arc<dyn Pane>)> = mux+ .iter_windows_in_workspace(&workspace)+ .into_iter()+ .filter_map(|window_id| {+ let window = mux.get_window(window_id)?;+ Some(+ window+ .iter()+ .flat_map(|tab| tab.iter_all_panes())+ .collect::<Vec<_>>(),+ )+ })+ .flatten()+ .filter(|pane| ids.contains(&pane.pane_id()))+ .map(|pane| (pane.pane_id(), pane))+ .collect();+ kept_output::save(Owner::Server, &workspace, &panes);+ }+ let workspaces = records+ .into_iter()+ .map(|(_, workspace)| workspace)+ .collect();+ kept_output::prune(Owner::Server, &workspaces);+}+fn thread_records(tree: &codec::ThinkTermTree) -> Vec<(String, String)> {tree.projects.iter()@@ -663,6 +725,8 @@ pub(crate) async fn restore_thread_layout(if let Some(window_id) = created_window {mux.kill_window(window_id);}+ } else {+ kept_output::finish(workspace);}result.map(|()| true)}@@ -700,11 +764,12 @@ async fn restore_decoded_layout(let domain = first.map(|entry| domain_for_entry(mux, entry, &specs, true)).unwrap_or(SpawnTabDomain::DefaultDomain);+ let command = first.and_then(|entry| kept_command(mux, workspace, entry, &domain, None));let (tab, pane, window_id) = mux.spawn_tab_or_window(*created_window,domain,- None,+ command,cwd,size,None,@@ -722,6 +787,7 @@ async fn restore_decoded_layout(&specs,project_path,&mut pane_map,+ workspace,).await?;for (saved, restored) in &pane_map {@@ -753,6 +819,7 @@ fn restore_node<'a>(specs: &'a HashMap<PaneId, StoredTerminalSpec>,project_path: &'a str,pane_map: &'a mut HashMap<PaneId, PaneId>,+ workspace: &'a str,) -> LocalBoxFuture<'a, Result<()>> {Box::pin(async move {match node {@@ -776,11 +843,13 @@ fn restore_node<'a>(dpi: dims.dpi,};for entry in stack.panes.iter().skip(1) {+ let domain = domain_for_entry(mux, entry, specs, false);+ let command = kept_command(mux, workspace, entry, &domain, Some(base_pane_id));let pane = mux.spawn_pane_in_stack(base_pane_id,- domain_for_entry(mux, entry, specs, false),- None,+ domain,+ command,cwd_for_entry(entry, specs, project_path),stack_size,)@@ -806,22 +875,35 @@ fn restore_node<'a>(node.second,)),};+ let domain = right_entry+ .map(|entry| domain_for_entry(mux, entry, specs, false))+ .unwrap_or(SpawnTabDomain::CurrentPaneDomain);+ let command = right_entry.and_then(|entry| {+ kept_command(mux, workspace, entry, &domain, Some(base_pane_id))+ });let (right_pane, _) = mux.split_pane(base_pane_id,request,SplitSource::Spawn {- command: None,+ command,command_dir: right_entry.and_then(|entry| cwd_for_entry(entry, specs, project_path)),},- right_entry- .map(|entry| domain_for_entry(mux, entry, specs, false))- .unwrap_or(SpawnTabDomain::CurrentPaneDomain),+ domain,).await.context("restore ThinkTerm split")?;- restore_node(mux, base_pane_id, left, specs, project_path, pane_map).await?;+ restore_node(+ mux,+ base_pane_id,+ left,+ specs,+ project_path,+ pane_map,+ workspace,+ )+ .await?;restore_node(mux,right_pane.pane_id(),@@ -829,6 +911,7 @@ fn restore_node<'a>(specs,project_path,pane_map,+ workspace,).await?;}@@ -837,6 +920,25 @@ fn restore_node<'a>(})}+/// The command that starts `entry`'s replacement with what it showed at the+/// last exit, when that was kept and a local domain here spawns it: the only+/// kind that reads the record (`mux::kept_output`).+fn kept_command(+ mux: &Mux,+ workspace: &str,+ entry: &PaneEntry,+ domain: &SpawnTabDomain,+ current: Option<PaneId>,+) -> Option<portable_pty::CommandBuilder> {+ let local = mux+ .resolve_spawn_tab_domain(current, domain)+ .is_ok_and(|domain| domain.downcast_ref::<LocalDomain>().is_some());+ if !local {+ return None;+ }+ kept_output::with_seed(Owner::Server, workspace, entry.pane_id, None)+}+fn first_pane_entry(node: &PaneNode) -> Option<&PaneEntry> {match node {PaneNode::Empty => None,diff --git a/wezterm-mux-server-impl/tests/kept_output.rs b/wezterm-mux-server-impl/tests/kept_output.rsnew file mode 100644index 00000000..1981b091--- /dev/null+++ b/wezterm-mux-server-impl/tests/kept_output.rs@@ -0,0 +1,260 @@+#![cfg(unix)]+//! With Settings keeping pane output, a Thread's panes come back from a+//! server exit with what they showed: kept at the exit, put back above the+//! new shell when the Thread is opened again, and spent.++use anyhow::{Context, Result};+use codec::{DecodedPdu, Pdu};+use config::keyassignment::SpawnTabDomain;+use mux::domain::{Domain, LocalDomain};+use mux::kept_output::{self, Owner};+use mux::localpane::LocalPane;+use mux::pane::Pane;+use mux::Mux;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use wezterm_mux_server_impl::sessionhandler::{ConnectionPeer, PduSender, SessionHandler};+use wezterm_mux_server_impl::thinkterm_layout;++struct Client {+ handler: SessionHandler,+ replies: smol::channel::Receiver<DecodedPdu>,+ serial: u64,+}++impl Client {+ fn new() -> Self {+ let (tx, replies) = smol::channel::unbounded();+ Self {+ handler: SessionHandler::for_peer(+ PduSender::new(move |pdu| {+ let mut bytes = vec![];+ pdu.pdu.encode(&mut bytes, pdu.serial)?;+ tx.try_send(Pdu::decode(bytes.as_slice())?)?;+ Ok(())+ }),+ ConnectionPeer::Local,+ ),+ replies,+ serial: 0,+ }+ }++ async fn call(&mut self, pdu: Pdu) -> Result<Pdu> {+ self.serial += 1;+ let mut bytes = vec![];+ pdu.encode(&mut bytes, self.serial)?;+ self.handler.process_one(Pdu::decode(bytes.as_slice())?);+ loop {+ let response = self.replies.recv().await?;+ if response.serial == self.serial {+ return Ok(response.pdu);+ }+ }+ }++ async fn open_thread(&mut self, thread_id: Option<String>) -> Result<(String, String)> {+ match self+ .call(Pdu::EnsureThinkTermThread(codec::EnsureThinkTermThread {+ preferred_thread_id: thread_id,+ size: wezterm_term::TerminalSize::default(),+ }))+ .await?+ {+ Pdu::EnsureThinkTermThreadResponse(landed) => Ok((landed.thread_id, landed.workspace)),+ other => anyhow::bail!("unexpected reply {:?}", other),+ }+ }+}++fn panes_in(mux: &Mux, workspace: &str) -> Vec<Arc<dyn Pane>> {+ mux.iter_windows_in_workspace(workspace)+ .into_iter()+ .filter_map(|window_id| {+ let window = mux.get_window(window_id)?;+ Some(+ window+ .iter()+ .flat_map(|tab| tab.iter_all_panes())+ .collect::<Vec<_>>(),+ )+ })+ .flatten()+ .collect()+}++fn rows(pane: &Arc<dyn Pane>) -> Vec<String> {+ pane.downcast_ref::<LocalPane>()+ .unwrap()+ .primary_screen_lines(1000)+ .iter()+ .map(|line| line.as_str().trim_end().to_string())+ .collect()+}++async fn until(pane: &Arc<dyn Pane>, done: impl Fn(&[String]) -> bool) -> Result<Vec<String>> {+ for _ in 0..200 {+ let rows = rows(pane);+ if done(&rows) {+ return Ok(rows);+ }+ smol::Timer::after(Duration::from_millis(50)).await;+ }+ anyhow::bail!("the pane never got there: {:?}", rows(pane))+}++fn separator(rows: &[String]) -> Option<usize> {+ rows.iter().position(|row| row.starts_with("── closed "))+}++async fn scenario() -> Result<()> {+ let mux = Mux::get();+ let mut client = Client::new();+ let (thread_id, workspace) = client.open_thread(None).await?;+ let pane = panes_in(&mux, &workspace)+ .pop()+ .context("the Thread opened with a shell")?;+ pane.writer()+ .write_all(b"echo kept-marker; echo API_TOKEN=abcdefgh12345678\n")?;+ until(&pane, |rows| {+ rows.iter().any(|row| row == "API_TOKEN=abcdefgh12345678")+ })+ .await?;++ // The server's exit: the layout, then what its panes show.+ thinkterm_layout::flush_now()?;+ thinkterm_layout::keep_pane_output();+ // Folder names keep a workspace name's letters, digits, `-` and `_`.+ let folder: String = workspace+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '_'+ }+ })+ .collect();+ let kept = config::DATA_DIR+ .join("kept-output")+ .join("server")+ .join(folder);+ assert_eq!(std::fs::read_dir(&kept)?.count(), 1);+ // Nothing on disk says what the token was.+ let packed = std::fs::read(kept.join(pane.pane_id().to_string()))?;+ let plain = String::from_utf8(zstd::decode_all(packed.as_slice())?)?;+ assert!(plain.contains("kept-marker"));+ assert!(!plain.contains("abcdefgh12345678"));++ // Its terminals end with it.+ for pane in panes_in(&mux, &workspace) {+ mux.remove_pane(pane.pane_id());+ }+ assert!(panes_in(&mux, &workspace).is_empty());++ let (reopened, _) = client.open_thread(Some(thread_id.clone())).await?;+ assert_eq!(reopened, thread_id);+ let restored = panes_in(&mux, &workspace)+ .pop()+ .context("the Thread was restored")?;+ // The new shell's first output lands below what came back.+ let rows = until(&restored, |rows| {+ separator(rows).is_some_and(|at| rows[at + 1..].iter().any(|row| !row.is_empty()))+ })+ .await?;+ let marker = rows.iter().position(|row| row == "kept-marker").unwrap();+ let token = rows+ .iter()+ .position(|row| row == &format!("API_TOKEN={}", "•".repeat(16)))+ .unwrap();+ let separator = separator(&rows).unwrap();+ assert!(marker < token && token < separator, "{:?}", rows);+ assert!(rows[separator].contains(" · restored "), "{:?}", rows);+ // Spent: a later exit keeps afresh.+ assert!(!kept.exists());++ // The app rebuilding a Thread of the local session server, as after the+ // server was stopped under it: it names the record in its spawn, and+ // the server's local domain reads it.+ let restored_id = restored.pane_id();+ thinkterm_layout::flush_now()?;+ thinkterm_layout::keep_pane_output();+ for pane in panes_in(&mux, &workspace) {+ mux.remove_pane(pane.pane_id());+ }+ let command = kept_output::with_seed(Owner::Server, &workspace, restored_id, None);+ assert!(command.is_some());+ let (_, rebuilt, _) = mux+ .spawn_tab_or_window(+ None,+ SpawnTabDomain::DefaultDomain,+ command,+ None,+ wezterm_term::TerminalSize::default(),+ None,+ workspace.clone(),+ None,+ )+ .await?;+ let rows = until(&rebuilt, |rows| {+ let separators: Vec<_> = rows+ .iter()+ .enumerate()+ .filter(|(_, row)| row.starts_with("── closed "))+ .map(|(at, _)| at)+ .collect();+ separators.len() == 2 && rows[separators[1] + 1..].iter().any(|row| !row.is_empty())+ })+ .await?;+ assert!(rows.iter().any(|row| row == "kept-marker"), "{:?}", rows);+ kept_output::finish(&workspace);+ assert!(!kept.exists());+ Ok(())+}++#[test]+fn a_thread_comes_back_with_what_its_panes_showed() {+ // This integration binary has one test and owns its process environment.+ let home = tempfile::Builder::new()+ .prefix("tt-kept-")+ .tempdir_in("/tmp")+ .unwrap();+ let path = home.path().canonicalize().unwrap();+ for key in [+ "HOME",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_RUNTIME_DIR",+ ] {+ std::env::set_var(key, &path);+ }+ std::env::remove_var("SSH_AUTH_SOCK");+ mux::kept_output::set_enabled(true).unwrap();+ config::use_test_configuration();+ let mut cfg = (*config::configuration()).clone();+ cfg.mux_enable_ssh_agent = false;+ cfg.default_prog = Some(vec!["/bin/sh".into()]);+ config::use_this_configuration(cfg);+ let local: Arc<dyn Domain> = Arc::new(LocalDomain::new("local").unwrap());+ let mux = Arc::new(Mux::new(Some(local)));+ Mux::set_mux(&mux);+ let executor = promise::spawn::SimpleExecutor::new();+ let result = Arc::new(Mutex::new(None));+ let completed = result.clone();+ promise::spawn::spawn(async move {+ let outcome = smol::future::or(scenario(), async {+ smol::Timer::after(Duration::from_secs(30)).await;+ anyhow::bail!("the kept output scenario timed out")+ })+ .await;+ *completed.lock().unwrap() = Some(outcome);+ })+ .detach();+ while result.lock().unwrap().is_none() {+ executor.tick().unwrap();+ }+ for pane in mux.iter_panes() {+ mux.remove_pane(pane.pane_id());+ }+ result.lock().unwrap().take().unwrap().unwrap();+}diff --git a/wezterm-mux-server/Cargo.toml b/wezterm-mux-server/Cargo.tomlindex f27edb8b..37eb21cc 100644--- a/wezterm-mux-server/Cargo.toml+++ b/wezterm-mux-server/Cargo.toml@@ -56,10 +56,12 @@ wezterm-term.workspace = truewinapi = { workspace=true, features = ["consoleapi","handleapi",+ "libloaderapi","minwinbase","minwindef","namedpipeapi","processenv",+ "processthreadsapi","winbase","winerror","winnt",diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex 23840663..e5068f38 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -731,6 +731,7 @@ fn terminate_with_error(err: anyhow::Error) -> ! {if let Err(flush_err) = wezterm_mux_server_impl::thinkterm_layout::flush_now() {log::error!("flushing ThinkTerm layouts before termination: {flush_err:#}");}+ wezterm_mux_server_impl::thinkterm_layout::keep_pane_output();std::process::exit(1);}@@ -746,6 +747,7 @@ fn install_shutdown_signal_handler() -> anyhow::Result<()> {if let Err(err) = wezterm_mux_server_impl::thinkterm_layout::flush_now() {log::error!("flushing ThinkTerm layouts before shutdown: {err:#}");}+ wezterm_mux_server_impl::thinkterm_layout::keep_pane_output();std::process::exit(0);}).detach();@@ -777,19 +779,42 @@ fn install_shutdown_signal_handler() -> anyhow::Result<()> {mod windows_daemon {use anyhow::Context as _;use mux::session_server::StopEvent;+ use std::ffi::OsStr;+ use std::os::windows::ffi::OsStrExt as _;use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, RawHandle};use std::os::windows::process::CommandExt as _;use std::sync::Mutex;- use winapi::shared::minwindef::{BOOL, DWORD, TRUE};+ use std::time::Duration;+ use winapi::shared::minwindef::{BOOL, DWORD, LPARAM, LRESULT, TRUE, UINT, WPARAM};+ use winapi::shared::windef::HWND;use winapi::shared::winerror::ERROR_ACCESS_DENIED;use winapi::um::consoleapi::SetConsoleCtrlHandler;use winapi::um::handleapi::{SetHandleInformation, INVALID_HANDLE_VALUE};+ use winapi::um::libloaderapi::GetModuleHandleW;use winapi::um::processenv::GetStdHandle;+ use winapi::um::processthreadsapi::SetProcessShutdownParameters;use winapi::um::winbase::{CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, DETACHED_PROCESS, HANDLE_FLAG_INHERIT,STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,};use winapi::um::winnt::HANDLE;+ use winapi::um::winuser::{+ CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, RegisterClassExW,+ TranslateMessage, MSG, WM_ENDSESSION, WM_QUERYENDSESSION, WNDCLASSEXW, WS_OVERLAPPED,+ };++ /// Windows ends the process as soon as the handlers below return; they+ /// wait this long for the main thread to keep what it keeps and exit on+ /// its own first.+ const EXIT_GRACE: Duration = Duration::from_secs(5);++ /// A logoff or shutdown ends processes a level at a time, highest first+ /// and in no set order within one. Every process starts at 0x280, the+ /// shells in the server's terminals among them: one level up, the server+ /// keeps what its panes show while they are still there. The desktop+ /// goes one further up, so it is gone before the server and never starts+ /// a new one to rebuild Threads into while the session ends.+ const SHUTDOWN_LEVEL: DWORD = 0x300;/// Held from `adopt` until `install_shutdown_handler` takes it.static STOP_EVENT: Mutex<Option<StopEvent>> = Mutex::new(None);@@ -977,15 +1002,111 @@ mod windows_daemon {}unsafe extern "system" fn ctrl_handler(_ctrl_type: DWORD) -> BOOL {- request_shutdown();+ shut_down_before_returning();TRUE}+ /// Windows announces a logoff or shutdown to a process only through its+ /// top-level windows: a detached server has no console for the handler+ /// above, and a console process that is not a service is not sent those+ /// events either. So a window nobody sees waits for the announcement, on+ /// a thread of its own.+ fn watch_session_end() -> anyhow::Result<()> {+ std::thread::Builder::new()+ .name("session-end".into())+ .spawn(|| {+ if let Err(err) = run_session_end_window() {+ log::warn!("not watching for logoff and shutdown: {err:#}");+ }+ })+ .context("spawning the session-end thread")?;+ Ok(())+ }++ fn run_session_end_window() -> anyhow::Result<()> {+ let wide =+ |text: &str| -> Vec<u16> { OsStr::new(text).encode_wide().chain(Some(0)).collect() };+ let name = wide("ThinkTermSessionEnd");+ // Shown should Windows list the server among the programs still+ // closing.+ let title = wide("ThinkTerm session server");+ // SAFETY: `class` and the strings outlive the calls that read them,+ // the procedure has the signature Windows calls it with, and the+ // window lives on this thread, which runs its message loop until the+ // process ends.+ unsafe {+ let instance = GetModuleHandleW(std::ptr::null());+ let class = WNDCLASSEXW {+ cbSize: std::mem::size_of::<WNDCLASSEXW>() as UINT,+ lpfnWndProc: Some(session_end_proc),+ hInstance: instance,+ lpszClassName: name.as_ptr(),+ ..std::mem::zeroed()+ };+ if RegisterClassExW(&class) == 0 {+ anyhow::bail!(+ "registering the window class: {}",+ std::io::Error::last_os_error()+ );+ }+ // Top-level and never shown: a message-only window is not told.+ let window = CreateWindowExW(+ 0,+ name.as_ptr(),+ title.as_ptr(),+ WS_OVERLAPPED,+ 0,+ 0,+ 0,+ 0,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ instance,+ std::ptr::null_mut(),+ );+ if window.is_null() {+ anyhow::bail!("creating the window: {}", std::io::Error::last_os_error());+ }+ let mut message: MSG = std::mem::zeroed();+ while GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) > 0 {+ TranslateMessage(&message);+ DispatchMessageW(&message);+ }+ }+ Ok(())+ }++ unsafe extern "system" fn session_end_proc(+ window: HWND,+ message: UINT,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> LRESULT {+ match message {+ // Never the one holding a logoff or shutdown up.+ WM_QUERYENDSESSION => TRUE as LRESULT,+ WM_ENDSESSION if wparam != 0 => {+ log::info!("the session is ending; flushing and exiting");+ shut_down_before_returning();+ 0+ }+ _ => DefWindowProcW(window, message, wparam, lparam),+ }+ }++ /// For a handler Windows ends the process after: the main thread is+ /// asked to keep what it keeps and exit, and given the time to.+ fn shut_down_before_returning() {+ request_shutdown();+ std::thread::sleep(EXIT_GRACE);+ }+fn request_shutdown() {promise::spawn::spawn_into_main_thread(async move {if let Err(err) = wezterm_mux_server_impl::thinkterm_layout::flush_now() {log::error!("flushing ThinkTerm layouts before shutdown: {err:#}");}+ wezterm_mux_server_impl::thinkterm_layout::keep_pane_output();std::process::exit(0);}).detach();@@ -1006,6 +1127,15 @@ mod windows_daemon {}).context("spawning the stop-event thread")?;unsafe { SetConsoleCtrlHandler(Some(ctrl_handler), TRUE) };+ if unsafe { SetProcessShutdownParameters(SHUTDOWN_LEVEL, 0) } == 0 {+ log::warn!(+ "setting the shutdown level: {}",+ std::io::Error::last_os_error()+ );+ }+ if let Err(err) = watch_session_end() {+ log::warn!("{err:#}");+ }Ok(())}}diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rsindex 92afecd1..fd5281f8 100644--- a/wezterm/src/cli/mod.rs+++ b/wezterm/src/cli/mod.rs@@ -19,6 +19,7 @@ mod list_clients;mod move_pane_to_new_tab;mod proxy;mod rename_workspace;+mod restore_output;mod send_key;mod send_text;mod set_pane_label;@@ -330,6 +331,11 @@ Outputs the pane-id for the newly created pane on success"/// Stop the background session server; the terminals in it end#[command(name = "stop-server")]StopServer(stop_server::StopServerCommand),++ /// Whether this machine keeps pane output to restore after its+ /// terminals stop+ #[command(name = "restore-output")]+ RestoreOutput(restore_output::RestoreOutputCommand),}async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()> {@@ -342,6 +348,11 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>if let CliSubCommand::StopServer(cmd) = &cli.sub {return cmd.run(&crate::init_config(opts)?);}+ // A switch in a file on this machine, which the server reads when it+ // needs it: nothing to ask a server.+ if let CliSubCommand::RestoreOutput(cmd) = &cli.sub {+ return cmd.run();+ }let mut ui = mux::connui::ConnectionUI::new_headless();let initial = true;@@ -417,7 +428,9 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>CliSubCommand::RenameWorkspace(cmd) => cmd.run(client).await,CliSubCommand::ZoomPane(cmd) => cmd.run(client).await,CliSubCommand::Agent(cmd) => cmd.run(client).await,- CliSubCommand::ColorSchemes(_) | CliSubCommand::StopServer(_) => {+ CliSubCommand::ColorSchemes(_)+ | CliSubCommand::StopServer(_)+ | CliSubCommand::RestoreOutput(_) => {unreachable!("handled without a client above")}}diff --git a/wezterm/src/cli/restore_output.rs b/wezterm/src/cli/restore_output.rsnew file mode 100644index 00000000..f43b94e3--- /dev/null+++ b/wezterm/src/cli/restore_output.rs@@ -0,0 +1,46 @@+//! `thinkterm cli restore-output …`: whether this machine keeps what its+//! panes show when its terminals stop, and puts it back when their layout is+//! restored. The desktop's Settings has the same switch for the machine it+//! runs on; on any other machine, a remote host say, this is how to turn it+//! on. See `mux::kept_output`.++use clap::Parser;++#[derive(Debug, Parser, Clone)]+pub struct RestoreOutputCommand {+ #[command(subcommand)]+ sub: RestoreOutputSubCommand,+}++#[derive(Debug, Parser, Clone)]+enum RestoreOutputSubCommand {+ /// Show whether this machine keeps pane output.+ #[command(name = "status")]+ Status,++ /// Keep each pane's output when this machine's terminals stop (quit,+ /// shutdown, the session server stopping) and put it back when their+ /// layout is restored. Passwords and tokens are masked before saving.+ #[command(name = "on")]+ On,++ /// Stop keeping pane output, and delete what was kept.+ #[command(name = "off")]+ Off,+}++impl RestoreOutputCommand {+ pub fn run(&self) -> anyhow::Result<()> {+ match self.sub {+ RestoreOutputSubCommand::Status => {}+ RestoreOutputSubCommand::On => mux::kept_output::set_enabled(true)?,+ RestoreOutputSubCommand::Off => mux::kept_output::set_enabled(false)?,+ }+ if mux::kept_output::enabled() {+ println!("on: this machine keeps pane output when its terminals stop");+ } else {+ println!("off: this machine keeps no pane output");+ }+ Ok(())+ }+}diff --git a/window/src/connection.rs b/window/src/connection.rsindex 2fc0eeb7..266c05a5 100644--- a/window/src/connection.rs+++ b/window/src/connection.rs@@ -54,6 +54,10 @@ pub enum ApplicationEvent {/// One of the entries the app gave for its icon's menu in the Dock was/// chosen; this is its `DockMenuItem::id`.DockMenuItem(String),+ /// The system is ending the process now -- a quit from the Dock, a+ /// logout, a shutdown -- and will not return to the event loop: what is+ /// to outlive it has to be written before the handler returns.+ WillTerminate,}/// An entry for the app's icon menu in the Dock (macOS).diff --git a/window/src/os/macos/app.rs b/window/src/os/macos/app.rsindex b45dfe8a..92186537 100644--- a/window/src/os/macos/app.rs+++ b/window/src/os/macos/app.rs@@ -75,6 +75,9 @@ extern "C" fn application_should_terminate(fn terminate_now() -> u64 {if let Some(conn) = Connection::get() {+ // AppKit exits inside `terminate:` once this answers: the loop below+ // is asked to stop, but `run` never returns to the code after it.+ conn.dispatch_app_event(ApplicationEvent::WillTerminate);conn.terminate_message_loop();}NSApplicationTerminateReply::NSTerminateNow as u64diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rsindex 3f874ca7..9ebef2a3 100644--- a/window/src/os/windows/window.rs+++ b/window/src/os/windows/window.rs@@ -2,11 +2,11 @@ use super::*;use crate::connection::ConnectionOps;use crate::parameters::{self, Parameters};use crate::{- Appearance, Clipboard, ClipboardContents, DeadKeyStatus, Dimensions, FilePickerOptions,- FolderPickerOptions, Handled, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor,- MouseEvent, MouseEventKind, MousePress, Point, RawKeyEvent, Rect, RequestedWindowGeometry,- ResolvedGeometry, ScreenPoint, ScreenRect, ULength, WindowDecorations, WindowEvent,- WindowEventSender, WindowOps, WindowState,+ Appearance, ApplicationEvent, Clipboard, ClipboardContents, DeadKeyStatus, Dimensions,+ FilePickerOptions, FolderPickerOptions, Handled, KeyCode, KeyEvent, Modifiers, MouseButtons,+ MouseCursor, MouseEvent, MouseEventKind, MousePress, Point, RawKeyEvent, Rect,+ RequestedWindowGeometry, ResolvedGeometry, ScreenPoint, ScreenRect, ULength, WindowDecorations,+ WindowEvent, WindowEventSender, WindowOps, WindowState,};use anyhow::{anyhow, bail};use async_trait::async_trait;@@ -3910,6 +3910,15 @@ unsafe fn do_wnd_proc(hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) ->}WM_DROPFILES => drop_files(hwnd, msg, wparam, lparam),WM_ERASEBKGND => Some(1),+ // A logoff or shutdown: the process ends once this returns, without+ // going back to the event loop, so what is to outlive it is written+ // now. Each window is told; what the app keeps, it keeps once.+ WM_ENDSESSION if wparam != 0 => {+ if let Some(conn) = Connection::get() {+ conn.dispatch_app_event(ApplicationEvent::WillTerminate);+ }+ Some(0)+ }WM_CLOSE => {if let Some(inner) = rc_from_hwnd(hwnd) {let mut inner = inner.borrow_mut();