Skip to content

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

feat(cli): reach panes on connected servers through the window

RoversX8b3109aa2ca9
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index 61a4a1bd..f8f6230b 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -895,7 +895,9 @@ macro_rules! pdu {
/// 83: Sharing a pane with other accounts on the machine (Share* PDUs).
/// 84: Render pushes say whether the program takes pastes bracketed
/// (GetPaneRenderChangesResponse::bracketed_paste).
-pub const CODEC_VERSION: usize = 84;
+/// 85: The machine a pane of another one is on (ListPanesResponse::
+/// pane_machines), as a window gives the panes it is connected to.
+pub const CODEC_VERSION: usize = 85;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
@@ -1331,6 +1333,18 @@ pub struct ListPanesResponse {
/// The labels of the panes that have one.
#[serde(default)]
pub pane_labels: HashMap<PaneId, String>,
+ /// The panes that are another machine's, as a window connected to it
+ /// gives them: the machine, and each one's id there.
+ #[serde(default)]
+ pub pane_machines: HashMap<PaneId, PaneMachine>,
+}
+
+/// Where a pane of another machine is: the name the window gives the
+/// machine, and the pane's id on it.
+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
+pub struct PaneMachine {
+ pub machine: String,
+ pub pane_id: PaneId,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
@@ -2792,6 +2806,7 @@ mod golden {
tab_titles: vec!["main".to_string()],
window_titles,
pane_labels: HashMap::new(),
+ pane_machines: Default::default(),
}
}
@@ -2937,10 +2952,11 @@ mod golden {
assert_eq!(back, command_spec());
}
- /// LIST_PANES as codec 81 writes it: the pane labels went on the end,
- /// and an empty map is one zero byte after the bytes captured before.
+ /// LIST_PANES as codec 85 writes it: the pane labels went on the end at
+ /// 81, the panes' machines after them at 85, and an empty map is one
+ /// zero byte, each after the bytes captured before.
fn list_panes_with_labels() -> Vec<u8> {
- [LIST_PANES, &[0]].concat()
+ [LIST_PANES, &[0, 0]].concat()
}
/// RENDER_CHANGES as codec 84 writes it: whether the program takes
@@ -3570,7 +3586,7 @@ mod test {
// tripwire: whoever bumps the codec must come here, confirm the
// round-trips still cover the new version, and advance it
// deliberately.
- assert_eq!(CODEC_VERSION, 84);
+ assert_eq!(CODEC_VERSION, 85);
use thinkterm_proto::{
AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport,
ProgramReportChild, ProgramReportState,
@@ -3640,7 +3656,7 @@ mod test {
#[test]
fn foreground_program_protocol_round_trip_at_version_74() {
// Same tripwire as the agent-status test above.
- assert_eq!(CODEC_VERSION, 84);
+ assert_eq!(CODEC_VERSION, 85);
use thinkterm_proto::ForegroundProgram;
fn round_trip(pdu: &Pdu) -> Pdu {
@@ -3741,7 +3757,7 @@ mod test {
#[test]
fn run_state_protocol_round_trip_at_version_80() {
// Same tripwire as the agent-status test above.
- assert_eq!(CODEC_VERSION, 84);
+ assert_eq!(CODEC_VERSION, 85);
use thinkterm_proto::{PaneExit, PaneRunState, ProgramState, ShellCommands};
let exit = PaneExit {
@@ -3804,6 +3820,13 @@ mod test {
tab_titles: vec![],
window_titles: HashMap::new(),
pane_labels: HashMap::from([(10, "reviewer".to_string())]),
+ pane_machines: HashMap::from([(
+ 12,
+ PaneMachine {
+ machine: "devbox".to_string(),
+ pane_id: 3,
+ },
+ )]),
}),
Pdu::GetWorkspaceNames(GetWorkspaceNames {}),
Pdu::GetWorkspaceNamesResponse(GetWorkspaceNamesResponse {
@@ -3840,7 +3863,7 @@ mod test {
fn frame_control_extension_round_trips_without_changing_legacy_version() {
// The extension is asked for, so it needed no bump of its own; 74
// is the foreground program's, which a server sends unasked.
- assert_eq!(CODEC_VERSION, 84);
+ assert_eq!(CODEC_VERSION, 85);
for pdu in [
Pdu::GetKittyImage(GetKittyImage { pane_id: 3, image_id: 7, data_hash: [9; 32], have_frames: 2, image_epoch: Some(4) }),
Pdu::GetKittyFrameSelections(GetKittyFrameSelections { pane_id: 3, subscribe: true }),
diff --git a/skills/thinkterm/SKILL.md b/skills/thinkterm/SKILL.md
index 9c137565..86fe9d40 100644
--- a/skills/thinkterm/SKILL.md
+++ b/skills/thinkterm/SKILL.md
@@ -11,6 +11,14 @@ Run `thinkterm cli --help` for all commands and `thinkterm cli <command> --help`
details. If `thinkterm` is not on PATH, it is in the folder named by the
WEZTERM_EXECUTABLE_DIR environment variable (thinkterm.exe on Windows).
+Panes on the servers the user's ThinkTerm window is connected to are listed by
+`thinkterm cli list` as `MACHINE/ID` (in JSON too, as a string, not a number), and
+named the same way, or as `MACHINE/LABEL`, with `--pane` -- never `--pane-id` -- in
+`get-text`, `send-text`, `send-key`, `wait` and `events`; an event of one says so in
+its `pane` field. They are
+there only as far as the user lets programs reach them in ThinkTerm's Settings ›
+Agents: not at all (the default), to read, or to read and type.
+
Some commands affect what the user or other agents are using, such as typing into a
pane you did not open, closing panes or stopping the server; you may want to ask the
user first. Whether to ask is up to you.
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 2fc9e340..a9b16b0b 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -159,6 +159,12 @@ settings-server-placement-description = Wie das Space-Menü Server zeigt: jeden
settings-server-placement-expanded = Ausgeklappt
settings-server-placement-one-row = Eine Zeile je Server
settings-server-placement-folders = Ordner
+settings-server-terminals-heading = Terminals auf Servern
+settings-server-terminals = Programme auf diesem Rechner
+settings-server-terminals-description = Lässt Programme in den Terminals dieses Rechners, auch KI-Agenten und Plugins, mit thinkterm cli die Terminals der verbundenen Server auflisten und lesen oder auch darin tippen. Sie nutzen die Verbindung, mit der Sie angemeldet sind: Auf dem Server handeln sie als Sie.
+settings-server-terminals-off = Aus
+settings-server-terminals-read = Lesen
+settings-server-terminals-type = Lesen & Tippen
settings-terminal-shade = Farbe des Terminals
settings-terminal-shade-description = Wie dunkel der Hintergrund des Terminals ist, in einem durchscheinenden Fenster.
settings-area-shade-dark = Dunkel
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index 9d13b5b4..2e34a24a 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -159,6 +159,12 @@ settings-server-placement-description = How the Space menu lists servers: every
settings-server-placement-expanded = Expanded
settings-server-placement-one-row = One Row Each
settings-server-placement-folders = Folders
+settings-server-terminals-heading = Servers' Terminals
+settings-server-terminals = Programs on This Machine
+settings-server-terminals-description = Let programs in this machine's terminals, AI agents and plugins included, list and read the terminals of the servers you are connected to with thinkterm cli, or type into them too. They use the connection you logged in on, so on the server they act as you.
+settings-server-terminals-off = Off
+settings-server-terminals-read = Read
+settings-server-terminals-type = Read & Type
settings-terminal-shade = Terminal color
settings-terminal-shade-description = How dark the terminal's background is, in a see-through window.
settings-area-shade-dark = Dark
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 68662b48..cc8a9862 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -159,6 +159,12 @@ settings-server-placement-description = Comment le menu des espaces présente le
settings-server-placement-expanded = Tout déplié
settings-server-placement-one-row = Une ligne par serveur
settings-server-placement-folders = Dossiers
+settings-server-terminals-heading = Terminaux des serveurs
+settings-server-terminals = Programmes de cette machine
+settings-server-terminals-description = Permet aux programmes des terminaux de cette machine, agents IA et plugins compris, de lister et lire avec thinkterm cli les terminaux des serveurs auxquels vous êtes connecté, ou d'y taper aussi. Ils utilisent la connexion où vous êtes identifié : sur le serveur, ils agissent en votre nom.
+settings-server-terminals-off = Désactivé
+settings-server-terminals-read = Lecture
+settings-server-terminals-type = Lecture et saisie
settings-terminal-shade = Couleur du terminal
settings-terminal-shade-description = Le ton du fond du terminal, dans une fenêtre transparente.
settings-area-shade-dark = Sombre
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 3fd35247..a8e0883a 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -156,6 +156,12 @@ settings-server-placement-description = スペースメニューでのサーバ
settings-server-placement-expanded = すべて展開
settings-server-placement-one-row = 1 台 1 行
settings-server-placement-folders = フォルダ
+settings-server-terminals-heading = サーバーのターミナル
+settings-server-terminals = このマシンのプログラム
+settings-server-terminals-description = このマシンのターミナルで動くプログラム(AI エージェントやプラグインを含む)が、thinkterm cli で接続中のサーバーのターミナルを一覧・読み取りできるようにします。入力まで許可することもできます。ログイン済みの接続を使うので、サーバー上ではあなたとして操作します。
+settings-server-terminals-off = オフ
+settings-server-terminals-read = 読むだけ
+settings-server-terminals-type = 読む・入力
settings-terminal-shade = ターミナルの色
settings-terminal-shade-description = ターミナルの背景の濃さ。ウインドウが透けているときに効きます。
settings-area-shade-dark = 濃い
diff --git a/thinkterm-i18n/i18n/ru-RU.ftl b/thinkterm-i18n/i18n/ru-RU.ftl
index fca8fb41..def11e5a 100644
--- a/thinkterm-i18n/i18n/ru-RU.ftl
+++ b/thinkterm-i18n/i18n/ru-RU.ftl
@@ -156,6 +156,12 @@ settings-server-placement-description = Как меню пространств
settings-server-placement-expanded = Развёрнуто
settings-server-placement-one-row = По строке на сервер
settings-server-placement-folders = Папки
+settings-server-terminals-heading = Терминалы на серверах
+settings-server-terminals = Программы на этой машине
+settings-server-terminals-description = Позволяет программам в терминалах этой машины, включая ИИ-агентов и плагины, через thinkterm cli видеть и читать терминалы серверов, к которым вы подключены, или ещё и печатать в них. Они используют ваше подключение, поэтому на сервере действуют от вашего имени.
+settings-server-terminals-off = Выкл.
+settings-server-terminals-read = Чтение
+settings-server-terminals-type = Чтение и ввод
settings-terminal-shade = Цвет терминала
settings-terminal-shade-description = Насколько тёмным будет фон терминала в прозрачном окне.
settings-area-shade-dark = Тёмный
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index d2f36457..6ca379d7 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -156,6 +156,12 @@ settings-server-placement-description = 空间菜单里怎么放服务器:每
settings-server-placement-expanded = 全部展开
settings-server-placement-one-row = 每台一行
settings-server-placement-folders = 文件夹
+settings-server-terminals-heading = 服务器上的终端
+settings-server-terminals = 本机程序
+settings-server-terminals-description = 让本机终端里的程序(包括 AI agent 和插件)通过 thinkterm cli 列出、读取你连着的服务器上的终端,或者也能往里打字。它们用的是你已经登录的连接,在服务器上等于以你的身份操作。
+settings-server-terminals-off = 关
+settings-server-terminals-read = 只能看
+settings-server-terminals-type = 能看也能打字
settings-terminal-shade = 终端颜色
settings-terminal-shade-description = 终端底色的深浅,窗口透明时生效。
settings-area-shade-dark = 深
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 8dbcea2f..00b77c6e 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -7452,6 +7452,7 @@ mod tests {
tab_titles: Vec::new(),
window_titles: Default::default(),
pane_labels: Default::default(),
+ pane_machines: Default::default(),
};
let at = |pane_id| tab_places(&layout, pane_id).map(|places| places.iter().map(|p| (p.pane, p.left, p.top)).collect::<Vec<_>>());
assert_eq!(at(10), Some(vec![(10, 0, 0)]));
diff --git a/thinkterm-web/src/chrome.rs b/thinkterm-web/src/chrome.rs
index 4600fa54..dbd94af6 100644
--- a/thinkterm-web/src/chrome.rs
+++ b/thinkterm-web/src/chrome.rs
@@ -225,6 +225,7 @@ mod tests {
tab_titles: vec!["".to_string(), "work".to_string(), "".to_string()],
window_titles: Default::default(),
pane_labels: Default::default(),
+ pane_machines: Default::default(),
}
}
@@ -283,6 +284,7 @@ mod tests {
tab_titles: vec![],
window_titles: Default::default(),
pane_labels: Default::default(),
+ pane_machines: Default::default(),
};
assert_eq!(first_choice(&stack).map(|e| e.pane_id), Some(31));
}
diff --git a/thinkterm-web/src/layout.rs b/thinkterm-web/src/layout.rs
index 0e0c4e2a..80ddad34 100644
--- a/thinkterm-web/src/layout.rs
+++ b/thinkterm-web/src/layout.rs
@@ -738,6 +738,7 @@ mod tests {
tab_titles: vec![],
window_titles: Default::default(),
pane_labels: Default::default(),
+ pane_machines: Default::default(),
};
assert!(matches!(tab_containing(&list, 7), Some(PaneNode::Leaf(e)) if e.pane_id == 7));
assert!(tab_containing(&list, 9).is_none());
@@ -755,6 +756,7 @@ mod tests {
tab_titles: vec!["a".into(), "b".into(), "c".into(), "d".into()],
window_titles: Default::default(),
pane_labels: Default::default(),
+ pane_machines: Default::default(),
};
let mut overflowing = pane(5, 80, 24, 0, 0, true);
overflowing.physical_top = StableRowIndex::MAX;
diff --git a/thinkterm-web/src/tree.rs b/thinkterm-web/src/tree.rs
index c36b6b68..5b77433a 100644
--- a/thinkterm-web/src/tree.rs
+++ b/thinkterm-web/src/tree.rs
@@ -1021,6 +1021,7 @@ mod tests {
tab_titles: vec![],
window_titles: Default::default(),
pane_labels: Default::default(),
+ pane_machines: Default::default(),
};
m.apply_panes(&list);
let rows = m.rows(30, "default", 3);
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index 0e819bc8..14317fb7 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -484,6 +484,42 @@ impl ClientPane {
self.remote_tab_id.load(Ordering::Relaxed)
}
+ /// `lines` as the server has them, asked of it now rather than read
+ /// from what this side holds: rows not shown here yet come back blank
+ /// from that, until fetched.
+ /// Whether what is typed here reaches the server: not while its
+ /// terminal is another device's to use, or not this side's yet, or the
+ /// connection is not up. Typing then is dropped, as the window shows.
+ pub fn frontend_gate(&self) -> crate::domain::RemoteFrontendGate {
+ self.client.remote_frontend_gate()
+ }
+
+ /// Where the cursor is and how far the rows run, as the server has
+ /// them now: what this side holds is only as fresh as what it has shown.
+ pub async fn fetch_dimensions(&self) -> anyhow::Result<GetPaneRenderableDimensionsResponse> {
+ self.client
+ .client
+ .get_dimensions(GetPaneRenderableDimensions {
+ pane_id: self.remote_pane_id,
+ })
+ .await
+ }
+
+ pub async fn fetch_lines(
+ &self,
+ lines: Vec<Range<StableRowIndex>>,
+ ) -> anyhow::Result<SerializedLines> {
+ let response = self
+ .client
+ .client
+ .get_lines(GetLines {
+ pane_id: self.remote_pane_id,
+ lines,
+ })
+ .await?;
+ Ok(response.lines)
+ }
+
pub fn remote_viewport_state(&self) -> Option<codec::ClientViewportState> {
self.client.remote_viewport_state(self.remote_tab_id())
}
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 55da2009..a531c325 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -1390,7 +1390,65 @@ pub(crate) fn cli_socket() -> Option<&'static std::path::Path> {
CLI_SOCKET.get().map(PathBuf::as_path)
}
+fn client_domain_is_foreign(config: &wezterm_client::domain::ClientDomainConfig) -> bool {
+ !matches!(config, wezterm_client::domain::ClientDomainConfig::Unix(unix)
+ if unix.proxy_command.is_none())
+}
+
+#[cfg(test)]
+mod server_terminal_tests {
+ use super::client_domain_is_foreign;
+ use wezterm_client::domain::ClientDomainConfig;
+
+ #[test]
+ fn direct_unix_connections_are_local_even_without_the_managed_host_flag() {
+ let mut unix = config::UnixDomain::default();
+ unix.local_session_host = false;
+ assert!(!client_domain_is_foreign(&ClientDomainConfig::Unix(
+ unix.clone()
+ )));
+ unix.proxy_command = Some(vec!["proxy".to_string()]);
+ assert!(client_domain_is_foreign(&ClientDomainConfig::Unix(unix)));
+ }
+}
+
+/// What the server this process runs for the command line lets the programs
+/// that ask have of the servers' terminals the windows are connected to:
+/// as far as Settings › Agents says.
+fn keep_servers_terminals() {
+ use crate::native_settings::NativeServerTerminals;
+ use wezterm_mux_server_impl::foreign_panes::{install, Policy, Reach};
+ install(Policy {
+ reach: || match crate::native_settings::server_terminals() {
+ NativeServerTerminals::Off => Reach::Off,
+ NativeServerTerminals::Read => Reach::Read,
+ NativeServerTerminals::Type => Reach::Type,
+ },
+ // A connection to a server -- to the session server there, or a
+ // plain SSH session; not the one this machine's own terminals are
+ // kept by.
+ foreign: |domain_id| {
+ !crate::local_sessions::is_host_domain_id(domain_id)
+ && mux::Mux::get().get_domain(domain_id).is_some_and(|domain| {
+ domain
+ .downcast_ref::<wezterm_client::domain::ClientDomain>()
+ .is_some_and(|client| {
+ client_domain_is_foreign(client.client_domain_config())
+ })
+ || domain.downcast_ref::<mux::ssh::RemoteSshDomain>().is_some()
+ })
+ },
+ machine: |domain_id| {
+ mux::Mux::get()
+ .get_domain(domain_id)
+ .map(|domain| crate::ssh_hosts::machine_label(domain.domain_name()))
+ .unwrap_or_else(|| format!("domain {domain_id}"))
+ },
+ });
+}
+
fn spawn_mux_server(unix_socket_path: PathBuf, should_publish: bool) -> anyhow::Result<()> {
+ keep_servers_terminals();
let mut listener =
wezterm_mux_server_impl::local::LocalListener::with_domain(&config::UnixDomain {
socket_path: Some(unix_socket_path.clone()),
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 650943b0..e0a3fa58 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -1751,6 +1751,42 @@ impl Default for NativeWebSettings {
}
}
+/// How far the programs on this machine -- `thinkterm cli`, the agents it
+/// is run by, plugins -- may reach the terminals of the servers a window is
+/// connected to: Settings › Agents. Off until turned on: what they would
+/// reach is a shell on another machine, logged in as the person at the
+/// window (`wezterm_mux_server_impl::foreign_panes`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub(crate) enum NativeServerTerminals {
+ #[default]
+ Off,
+ /// Listed and read, not typed into.
+ Read,
+ /// Listed, read and typed into.
+ Type,
+}
+
+impl NativeServerTerminals {
+ /// Every choice, in the order the settings window offers them.
+ pub(crate) const ALL: [Self; 3] = [Self::Off, Self::Read, Self::Type];
+}
+
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(default)]
+pub(crate) struct NativeAgentsSettings {
+ /// A build without a choice a newer one made falls back to off rather
+ /// than failing the file.
+ #[serde(deserialize_with = "choice_or_default")]
+ pub(crate) server_terminals: NativeServerTerminals,
+}
+
+/// How far the programs here may reach servers' terminals. Through the
+/// shared handle: asked of every request a program makes of one.
+pub(crate) fn server_terminals() -> NativeServerTerminals {
+ load_shared().agents.server_terminals
+}
+
/// Sharing a terminal with other accounts on its machine
/// (`termwindow::share`): the Share & Sync page. Off until turned on.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
@@ -2084,6 +2120,7 @@ pub(crate) struct ThinkTermNativeSettings {
pub(crate) web: NativeWebSettings,
pub(crate) tab_icons: NativeTabIconSettings,
pub(crate) sharing: NativeSharingSettings,
+ pub(crate) agents: NativeAgentsSettings,
}
impl Default for ThinkTermNativeSettings {
@@ -2104,6 +2141,7 @@ impl Default for ThinkTermNativeSettings {
web: NativeWebSettings::default(),
tab_icons: NativeTabIconSettings::default(),
sharing: NativeSharingSettings::default(),
+ agents: NativeAgentsSettings::default(),
}
}
}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index ea866dd4..fa795e4a 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -1286,6 +1286,9 @@ impl SettingsSection {
"Copilot",
"Cursor",
"Detection Rules",
+ "Servers",
+ "Remote",
+ "thinkterm cli",
],
Self::Archived => &[
"Archive",
@@ -1866,6 +1869,15 @@ fn localized_window_tabs_label(mode: crate::native_settings::NativeWindowTabs) -
})
}
+fn localized_server_terminals_label(reach: crate::native_settings::NativeServerTerminals) -> String {
+ use crate::native_settings::NativeServerTerminals;
+ crate::i18n::tr(match reach {
+ NativeServerTerminals::Off => "settings-server-terminals-off",
+ NativeServerTerminals::Read => "settings-server-terminals-read",
+ NativeServerTerminals::Type => "settings-server-terminals-type",
+ })
+}
+
fn localized_server_placement_label(
placement: crate::native_settings::NativeServerPlacement,
) -> String {
@@ -2297,6 +2309,7 @@ enum SettingsAction {
SetTabBarShade(crate::native_settings::NativeShade),
SetWindowTabs(crate::native_settings::NativeWindowTabs),
SetServerPlacement(crate::native_settings::NativeServerPlacement),
+ SetServerTerminals(crate::native_settings::NativeServerTerminals),
SetTerminalShade(crate::native_settings::NativeShade),
SetThreadIcons(crate::native_settings::NativeThreadIcons),
SetThreadStatus(crate::native_settings::NativeThreadStatus),
@@ -6714,6 +6727,7 @@ impl SettingsWindow {
SettingsAction::SetServerPlacement(placement) => {
self.apply_server_placement(placement)
}
+ SettingsAction::SetServerTerminals(reach) => self.apply_server_terminals(reach),
SettingsAction::SetTerminalShade(shade) => self.apply_window_areas(
"settings-terminal-shade",
localized_shade_label(shade),
@@ -10732,6 +10746,70 @@ impl SettingsWindow {
/// Settings › Agents › Status Display: a picture of where a program's
/// own report shows, numbered like the switches under it, then one
/// switch per part. Returns where the card ends.
+ /// Settings › Agents' card on how far the programs here may reach the
+ /// terminals of the servers a window is connected to, under its own
+ /// heading below `above`. Returns where it ends.
+ fn paint_server_terminals_card(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ above: f32,
+ max_width: f32,
+ ) -> anyhow::Result<f32> {
+ use crate::native_settings::NativeServerTerminals;
+ let card_padding = self.ui_px(36.0);
+ let row_x = x + card_padding;
+ let row_width = max_width - card_padding * 2.0;
+ let card_y = self.paint_card_heading(
+ layers,
+ x,
+ above,
+ max_width,
+ &crate::i18n::tr("settings-server-terminals-heading"),
+ )?;
+ // What turning it on lets a program do, as whom, takes its lines.
+ let layout = CardLayout {
+ description_lines: 4,
+ ..self.card_layout()
+ };
+ self.paint_card_as(layers, x, card_y, max_width, layout, |this, layers, top| {
+ let mut rows = RowCursor::new(top, this);
+ let options: Vec<(String, SettingsAction)> = NativeServerTerminals::ALL
+ .iter()
+ .map(|reach| {
+ (
+ localized_server_terminals_label(*reach),
+ SettingsAction::SetServerTerminals(*reach),
+ )
+ })
+ .collect();
+ let selected = NativeServerTerminals::ALL
+ .iter()
+ .position(|reach| *reach == this.native_settings.agents.server_terminals)
+ .unwrap_or(0);
+ let (tx, tw) = this.paint_row_tile(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ SvgIcon::Server,
+ TileColor::Orange,
+ )?;
+ rows.add(this.paint_segmented_setting_row(
+ layers,
+ tx,
+ rows.y,
+ tw,
+ &crate::i18n::tr("settings-server-terminals"),
+ &crate::i18n::tr("settings-server-terminals-description"),
+ &options,
+ selected,
+ rows.rule(),
+ )?);
+ Ok(rows.bottom)
+ })
+ }
+
fn paint_agent_status_card(
&mut self,
layers: &mut TripleLayerQuadAllocator<'_>,
@@ -12528,6 +12606,7 @@ impl SettingsWindow {
)?;
let (status_card_y, _) = self.settings_card_geometry(section_y, 0);
let status_bottom = self.paint_agent_status_card(layers, x, status_card_y, max_width)?;
+ let status_bottom = self.paint_server_terminals_card(layers, x, status_bottom, max_width)?;
let integrations_title_y = status_bottom + self.settings_section_card_gap();
let integrations_card_y = integrations_title_y + self.settings_section_card_gap();
let integrations_first_row_y = integrations_card_y + self.settings_card_top_padding();
@@ -20210,6 +20289,38 @@ impl SettingsWindow {
}
}
+ /// How far the programs here may reach servers' terminals. The window's
+ /// server for the command line asks each time a program asks, so
+ /// saving is all it owes.
+ fn apply_server_terminals(&mut self, reach: crate::native_settings::NativeServerTerminals) {
+ self.ui.open_dropdown = None;
+ if crate::native_settings::load_shared().agents.server_terminals == reach {
+ return;
+ }
+ let mut merged = crate::native_settings::load();
+ merged.agents.server_terminals = reach;
+ self.set_native_settings(merged);
+ let setting = crate::i18n::tr("settings-server-terminals");
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => {
+ self.status = settings_tr(
+ "settings-status-value-now",
+ &[
+ ("setting", setting),
+ ("value", localized_server_terminals_label(reach)),
+ ],
+ );
+ }
+ Err(err) => {
+ self.set_native_settings(crate::native_settings::load());
+ self.status = settings_tr(
+ "settings-status-save-error",
+ &[("setting", setting), ("error", format!("{err:#}"))],
+ );
+ }
+ }
+ }
+
/// What a see-through window shows behind it on macOS, in every window
/// at once, as the window opacity is.
fn apply_mac_glass(&mut self, glass: crate::native_settings::NativeMacGlass) {
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
index 415b53d6..aa63fb57 100644
--- a/wezterm-gui/src/ssh_hosts.rs
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -760,6 +760,28 @@ pub fn connect_domain_label(domain_name: &str) -> String {
domain_name.to_string()
}
+/// What a domain that is a connection to another machine is called where
+/// the command line names it (`--pane MACHINE/ID`): the label of the saved
+/// host it reaches -- over a session server there, or a plain SSH session --
+/// or, for one that is not saved, its own name.
+pub fn machine_label(domain_name: &str) -> String {
+ if let Ok(store) = host_store() {
+ let label = store
+ .hosts
+ .iter()
+ .map(|record| &record.spec)
+ .find(|spec| {
+ connect_domain_name(spec) == domain_name || ssh_domain_name(spec) == domain_name
+ })
+ .map(|spec| spec.label.trim().to_string())
+ .filter(|label| !label.is_empty());
+ if let Some(label) = label {
+ return label;
+ }
+ }
+ connect_domain_label(domain_name)
+}
+
fn label_for_connect_domain<'a>(
mut specs: impl Iterator<Item = &'a SshHostSpec>,
domain_name: &str,
diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rs
index e6ad0ff9..bf2bd613 100644
--- a/wezterm-mux-server-impl/src/dispatch.rs
+++ b/wezterm-mux-server-impl/src/dispatch.rs
@@ -910,6 +910,12 @@ async fn say_why<S: ConnectionStream>(
/// everything else becomes the PDU it will be sent as, with whatever the
/// mux has to be asked read here.
fn item_for_notification(n: MuxNotification) -> Option<Item> {
+ // Not a word of another machine's terminals a window keeps from the
+ // programs here, asked again as each is sent: one that heard of them
+ // while it might goes on hearing of them no longer.
+ if crate::foreign_panes::hides(&n) {
+ return None;
+ }
let write = |pdu: Pdu| Some(Item::WritePdu(DecodedPdu { serial: 0, pdu }));
match n {
MuxNotification::PaneOutput(_)
diff --git a/wezterm-mux-server-impl/src/foreign_panes.rs b/wezterm-mux-server-impl/src/foreign_panes.rs
new file mode 100644
index 00000000..8e540978
--- /dev/null
+++ b/wezterm-mux-server-impl/src/foreign_panes.rs
@@ -0,0 +1,497 @@
+//! The terminals of other machines a window is connected to, as the server
+//! a window runs for the command line hands them to the programs that ask
+//! (`thinkterm cli`, a plugin): only as far as the window's Settings let
+//! them. A program here asking after them is not the person at the window,
+//! and what they reach is a shell on another machine, logged in as that
+//! person. A server without a window to say otherwise has none to keep.
+
+use codec::{PaneMachine, Pdu};
+use mux::domain::DomainId;
+use mux::pane::PaneId;
+use mux::tab::TabId;
+use mux::{Mux, MuxNotification};
+use std::sync::OnceLock;
+use thinkterm_proto::SpawnTabDomain;
+
+/// How far the programs on this machine may reach the terminals of the
+/// machines a window is connected to.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Reach {
+ /// Not at all: they are not listed, read or typed into.
+ Off,
+ /// Listed and read, not typed into.
+ Read,
+ /// Listed, read and typed into, as the person at the window would.
+ Type,
+}
+
+/// What a window says of the terminals of other machines.
+pub struct Policy {
+ /// How far the programs here may reach them, asked as each asks.
+ pub reach: fn() -> Reach,
+ /// Whether a domain is a connection to another machine. Asked of every
+ /// pane's output, so it must be quick.
+ pub foreign: fn(DomainId) -> bool,
+ /// What the window calls the machine such a domain connects to.
+ pub machine: fn(DomainId) -> String,
+}
+
+static POLICY: OnceLock<Policy> = OnceLock::new();
+
+/// Set by a window's process, once, for the server it runs for the
+/// command line.
+pub fn install(policy: Policy) {
+ let _ = POLICY.set(policy);
+}
+
+/// What a request does to a pane: reads it, or acts on it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Use {
+ Read,
+ Act,
+}
+
+/// What a request is about.
+#[derive(Clone, Debug, PartialEq)]
+enum Subject {
+ Pane(PaneId),
+ Tab(TabId),
+ Domain(SpawnTabDomain, Option<PaneId>),
+}
+
+/// What `pdu` reads or acts on, and which: nothing for what is about no one
+/// pane -- a list, a version, the window's own business.
+fn subject(pdu: &Pdu) -> Vec<(Subject, Use)> {
+ use Subject::{Domain, Pane, Tab};
+ use Use::{Act, Read};
+ match pdu {
+ Pdu::GetPaneRenderChanges(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetPaneRenderableDimensions(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetLines(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::SearchScrollbackRequest(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetPaneRunState(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetPaneDirection(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetKittyImage(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetKittyFrameSelections(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::GetImageCell(req) => vec![(Pane(req.pane_id), Read)],
+ Pdu::WriteToPane(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::SendKeyDown(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::SendMouseEvent(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::SendPaste(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::KillPane(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::EraseScrollbackRequest(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::MarkProgramStatusSeen(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::ActivatePaneDirection(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::AdjustPaneSize(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::SetFocusedPane(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::PaneLabelChanged(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::ActivatePaneInStack(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::MovePaneToNewTab(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::SetPaneZoomed(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::Resize(req) => vec![(Pane(req.pane_id), Act)],
+ Pdu::SplitPane(req) => {
+ let mut subjects = vec![
+ (Pane(req.pane_id), Act),
+ (Domain(req.domain.clone(), Some(req.pane_id)), Act),
+ ];
+ if let Some(pane_id) = req.move_pane_id {
+ subjects.push((Pane(pane_id), Act));
+ }
+ subjects
+ }
+ Pdu::SpawnPaneInStack(req) => {
+ vec![
+ (Pane(req.pane_id), Act),
+ (Domain(req.domain.clone(), Some(req.pane_id)), Act),
+ ]
+ }
+ Pdu::MovePaneToStack(req) => vec![
+ (Pane(req.source_pane_id), Act),
+ (Pane(req.target_pane_id), Act),
+ ],
+ Pdu::SwapPanes(req) => vec![(Pane(req.pane_id), Act), (Pane(req.other_pane_id), Act)],
+ Pdu::SpawnV2(req) => vec![(Domain(req.domain.clone(), None), Act)],
+ Pdu::MoveTab(req) => vec![(Tab(req.tab_id), Act)],
+ Pdu::TabTitleChanged(req) => vec![(Tab(req.tab_id), Act)],
+ Pdu::SetClientViewport(req) => vec![(Tab(req.tab_id), Act)],
+ Pdu::SetClientView(req) => vec![(Tab(req.tab_id), Act)],
+ Pdu::ClaimClientViewport(req) => vec![(Tab(req.tab_id), Act)],
+ _ => vec![],
+ }
+}
+
+/// The domain of the other machine `subject` is on, when it is on one.
+fn foreign_domain(policy: &Policy, subject: &Subject) -> Option<DomainId> {
+ foreign_domain_in(&Mux::get(), policy, subject)
+}
+
+fn foreign_domain_in(mux: &Mux, policy: &Policy, subject: &Subject) -> Option<DomainId> {
+ let domain = match subject {
+ Subject::Pane(pane_id) => mux.get_pane(*pane_id)?.domain_id(),
+ Subject::Tab(tab_id) => mux.get_tab(*tab_id)?.get_active_pane()?.domain_id(),
+ Subject::Domain(domain, pane_id) => mux
+ .resolve_spawn_tab_domain(*pane_id, domain)
+ .ok()?
+ .domain_id(),
+ };
+ (policy.foreign)(domain).then_some(domain)
+}
+
+/// Whether `reach` lets a program here `what` a terminal of another
+/// machine; why not, if it does not.
+fn allows(reach: Reach, what: Use, machine: &str) -> Result<(), String> {
+ match (reach, what) {
+ (Reach::Type, _) | (Reach::Read, Use::Read) => Ok(()),
+ (Reach::Read, Use::Act) => Err(format!(
+ "the terminals on {machine} can only be read from this machine: \
+ let programs here type into them too in ThinkTerm's \
+ Settings › Agents"
+ )),
+ (Reach::Off, _) => Err(format!(
+ "the terminals on {machine} are not reachable from this machine: \
+ let programs here reach them in ThinkTerm's Settings › Agents"
+ )),
+ }
+}
+
+/// Refuse what `pdu` asks of a terminal of another machine that the
+/// window's Settings do not let programs here have.
+pub fn gate(pdu: &Pdu) -> anyhow::Result<()> {
+ let Some(policy) = POLICY.get() else {
+ return Ok(());
+ };
+ gate_with_policy(&Mux::get(), policy, pdu)
+}
+
+fn gate_with_policy(mux: &Mux, policy: &Policy, pdu: &Pdu) -> anyhow::Result<()> {
+ let subjects = subject(pdu);
+ if subjects.is_empty() {
+ return Ok(());
+ }
+ let reach = (policy.reach)();
+ let types = matches!(
+ pdu,
+ Pdu::WriteToPane(_) | Pdu::SendPaste(_) | Pdu::SendKeyDown(_) | Pdu::SendMouseEvent(_)
+ );
+ for (subject, what) in subjects {
+ if let Some(domain) = foreign_domain_in(mux, policy, &subject) {
+ let machine = (policy.machine)(domain);
+ allows(reach, what, &machine).map_err(anyhow::Error::msg)?;
+ // What would be dropped without a word, typed into a terminal
+ // the window may not type into just now: why, instead.
+ if let (Subject::Pane(pane_id), true) = (&subject, types) {
+ if let Some(why) = held_back(*pane_id, &machine) {
+ anyhow::bail!(why);
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Why what is sent to `pane_id`, on `machine`, would not reach it; `None`
+/// when it would.
+fn held_back(pane_id: PaneId, machine: &str) -> Option<String> {
+ use wezterm_client::domain::RemoteFrontendGate;
+ let pane = Mux::get().get_pane(pane_id)?;
+ let remote = pane.downcast_ref::<wezterm_client::pane::ClientPane>()?;
+ match remote.frontend_gate() {
+ RemoteFrontendGate::Visible => None,
+ RemoteFrontendGate::Claimable { owner: Some(_) } => Some(format!(
+ "the terminal on {machine} is in use on another device just now: \
+ take it back in the ThinkTerm window first"
+ )),
+ RemoteFrontendGate::Claimable { owner: None } => Some(format!(
+ "the ThinkTerm window has not taken up the terminals on {machine} yet: \
+ open one of them there first"
+ )),
+ RemoteFrontendGate::Connecting
+ | RemoteFrontendGate::Reconnecting
+ | RemoteFrontendGate::Syncing => Some(format!(
+ "the ThinkTerm window is still connecting to {machine}: try again in a moment"
+ )),
+ RemoteFrontendGate::Offline => Some(format!(
+ "the ThinkTerm window is not connected to {machine} just now"
+ )),
+ }
+}
+
+/// Whether `pane_id` is on another machine and not to be shown to the
+/// programs here at all.
+pub fn hidden(pane_id: PaneId) -> bool {
+ let Some(policy) = POLICY.get() else {
+ return false;
+ };
+ (policy.reach)() == Reach::Off && foreign_domain(policy, &Subject::Pane(pane_id)).is_some()
+}
+
+/// Remove hidden panes without losing local siblings in splits or stacks.
+pub(crate) fn visible_tree(
+ tree: thinkterm_proto::PaneNode,
+ hidden: &impl Fn(PaneId) -> bool,
+) -> thinkterm_proto::PaneNode {
+ use thinkterm_proto::PaneNode;
+ match tree {
+ PaneNode::Leaf(entry) if hidden(entry.pane_id) => PaneNode::Empty,
+ PaneNode::Stack(mut stack) => {
+ let active = stack.panes.get(stack.active).map(|pane| pane.pane_id);
+ stack.panes.retain(|pane| !hidden(pane.pane_id));
+ stack.active = stack
+ .panes
+ .iter()
+ .position(|pane| Some(pane.pane_id) == active)
+ .unwrap_or(0);
+ if stack.panes.is_empty() {
+ PaneNode::Empty
+ } else {
+ PaneNode::Stack(stack)
+ }
+ }
+ PaneNode::Split { left, right, node } => {
+ let left = visible_tree(*left, hidden);
+ let right = visible_tree(*right, hidden);
+ match (left, right) {
+ (PaneNode::Empty, right) => right,
+ (left, PaneNode::Empty) => left,
+ (left, right) => PaneNode::Split {
+ left: Box::new(left),
+ right: Box::new(right),
+ node,
+ },
+ }
+ }
+ tree => tree,
+ }
+}
+
+/// Whether `notification` tells of another machine's terminal that the
+/// programs here are not to hear of at all: what a program there runs, what
+/// it copies, what it is called, as much as what it prints.
+pub fn hides(notification: &MuxNotification) -> bool {
+ let Some(policy) = POLICY.get() else {
+ return false;
+ };
+ if (policy.reach)() != Reach::Off {
+ return false;
+ }
+ let subject = match notification {
+ MuxNotification::PaneOutput(pane_id)
+ | MuxNotification::Alert { pane_id, .. }
+ | MuxNotification::PaneAdded(pane_id)
+ | MuxNotification::PaneExited { pane_id, .. }
+ | MuxNotification::PaneRemoved(pane_id)
+ | MuxNotification::AgentStatusChanged(pane_id)
+ | MuxNotification::ForegroundProgramChanged(pane_id)
+ | MuxNotification::AssignClipboard { pane_id, .. }
+ | MuxNotification::PaneFocused(pane_id)
+ | MuxNotification::PaneLabelChanged { pane_id, .. } => Subject::Pane(*pane_id),
+ MuxNotification::TabAddedToWindow { tab_id, .. }
+ | MuxNotification::TabResized(tab_id)
+ | MuxNotification::TabTitleChanged { tab_id, .. } => Subject::Tab(*tab_id),
+ _ => return false,
+ };
+ foreign_domain(policy, &subject).is_some()
+}
+
+/// Where `pane_id` is, if on another machine whose terminals the programs
+/// here may see: the machine, and its id there -- the id the session server
+/// there gives it, or over a plain SSH session, which has none, its id here.
+pub fn machine(pane_id: PaneId) -> Option<PaneMachine> {
+ let policy = POLICY.get()?;
+ if (policy.reach)() == Reach::Off {
+ return None;
+ }
+ on_its_machine(pane_id)
+}
+
+/// `machine`, whether or not the programs here may see the pane: how the
+/// command line names it once they may, for the window to show.
+pub fn on_its_machine(pane_id: PaneId) -> Option<PaneMachine> {
+ let policy = POLICY.get()?;
+ let domain = foreign_domain(policy, &Subject::Pane(pane_id))?;
+ let pane = Mux::get().get_pane(pane_id)?;
+ let there = pane
+ .downcast_ref::<wezterm_client::pane::ClientPane>()
+ .map_or(pane_id, |remote| remote.remote_pane_id);
+ Some(PaneMachine {
+ machine: (policy.machine)(domain),
+ pane_id: there,
+ })
+}
+
+/// Where the cursor of `pane_id` is and how far its rows run, as its own
+/// machine has them, when it is another one's: a window keeps them only as
+/// fresh as what it has shown. `None` for a pane of this machine's.
+pub async fn dimensions_from_its_machine(
+ pane_id: PaneId,
+) -> Option<anyhow::Result<codec::GetPaneRenderableDimensionsResponse>> {
+ let policy = POLICY.get()?;
+ foreign_domain(policy, &Subject::Pane(pane_id))?;
+ let pane = Mux::get().get_pane(pane_id)?;
+ let remote = pane.downcast_ref::<wezterm_client::pane::ClientPane>()?;
+ Some(remote.fetch_dimensions().await.map(|response| {
+ codec::GetPaneRenderableDimensionsResponse {
+ pane_id,
+ ..response
+ }
+ }))
+}
+
+/// The rows of `pane_id` as its own machine has them, when it is another
+/// one's: a window holds only the rows it has shown, and the rest come back
+/// blank until fetched. `None` for a pane of this machine's.
+pub async fn lines_from_its_machine(
+ pane_id: PaneId,
+ lines: Vec<std::ops::Range<wezterm_term::StableRowIndex>>,
+) -> Option<anyhow::Result<codec::SerializedLines>> {
+ let policy = POLICY.get()?;
+ foreign_domain(policy, &Subject::Pane(pane_id))?;
+ let pane = Mux::get().get_pane(pane_id)?;
+ let remote = pane.downcast_ref::<wezterm_client::pane::ClientPane>()?;
+ Some(remote.fetch_lines(lines).await)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_policy(reach: fn() -> Reach) -> Policy {
+ Policy {
+ reach,
+ foreign: |_| true,
+ machine: |_| "devbox".to_string(),
+ }
+ }
+
+ #[test]
+ fn implicit_remote_domains_obey_the_same_policy_as_explicit_ones() {
+ use mux::domain::{Domain, LocalDomain};
+ use std::sync::Arc;
+ let mux = Mux::new(None);
+ let domain: Arc<dyn Domain> = Arc::new(LocalDomain::new("devbox").unwrap());
+ mux.add_domain(&domain);
+ mux.set_default_domain(&domain);
+ for domain in [
+ SpawnTabDomain::DefaultDomain,
+ SpawnTabDomain::CurrentPaneDomain,
+ SpawnTabDomain::DomainId(domain.domain_id()),
+ SpawnTabDomain::DomainName("devbox".to_string()),
+ ] {
+ let spawn = Pdu::SpawnV2(codec::SpawnV2 {
+ domain,
+ window_id: None,
+ command: None,
+ command_dir: None,
+ size: wezterm_term::TerminalSize::default(),
+ workspace: "default".to_string(),
+ });
+ assert!(gate_with_policy(&mux, &test_policy(|| Reach::Off), &spawn).is_err());
+ assert!(gate_with_policy(&mux, &test_policy(|| Reach::Read), &spawn).is_err());
+ assert!(gate_with_policy(&mux, &test_policy(|| Reach::Type), &spawn).is_ok());
+ }
+ }
+
+ #[test]
+ fn a_split_move_checks_the_source_as_a_mutation() {
+ let split = Pdu::SplitPane(codec::SplitPane {
+ pane_id: 1,
+ split_request: Default::default(),
+ command: None,
+ command_dir: None,
+ domain: SpawnTabDomain::CurrentPaneDomain,
+ move_pane_id: Some(2),
+ });
+ assert!(subject(&split).contains(&(Subject::Pane(2), Use::Act)));
+ }
+
+ fn entry(pane_id: PaneId) -> thinkterm_proto::PaneEntry {
+ thinkterm_proto::PaneEntry {
+ window_id: 1,
+ tab_id: 1,
+ pane_id,
+ title: "shell".to_string(),
+ size: wezterm_term::TerminalSize::default(),
+ working_dir: None,
+ is_active_pane: false,
+ is_zoomed_pane: false,
+ alt_screen: false,
+ workspace: "default".to_string(),
+ cursor_pos: Default::default(),
+ physical_top: 0,
+ top_row: 0,
+ left_col: 0,
+ tty_name: None,
+ }
+ }
+
+ #[test]
+ fn filtering_remote_leaves_keeps_local_splits_and_stack_members() {
+ use thinkterm_proto::{PaneNode, PaneStackEntry, SplitDirection, SplitDirectionAndSize};
+ let tree = PaneNode::Split {
+ left: Box::new(PaneNode::Leaf(entry(1))),
+ right: Box::new(PaneNode::Stack(PaneStackEntry {
+ active: 2,
+ panes: vec![entry(2), entry(3), entry(4)],
+ pane_stack_id: Some(7),
+ })),
+ node: SplitDirectionAndSize {
+ direction: SplitDirection::Horizontal,
+ first: Default::default(),
+ second: Default::default(),
+ },
+ };
+ let tree = visible_tree(tree, &|id| id == 1 || id == 2);
+ assert_eq!(
+ tree.entries().iter().map(|p| p.pane_id).collect::<Vec<_>>(),
+ vec![3, 4]
+ );
+ assert!(
+ matches!(&tree, PaneNode::Stack(stack) if stack.active == 1 && stack.pane_stack_id == Some(7))
+ );
+ let tree = visible_tree(tree, &|id| id == 4);
+ assert!(matches!(&tree, PaneNode::Stack(stack) if stack.active == 0));
+ assert!(matches!(visible_tree(tree, &|_| true), PaneNode::Empty));
+ assert_eq!(
+ visible_tree(PaneNode::Leaf(entry(5)), &|_| false),
+ PaneNode::Leaf(entry(5))
+ );
+ }
+
+ #[test]
+ fn reading_is_one_thing_and_typing_another() {
+ assert!(allows(Reach::Read, Use::Read, "devbox").is_ok());
+ assert!(allows(Reach::Read, Use::Act, "devbox").is_err());
+ assert!(allows(Reach::Type, Use::Act, "devbox").is_ok());
+ assert!(allows(Reach::Off, Use::Read, "devbox").is_err());
+ let why = allows(Reach::Off, Use::Read, "devbox").unwrap_err();
+ assert!(why.contains("devbox") && why.contains("Settings"), "{why}");
+ }
+
+ #[test]
+ fn what_reads_and_what_acts() {
+ let reads = Pdu::GetLines(codec::GetLines {
+ pane_id: 4,
+ lines: vec![],
+ });
+ assert_eq!(subject(&reads), vec![(Subject::Pane(4), Use::Read)]);
+ let types = Pdu::WriteToPane(codec::WriteToPane {
+ pane_id: 4,
+ data: b"ls\r".to_vec(),
+ });
+ assert_eq!(subject(&types), vec![(Subject::Pane(4), Use::Act)]);
+ let lists = Pdu::ListPanes(codec::ListPanes {});
+ assert!(subject(&lists).is_empty());
+ }
+
+ #[test]
+ fn with_no_window_nothing_is_kept_from_anyone() {
+ // No policy installed in a test process.
+ let types = Pdu::WriteToPane(codec::WriteToPane {
+ pane_id: 4,
+ data: b"ls\r".to_vec(),
+ });
+ assert!(gate(&types).is_ok());
+ assert!(!hidden(4));
+ assert!(machine(4).is_none());
+ }
+}
diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rs
index 713e28cd..ce70bd26 100644
--- a/wezterm-mux-server-impl/src/lib.rs
+++ b/wezterm-mux-server-impl/src/lib.rs
@@ -7,6 +7,7 @@ use wezterm_client::domain::{ClientDomain, ClientDomainConfig};
pub mod connections;
pub mod dispatch;
+pub mod foreign_panes;
#[cfg(any(unix, windows))]
pub mod handoff;
#[cfg(target_os = "macos")]
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index fe19f7b7..4025ed62 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -1619,6 +1619,13 @@ impl SessionHandler {
}
}
+ // The terminals of the machines a window is connected to, as far as
+ // its Settings let the programs on this one have them.
+ if let Err(err) = crate::foreign_panes::gate(&decoded.pdu) {
+ send_response(Err(err));
+ return;
+ }
+
if requires_existing_frontend_access(&decoded.pdu) {
if let Err(err) = require_registered_frontend_access(
&Mux::get(),
@@ -1806,6 +1813,9 @@ impl SessionHandler {
let Some(status) = pane.agent_status() else {
continue;
};
+ if crate::foreign_panes::hidden(pane.pane_id()) {
+ continue;
+ }
agents.push((pane.pane_id(), status, pane.get_title()));
}
if agents.is_empty() {
@@ -1860,6 +1870,9 @@ impl SessionHandler {
.iter_panes()
.into_iter()
.filter_map(|pane| {
+ if crate::foreign_panes::hidden(pane.pane_id()) {
+ return None;
+ }
let program = pane.foreground_program()?;
Some(ForegroundProgramEntry {
pane_id: pane.pane_id(),
@@ -1899,20 +1912,39 @@ impl SessionHandler {
let mut tabs = vec![];
let mut tab_titles = vec![];
let mut window_titles = HashMap::new();
+ let mut pane_machines = HashMap::new();
for window_id in mux.iter_windows().into_iter() {
let window = mux.get_window(window_id).unwrap();
window_titles.insert(window_id, window.get_title().to_string());
for tab in window.iter() {
- tabs.push(tab.codec_pane_tree());
+ let tree = crate::foreign_panes::visible_tree(
+ tab.codec_pane_tree(),
+ &crate::foreign_panes::hidden,
+ );
+ if matches!(tree, mux::tab::PaneNode::Empty) {
+ continue;
+ }
+ for pane in tree.entries() {
+ if let Some(machine) =
+ crate::foreign_panes::machine(pane.pane_id)
+ {
+ pane_machines.insert(pane.pane_id, machine);
+ }
+ }
+ tabs.push(tree);
tab_titles.push(tab.get_title());
}
}
log::trace!("ListPanes {tabs:#?} {tab_titles:?}");
+ let mut pane_labels = mux.pane_labels();
+ pane_labels
+ .retain(|pane_id, _| !crate::foreign_panes::hidden(*pane_id));
Ok(Pdu::ListPanesResponse(ListPanesResponse {
tabs,
tab_titles,
window_titles,
- pane_labels: mux.pane_labels(),
+ pane_labels,
+ pane_machines,
}))
},
send_response,
@@ -2619,6 +2651,13 @@ impl SessionHandler {
Pdu::GetPaneRenderableDimensions(GetPaneRenderableDimensions { pane_id }) => {
spawn_into_main_thread(async move {
+ // Another machine's pane, as that machine has it.
+ if let Some(fetched) =
+ crate::foreign_panes::dimensions_from_its_machine(pane_id).await
+ {
+ send_response(fetched.map(Pdu::GetPaneRenderableDimensionsResponse));
+ return;
+ }
catch(
move || {
let mux = Mux::get();
@@ -2729,6 +2768,19 @@ impl SessionHandler {
lines
};
spawn_into_main_thread(async move {
+ // The upstream connection belongs to the owner and
+ // does not carry this viewer's history restriction.
+ // Screen-only shares must use get_screen_lines below.
+ if !screen_only {
+ if let Some(fetched) =
+ crate::foreign_panes::lines_from_its_machine(pane_id, lines.clone()).await
+ {
+ send_response(fetched.map(|lines| {
+ Pdu::GetLinesResponse(GetLinesResponse { pane_id, lines })
+ }));
+ return;
+ }
+ }
// Read once the pane can be read without waiting, like
// a push: the client asks again for rows it does not
// get, and the main thread has everyone else's work.
diff --git a/wezterm/src/cli/events.rs b/wezterm/src/cli/events.rs
index c30033c8..359d9c37 100644
--- a/wezterm/src/cli/events.rs
+++ b/wezterm/src/cli/events.rs
@@ -4,6 +4,7 @@ use anyhow::{bail, Context};
use clap::Parser;
use codec::Pdu;
use mux::pane::PaneId;
+use std::collections::{HashMap, VecDeque};
use std::io::Write;
use std::time::Duration;
use thinkterm_proto::{TabId, WindowId};
@@ -393,20 +394,81 @@ impl Event {
}
}
+/// Current identities plus a bounded tail for removals queued before a
+/// listing refresh. A removal releases its identity once printed.
+#[derive(Default)]
+struct PaneNames {
+ live: HashMap<PaneId, Option<String>>,
+ removed: VecDeque<(PaneId, String)>,
+}
+
+impl PaneNames {
+ fn refresh(&mut self, listing: codec::ListPanesResponse) {
+ let mut live: HashMap<PaneId, Option<String>> = listing
+ .tabs
+ .iter()
+ .flat_map(|tab| tab.entries())
+ .map(|pane| (pane.pane_id, None))
+ .collect();
+ for (pane_id, on) in listing.pane_machines {
+ live.insert(pane_id, Some(format!("{}/{}", on.machine, on.pane_id)));
+ }
+ for (pane_id, name) in std::mem::replace(&mut self.live, live) {
+ if !self.live.contains_key(&pane_id) {
+ if let Some(name) = name {
+ self.removed.push_back((pane_id, name));
+ }
+ }
+ }
+ while self.removed.len() > BACKLOG {
+ self.removed.pop_front();
+ }
+ }
+
+ fn knows(&self, pane_id: PaneId) -> bool {
+ self.live.contains_key(&pane_id) || self.removed.iter().any(|(id, _)| *id == pane_id)
+ }
+
+ fn get(&self, pane_id: PaneId) -> Option<&str> {
+ if let Some(name) = self.live.get(&pane_id) {
+ return name.as_deref();
+ }
+ self.removed
+ .iter()
+ .rev()
+ .find(|(id, _)| *id == pane_id)
+ .map(|(_, name)| name.as_str())
+ }
+
+ fn forget(&mut self, pane_id: PaneId) {
+ self.live.remove(&pane_id);
+ self.removed.retain(|(id, _)| *id != pane_id);
+ }
+}
+
impl EventsCommand {
pub async fn run(self, client: Client) -> anyhow::Result<()> {
- let only_pane = match &self.pane {
- Some(name) => Some(crate::cli::target::resolve(&client, None, Some(name)).await?),
- None => self.pane_id,
+ let (client, only_pane) = match &self.pane {
+ Some(name) => {
+ let (client, pane_id) =
+ crate::cli::target::resolve_reaching_servers(client, None, Some(name)).await?;
+ (client, Some(pane_id))
+ }
+ None => (client, self.pane_id),
};
let format = if self.json {
CliOutputFormatKind::Json
} else {
self.format
};
+ // A pane on a server, heard of through the window, by the name
+ // that reaches it again -- `MACHINE/ID` -- rather than the window's
+ // own number for it, which names some other pane anywhere else.
let pushes = wezterm_client::client::tap_unilateral_pdus(BACKLOG);
client.subscribe_events(codec::SubscribeEvents {}).await?;
let mut subscribed_on = client.connection_generation();
+ let mut on_servers = PaneNames::default();
+ on_servers.refresh(client.list_panes().await?);
let out = std::io::stdout();
loop {
@@ -415,6 +477,7 @@ impl EventsCommand {
if client.connection_generation() != subscribed_on {
subscribed_on = client.connection_generation();
client.subscribe_events(codec::SubscribeEvents {}).await?;
+ on_servers.refresh(client.list_panes().await?);
}
let next = smol::future::or(async { Some(pushes.recv().await) }, async {
smol::Timer::after(LIVENESS_INTERVAL).await;
@@ -435,18 +498,46 @@ impl EventsCommand {
let Some(event) = Event::from_pdu(pdu) else {
continue;
};
+ if matches!(event, Event::PaneAdded { .. } | Event::TabAdded { .. })
+ || event.pane_id().is_some_and(|id| !on_servers.knows(id))
+ {
+ on_servers.refresh(client.list_panes().await?);
+ }
if only_pane.is_some() && event.pane_id() != only_pane {
+ if let Event::PaneRemoved { pane_id } = event {
+ on_servers.forget(pane_id);
+ }
continue;
}
+ let on_server = event.pane_id().and_then(|pane_id| {
+ on_servers
+ .get(pane_id)
+ .map(|name| (format!("pane {pane_id}"), name))
+ });
let line = match format {
- CliOutputFormatKind::Json => serde_json::to_string(&event)?,
- CliOutputFormatKind::Table => format!(
- "{} {}",
- chrono::Local::now().format("%H:%M:%S"),
- printable(&event.describe())
- ),
+ CliOutputFormatKind::Json => {
+ let mut value = serde_json::to_value(&event)?;
+ if let (Some((_, name)), Some(fields)) = (&on_server, value.as_object_mut()) {
+ fields.insert("pane".to_string(), (*name).into());
+ }
+ value.to_string()
+ }
+ CliOutputFormatKind::Table => {
+ let mut text = event.describe();
+ if let Some((window_number, name)) = &on_server {
+ text = text.replacen(window_number.as_str(), &format!("pane {name}"), 1);
+ }
+ format!(
+ "{} {}",
+ chrono::Local::now().format("%H:%M:%S"),
+ printable(&text)
+ )
+ }
};
writeln!(out.lock(), "{line}").map_err(crate::stdout_error)?;
+ if let Event::PaneRemoved { pane_id } = event {
+ on_servers.forget(pane_id);
+ }
}
}
}
@@ -455,6 +546,55 @@ impl EventsCommand {
mod tests {
use super::*;
+ fn machines(ids: &[PaneId]) -> codec::ListPanesResponse {
+ codec::ListPanesResponse {
+ tabs: vec![],
+ tab_titles: vec![],
+ window_titles: HashMap::new(),
+ pane_labels: HashMap::new(),
+ pane_machines: ids
+ .iter()
+ .map(|id| {
+ (
+ *id,
+ codec::PaneMachine {
+ machine: "devbox".to_string(),
+ pane_id: id + 10,
+ },
+ )
+ })
+ .collect(),
+ }
+ }
+
+ #[test]
+ fn event_names_follow_new_panes_and_survive_refresh_until_removal() {
+ let mut names = PaneNames::default();
+ names.refresh(machines(&[1]));
+ names.refresh(machines(&[1, 2]));
+ assert_eq!(names.get(2), Some("devbox/12"));
+ // A reconnect/list refresh can precede queued removal events.
+ names.refresh(machines(&[2, 3]));
+ assert_eq!(names.get(1), Some("devbox/11"));
+ assert_eq!(names.get(3), Some("devbox/13"));
+ names.forget(1);
+ assert!(!names.knows(1));
+ names.forget(2);
+ assert!(!names.knows(2));
+ }
+
+ #[test]
+ fn lost_removal_events_cannot_grow_retired_names_without_bound() {
+ let mut names = PaneNames::default();
+ for id in 0..BACKLOG + 2 {
+ names.refresh(machines(&[id]));
+ }
+ assert_eq!(names.removed.len(), BACKLOG);
+ assert_eq!(names.get(0), None);
+ assert!(names.get(BACKLOG).is_some());
+ assert!(names.get(BACKLOG + 1).is_some());
+ }
+
#[test]
fn an_unavailable_program_exit_status_is_explicit() {
let event = Event::from_pdu(Pdu::PaneExited(codec::PaneExited {
diff --git a/wezterm/src/cli/get_text.rs b/wezterm/src/cli/get_text.rs
index 3f40cedf..ce9dddf9 100644
--- a/wezterm/src/cli/get_text.rs
+++ b/wezterm/src/cli/get_text.rs
@@ -87,8 +87,12 @@ impl GetText {
client: Client,
pushes: Option<smol::channel::Receiver<Pdu>>,
) -> anyhow::Result<()> {
- let pane_id =
- crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;
+ let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
+ client,
+ self.pane_id,
+ self.pane.as_deref(),
+ )
+ .await?;
let info = client
.get_dimensions(codec::GetPaneRenderableDimensions { pane_id })
diff --git a/wezterm/src/cli/list.rs b/wezterm/src/cli/list.rs
index 565ac611..f293da9a 100644
--- a/wezterm/src/cli/list.rs
+++ b/wezterm/src/cli/list.rs
@@ -1,5 +1,7 @@
use crate::cli::CliOutputFormatKind;
use clap::Parser;
+use codec::ListPanesResponse;
+use mux::pane::PaneId;
use tabout::{tabulate_output, Alignment, Column};
use wezterm_client::client::Client;
use wezterm_term::TerminalSize;
@@ -18,32 +20,22 @@ pub struct ListCommand {
impl ListCommand {
pub async fn run(&self, client: Client) -> anyhow::Result<()> {
- let mut output_items = vec![];
let panes = client.list_panes().await?;
-
- for (tabroot, tab_title) in panes.tabs.into_iter().zip(panes.tab_titles.iter()) {
- let mut cursor = tabroot.into_tree().cursor();
-
- loop {
- if let Some(stack) = cursor.leaf_mut() {
- for entry in &stack.panes {
- let window_title = panes
- .window_titles
- .get(&entry.window_id)
- .map(|s| s.as_str())
- .unwrap_or("");
- output_items.push(CliListResultItem::from(
- entry.clone(),
- tab_title,
- window_title,
- panes.pane_labels.get(&entry.pane_id).cloned(),
- ));
- }
- }
- match cursor.preorder_next() {
- Ok(c) => cursor = c,
- Err(_) => break,
- }
+ let mut output_items = items(panes, |_| true);
+ // Then the panes on servers, as the window this machine has open
+ // is connected to them and its Settings let programs here have
+ // them: asked of it unless it was asked already, and not waited
+ // on for long.
+ if crate::cli::servers_terminals_reachable()
+ && !output_items.iter().any(|item| item.machine.is_some())
+ {
+ let theirs = crate::cli::within_window_wait(async {
+ crate::cli::window_client().await?.list_panes().await.ok()
+ })
+ .await;
+ if let Some(theirs) = theirs {
+ let on_servers: Vec<PaneId> = theirs.pane_machines.keys().copied().collect();
+ output_items.extend(items(theirs, |pane_id| on_servers.contains(&pane_id)));
}
}
let format = if self.json {
@@ -113,6 +105,66 @@ impl ListCommand {
}
}
+/// The panes `panes` lists, those `keep` keeps, as `list` prints them.
+fn items(panes: ListPanesResponse, keep: impl Fn(PaneId) -> bool) -> Vec<CliListResultItem> {
+ let mut output_items = vec![];
+ for (tabroot, tab_title) in panes.tabs.into_iter().zip(panes.tab_titles.iter()) {
+ let mut cursor = tabroot.into_tree().cursor();
+
+ loop {
+ if let Some(stack) = cursor.leaf_mut() {
+ for entry in &stack.panes {
+ if !keep(entry.pane_id) {
+ continue;
+ }
+ let window_title = panes
+ .window_titles
+ .get(&entry.window_id)
+ .map(|s| s.as_str())
+ .unwrap_or("");
+ let mut item = CliListResultItem::from(
+ entry.clone(),
+ tab_title,
+ window_title,
+ panes.pane_labels.get(&entry.pane_id).cloned(),
+ );
+ // Named by its machine and its id there.
+ if let Some(on) = panes.pane_machines.get(&entry.pane_id) {
+ item.machine = Some(on.machine.clone());
+ item.pane_id =
+ ListedPaneId::There(format!("{}/{}", on.machine, on.pane_id));
+ }
+ output_items.push(item);
+ }
+ }
+ match cursor.preorder_next() {
+ Ok(c) => cursor = c,
+ Err(_) => break,
+ }
+ }
+ }
+ output_items
+}
+
+/// A pane's id as `list` gives it: a number for one of this machine's, and
+/// `MACHINE/ID` for one on a server -- a string, so that it is never taken
+/// for one of this machine's and passed to `--pane-id`, but to `--pane`.
+#[derive(serde::Serialize)]
+#[serde(untagged)]
+enum ListedPaneId {
+ Here(PaneId),
+ There(String),
+}
+
+impl std::fmt::Display for ListedPaneId {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ match self {
+ Self::Here(pane_id) => write!(f, "{pane_id}"),
+ Self::There(target) => f.write_str(target),
+ }
+ }
+}
+
#[derive(serde::Serialize)]
struct CliListResultPtySize {
rows: usize,
@@ -133,9 +185,12 @@ struct CliListResultPtySize {
struct CliListResultItem {
window_id: mux::window::WindowId,
tab_id: mux::tab::TabId,
- pane_id: mux::pane::PaneId,
+ pane_id: ListedPaneId,
/// The label the pane was given, if any.
label: Option<String>,
+ /// The server the pane is on, when it is not this machine's: then
+ /// `pane_id` is `MACHINE/ID`, for `--pane`.
+ machine: Option<String>,
workspace: String,
size: CliListResultPtySize,
title: String,
@@ -192,8 +247,9 @@ impl CliListResultItem {
CliListResultItem {
window_id,
tab_id,
- pane_id,
+ pane_id: ListedPaneId::Here(pane_id),
label,
+ machine: None,
workspace,
size: CliListResultPtySize {
rows,
@@ -222,3 +278,20 @@ impl CliListResultItem {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_pane_on_a_server_is_listed_by_a_name_no_id_here_could_be() {
+ let here = serde_json::to_string(&ListedPaneId::Here(3)).unwrap();
+ let there = serde_json::to_string(&ListedPaneId::There("devbox/3".into())).unwrap();
+ assert_eq!(here, "3");
+ assert_eq!(there, "\"devbox/3\"");
+ assert_eq!(
+ ListedPaneId::There("devbox/3".into()).to_string(),
+ "devbox/3"
+ );
+ }
+}
diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rs
index 13b2fa40..77b4e4ac 100644
--- a/wezterm/src/cli/mod.rs
+++ b/wezterm/src/cli/mod.rs
@@ -345,7 +345,71 @@ Outputs the pane-id for the newly created pane on success"
RestoreOutput(restore_output::RestoreOutputCommand),
}
+/// The window class `thinkterm cli` was asked to find, for reaching the
+/// window this machine has open as well as the server it asks.
+static WINDOW_CLASS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
+
+/// Whether the window's Settings let the programs here reach the terminals
+/// of its servers at all, as its settings file says: unless they do, there
+/// is nothing to ask it about them.
+pub(crate) fn servers_terminals_reachable() -> bool {
+ #[derive(serde::Deserialize, Default)]
+ #[serde(default)]
+ struct Agents {
+ server_terminals: String,
+ }
+ #[derive(serde::Deserialize, Default)]
+ #[serde(default)]
+ struct Settings {
+ agents: Agents,
+ }
+ std::fs::read(config::native_settings_path())
+ .ok()
+ .and_then(|bytes| serde_json::from_slice::<Settings>(&bytes).ok())
+ .is_some_and(|settings| {
+ matches!(settings.agents.server_terminals.as_str(), "read" | "type")
+ })
+}
+
+/// How long the window is waited on for what its servers have: a window
+/// busy starting or reloading does not hold up what this machine has.
+const WINDOW_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
+
+/// `ask` of the window, given `WINDOW_WAIT` to answer; `None` past it.
+pub(crate) async fn within_window_wait<T>(
+ ask: impl std::future::Future<Output = Option<T>>,
+) -> Option<T> {
+ smol::future::or(ask, async {
+ smol::Timer::after(WINDOW_WAIT).await;
+ None
+ })
+ .await
+}
+
+/// The window this machine has open, which is connected to the servers whose
+/// panes the programs here may reach as far as its Settings say; `None`
+/// without one.
+pub(crate) async fn window_client() -> Option<Client> {
+ let class = WINDOW_CLASS
+ .get()
+ .map(String::as_str)
+ .unwrap_or(wezterm_gui_subcommands::DEFAULT_WINDOW_CLASS);
+ let socket_path = wezterm_client::discovery::resolve_gui_sock_path(class).ok()?;
+ let domain = config::UnixDomain {
+ socket_path: Some(socket_path),
+ no_serve_automatically: true,
+ ..Default::default()
+ };
+ let mut ui = mux::connui::ConnectionUI::new_headless();
+ let client = Client::new_unix_domain(None, &domain, true, &mut ui, true).ok()?;
+ client.verify_version_compat(&ui).await.ok()?;
+ Some(client)
+}
+
async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()> {
+ if let Some(class) = &cli.class {
+ let _ = WINDOW_CLASS.set(class.clone());
+ }
// The scheme table is compiled in; asking a server for it (or starting
// one) would only get in the way.
if let CliSubCommand::ColorSchemes(cmd) = &cli.sub {
diff --git a/wezterm/src/cli/send_key.rs b/wezterm/src/cli/send_key.rs
index 029dd0ec..734d3ef7 100644
--- a/wezterm/src/cli/send_key.rs
+++ b/wezterm/src/cli/send_key.rs
@@ -56,14 +56,22 @@ impl SendKey {
.map_err(|err| UsageError(format!("{err:#}")))?;
if !self.wait {
- let pane_id =
- crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;
+ let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
+ client,
+ self.pane_id,
+ self.pane.as_deref(),
+ )
+ .await?;
return send_keys(&client, pane_id, events).await;
}
let code = with_deadline(deadline, async {
// Finding the focused pane asks the server too.
- let pane_id =
- crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;
+ let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
+ client.clone(),
+ self.pane_id,
+ self.pane.as_deref(),
+ )
+ .await?;
// Counted before the keys go, so a command that finishes at
// once is not missed.
let before = shell_commands(&client, pane_id).await?.finished;
diff --git a/wezterm/src/cli/send_text.rs b/wezterm/src/cli/send_text.rs
index c2e8c535..c70d97c0 100644
--- a/wezterm/src/cli/send_text.rs
+++ b/wezterm/src/cli/send_text.rs
@@ -36,8 +36,12 @@ pub struct SendText {
impl SendText {
pub async fn run(self, client: Client) -> anyhow::Result<()> {
- let pane_id =
- crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;
+ let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
+ client,
+ self.pane_id,
+ self.pane.as_deref(),
+ )
+ .await?;
let data = match self.text {
Some(text) => text,
diff --git a/wezterm/src/cli/target.rs b/wezterm/src/cli/target.rs
index c7f6ec98..62f2c379 100644
--- a/wezterm/src/cli/target.rs
+++ b/wezterm/src/cli/target.rs
@@ -1,6 +1,8 @@
-//! `--pane NAME`: a pane named by its label or by its thread.
+//! `--pane NAME`: a pane named by its label or by its thread, or a pane on
+//! a server as `MACHINE/NAME`.
use crate::cli::{printable, NoSuchTarget, UsageError};
+use codec::PaneMachine;
use mux::pane::PaneId;
use std::collections::HashMap;
use wezterm_client::client::Client;
@@ -17,6 +19,92 @@ pub async fn resolve(
}
}
+/// The pane `pane` names, and the client that reaches it: a pane of this
+/// machine's through `client`; one that is not, but on a server as
+/// `MACHINE/NAME` names it, through the window this machine has open, which
+/// is connected to the server -- as far as the window's Settings let it be.
+pub async fn resolve_reaching_servers(
+ client: Client,
+ pane_id: Option<PaneId>,
+ pane: Option<&str>,
+) -> anyhow::Result<(Client, PaneId)> {
+ let here = resolve(&client, pane_id, pane).await;
+ let (why, name) = match (here, pane) {
+ (Ok(pane_id), _) => return Ok((client, pane_id)),
+ (Err(why), Some(name)) if name.contains('/') => (why, name),
+ (Err(why), _) => return Err(why),
+ };
+ if !crate::cli::servers_terminals_reachable() {
+ return Err(why.context(SERVER_PANES));
+ }
+ let asked = crate::cli::within_window_wait(async {
+ let window = crate::cli::window_client().await?;
+ let panes = candidates(&window).await.ok()?;
+ Some((window, panes))
+ })
+ .await;
+ let Some((window, panes)) = asked else {
+ return Err(why.context(SERVER_PANES));
+ };
+ match on_machine(&panes, name.trim()) {
+ Some(Ok(pane_id)) => Ok((window, pane_id)),
+ Some(Err(why)) => Err(NoSuchTarget(why).into()),
+ None => Err(why.context(SERVER_PANES)),
+ }
+}
+
+/// How a pane on a server is named, said where a name names nothing here.
+const SERVER_PANES: &str = "a pane on a server is named MACHINE/NAME, as `thinkterm cli list` \
+ shows it, with ThinkTerm open and Settings › Agents letting programs here reach it";
+
+/// The pane `name` names on a machine, as `MACHINE/ID` or `MACHINE/NAME`;
+/// `None` when it starts with no machine's name.
+fn on_machine(panes: &[Candidate], name: &str) -> Option<Result<PaneId, String>> {
+ // Match the complete label, including any slashes in it. Prefer the
+ // longest known label so that names printed by list round-trip.
+ let (machine, rest) = name
+ .match_indices('/')
+ .rev()
+ .map(|(at, _)| (&name[..at], &name[at + 1..]))
+ .find(|(machine, _)| {
+ panes.iter().any(|pane| {
+ pane.machine
+ .as_ref()
+ .is_some_and(|on| same(&on.machine, machine))
+ })
+ })?;
+ let there: Vec<Candidate> = panes
+ .iter()
+ .filter(|pane| {
+ pane.machine
+ .as_ref()
+ .is_some_and(|on| same(&on.machine, machine))
+ })
+ .cloned()
+ .collect();
+ if there.is_empty() {
+ return None;
+ }
+ // Its id there, as the panes on it know it.
+ if let Some(id) = as_pane_id(rest) {
+ let by_id: Vec<&Candidate> = there
+ .iter()
+ .filter(|pane| pane.machine.as_ref().is_some_and(|on| on.pane_id == id))
+ .collect();
+ return Some(match by_id.as_slice() {
+ [pane] => Ok(pane.pane_id),
+ [] => Err(format!(
+ "there is no pane {id} on {machine}; `thinkterm cli list` shows them"
+ )),
+ _ => Err(format!(
+ "{name:?} is ambiguous: multiple machines have the same label and pane id; \
+ give the machines distinct labels before targeting this pane"
+ )),
+ });
+ }
+ Some(choose(&there, rest, None))
+}
+
/// A pane as a name can pick it.
#[derive(Debug, Clone, PartialEq)]
pub struct Candidate {
@@ -26,6 +114,8 @@ pub struct Candidate {
pub workspace: String,
/// The project and the thread its workspace backs, if a thread does.
pub thread: Option<(String, String)>,
+ /// The server it is on, and its id there, for a pane of another machine.
+ pub machine: Option<PaneMachine>,
}
async fn find(client: &Client, name: &str) -> anyhow::Result<PaneId> {
@@ -62,6 +152,7 @@ pub async fn candidates(client: &Client) -> anyhow::Result<Vec<Candidate>> {
title: entry.title.clone(),
workspace: entry.workspace.clone(),
thread: threads.get(&entry.workspace).cloned(),
+ machine: listing.pane_machines.get(&entry.pane_id).cloned(),
});
}
}
@@ -198,9 +289,13 @@ fn describe(pane: &Candidate) -> String {
Some((project, thread)) => format!("thread {}", thread_display_name(project, thread)),
None => format!("workspace {}", pane.workspace),
};
+ let id = match &pane.machine {
+ Some(on) => format!("{}/{}", on.machine, on.pane_id),
+ None => pane.pane_id.to_string(),
+ };
printable(&format!(
"{:>4} {} {} ({place})",
- pane.pane_id,
+ id,
pane.label.as_deref().unwrap_or("-"),
pane.title
))
@@ -222,9 +317,60 @@ mod tests {
title: "zsh".to_string(),
workspace: workspace.to_string(),
thread: thread.map(|thread| ("project".to_string(), thread.to_string())),
+ machine: None,
}
}
+ /// Pane `pane_id` here, `there` on `machine`.
+ fn on(pane_id: PaneId, machine: &str, there: PaneId, label: Option<&str>) -> Candidate {
+ Candidate {
+ machine: Some(PaneMachine {
+ machine: machine.to_string(),
+ pane_id: there,
+ }),
+ ..pane(pane_id, label, "w-server", None)
+ }
+ }
+
+ #[test]
+ fn a_pane_on_a_server_is_named_by_its_machine_and_its_id_or_label_there() {
+ let mut panes = panes();
+ panes.push(on(20, "devbox", 3, Some("logs")));
+ panes.push(on(21, "devbox", 4, None));
+ panes.push(on(22, "server-b", 3, Some("logs")));
+ assert_eq!(on_machine(&panes, "devbox/3"), Some(Ok(20)));
+ assert_eq!(on_machine(&panes, "DevBox/4"), Some(Ok(21)));
+ assert_eq!(on_machine(&panes, "server-b/logs"), Some(Ok(22)));
+ assert_eq!(on_machine(&panes, "devbox/logs"), Some(Ok(20)));
+ let why = on_machine(&panes, "devbox/9").unwrap().unwrap_err();
+ assert!(why.contains("no pane 9 on devbox"), "{}", why);
+ // A thread of this machine's is no machine.
+ assert_eq!(on_machine(&panes, "fix login/reviewer"), None);
+ assert_eq!(on_machine(&panes, "devbox"), None);
+ }
+
+ #[test]
+ fn duplicate_machine_labels_never_pick_the_first_pane() {
+ for second in ["devbox", "DevBox"] {
+ let panes = vec![on(20, "devbox", 3, None), on(21, second, 3, None)];
+ assert!(on_machine(&panes, "devbox/3")
+ .unwrap()
+ .unwrap_err()
+ .contains("ambiguous"));
+ }
+ }
+
+ #[test]
+ fn machine_labels_with_slashes_round_trip() {
+ let panes = vec![
+ on(20, "team/devbox", 3, Some("logs")),
+ on(21, "team", 3, None),
+ ];
+ assert_eq!(on_machine(&panes, "team/devbox/3"), Some(Ok(20)));
+ assert_eq!(on_machine(&panes, "TEAM/DEVBOX/logs"), Some(Ok(20)));
+ assert_eq!(on_machine(&panes, "team/3"), Some(Ok(21)));
+ }
+
fn panes() -> Vec<Candidate> {
vec![
pane(1, Some("reviewer"), "w-login", Some("fix login")),
diff --git a/wezterm/src/cli/wait.rs b/wezterm/src/cli/wait.rs
index c6274030..d605f4eb 100644
--- a/wezterm/src/cli/wait.rs
+++ b/wezterm/src/cli/wait.rs
@@ -48,8 +48,12 @@ impl WaitCommand {
pub async fn run(self, client: Client) -> anyhow::Result<()> {
let deadline = self.timeout.map(|t| Instant::now() + t);
let code = with_deadline(deadline, async {
- let pane_id =
- crate::cli::target::resolve(&client, self.pane_id, self.pane.as_deref()).await?;
+ let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
+ client.clone(),
+ self.pane_id,
+ self.pane.as_deref(),
+ )
+ .await?;
Ok(if self.command {
let before = shell_commands(&client, pane_id).await?;
// A command typed a moment ago may not have reached the shell.