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(gui): add tailscale to remote hosts

RoversX211eb5f6e452
diff --git a/thinkterm-core/src/ssh_hosts.rs b/thinkterm-core/src/ssh_hosts.rs
index 7a14fbfd..d540c5f6 100644
--- a/thinkterm-core/src/ssh_hosts.rs
+++ b/thinkterm-core/src/ssh_hosts.rs
@@ -12,13 +12,33 @@ pub type SshHostId = String;
/// The ssh option carrying a host's other addresses to the connection:
/// wezterm-ssh's `OTHER_ADDRESSES`.
pub const OTHER_ADDRESSES_OPTION: &str = "thinkterm_other_addresses";
+pub const NETWORK_OPTION: &str = "thinkterm_network";
pub const DEFAULT_MOSH_SERVER_COMMAND: &str = "mosh-server new -s -l LANG=en_US.UTF-8";
+#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(rename_all = "snake_case")]
+pub enum SshNetwork {
+ #[default]
+ System,
+ Tailnet,
+}
+
+impl SshNetwork {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::System => "system",
+ Self::Tailnet => "tailnet",
+ }
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SshHostSpec {
pub label: String,
pub host: String,
#[serde(default)]
+ pub network: SshNetwork,
+ #[serde(default)]
pub port: Option<u16>,
/// Other addresses the host answers at -- a LAN name, a Tailscale name,
/// a public address with a forwarded port -- tried after `host`, in
@@ -193,6 +213,7 @@ pub fn parse_system_ssh_config(content: &str) -> Vec<SshHostEntry> {
host: alias,
port: block.port,
other_addresses: Vec::new(),
+ network: Default::default(),
username: block.user.clone(),
identity_file: block.identity_file.clone(),
password: None,
@@ -294,7 +315,10 @@ pub fn endpoint(spec: &SshHostSpec) -> String {
}
pub fn ssh_domain_name(spec: &SshHostSpec) -> String {
- format!("ssh:{}", endpoint(spec))
+ match spec.network {
+ SshNetwork::System => format!("ssh:{}", endpoint(spec)),
+ SshNetwork::Tailnet => format!("ssh:tailnet:{}", endpoint(spec)),
+ }
}
/// The host's other addresses as they are tried: trimmed, without blanks,
@@ -325,6 +349,7 @@ pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {
.iter()
.map(|(key, value)| (key.to_lowercase(), value.clone()))
.collect::<HashMap<_, _>>();
+ ssh_option.insert(NETWORK_OPTION.into(), spec.network.as_str().into());
if let Some(identity) = &spec.identity_file {
if !identity.trim().is_empty() {
ssh_option.insert("identityfile".into(), identity.clone());
@@ -360,6 +385,34 @@ pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {
mod tests {
use super::*;
+ #[test]
+ fn a_saved_host_selects_one_network_for_all_its_addresses() {
+ assert_eq!(NETWORK_OPTION, wezterm_ssh::NETWORK);
+ let mut spec: SshHostSpec = serde_json::from_value(serde_json::json!({
+ "label": "server-a", "host": "100.64.0.2"
+ }))
+ .unwrap();
+ assert_eq!(spec.network, SshNetwork::System);
+ let system = build_ssh_domain(&spec);
+ assert_eq!(system.ssh_option[NETWORK_OPTION], "system");
+ spec.network = SshNetwork::Tailnet;
+ spec.other_addresses.push("server-a.example.ts.net".into());
+ spec.ssh_options
+ .insert(NETWORK_OPTION.into(), "system".into());
+ let tailnet = build_ssh_domain(&spec);
+ assert_eq!(tailnet.ssh_option[NETWORK_OPTION], "tailnet");
+ assert_eq!(
+ tailnet.ssh_option[OTHER_ADDRESSES_OPTION],
+ "server-a.example.ts.net"
+ );
+ assert_ne!(system.name, tailnet.name);
+ let saved = serde_json::to_string(&spec).unwrap();
+ assert_eq!(
+ serde_json::from_str::<SshHostSpec>(&saved).unwrap().network,
+ SshNetwork::Tailnet
+ );
+ }
+
#[test]
fn the_option_is_the_one_the_connection_reads() {
assert_eq!(OTHER_ADDRESSES_OPTION, wezterm_ssh::OTHER_ADDRESSES);
@@ -432,6 +485,7 @@ mod tests {
host: "example.test".into(),
port: Some(22),
other_addresses: Vec::new(),
+ network: Default::default(),
username: Some("root".into()),
identity_file: None,
password: None,
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index f186090d..e2e67eab 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -524,6 +524,10 @@ ssh-system-hosts = System-SSH ({ $count })
ssh-edit-host = Host bearbeiten
ssh-new-host = Neuer Host
ssh-field-name = Name
+ssh-field-network = Netzwerk
+ssh-network-system = System
+ssh-network-tailnet = Internes Tailnet
+ssh-error-tailnet-mosh = Mosh verwendet das Systemnetzwerk. Deaktiviere Mosh, bevor du das interne Tailnet auswählst.
ssh-field-host = Host
ssh-field-port = Port
ssh-field-other-addresses = Weitere Adressen
@@ -560,6 +564,54 @@ ssh-error-mosh-command = Mosh-Server-Befehl ist erforderlich
ssh-error-host-missing = Host existiert nicht mehr
ssh-error-save = Host konnte nicht gespeichert werden: { $error }
ssh-error-encrypt = Passwort konnte nicht verschlüsselt werden: { $error }
+# --- Remote-Hosts: die Tailscale-Gruppe und ihr Bereich ---
+ssh-group-tailscale = Tailscale
+ssh-group-tailscale-count = Tailscale ({ $count })
+ssh-tailscale-off = Aus
+ssh-tailscale-starting = Verbinde…
+ssh-tailscale-login = Anmeldung nötig
+ssh-tailscale-connected = Verbunden
+ssh-tailscale-failed = Nicht verbunden
+ssh-tailscale-elsewhere = Anderswo in Gebrauch
+ssh-tailscale-not-saved = Nicht gespeichert
+ssh-tailscale-online = Online
+ssh-tailscale-offline = Offline
+ssh-tailscale-added = Hinzugefügt
+ssh-tailscale-off-title = Die Rechner in Ihrem Tailnet erreichen
+ssh-tailscale-off-subtitle = Ohne die Tailscale-App
+ssh-tailscale-turn-on = Einschalten
+ssh-tailscale-login-description = Im Browser anmelden, um diesen Computer dem Tailnet hinzuzufügen.
+ssh-tailscale-login-button = Anmelden
+ssh-tailscale-starting-subtitle = Sobald verbunden, stehen die Rechner des Tailnets hier.
+ssh-tailscale-settings-button = Einstellungen
+ssh-tailscale-empty-title = Noch keine anderen Rechner im Tailnet
+ssh-tailscale-empty-subtitle = Geräte, die beitreten, erscheinen hier.
+ssh-tailscale-status = Status
+ssh-tailscale-state-off = Aus. Eingeschaltet läuft SSH zum Namen eines Tailnet-Rechners darüber.
+ssh-tailscale-state-connected = Verbunden als { $name } · { $address }
+ssh-tailscale-state-connected-no-address = Verbunden als { $name }
+ssh-tailscale-state-failed = Nicht verbunden: { $error }
+ssh-tailscale-state-elsewhere = Ein anderer ThinkTerm-Prozess auf diesem Computer hält dessen Knoten.
+ssh-tailscale-server-not-running = Der Hintergrunddienst, der dem Tailnet beitritt, läuft nicht; er wird gestartet …
+ssh-tailscale-serving-ssh = Rechner im Tailnet können sich per SSH mit diesem verbinden (thinkterm tailnet up).
+ssh-tailscale-save-error = Nicht gespeichert: { $error }
+ssh-tailscale-read-error = Die Einstellungen konnten nicht gelesen werden: { $error }
+ssh-tailscale-unreadable = Einstellungen unlesbar
+ssh-tailscale-login-section = Anmelden
+ssh-tailscale-login-open = Anmeldelink öffnen
+ssh-tailscale-login-copy = Link kopieren
+ssh-tailscale-copied = Kopiert
+ssh-tailscale-auth-key = Auth-Key (statt des Browsers)
+ssh-tailscale-auth-key-placeholder = tskey-auth-…
+ssh-tailscale-auth-key-saved = Gespeichert. Ein neuer ersetzt ihn
+ssh-tailscale-control = Steuerserver
+ssh-tailscale-control-placeholder = Leer für Tailscale, sonst Ihr Headscale
+ssh-tailscale-hostname = Name im Tailnet
+ssh-tailscale-hostname-placeholder = Automatisch, etwa thinkterm-1a2b
+ssh-tailscale-logout = Abmelden
+ssh-tailscale-logout-description = Verlässt das Tailnet und vergisst die Identität dieses Computers und den Auth-Key.
+settings-section-tailscale = Tailscale → Remote-Hosts
+settings-tailscale-needs-a-window = Öffnen Sie zuerst ein Terminalfenster — Tailscale wird auf dessen Seite „Remote-Hosts“ eingerichtet.
remote-thread-connecting-to = Verbinden mit { $endpoint }…
remote-thread-not-connected = Dieser SSH-Thread ist nicht verbunden.
remote-thread-connection = Verbindung
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index 8605c60b..6e84f60c 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -524,6 +524,10 @@ ssh-system-hosts = System SSH ({ $count })
ssh-edit-host = Edit Host
ssh-new-host = New Host
ssh-field-name = Name
+ssh-field-network = Network
+ssh-network-system = System
+ssh-network-tailnet = Built-in Tailnet
+ssh-error-tailnet-mosh = Mosh uses the system network. Turn off Mosh before selecting the built-in Tailnet.
ssh-field-host = Host
ssh-field-port = Port
ssh-field-other-addresses = Other addresses
@@ -560,6 +564,54 @@ ssh-error-mosh-command = Mosh server command is required
ssh-error-host-missing = Host no longer exists
ssh-error-save = Failed to save host: { $error }
ssh-error-encrypt = Failed to encrypt password: { $error }
+# --- Remote Hosts: the Tailscale group and its panel ---
+ssh-group-tailscale = Tailscale
+ssh-group-tailscale-count = Tailscale ({ $count })
+ssh-tailscale-off = Off
+ssh-tailscale-starting = Connecting…
+ssh-tailscale-login = Needs you to log in
+ssh-tailscale-connected = Connected
+ssh-tailscale-failed = Not connected
+ssh-tailscale-elsewhere = In use elsewhere
+ssh-tailscale-not-saved = Not saved
+ssh-tailscale-online = Online
+ssh-tailscale-offline = Offline
+ssh-tailscale-added = Added
+ssh-tailscale-off-title = Reach the machines in your tailnet
+ssh-tailscale-off-subtitle = No Tailscale app needed
+ssh-tailscale-turn-on = Turn On
+ssh-tailscale-login-description = Log in in a browser to add this computer to the tailnet.
+ssh-tailscale-login-button = Log In
+ssh-tailscale-starting-subtitle = Once connected, the tailnet's machines are listed here.
+ssh-tailscale-settings-button = Settings
+ssh-tailscale-empty-title = No other machines in the tailnet yet
+ssh-tailscale-empty-subtitle = Devices that join it show up here.
+ssh-tailscale-status = Status
+ssh-tailscale-state-off = Off. Once on, SSH to a tailnet machine's name goes through it.
+ssh-tailscale-state-connected = Connected as { $name } · { $address }
+ssh-tailscale-state-connected-no-address = Connected as { $name }
+ssh-tailscale-state-failed = Not connected: { $error }
+ssh-tailscale-state-elsewhere = Another ThinkTerm process on this computer holds its node.
+ssh-tailscale-server-not-running = The background service that joins the tailnet is not running; starting it…
+ssh-tailscale-serving-ssh = Machines in the tailnet can SSH into this one (thinkterm tailnet up).
+ssh-tailscale-save-error = Not saved: { $error }
+ssh-tailscale-read-error = The settings could not be read: { $error }
+ssh-tailscale-unreadable = Settings unreadable
+ssh-tailscale-login-section = Log In
+ssh-tailscale-login-open = Open Login Link
+ssh-tailscale-login-copy = Copy Link
+ssh-tailscale-copied = Copied
+ssh-tailscale-auth-key = Auth key (instead of the browser)
+ssh-tailscale-auth-key-placeholder = tskey-auth-…
+ssh-tailscale-auth-key-saved = Saved. Typing a new one replaces it
+ssh-tailscale-control = Control server
+ssh-tailscale-control-placeholder = Tailscale if empty, or your Headscale
+ssh-tailscale-hostname = Name in the tailnet
+ssh-tailscale-hostname-placeholder = Automatic, like thinkterm-1a2b
+ssh-tailscale-logout = Log Out
+ssh-tailscale-logout-description = Leaves, and forgets this computer's identity and auth key.
+settings-section-tailscale = Tailscale → Remote Hosts
+settings-tailscale-needs-a-window = Open a terminal window first -- Tailscale is set up on its Remote Hosts page.
remote-thread-connecting-to = Connecting to { $endpoint }…
remote-thread-not-connected = This SSH thread is not connected.
remote-thread-connection = Connection
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 2149f97c..eb2329b3 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -524,6 +524,10 @@ ssh-system-hosts = SSH système ({ $count })
ssh-edit-host = Modifier l’hôte
ssh-new-host = Nouvel hôte
ssh-field-name = Nom
+ssh-field-network = Réseau
+ssh-network-system = Système
+ssh-network-tailnet = Tailnet intégré
+ssh-error-tailnet-mosh = Mosh utilise le réseau du système. Désactivez Mosh avant de sélectionner le Tailnet intégré.
ssh-field-host = Hôte
ssh-field-port = Port
ssh-field-other-addresses = Autres adresses
@@ -560,6 +564,54 @@ ssh-error-mosh-command = La commande du serveur Mosh est obligatoire
ssh-error-host-missing = L’hôte n’existe plus
ssh-error-save = Impossible d’enregistrer l’hôte : { $error }
ssh-error-encrypt = Impossible de chiffrer le mot de passe : { $error }
+# --- Hôtes distants : le groupe Tailscale et son panneau ---
+ssh-group-tailscale = Tailscale
+ssh-group-tailscale-count = Tailscale ({ $count })
+ssh-tailscale-off = Désactivé
+ssh-tailscale-starting = Connexion…
+ssh-tailscale-login = Connexion requise
+ssh-tailscale-connected = Connecté
+ssh-tailscale-failed = Non connecté
+ssh-tailscale-elsewhere = Utilisé ailleurs
+ssh-tailscale-not-saved = Non enregistré
+ssh-tailscale-online = En ligne
+ssh-tailscale-offline = Hors ligne
+ssh-tailscale-added = Ajoutée
+ssh-tailscale-off-title = Joindre les machines de votre tailnet
+ssh-tailscale-off-subtitle = Sans l'app Tailscale
+ssh-tailscale-turn-on = Activer
+ssh-tailscale-login-description = Connectez-vous dans un navigateur pour ajouter cet ordinateur au tailnet.
+ssh-tailscale-login-button = Se connecter
+ssh-tailscale-starting-subtitle = Une fois connecté, les machines du tailnet sont listées ici.
+ssh-tailscale-settings-button = Réglages
+ssh-tailscale-empty-title = Aucune autre machine dans le tailnet pour l'instant
+ssh-tailscale-empty-subtitle = Les appareils qui le rejoignent apparaissent ici.
+ssh-tailscale-status = État
+ssh-tailscale-state-off = Désactivé. Une fois activé, SSH vers le nom d'une machine du tailnet passe par lui.
+ssh-tailscale-state-connected = Connecté en tant que { $name } · { $address }
+ssh-tailscale-state-connected-no-address = Connecté en tant que { $name }
+ssh-tailscale-state-failed = Non connecté : { $error }
+ssh-tailscale-state-elsewhere = Un autre processus ThinkTerm de cet ordinateur détient son nœud.
+ssh-tailscale-server-not-running = Le service d'arrière-plan qui rejoint le tailnet ne tourne pas ; démarrage…
+ssh-tailscale-serving-ssh = Les machines du tailnet peuvent se connecter en SSH à celle-ci (thinkterm tailnet up).
+ssh-tailscale-save-error = Non enregistré : { $error }
+ssh-tailscale-read-error = Les réglages n'ont pas pu être lus : { $error }
+ssh-tailscale-unreadable = Réglages illisibles
+ssh-tailscale-login-section = Connexion
+ssh-tailscale-login-open = Ouvrir le lien de connexion
+ssh-tailscale-login-copy = Copier le lien
+ssh-tailscale-copied = Copié
+ssh-tailscale-auth-key = Clé d'authentification (au lieu du navigateur)
+ssh-tailscale-auth-key-placeholder = tskey-auth-…
+ssh-tailscale-auth-key-saved = Enregistrée. En saisir une nouvelle la remplace
+ssh-tailscale-control = Serveur de contrôle
+ssh-tailscale-control-placeholder = Vide : Tailscale ; sinon votre Headscale
+ssh-tailscale-hostname = Nom dans le tailnet
+ssh-tailscale-hostname-placeholder = Automatique, comme thinkterm-1a2b
+ssh-tailscale-logout = Se déconnecter
+ssh-tailscale-logout-description = Quitte le tailnet et oublie l'identité de cet ordinateur et sa clé.
+settings-section-tailscale = Tailscale → Hôtes distants
+settings-tailscale-needs-a-window = Ouvrez d'abord une fenêtre de terminal : Tailscale se règle sur sa page Hôtes distants.
remote-thread-connecting-to = Connexion à { $endpoint }…
remote-thread-not-connected = Cette session SSH n’est pas connectée.
remote-thread-connection = Connexion
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 200d73c4..a2d48821 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -515,6 +515,10 @@ ssh-system-hosts = システム SSH({ $count })
ssh-edit-host = ホストを編集
ssh-new-host = 新しいホスト
ssh-field-name = 名前
+ssh-field-network = ネットワーク
+ssh-network-system = システム
+ssh-network-tailnet = 内蔵 Tailnet
+ssh-error-tailnet-mosh = Mosh はシステムのネットワークを使用します。内蔵 Tailnet を選ぶ前に Mosh をオフにしてください。
ssh-field-host = ホスト
ssh-field-port = ポート
ssh-field-other-addresses = その他のアドレス
@@ -551,6 +555,54 @@ ssh-error-mosh-command = Mosh サーバーコマンドは必須です
ssh-error-host-missing = ホストは存在しません
ssh-error-save = ホストを保存できません:{ $error }
ssh-error-encrypt = パスワードを暗号化できません:{ $error }
+# --- リモートホスト: Tailscale グループとそのパネル ---
+ssh-group-tailscale = Tailscale
+ssh-group-tailscale-count = Tailscale({ $count })
+ssh-tailscale-off = オフ
+ssh-tailscale-starting = 接続中…
+ssh-tailscale-login = ログインが必要
+ssh-tailscale-connected = 接続済み
+ssh-tailscale-failed = 未接続
+ssh-tailscale-elsewhere = 別のプロセスが使用中
+ssh-tailscale-not-saved = 保存できませんでした
+ssh-tailscale-online = オンライン
+ssh-tailscale-offline = オフライン
+ssh-tailscale-added = 追加済み
+ssh-tailscale-off-title = tailnet のマシンに接続
+ssh-tailscale-off-subtitle = Tailscale アプリは不要です
+ssh-tailscale-turn-on = オンにする
+ssh-tailscale-login-description = ブラウザでログインして、このコンピュータを tailnet に追加します。
+ssh-tailscale-login-button = ログイン
+ssh-tailscale-starting-subtitle = 接続すると、tailnet のマシンがここに表示されます。
+ssh-tailscale-settings-button = 設定
+ssh-tailscale-empty-title = tailnet にほかのマシンはまだありません
+ssh-tailscale-empty-subtitle = ほかのデバイスが参加するとここに表示されます。
+ssh-tailscale-status = 状態
+ssh-tailscale-state-off = オフ。オンにすると、tailnet のマシン名への SSH はここを通ります。
+ssh-tailscale-state-connected = 接続済み · { $name } · { $address }
+ssh-tailscale-state-connected-no-address = 接続済み · { $name }
+ssh-tailscale-state-failed = 未接続: { $error }
+ssh-tailscale-state-elsewhere = このコンピュータの別の ThinkTerm プロセスがノードを使用中です。
+ssh-tailscale-server-not-running = tailnet に参加するバックグラウンドサービスが動いていません。起動しています…
+ssh-tailscale-serving-ssh = tailnet のマシンからこのマシンへ SSH できます(thinkterm tailnet up)。
+ssh-tailscale-save-error = 保存できませんでした: { $error }
+ssh-tailscale-read-error = 設定ファイルを読めません: { $error }
+ssh-tailscale-unreadable = 設定を読めません
+ssh-tailscale-login-section = ログイン
+ssh-tailscale-login-open = ログインリンクを開く
+ssh-tailscale-login-copy = リンクをコピー
+ssh-tailscale-copied = コピーしました
+ssh-tailscale-auth-key = 認証キー(ブラウザの代わりに)
+ssh-tailscale-auth-key-placeholder = tskey-auth-…
+ssh-tailscale-auth-key-saved = 保存済み。新しいキーを入力すると置き換えます
+ssh-tailscale-control = コントロールサーバー
+ssh-tailscale-control-placeholder = 空欄なら Tailscale、Headscale は URL
+ssh-tailscale-hostname = tailnet での名前
+ssh-tailscale-hostname-placeholder = 自動(例: thinkterm-1a2b)
+ssh-tailscale-logout = ログアウト
+ssh-tailscale-logout-description = tailnet から抜け、このコンピュータの ID と認証キーを消去します。
+settings-section-tailscale = Tailscale → リモートホスト
+settings-tailscale-needs-a-window = 先にターミナルウィンドウを開いてください。Tailscale はその「リモートホスト」ページで設定します。
remote-thread-connecting-to = { $endpoint } に接続中…
remote-thread-not-connected = この SSH セッションは接続されていません。
remote-thread-connection = 接続
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index f0512d5b..a0b386c9 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -515,6 +515,10 @@ ssh-system-hosts = 系统 SSH({ $count })
ssh-edit-host = 编辑主机
ssh-new-host = 新建主机
ssh-field-name = 名称
+ssh-field-network = 网络
+ssh-network-system = 系统
+ssh-network-tailnet = 内置 Tailnet
+ssh-error-tailnet-mosh = Mosh 使用系统网络。选择内置 Tailnet 前,请先关闭 Mosh。
ssh-field-host = 主机
ssh-field-port = 端口
ssh-field-other-addresses = 其他地址
@@ -551,6 +555,54 @@ ssh-error-mosh-command = 必须填写 Mosh 服务器命令
ssh-error-host-missing = 主机已不存在
ssh-error-save = 无法保存主机:{ $error }
ssh-error-encrypt = 无法加密密码:{ $error }
+# --- 远程主机:Tailscale 这一组和它的面板 ---
+ssh-group-tailscale = Tailscale
+ssh-group-tailscale-count = Tailscale({ $count })
+ssh-tailscale-off = 未开启
+ssh-tailscale-starting = 正在连接…
+ssh-tailscale-login = 需要登录
+ssh-tailscale-connected = 已连接
+ssh-tailscale-failed = 没连上
+ssh-tailscale-elsewhere = 别的进程在用
+ssh-tailscale-not-saved = 没保存上
+ssh-tailscale-online = 在线
+ssh-tailscale-offline = 离线
+ssh-tailscale-added = 已添加
+ssh-tailscale-off-title = 连 tailnet 里的机器
+ssh-tailscale-off-subtitle = 不装 Tailscale 也能连
+ssh-tailscale-turn-on = 开启
+ssh-tailscale-login-description = 在浏览器里登录,把这台电脑加进 tailnet。
+ssh-tailscale-login-button = 登录
+ssh-tailscale-starting-subtitle = 连上以后,tailnet 里的机器会列在这里。
+ssh-tailscale-settings-button = 设置
+ssh-tailscale-empty-title = tailnet 里还没有别的机器
+ssh-tailscale-empty-subtitle = 别的设备加入以后会出现在这里。
+ssh-tailscale-status = 状态
+ssh-tailscale-state-off = 未开启。开启后,SSH 连 tailnet 里的机器名会走它。
+ssh-tailscale-state-connected = 已连接 · { $name } · { $address }
+ssh-tailscale-state-connected-no-address = 已连接 · { $name }
+ssh-tailscale-state-failed = 没连上:{ $error }
+ssh-tailscale-state-elsewhere = 这台电脑上另一个 ThinkTerm 进程正在用它的 tailnet 身份。
+ssh-tailscale-server-not-running = 负责加入 tailnet 的后台服务没在运行,正在启动它…
+ssh-tailscale-serving-ssh = tailnet 里的机器可以 SSH 到这台电脑(thinkterm tailnet up)。
+ssh-tailscale-save-error = 没保存上:{ $error }
+ssh-tailscale-read-error = 读不了设置文件:{ $error }
+ssh-tailscale-unreadable = 设置读不了
+ssh-tailscale-login-section = 登录
+ssh-tailscale-login-open = 打开登录链接
+ssh-tailscale-login-copy = 复制链接
+ssh-tailscale-copied = 已复制
+ssh-tailscale-auth-key = Auth key(不开浏览器时用)
+ssh-tailscale-auth-key-placeholder = tskey-auth-…
+ssh-tailscale-auth-key-saved = 已保存;输入新的会替换
+ssh-tailscale-control = 控制服务器
+ssh-tailscale-control-placeholder = 留空用 Tailscale;Headscale 填地址
+ssh-tailscale-hostname = 本机名字
+ssh-tailscale-hostname-placeholder = 自动起名,如 thinkterm-1a2b
+ssh-tailscale-logout = 退出登录
+ssh-tailscale-logout-description = 退出 tailnet,并在本机忘掉这台电脑的身份和 auth key。
+settings-section-tailscale = Tailscale → 远程主机
+settings-tailscale-needs-a-window = 先开一个终端窗口 —— Tailscale 在它的“远程主机”页里设置。
remote-thread-connecting-to = 正在连接到 { $endpoint }…
remote-thread-not-connected = 此 SSH 会话尚未连接。
remote-thread-connection = 连接
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 31a55b4d..9a72c520 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -56,6 +56,7 @@ mod native_paths;
mod native_settings;
mod notification_click;
mod overlay;
+mod page_poll;
mod perf;
mod plugins;
mod quad;
@@ -77,6 +78,7 @@ mod state_backup;
mod stats;
mod tab_icons;
mod tabbar;
+mod tailnet;
mod termwindow;
mod ui;
mod unicode_names;
@@ -218,6 +220,7 @@ fn run_ssh(opts: SshCommand) -> anyhow::Result<()> {
build_initial_mux(&config::configuration(), None, None)?;
let gui = crate::frontend::try_new()?;
+ crate::tailnet::start();
promise::spawn::spawn(async {
if let Err(err) = async_run_ssh(opts).await {
@@ -272,6 +275,7 @@ fn run_serial(config: config::ConfigHandle, opts: SerialCommand) -> anyhow::Resu
build_initial_mux(&config, None, None)?;
let gui = crate::frontend::try_new()?;
+ crate::tailnet::start();
promise::spawn::spawn(async {
if let Err(err) = async_run_serial(opts).await {
@@ -482,12 +486,19 @@ async fn spawn_tab_in_domain_if_mux_is_empty(
pub(crate) fn connect_domain_from_ssh_host(name: &str) -> anyhow::Result<Arc<dyn Domain>> {
let entry = crate::ssh_hosts::list_all_hosts()
.into_iter()
- .find(|entry| entry.spec.label == name || entry.id == name)
+ .find(|entry| {
+ entry.spec.label == name
+ || entry.id == name
+ || crate::ssh_hosts::connect_domain_name(&entry.spec) == name
+ })
.ok_or_else(|| {
anyhow!("invalid domain {name}: not in ssh_domains and not a saved SSH host")
})?;
let mut dom = crate::ssh_hosts::build_ssh_domain(&entry.spec);
- dom.name = name.to_string();
+ dom.name = match entry.spec.network {
+ crate::ssh_hosts::SshNetwork::System => name.to_string(),
+ crate::ssh_hosts::SshNetwork::Tailnet => crate::ssh_hosts::connect_domain_name(&entry.spec),
+ };
dom.multiplexing = SshMultiplexing::WezTerm;
dom.stored_password = entry
.spec
@@ -1448,6 +1459,9 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->
}
let gui = crate::frontend::try_new()?;
+ // Only now: up to here this process could still have handed the
+ // request to a running one and exited.
+ crate::tailnet::start();
let activity = Activity::new();
promise::spawn::spawn(async move {
@@ -1496,6 +1510,29 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->
})
.detach();
}
+ // And the Remote Hosts page; `tailscale` opens it on its Tailscale panel.
+ if let Some(page) = std::env::var_os("THINKTERM_OPEN_REMOTE_HOSTS") {
+ promise::spawn::spawn_into_main_thread(async move {
+ smol::Timer::after(std::time::Duration::from_millis(2500)).await;
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ let tailscale = page == "tailscale";
+ gui_window
+ .window
+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ move |term_window| {
+ if tailscale {
+ term_window.open_ssh_hosts_view_tailscale();
+ } else {
+ term_window.toggle_ssh_hosts_view();
+ }
+ },
+ )));
+ }
+ }
+ })
+ .detach();
+ }
gui.run_forever()
}
diff --git a/wezterm-gui/src/page_poll.rs b/wezterm-gui/src/page_poll.rs
new file mode 100644
index 00000000..ddd713b3
--- /dev/null
+++ b/wezterm-gui/src/page_poll.rs
@@ -0,0 +1,38 @@
+//! The wake-up a settings page that reads something every few seconds
+//! comes back by: what it shows changes elsewhere, and nothing else
+//! repaints it when that happens.
+
+use std::sync::Mutex;
+use std::time::Duration;
+use window::{Window, WindowOps};
+
+/// One wake-up at a time for a page. Asking again while one is pending only
+/// points it at the newest window, so a Settings window closed and opened
+/// again before the wake-up comes is the one it repaints.
+pub struct PollTimer {
+ pending: Mutex<Option<Window>>,
+}
+
+impl PollTimer {
+ pub const fn new() -> Self {
+ Self {
+ pending: Mutex::new(None),
+ }
+ }
+
+ /// Repaints `window` once `due_in` has passed, when the page reads
+ /// again. Asked from the page's paint alone, so leaving the page stops
+ /// it after one last tick.
+ pub fn arm(&'static self, window: Window, due_in: Duration) {
+ if self.pending.lock().unwrap().replace(window).is_some() {
+ return;
+ }
+ promise::spawn::spawn_into_main_thread(async move {
+ smol::Timer::after(due_in).await;
+ if let Some(window) = self.pending.lock().unwrap().take() {
+ window.invalidate();
+ }
+ })
+ .detach();
+ }
+}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 9ba91cc2..f5dee6e6 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -626,6 +626,10 @@ enum SettingsSection {
Workspaces,
Agents,
Web,
+ /// Not a page: what a search for it finds, which leads to the Tailscale
+ /// group in Remote Hosts, where the tailnet is set up beside its
+ /// machines.
+ Tailscale,
Archived,
Keymap,
CommandPalette,
@@ -759,6 +763,7 @@ impl SettingsSection {
Self::Workspaces => crate::i18n::tr("settings-section-workspaces"),
Self::Agents => crate::i18n::tr("settings-section-agents"),
Self::Web => crate::i18n::tr("settings-section-web"),
+ Self::Tailscale => crate::i18n::tr("settings-section-tailscale"),
Self::Archived => crate::i18n::tr("settings-section-archived"),
Self::Keymap => crate::i18n::tr("settings-section-keymap"),
Self::CommandPalette => crate::i18n::tr("settings-section-command-palette"),
@@ -782,6 +787,7 @@ impl SettingsSection {
Self::Workspaces => SettingsIcon::Workspaces,
Self::Agents => SettingsIcon::Agents,
Self::Web => SettingsIcon::Web,
+ Self::Tailscale => SettingsIcon::Tailscale,
Self::Archived => SettingsIcon::Archived,
Self::Keymap => SettingsIcon::Keymap,
Self::CommandPalette => SettingsIcon::CommandPalette,
@@ -807,6 +813,7 @@ impl SettingsSection {
Self::Workspaces => TileColor::Yellow,
Self::Agents => TileColor::Orange,
Self::Web => TileColor::Teal,
+ Self::Tailscale => TileColor::Blue,
Self::Archived => TileColor::Indigo,
Self::Keymap => TileColor::Gray,
Self::CommandPalette => TileColor::Blue,
@@ -850,6 +857,14 @@ impl SettingsSection {
"Port",
"Listener",
],
+ Self::Tailscale => &[
+ "Tailscale",
+ "Tailnet",
+ "Headscale",
+ "VPN",
+ "Auth Key",
+ "Control Server",
+ ],
Self::TabIcons => &[
"Tab Icons",
"Tab Icon",
@@ -1040,6 +1055,12 @@ impl SettingsSection {
}
}
+ /// A section that is no page here: picking it goes to where the thing
+ /// is set up instead.
+ fn leads_elsewhere(self) -> bool {
+ self == Self::Tailscale
+ }
+
fn matches_search(self, query: &str) -> bool {
self.label().to_lowercase().contains(query)
|| self
@@ -1067,6 +1088,19 @@ mod settings_search_tests {
let localized_label = crate::i18n::tr("settings-language").to_lowercase();
assert!(SettingsSection::General.matches_search(&localized_label));
}
+
+ #[test]
+ fn tailscale_is_found_by_a_search_but_listed_nowhere() {
+ // Its settings are in Remote Hosts; a search for them leads there.
+ assert!(!BASE_SECTIONS.contains(&SettingsSection::Tailscale));
+ assert!(!DEVELOPER_SECTIONS.contains(&SettingsSection::Tailscale));
+ assert!(SettingsSection::Tailscale.leads_elsewhere());
+ assert!(SettingsSection::Tailscale.matches_search("tailscale"));
+ assert!(SettingsSection::Tailscale.matches_search("headscale"));
+ assert!(BASE_SECTIONS
+ .iter()
+ .all(|section| !section.leads_elsewhere()));
+ }
}
/// How often a drag of the window-opacity slider shows itself in the windows:
@@ -4310,7 +4344,12 @@ impl SettingsWindow {
}
fn sync_selected_section_with_search(&mut self) {
- let sections = self.filtered_sections();
+ // A result that leads elsewhere is no page to show in the meantime.
+ let sections: Vec<SettingsSection> = self
+ .filtered_sections()
+ .into_iter()
+ .filter(|section| !section.leads_elsewhere())
+ .collect();
if !sections.is_empty() && !sections.contains(&self.selected) {
self.selected = sections[0];
if self.selected == SettingsSection::Terminal {
@@ -5046,6 +5085,22 @@ impl SettingsWindow {
.or_else(|| windows.into_iter().next())
}
+ /// Where a search for Tailscale leads: Remote Hosts with its Tailscale
+ /// panel open, in the window Settings was opened from -- brought
+ /// forward, for the page opens behind this window otherwise.
+ fn open_tailscale_in_remote_hosts(&mut self) {
+ let Some(gui_window) = self.color_scheme_picker_target() else {
+ self.status = crate::i18n::tr("settings-tailscale-needs-a-window");
+ return;
+ };
+ gui_window.window.focus();
+ gui_window
+ .window
+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ |term_window| term_window.open_ssh_hosts_view_tailscale(),
+ )));
+ }
+
fn refresh_chrome(&mut self) {
// The standalone window has no per-window overrides of its own, so it
// reads the configuration file's `ui_colors` rather than a terminal
@@ -5405,6 +5460,10 @@ impl SettingsWindow {
self.cleanup();
window.close();
}
+ SettingsAction::Select(section) if section.leads_elsewhere() => {
+ self.commit_focused_input();
+ self.open_tailscale_in_remote_hosts();
+ }
SettingsAction::Select(section) => {
self.commit_focused_input();
self.enter_section(section);
@@ -7592,6 +7651,8 @@ impl SettingsWindow {
SettingsSection::Workspaces => self.paint_workspaces(layers, x, max_width)?,
SettingsSection::Agents => self.paint_agents(layers, x, max_width)?,
SettingsSection::Web => self.paint_web(layers, x, max_width)?,
+ // Never selected: picking it opens Remote Hosts instead.
+ SettingsSection::Tailscale => {}
SettingsSection::Archived => self.paint_archived(layers, x, max_width)?,
SettingsSection::Keymap => self.paint_keymap(layers, x, max_width)?,
SettingsSection::CommandPalette => {
@@ -17709,10 +17770,16 @@ impl SettingsWindow {
if query.is_empty() {
return sections;
}
- sections
+ let mut found: Vec<SettingsSection> = sections
.into_iter()
.filter(|section| section.matches_search(&query))
- .collect()
+ .collect();
+ // Listed nowhere, found by a search: its settings moved to Remote
+ // Hosts, and someone looking here is shown the way.
+ if crate::tailnet::available() && SettingsSection::Tailscale.matches_search(&query) {
+ found.push(SettingsSection::Tailscale);
+ }
+ found
}
/// `layer_num` is the layer the whole field paints on -- frame, selection,
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
index d7b4e76a..09545129 100644
--- a/wezterm-gui/src/ssh_hosts.rs
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -24,7 +24,7 @@ use wezterm_ssh::{Session, SessionEvent};
pub use thinkterm_core::ssh_hosts::{
default_mosh_server_command, parse_other_addresses, ShellIntegrationFailure, SshHostEntry,
- SshHostId, SshHostSource, SshHostSpec, DEFAULT_MOSH_SERVER_COMMAND,
+ SshHostId, SshHostSource, SshHostSpec, SshNetwork, DEFAULT_MOSH_SERVER_COMMAND,
};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
@@ -481,13 +481,21 @@ pub fn build_mosh_args(spec: &SshHostSpec) -> Vec<String> {
args
}
-pub fn build_mosh_fallback_spawn(spec: &SshHostSpec) -> SpawnCommand {
- SpawnCommand {
+fn check_mosh_network(spec: &SshHostSpec) -> Result<()> {
+ if spec.network == SshNetwork::Tailnet {
+ bail!(crate::i18n::tr("ssh-error-tailnet-mosh"));
+ }
+ Ok(())
+}
+
+pub fn build_mosh_fallback_spawn(spec: &SshHostSpec) -> Result<SpawnCommand> {
+ check_mosh_network(spec)?;
+ Ok(SpawnCommand {
label: Some(format!("mosh {}", spec.label)),
args: Some(build_mosh_args(spec)),
domain: crate::local_sessions::local_spawn_domain(),
..Default::default()
- }
+ })
}
fn parse_mosh_connect(output: &str) -> Option<(u16, String)> {
@@ -586,6 +594,7 @@ async fn connect_mosh_bootstrap_session(spec: &SshHostSpec) -> Result<(Session,
}
pub async fn build_integrated_mosh_spawn(spec: &SshHostSpec) -> Result<SpawnCommand> {
+ check_mosh_network(spec)?;
let command = spec.mosh_server_command.trim();
if command.is_empty() {
bail!("Mosh server command is empty");
@@ -675,16 +684,55 @@ pub fn register_saved_hosts() {
}
}
+/// What a host on the embedded tailnet names its ThinkTerm Connect domain
+/// after: its address, so that saving it on the other network makes a new
+/// domain rather than finding the old one, connected the old way.
+const TAILNET_CONNECT_PREFIX: &str = "tailnet:";
+
+pub fn connect_domain_name(spec: &SshHostSpec) -> String {
+ match spec.network {
+ SshNetwork::System => spec.label.clone(),
+ SshNetwork::Tailnet => format!("{TAILNET_CONNECT_PREFIX}{}", endpoint(spec)),
+ }
+}
+
+/// What a ThinkTerm Connect domain is called on screen: the name of the host
+/// it belongs to. Only a domain of the embedded tailnet is named otherwise,
+/// and only a host saved here can be on it -- `~/.ssh/config` has none.
+pub fn connect_domain_label(domain_name: &str) -> String {
+ if domain_name.starts_with(TAILNET_CONNECT_PREFIX) {
+ if let Ok(store) = host_store() {
+ let specs = store.hosts.iter().map(|record| &record.spec);
+ if let Some(label) = label_for_connect_domain(specs, domain_name) {
+ return label;
+ }
+ }
+ }
+ domain_name.to_string()
+}
+
+fn label_for_connect_domain<'a>(
+ mut specs: impl Iterator<Item = &'a SshHostSpec>,
+ domain_name: &str,
+) -> Option<String> {
+ specs
+ .find(|spec| connect_domain_name(spec) == domain_name)
+ .map(|spec| spec.label.trim().to_string())
+ .filter(|label| !label.is_empty())
+}
+
/// Every name this host can be connected under.
///
/// A ThinkTerm Connect host attaches its persistent mux domain under the
-/// user's label; a direct host registers as `ssh:user@host`. A Space mirrored
+/// user's label (on the embedded tailnet, under its address: see
+/// `connect_domain_name`); a direct host registers as `ssh:user@host`. A Space mirrored
/// from that machine is tagged with whichever one it arrived through.
pub fn domain_names_for_host(spec: &SshHostSpec) -> Vec<String> {
let mut names = vec![ssh_domain_name(spec)];
- let label = spec.label.trim();
- if !label.is_empty() && !names.iter().any(|name| name == label) {
- names.push(label.to_string());
+ let name = connect_domain_name(spec);
+ let name = name.trim();
+ if !name.is_empty() && !names.iter().any(|other| other == name) {
+ names.push(name.to_string());
}
names
}
@@ -701,7 +749,7 @@ fn domain_name_is_reachable(domain_name: &str) -> bool {
}
list_all_hosts()
.into_iter()
- .any(|entry| entry.spec.label == domain_name || entry.id == domain_name)
+ .any(|entry| connect_domain_name(&entry.spec) == domain_name || entry.id == domain_name)
}
/// Drop this device's copy of every Space whose mux server it can no longer
@@ -800,6 +848,7 @@ fn parse_system_ssh_config_str(content: &str) -> Vec<SshHostEntry> {
host: alias.clone(),
port: block.port,
other_addresses: Vec::new(),
+ network: Default::default(),
username: block.user.clone(),
identity_file: block.identity_file.clone(),
password: None,
@@ -903,7 +952,7 @@ fn fnv1a(input: &str) -> u64 {
hash
}
-/// The record id for a host, derived from `user@host:port` alone -- so two
+/// The record id for a host, derived from its network and `user@host:port`: two
/// hosts that dial the same endpoint are the same record no matter what they
/// are named. Both save paths lean on that: see `try_create_host` and
/// `try_update_host`.
@@ -914,6 +963,10 @@ pub fn host_id_for_host(spec: &SshHostSpec) -> SshHostId {
spec.host,
spec.port.unwrap_or(22)
);
+ let key = match spec.network {
+ SshNetwork::System => key,
+ SshNetwork::Tailnet => format!("tailnet:{key}"),
+ };
format!("ssh-{:x}", fnv1a(&key))
}
@@ -925,6 +978,41 @@ fn system_host_id(alias: &str) -> SshHostId {
mod tests {
use super::*;
+ #[test]
+ fn the_same_address_on_two_networks_has_distinct_records_and_domains() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.label = "server-a".into();
+ spec.host = "100.64.0.2".into();
+ let id = host_id_for_host(&spec);
+ let domains = domain_names_for_host(&spec);
+ spec.network = SshNetwork::Tailnet;
+ assert_ne!(host_id_for_host(&spec), id);
+ assert!(domain_names_for_host(&spec)
+ .iter()
+ .all(|name| !domains.contains(name)));
+ assert!(build_mosh_fallback_spawn(&spec).is_err());
+ }
+
+ #[test]
+ fn a_tailnet_connect_domain_is_shown_by_its_hosts_name() {
+ let mut spec = spec_with_options(HashMap::new());
+ spec.label = "server-a".into();
+ spec.host = "100.64.0.2".into();
+ spec.network = SshNetwork::Tailnet;
+ let domain = connect_domain_name(&spec);
+ assert_ne!(domain, "server-a");
+ assert_eq!(
+ label_for_connect_domain(std::iter::once(&spec), &domain).as_deref(),
+ Some("server-a")
+ );
+ assert_eq!(
+ label_for_connect_domain(std::iter::once(&spec), "tailnet:server-b"),
+ None
+ );
+ // Any other domain is already called what it is named.
+ assert_eq!(connect_domain_label("server-b"), "server-b");
+ }
+
#[test]
fn a_failed_catalog_load_is_retried_before_editing() {
let mut cached = None;
@@ -1065,6 +1153,7 @@ Host prod *.internal
host: "example.com".to_string(),
port: None,
other_addresses: Vec::new(),
+ network: Default::default(),
username: None,
identity_file: None,
password: None,
diff --git a/wezterm-gui/src/tailnet.rs b/wezterm-gui/src/tailnet.rs
new file mode 100644
index 00000000..80715f4a
--- /dev/null
+++ b/wezterm-gui/src/tailnet.rs
@@ -0,0 +1,767 @@
+//! The app's side of an embedded tailnet (see thinkterm_tailnet): the
+//! Remote Hosts page turns it on and off and lists its machines, the
+//! machine's mux server holds the node -- started from here when the tailnet
+//! is on and no server runs -- and the page shows how the node is doing from
+//! the server's report. SSH sessions to the tailnet's machines go through the
+//! server's node. Built without the `tailnet` feature the page has no
+//! Tailscale group, and nothing here does anything.
+
+use std::net::IpAddr;
+
+// Built without the feature, nothing makes these: the group never shows.
+#[cfg_attr(not(feature = "tailnet"), allow(dead_code))]
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub enum State {
+ #[default]
+ Off,
+ Starting,
+ /// The link that approves this machine.
+ NeedsLogin(String),
+ Connected {
+ name: String,
+ address: Option<String>,
+ },
+ Failed(String),
+ /// Another ThinkTerm process on this machine holds the node.
+ HeldElsewhere,
+}
+
+/// What kind of device a machine of the tailnet is, as far as it says.
+#[cfg_attr(not(feature = "tailnet"), allow(dead_code))]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Device {
+ Mac,
+ IPhone,
+ IPad,
+ AppleTv,
+ Android,
+ Linux,
+ Windows,
+ /// Another system, or one that does not say.
+ #[default]
+ Unknown,
+}
+
+impl Device {
+ /// From the system a machine reports, as Tailscale names it ("macOS",
+ /// "iOS", "android", "linux", "windows"), and the model a phone or
+ /// tablet reports: an iPad says iOS too, and only its model ("iPad13,4")
+ /// tells it from an iPhone.
+ #[cfg_attr(not(feature = "tailnet"), allow(dead_code))]
+ pub fn reported(os: &str, model: &str) -> Self {
+ match os.trim().to_ascii_lowercase().as_str() {
+ "macos" | "darwin" => Self::Mac,
+ "ios" | "ipados" if model.trim().starts_with("iPad") => Self::IPad,
+ "ios" | "ipados" => Self::IPhone,
+ "tvos" => Self::AppleTv,
+ "android" => Self::Android,
+ "linux" => Self::Linux,
+ "windows" => Self::Windows,
+ _ => Self::Unknown,
+ }
+ }
+
+ /// What a card calls it. Names, the same in every language.
+ pub fn name(self) -> Option<&'static str> {
+ match self {
+ Self::Mac => Some("Mac"),
+ Self::IPhone => Some("iPhone"),
+ Self::IPad => Some("iPad"),
+ Self::AppleTv => Some("Apple TV"),
+ Self::Android => Some("Android"),
+ Self::Linux => Some("Linux"),
+ Self::Windows => Some("Windows"),
+ Self::Unknown => None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Machine {
+ pub name: String,
+ /// An unambiguous host address: what a host saved from the machine
+ /// connects to.
+ pub target: String,
+ /// Its name with the tailnet's domain; empty when the server did not
+ /// say.
+ pub fqdn: String,
+ pub addresses: Vec<IpAddr>,
+ pub online: Option<bool>,
+ pub device: Device,
+ /// Its Linux distribution ("ubuntu"), when it says.
+ pub distro: String,
+}
+
+impl Machine {
+ /// Whether `host`, a saved host's address, names this machine: by its
+ /// name, its name with the tailnet's domain, or one of its addresses.
+ pub fn answers_to(&self, host: &str) -> bool {
+ let host = host.trim().trim_end_matches('.');
+ if host.is_empty() {
+ return false;
+ }
+ match host.parse::<IpAddr>() {
+ Ok(ip) => self.addresses.contains(&ip),
+ Err(_) => {
+ self.name.eq_ignore_ascii_case(host)
+ || (!self.fqdn.is_empty()
+ && self.fqdn.trim_end_matches('.').eq_ignore_ascii_case(host))
+ }
+ }
+ }
+}
+
+/// What the Tailscale group and its panel show.
+#[derive(Clone, Debug, Default)]
+pub struct View {
+ pub enabled: bool,
+ /// `thinkterm tailnet up` let the tailnet's machines SSH into this one.
+ pub serves_ssh: bool,
+ /// A mux server is running to hold the node; the state and the machines
+ /// are its, as it last reported them.
+ pub server_running: bool,
+ pub control_url: String,
+ pub hostname: String,
+ pub has_auth_key: bool,
+ /// The machine has been a node, so there is an identity to forget.
+ pub has_identity: bool,
+ pub state: State,
+ /// Online ones first, then by name.
+ pub machines: Vec<Machine>,
+ /// Why the last change was not saved.
+ pub error: Option<String>,
+ /// Why the settings file could not be read, while it cannot: the page
+ /// shows the defaults meanwhile.
+ pub read_error: Option<String>,
+ /// The settings have been read and, while the tailnet is on, the
+ /// server's report too: until then what the page would show is a guess
+ /// -- the tailnet off, or no server running.
+ pub known: bool,
+}
+
+impl View {
+ /// The link that approves this machine, while the control server waits
+ /// for someone to.
+ pub fn login_url(&self) -> Option<&str> {
+ match &self.state {
+ State::NeedsLogin(url) if self.enabled => Some(url),
+ _ => None,
+ }
+ }
+}
+
+/// Online machines first, then by name, the way the group lists them.
+#[cfg_attr(not(feature = "tailnet"), allow(dead_code))]
+fn sort_machines(machines: &mut [Machine]) {
+ machines.sort_by(|a, b| {
+ let offline = |machine: &Machine| machine.online != Some(true);
+ offline(a)
+ .cmp(&offline(b))
+ .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
+ .then_with(|| a.target.cmp(&b.target))
+ });
+}
+
+pub use imp::*;
+
+#[cfg(feature = "tailnet")]
+mod imp {
+ use super::{Device, Machine, State, View};
+ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+ use std::sync::{LazyLock, Mutex};
+ use std::time::{Duration, Instant};
+ use thinkterm_tailnet::{Peer, Report, Settings, Status, Summary};
+ use window::{Window, WindowOps};
+
+ /// What the page paints from, until it goes (see `release`). The
+ /// settings are read without their secrets.
+ #[derive(Default)]
+ struct Cache {
+ settings: Summary,
+ server: Option<Report>,
+ error: Option<String>,
+ refreshed_at: Option<Instant>,
+ reading: bool,
+ /// Bumped by every change: a read begun before one carries the
+ /// settings from before it, and is not painted over them.
+ generation: u64,
+ /// The number of the last change saved, or tried: they are saved
+ /// in the order they were made.
+ saved_through: u64,
+ /// The changes that could not be saved since one last was, latest
+ /// last: each field whose change is among them keeps what was typed,
+ /// and `error` says why the last could not. A few are kept, one for
+ /// each field the page has and some to spare.
+ failed: std::collections::VecDeque<u64>,
+ /// Why the settings file could not be read when last read.
+ read_error: Option<String>,
+ /// The window of the page that read last, repainted when a change
+ /// is in.
+ window: Option<Window>,
+ /// The settings have been read, here or at launch. They outlast a
+ /// page; the server's report does not.
+ settings_known: bool,
+ server_known: bool,
+ }
+
+ static CACHE: LazyLock<Mutex<Cache>> = LazyLock::new(Default::default);
+
+ type Change = Box<dyn FnOnce(&mut Settings) + Send>;
+
+ /// Numbers the changes as they are made.
+ static MADE: AtomicU64 = AtomicU64::new(0);
+
+ /// The changes waiting to be saved. One saver takes them in the order
+ /// they were made, so that an earlier change landing after a later one
+ /// cannot undo it: a switch turned on just before Log out, say.
+ static CHANGES: LazyLock<smol::channel::Sender<(u64, Change)>> = LazyLock::new(|| {
+ let (changes, waiting) = smol::channel::unbounded::<(u64, Change)>();
+ promise::spawn::spawn(async move {
+ while let Ok((number, change)) = waiting.recv().await {
+ save(number, change).await;
+ }
+ })
+ .detach();
+ changes
+ });
+
+ /// How often the page reads the settings file and the server's report
+ /// again while it is on screen: both can change from outside this
+ /// process.
+ const POLL_INTERVAL: Duration = Duration::from_secs(2);
+
+ /// How long after launch the app looks for a server to hold the node:
+ /// by then the server local sessions run in is up, and holds it.
+ const LAUNCH_WAIT: Duration = Duration::from_secs(5);
+
+ /// How soon after starting a mux server the app may start one again: a
+ /// daemonizing server takes a moment to answer on its socket.
+ const SERVER_RETRY: Duration = Duration::from_secs(10);
+
+ /// How many failed changes are remembered (see `Cache::failed`).
+ const FAILURES_KEPT: usize = 8;
+
+ /// Whether this build can join a tailnet, and so has the group.
+ pub fn available() -> bool {
+ thinkterm_tailnet::SUPPORTED
+ }
+
+ /// From now on: try the tailnet first for every new SSH connection, and
+ /// keep a mux server running to hold the node while the tailnet is on.
+ /// A host that is not one of the tailnet's machines, or one asked for
+ /// while the tailnet is off, goes out as before.
+ pub fn start() {
+ if !available() {
+ return;
+ }
+ thinkterm_tailnet::use_for_ssh();
+ let spawned = std::thread::Builder::new()
+ .name("tailnet-launch".into())
+ .spawn(|| {
+ seed_settings();
+ std::thread::sleep(LAUNCH_WAIT);
+ if thinkterm_tailnet::load_summary().is_ok_and(|settings| settings.enabled) {
+ ensure_server();
+ }
+ });
+ if let Err(err) = spawned {
+ log::warn!("tailnet: {err}");
+ }
+ }
+
+ /// Reads the settings as the app starts, so that a page painting before
+ /// its own read lands shows the switch as the file has it rather than
+ /// off. A change made meanwhile, or a read landed, wins.
+ fn seed_settings() {
+ let asked_at = CACHE.lock().unwrap().generation;
+ let Ok(settings) = thinkterm_tailnet::load_summary() else {
+ return;
+ };
+ let mut cache = CACHE.lock().unwrap();
+ if cache.generation == asked_at && !cache.settings_known {
+ cache.settings = settings;
+ cache.settings_known = true;
+ }
+ }
+
+ /// Starts a mux server to hold the node unless one is running, the way
+ /// local sessions start theirs; tried at most every SERVER_RETRY. One
+ /// started here is not this app's to stop: it holds the node for every
+ /// ThinkTerm process on the machine.
+ fn ensure_server() {
+ static TRIED: Mutex<Option<Instant>> = Mutex::new(None);
+ {
+ let mut tried = TRIED.lock().unwrap();
+ if tried.is_some_and(|at| at.elapsed() < SERVER_RETRY) {
+ return;
+ }
+ *tried = Some(Instant::now());
+ }
+ let spawned = std::thread::Builder::new()
+ .name("tailnet-server".into())
+ .spawn(|| {
+ let config = config::configuration();
+ let Some(unix) = crate::local_sessions::candidate(&config) else {
+ log::warn!("tailnet: no unix domain to start a mux server for");
+ return;
+ };
+ if wezterm_mux_server_impl::local::someone_listens(&unix.socket_path()) {
+ return;
+ }
+ // Nothing but the node: no shell for a workspace nothing shows.
+ if let Err(err) =
+ wezterm_client::client::spawn_server(&unix, &["--no-initial-pane"])
+ {
+ log::warn!("tailnet: starting the mux server: {err:#}");
+ }
+ });
+ if let Err(err) = spawned {
+ log::warn!("tailnet: {err}");
+ }
+ }
+
+ pub fn view() -> View {
+ let (settings, server, error, read_error, settings_known, server_known) = {
+ let cache = CACHE.lock().unwrap();
+ (
+ cache.settings.clone(),
+ cache.server.clone(),
+ cache.error.clone(),
+ cache.read_error.clone(),
+ cache.settings_known,
+ cache.server_known,
+ )
+ };
+ let known = settings_known && (server_known || !settings.enabled);
+ let server_running = server.is_some();
+ let (status, peers) = server
+ .map(|report| (report.status, report.peers))
+ .unwrap_or_default();
+ let mut machines: Vec<Machine> = peers.iter().map(machine).collect();
+ super::sort_machines(&mut machines);
+ View {
+ enabled: settings.enabled,
+ serves_ssh: settings.serve_ssh,
+ server_running,
+ control_url: settings.control_url.unwrap_or_default(),
+ hostname: settings.hostname.unwrap_or_default(),
+ has_auth_key: settings.has_auth_key,
+ has_identity: settings.has_node_keys,
+ state: match status {
+ Status::Off => State::Off,
+ Status::Starting => State::Starting,
+ Status::NeedsLogin { url } => State::NeedsLogin(url),
+ Status::Connected { name, address } => State::Connected {
+ name,
+ address: address.map(|address| address.to_string()),
+ },
+ Status::Failed { error } => State::Failed(error),
+ Status::HeldElsewhere => State::HeldElsewhere,
+ },
+ machines,
+ error,
+ read_error,
+ known,
+ }
+ }
+
+ fn machine(peer: &Peer) -> Machine {
+ Machine {
+ name: peer.name.clone(),
+ target: if peer.fqdn.is_empty() {
+ peer.address()
+ .map(|address| address.to_string())
+ .unwrap_or_else(|| peer.name.clone())
+ } else {
+ peer.fqdn.clone()
+ },
+ fqdn: peer.fqdn.clone(),
+ addresses: peer
+ .ipv4
+ .map(std::net::IpAddr::V4)
+ .into_iter()
+ .chain(peer.ipv6.map(std::net::IpAddr::V6))
+ .collect(),
+ online: peer.online,
+ device: Device::reported(&peer.os, &peer.model),
+ distro: peer.distro.clone(),
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn same_short_names_keep_distinct_connection_targets() {
+ let first = Peer {
+ name: "server-a".into(),
+ fqdn: "server-a.first.example".into(),
+ ipv4: Some(std::net::Ipv4Addr::new(100, 64, 0, 2)),
+ ipv6: None,
+ online: Some(true),
+ ..Default::default()
+ };
+ let second = Peer {
+ fqdn: "server-a.second.example".into(),
+ ipv4: Some(std::net::Ipv4Addr::new(100, 64, 0, 3)),
+ ..first.clone()
+ };
+ assert_eq!(machine(&first).name, machine(&second).name);
+ assert_ne!(machine(&first).target, machine(&second).target);
+ assert!(first.answers_to(&machine(&first).target));
+ assert!(!second.answers_to(&machine(&first).target));
+ assert!(second.answers_to(&machine(&second).target));
+ let unnamed = Peer {
+ fqdn: String::new(),
+ ..second
+ };
+ assert_eq!(machine(&unnamed).target, "100.64.0.3");
+ }
+
+ #[test]
+ fn a_machine_answers_to_what_its_peer_does() {
+ let peer = Peer {
+ name: "server-a".into(),
+ fqdn: "server-a.example.ts.net".into(),
+ ipv4: Some(std::net::Ipv4Addr::new(100, 64, 0, 2)),
+ ipv6: Some("fd7a:115c:a1e0::2".parse().unwrap()),
+ online: Some(false),
+ os: "linux".into(),
+ distro: "debian".into(),
+ ..Default::default()
+ };
+ let machine = machine(&peer);
+ for host in [
+ "server-a",
+ "SERVER-A",
+ "server-a.example.ts.net.",
+ "100.64.0.2",
+ "fd7a:115c:a1e0:0::2",
+ "server-b",
+ "100.64.0.3",
+ ] {
+ assert_eq!(machine.answers_to(host), peer.answers_to(host), "{host}");
+ }
+ assert!(!machine.answers_to(""));
+ assert_eq!(machine.device, Device::Linux);
+ assert_eq!(machine.distro, "debian");
+ }
+ }
+
+ /// Whether the page should read the files again.
+ pub fn poll_is_due() -> bool {
+ let cache = CACHE.lock().unwrap();
+ !cache.reading
+ && cache
+ .refreshed_at
+ .is_none_or(|at| at.elapsed() >= POLL_INTERVAL)
+ }
+
+ /// When the page should paint again to read the files: None while a
+ /// read is out, which repaints when it lands.
+ pub fn next_poll_at() -> Option<Instant> {
+ let cache = CACHE.lock().unwrap();
+ if cache.reading {
+ return None;
+ }
+ Some(
+ cache
+ .refreshed_at
+ .map(|at| at + POLL_INTERVAL)
+ .unwrap_or_else(Instant::now),
+ )
+ }
+
+ /// Reads the settings and the server's report off the UI thread, then
+ /// repaints `window`. One read at a time. With the tailnet on and no
+ /// server to report, one is started.
+ pub fn refresh(window: Window) {
+ let asked_at = {
+ let mut cache = CACHE.lock().unwrap();
+ cache.window = Some(window.clone());
+ if std::mem::replace(&mut cache.reading, true) {
+ return;
+ }
+ cache.generation
+ };
+ promise::spawn::spawn(async move {
+ let (settings, server) = smol::unblock(|| {
+ (
+ thinkterm_tailnet::load_summary(),
+ thinkterm_tailnet::read_live_report(),
+ )
+ })
+ .await;
+ if server.is_none() && settings.as_ref().is_ok_and(|settings| settings.enabled) {
+ ensure_server();
+ }
+ {
+ let mut cache = CACHE.lock().unwrap();
+ cache.reading = false;
+ if cache.generation == asked_at {
+ match settings {
+ Ok(settings) => {
+ cache.settings = settings;
+ cache.read_error = None;
+ }
+ Err(err) => {
+ log::warn!("tailnet: {err:#}");
+ cache.read_error = Some(format!("{err:#}"));
+ }
+ }
+ cache.server = server;
+ cache.refreshed_at = Some(Instant::now());
+ // Read, if not well: a file that does not parse shows
+ // as the defaults, as it did before.
+ cache.settings_known = true;
+ cache.server_known = true;
+ } else {
+ // A change landed meanwhile, or the page went: read
+ // again at the next paint.
+ cache.refreshed_at = None;
+ }
+ }
+ window.invalidate();
+ })
+ .detach();
+ }
+
+ /// How many Remote Hosts pages are open, each window having its own.
+ static PAGES: AtomicUsize = AtomicUsize::new(0);
+
+ /// Held by each open Remote Hosts page: the last to close lets go of
+ /// what they showed (see `release`).
+ pub struct Page(());
+
+ impl Page {
+ pub fn open() -> Self {
+ PAGES.fetch_add(1, Ordering::SeqCst);
+ Self(())
+ }
+ }
+
+ impl Drop for Page {
+ fn drop(&mut self) {
+ if PAGES.fetch_sub(1, Ordering::SeqCst) == 1 {
+ release();
+ }
+ }
+ }
+
+ /// Lets go of what the pages showed once the last is gone: the server's
+ /// list of machines, the last error and the window. The settings stay, a
+ /// few short fields, so that coming back paints them at once; they are
+ /// read afresh as it does.
+ fn release() {
+ let mut cache = CACHE.lock().unwrap();
+ cache.server = None;
+ cache.server_known = false;
+ cache.error = None;
+ cache.failed.clear();
+ cache.read_error = None;
+ cache.refreshed_at = None;
+ cache.window = None;
+ // A read still out lands as one from before.
+ cache.generation += 1;
+ }
+
+ /// Queues a change to be saved off the UI thread -- the file is locked,
+ /// and waited onto the disk -- after those made before it. Returns its
+ /// number (see `saved`).
+ fn change(change: impl FnOnce(&mut Settings) + Send + 'static) -> u64 {
+ CACHE.lock().unwrap().generation += 1;
+ let number = MADE.fetch_add(1, Ordering::SeqCst) + 1;
+ if CHANGES.try_send((number, Box::new(change))).is_err() {
+ log::warn!("tailnet: the settings change was not saved");
+ }
+ number
+ }
+
+ /// Saves one change and repaints once it is in. Whatever went wrong is
+ /// shown until the next change is saved. With the tailnet on, a server
+ /// is started to act on it if none runs.
+ async fn save(number: u64, change: Change) {
+ let saved = smol::unblock(move || {
+ thinkterm_tailnet::update(change).map(|settings| settings.summary())
+ })
+ .await;
+ if saved.as_ref().is_ok_and(|settings| settings.enabled) {
+ ensure_server();
+ }
+ let window = {
+ let mut cache = CACHE.lock().unwrap();
+ cache.generation += 1;
+ cache.refreshed_at = None;
+ cache.saved_through = number;
+ match saved {
+ Ok(settings) => {
+ cache.settings = settings;
+ cache.settings_known = true;
+ cache.error = None;
+ cache.failed.clear();
+ cache.read_error = None;
+ }
+ Err(err) => {
+ cache.error = Some(format!("{err:#}"));
+ if cache.failed.len() == FAILURES_KEPT {
+ cache.failed.pop_front();
+ }
+ cache.failed.push_back(number);
+ }
+ }
+ cache.window.clone()
+ };
+ if let Some(window) = window {
+ window.invalidate();
+ }
+ }
+
+ /// Whether change `number` is in: None while it is still to be saved,
+ /// Some(false) once it could not be, until another change is saved.
+ pub fn saved(number: u64) -> Option<bool> {
+ let cache = CACHE.lock().unwrap();
+ (cache.saved_through >= number).then(|| !cache.failed.contains(&number))
+ }
+
+ /// The switch: on has the mux server join; off has it leave, and closes
+ /// the machine to SSH from the tailnet if `thinkterm tailnet up` had
+ /// opened it -- the switch never opens it. Decided on the file as it is
+ /// when saved, so two clicks before the first is in make two changes.
+ pub fn toggle() {
+ change(|settings| {
+ settings.enabled = !settings.enabled;
+ if !settings.enabled {
+ settings.serve_ssh = false;
+ }
+ });
+ }
+
+ /// Has the mux server join, whatever the file said: the button that
+ /// offers it shows while the tailnet is off, and a second click before
+ /// the first is in changes nothing.
+ pub fn turn_on() {
+ change(|settings| settings.enabled = true);
+ }
+
+ /// Empty goes back to Tailscale's own (see Settings::normalize).
+ /// Returns the change's number (see `saved`).
+ pub fn set_control_url(text: &str) -> u64 {
+ let text = text.to_string();
+ change(|settings| settings.control_url = Some(text))
+ }
+
+ /// Empty goes back to the automatic name. Returns the change's number.
+ pub fn set_hostname(text: &str) -> u64 {
+ let text = text.to_string();
+ change(|settings| settings.hostname = Some(text))
+ }
+
+ /// An empty key leaves the saved one as it is. Returns the change's
+ /// number, when there is one.
+ pub fn set_auth_key(text: &str) -> Option<u64> {
+ if text.trim().is_empty() {
+ return None;
+ }
+ let key = text.to_string();
+ Some(change(|settings| settings.auth_key = Some(key)))
+ }
+
+ /// Leaves, and forgets the machine's identity and the auth key: the
+ /// next join is a new machine.
+ pub fn logout() {
+ change(|settings| {
+ settings.enabled = false;
+ settings.serve_ssh = false;
+ settings.auth_key = None;
+ settings.node_keys = None;
+ });
+ }
+}
+
+#[cfg(not(feature = "tailnet"))]
+mod imp {
+ use super::View;
+ use std::time::Instant;
+ use window::Window;
+
+ pub fn available() -> bool {
+ false
+ }
+ pub fn start() {}
+ pub fn view() -> View {
+ View::default()
+ }
+ pub fn poll_is_due() -> bool {
+ false
+ }
+ pub fn next_poll_at() -> Option<Instant> {
+ None
+ }
+ pub fn refresh(_window: Window) {}
+ pub struct Page;
+ impl Page {
+ pub fn open() -> Self {
+ Self
+ }
+ }
+ pub fn saved(_number: u64) -> Option<bool> {
+ Some(true)
+ }
+ pub fn toggle() {}
+ pub fn turn_on() {}
+ pub fn set_control_url(_text: &str) -> u64 {
+ 0
+ }
+ pub fn set_hostname(_text: &str) -> u64 {
+ 0
+ }
+ pub fn set_auth_key(_text: &str) -> Option<u64> {
+ None
+ }
+ pub fn logout() {}
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_device_is_told_by_its_system_and_model() {
+ assert_eq!(Device::reported("macOS", ""), Device::Mac);
+ assert_eq!(Device::reported("iOS", "iPhone15,2"), Device::IPhone);
+ assert_eq!(Device::reported("iOS", "iPad13,4"), Device::IPad);
+ // An iOS device that names no model is far more often a phone.
+ assert_eq!(Device::reported("iOS", ""), Device::IPhone);
+ assert_eq!(Device::reported("tvOS", "AppleTV11,1"), Device::AppleTv);
+ assert_eq!(Device::reported("android", "Pixel 8"), Device::Android);
+ assert_eq!(Device::reported("linux", ""), Device::Linux);
+ assert_eq!(Device::reported("windows", ""), Device::Windows);
+ assert_eq!(Device::reported("freebsd", ""), Device::Unknown);
+ // A report from before machines said: nothing to go by.
+ assert_eq!(Device::reported("", ""), Device::Unknown);
+ assert_eq!(Device::Unknown.name(), None);
+ }
+
+ fn machine(name: &str, online: Option<bool>) -> Machine {
+ Machine {
+ name: name.into(),
+ target: format!("{name}.example.ts.net"),
+ online,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn online_machines_come_first_then_by_name() {
+ let mut machines = vec![
+ machine("build-box", Some(false)),
+ machine("Server-b", Some(true)),
+ machine("devbox", None),
+ machine("server-a", Some(true)),
+ ];
+ sort_machines(&mut machines);
+ let names: Vec<&str> = machines.iter().map(|m| m.name.as_str()).collect();
+ assert_eq!(names, ["server-a", "Server-b", "build-box", "devbox"]);
+ }
+}
diff --git a/wezterm-gui/src/termwindow/content_view.rs b/wezterm-gui/src/termwindow/content_view.rs
index 48c7ad9e..7aed871e 100644
--- a/wezterm-gui/src/termwindow/content_view.rs
+++ b/wezterm-gui/src/termwindow/content_view.rs
@@ -554,6 +554,11 @@ pub(crate) trait ContentView {
/// Default is a no-op; only the SSH hosts view reacts.
fn begin_new_remote_host(&mut self) {}
+ /// Send an already-open hosts page to its Tailscale panel: where a
+ /// search for Tailscale in Settings leads. Default is a no-op; only the
+ /// SSH hosts view reacts.
+ fn show_tailscale_panel(&mut self) {}
+
/// Run one entry of that page's card menu. Default is a no-op; only the
/// remote hosts page reacts.
fn run_remote_host_command(
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 36784071..df2985b3 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -8413,12 +8413,34 @@ impl TermWindow {
}
None => {
self.open_content_view(Box::new(
- crate::termwindow::ssh_hosts_view::SshHostsView::new_host(),
+ crate::termwindow::ssh_hosts_view::SshHostsView::new_host()
+ .in_window(self.window.clone()),
));
}
}
}
+ /// Open the SSH hosts page on its Tailscale panel: where a search for
+ /// Tailscale in Settings leads. Like the new-host entry, it never closes
+ /// an open page.
+ pub(crate) fn open_ssh_hosts_view_tailscale(&mut self) {
+ let key = crate::termwindow::ssh_hosts_view::SSH_HOSTS_CONTENT_VIEW_KEY;
+ let id = match self.content_view_id_for_key(key) {
+ Some(id) => {
+ self.activate_content_view(id);
+ id
+ }
+ None => self.open_content_view(Box::new(
+ crate::termwindow::ssh_hosts_view::SshHostsView::new()
+ .in_window(self.window.clone()),
+ )),
+ };
+ if let Some(view) = self.content_view_mut_by_id(id) {
+ view.show_tailscale_panel();
+ }
+ self.invalidate_window();
+ }
+
/// Toggle the SSH hosts content view (sidebar button / OpenSshHosts).
pub(crate) fn toggle_ssh_hosts_view(&mut self) {
let key = crate::termwindow::ssh_hosts_view::SSH_HOSTS_CONTENT_VIEW_KEY;
@@ -8428,7 +8450,8 @@ impl TermWindow {
self.activate_content_view(id);
} else {
self.open_content_view(Box::new(
- crate::termwindow::ssh_hosts_view::SshHostsView::new(),
+ crate::termwindow::ssh_hosts_view::SshHostsView::new()
+ .in_window(self.window.clone()),
));
}
}
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index c775565a..c66724da 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -6685,7 +6685,7 @@ impl super::TermWindow {
// in its dedicated Space — the same flow as `thinkterm connect
// <name>` — rather than opening a direct-ssh remote thread.
if spec.multiplexing && !spec.use_mosh {
- let name = spec.label.clone();
+ let name = crate::ssh_hosts::connect_domain_name(&spec);
// These hosts used to skip OS detection entirely: the branch
// returned before anything read `detect_os`, and both detection
// call sites downcast to `RemoteSshDomain`, which a mux client
@@ -6699,7 +6699,7 @@ impl super::TermWindow {
promise::spawn::spawn(async move {
let domain = match Mux::get().get_domain_by_name(&name) {
Some(domain) => domain,
- None => match crate::connect_domain_from_ssh_host(&name) {
+ None => match crate::connect_domain_from_ssh_host(&host_id) {
Ok(domain) => domain,
Err(err) => {
log::error!("connect {name}: {err:#}");
@@ -6802,6 +6802,18 @@ impl super::TermWindow {
return false;
};
+ let fallback_spawn = match crate::ssh_hosts::build_mosh_fallback_spawn(&spec) {
+ Ok(spawn) => spawn,
+ Err(err) => {
+ if let Some(view_id) = view_id {
+ self.fail_remote_connect(view_id, &format!("{err:#}"));
+ } else {
+ log::error!("cannot connect with Mosh: {err:#}");
+ }
+ return true;
+ }
+ };
+
self.snapshot_active_workspace_thread_layout();
if view_id.is_none() {
self.workspace_sidebar_pending_thread_selection = None;
@@ -6842,7 +6854,6 @@ impl super::TermWindow {
let window = self.window.clone();
let thread_id_for_task = thread_id.clone();
let label = spec.label.clone();
- let fallback_spawn = crate::ssh_hosts::build_mosh_fallback_spawn(&spec);
let bootstrap_spec = spec.clone();
let cancel_token_for_task = cancel_token.clone();
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
index 8aa05aa9..e86278f8 100644
--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -7,9 +7,14 @@
//! [`SshViewOutcome`] so `TermWindow` integration stays minimal.
use crate::quad::{HeapQuadAllocator, QuadClipRect, TripleLayerQuadAllocator};
-use crate::ssh_hosts::{self, ShellIntegrationFailure, SshHostEntry, SshHostSource, SshHostSpec};
+use crate::ssh_hosts::{
+ self, ShellIntegrationFailure, SshHostEntry, SshHostSource, SshHostSpec, SshNetwork,
+};
+use crate::tailnet::{
+ Device, Machine as TailnetMachine, State as TailnetState, View as TailnetView,
+};
use crate::termwindow::content_view::{ContentView, ContentViewResponse, RemoteHostCommand};
-use crate::termwindow::ui::icons::{distro_to_icon, SvgIcon};
+use crate::termwindow::ui::icons::{distro_to_icon, BrandIcon, SvgIcon};
use crate::termwindow::ui::right_sidebar::wrap_snippet_text_for_width;
use crate::termwindow::TermWindow;
use crate::ui::anim::Easing;
@@ -25,11 +30,11 @@ use crate::utilsprites::RenderMetrics;
use crate::workspace_threads;
use fluent_bundle::FluentArgs;
use std::rc::Rc;
-use std::time::Instant;
+use std::time::{Duration, Instant};
use wezterm_font::LoadedFont;
use wezterm_term::{KeyCode, KeyModifiers};
use window::color::LinearRgba;
-use window::{MouseEvent, MouseEventKind as WMEK, MousePress, RectF};
+use window::{MouseEvent, MouseEventKind as WMEK, MousePress, RectF, Window};
pub(crate) const SSH_HOSTS_CONTENT_VIEW_KEY: &str = "ssh-hosts";
@@ -138,6 +143,21 @@ const DOUBLE_CLICK: std::time::Duration = std::time::Duration::from_millis(450);
/// How far the pointer may drift between the two clicks of a double click.
const DOUBLE_CLICK_SLOP: f32 = 6.0;
+/// The Tailscale panel's fields, in tab order.
+const TAILNET_AUTH_KEY: usize = 0;
+const TAILNET_CONTROL_URL: usize = 1;
+const TAILNET_HOSTNAME: usize = 2;
+const TAILNET_FIELD_COUNT: usize = 3;
+/// A machine of the tailnet that is online, and the tailnet while it is up:
+/// the system's green.
+const ONLINE_GREEN: (u8, u8, u8) = (0x30, 0xD1, 0x58);
+/// The tailnet on its way up, or waiting for someone to log in.
+const WAITING_ORANGE: (u8, u8, u8) = (0xFF, 0x9F, 0x0A);
+/// How long the login link's button says it was copied.
+const COPIED_FOR: Duration = Duration::from_millis(1400);
+/// The gear at the end of the Tailscale group's caption.
+const TAILNET_GEAR: f32 = 36.0;
+
/// Clickable targets inside the view. `usize` payloads index into the current
/// filtered host list, so the action type stays `Copy` (needed by `UiContext`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -149,6 +169,7 @@ enum SshViewAction {
/// Connect to the host the inspector is showing.
Connect,
FocusField(usize),
+ SetNetwork(SshNetwork),
ToggleDetect,
ToggleMosh,
ToggleMux,
@@ -165,6 +186,29 @@ enum SshViewAction {
FocusOptionValue(usize),
RemoveOption(usize),
AddOption,
+ /// The Tailscale group's caption: folds the group away, or back.
+ ToggleTailnetGroup,
+ /// The gear by that caption: the Tailscale panel, opened or closed.
+ TailnetSettings,
+ /// A machine of the tailnet, by its place in the group as painted.
+ TailnetMachine(usize),
+ /// The button on the card the group shows instead of machines; what it
+ /// does is what it said when painted (see `TailnetGroup::notice`).
+ TailnetNotice,
+ /// The switch in the Tailscale panel's header.
+ ToggleTailnet,
+ OpenTailnetLogin,
+ CopyTailnetLogin,
+ FocusTailnetField(usize),
+ TailnetLogout,
+}
+
+/// What the button on the Tailscale group's card does.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum NoticeButton {
+ TurnOn,
+ LogIn,
+ Settings,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -175,6 +219,54 @@ enum Focus {
OptionKey(usize),
/// `ssh_options` row `n`, value column.
OptionValue(usize),
+ /// One of the Tailscale panel's fields.
+ Tailnet(usize),
+}
+
+/// The Tailscale group: its panel's fields and what it painted last, for
+/// the clicks that come after.
+#[derive(Default)]
+struct TailnetGroup {
+ /// The panel shows in the inspector, in place of a host's form.
+ panel_open: bool,
+ collapsed: bool,
+ /// The machines as painted, those the search finds: cards name one by
+ /// its place here.
+ machines: Vec<TailnetMachine>,
+ /// The approval link as painted, for the buttons that open and copy it.
+ login_url: Option<String>,
+ /// What the card's button said when painted.
+ notice: Option<NoticeButton>,
+ /// The auth key, the control server and this machine's name in the
+ /// tailnet. The key's never shows a saved key, only one being typed,
+ /// and empties once that one is saved.
+ fields: [TextInputState; TAILNET_FIELD_COUNT],
+ /// Typed into since the field last went out.
+ dirty: [bool; TAILNET_FIELD_COUNT],
+ /// The change each field's text went out as: the text stays while it
+ /// is saved, or could not be (see crate::tailnet::saved).
+ changes: [Option<u64>; TAILNET_FIELD_COUNT],
+ /// The login link's button says "Copied" until then.
+ copied_until: Option<Instant>,
+}
+
+/// What the Tailscale group holds under its caption.
+enum TailnetBody {
+ /// Nothing yet: the page has not read how the tailnet is.
+ Pending,
+ /// Its machines, as `TailnetGroup::machines` holds them.
+ Machines,
+ /// One card instead: the tailnet off, on its way, or waiting.
+ Notice(TailnetNotice),
+}
+
+struct TailnetNotice {
+ icon: SvgIcon,
+ title: String,
+ subtitle: String,
+ button: Option<(String, NoticeButton)>,
+ /// The invitation to turn it on, drawn in the accent.
+ invite: bool,
}
#[derive(Default, Clone)]
@@ -187,6 +279,7 @@ struct HostForm {
/// the user is still typing.
options: Vec<(TextInputState, TextInputState)>,
advanced_open: bool,
+ network: SshNetwork,
detect_os: bool,
use_mosh: bool,
multiplexing: bool,
@@ -242,6 +335,14 @@ pub(crate) struct SshHostsView {
/// paints for each scroll step and caret blink; the file is read again
/// only when its stamp moves.
system_hosts: Option<(ssh_hosts::SshConfigStamp, Vec<SshHostEntry>)>,
+ /// Every host saved here, whatever the search: what tells a machine of
+ /// the tailnet already saved as a host.
+ saved_hosts: Vec<SshHostEntry>,
+ /// The window the page is in, repainted when a read of the tailnet
+ /// lands. None in tests.
+ window: Option<Window>,
+ tailnet: TailnetGroup,
+ _tailnet_page: crate::tailnet::Page,
}
impl SshHostsView {
@@ -269,11 +370,21 @@ impl SshHostsView {
scroll: ScrollState::new(),
scroll_animating: false,
system_hosts: None,
+ saved_hosts: Vec::new(),
+ window: None,
+ tailnet: TailnetGroup::default(),
+ _tailnet_page: crate::tailnet::Page::open(),
};
view.refresh();
view
}
+ /// The page in `window`: what the tailnet's reads repaint.
+ pub(crate) fn in_window(mut self, window: Option<Window>) -> Self {
+ self.window = window;
+ self
+ }
+
/// A page that opens straight on a blank host form, for the "Add Remote
/// Host" entry point.
pub(crate) fn new_host() -> Self {
@@ -296,7 +407,13 @@ impl SshHostsView {
self.system_hosts = stamp.map(|stamp| (stamp, hosts.clone()));
hosts
});
- self.filtered = ssh_hosts::list_all_hosts_with(system_hosts)
+ let all = ssh_hosts::list_all_hosts_with(system_hosts);
+ self.saved_hosts = all
+ .iter()
+ .filter(|entry| entry.source == SshHostSource::ThinkTerm)
+ .cloned()
+ .collect();
+ self.filtered = all
.into_iter()
.filter(|entry| {
if needle.is_empty() {
@@ -338,6 +455,7 @@ impl SshHostsView {
}
fn open_new_form(&mut self) {
+ self.close_tailnet_panel();
self.password_visible = false;
let mut form = HostForm::default();
form.fields[FIELD_PORT].set_text_end("22".to_string());
@@ -356,6 +474,7 @@ impl SshHostsView {
let Some(spec) = ssh_hosts::host_spec(project_id) else {
return;
};
+ self.close_tailnet_panel();
// Revealing a password is a decision about one host. Carrying it into
// the next one would put a stored password on screen unasked.
self.password_visible = false;
@@ -378,6 +497,7 @@ impl SshHostsView {
input.set_text_end(text);
input
});
+ let network = spec.network;
let detect_os = spec.detect_os;
let use_mosh = spec.use_mosh;
let multiplexing = spec.multiplexing;
@@ -401,6 +521,7 @@ impl SshHostsView {
fields,
options,
advanced_open,
+ network,
detect_os,
use_mosh,
multiplexing,
@@ -432,6 +553,10 @@ impl SshHostsView {
/// the form; on error records the message and keeps the form open.
fn persist_form(&mut self) -> Option<String> {
let form = self.form.as_mut()?;
+ if form.network == SshNetwork::Tailnet && form.use_mosh {
+ form.error = Some(crate::i18n::tr("ssh-error-tailnet-mosh"));
+ return None;
+ }
let host = form.fields[FIELD_HOST].text().trim().to_string();
if host.is_empty() {
form.error = Some(crate::i18n::tr("ssh-error-host-required"));
@@ -458,6 +583,7 @@ impl SshHostsView {
host: host.clone(),
port,
other_addresses: Vec::new(),
+ network: Default::default(),
username: None,
identity_file: None,
password: None,
@@ -477,6 +603,7 @@ impl SshHostsView {
spec.label = label;
spec.host = host;
spec.port = port;
+ spec.network = form.network;
spec.other_addresses =
ssh_hosts::parse_other_addresses(&form.fields[FIELD_OTHER_ADDRESSES].text());
spec.username = opt(&form.fields[FIELD_USER].text());
@@ -602,6 +729,7 @@ impl SshHostsView {
SshViewAction::FocusField(n) => Some((Focus::Field(n), x)),
SshViewAction::FocusOptionKey(n) => Some((Focus::OptionKey(n), x)),
SshViewAction::FocusOptionValue(n) => Some((Focus::OptionValue(n), x)),
+ SshViewAction::FocusTailnetField(n) => Some((Focus::Tailnet(n), x)),
_ => None,
};
return self.apply(a);
@@ -705,6 +833,17 @@ impl SshHostsView {
self.focus = Focus::Field(n.min(count - 1));
ContentViewResponse::Redraw
}
+ SshViewAction::SetNetwork(network) => {
+ if let Some(form) = self.form.as_mut() {
+ if network == SshNetwork::Tailnet && form.use_mosh {
+ form.error = Some(crate::i18n::tr("ssh-error-tailnet-mosh"));
+ } else {
+ form.network = network;
+ form.error = None;
+ }
+ }
+ ContentViewResponse::Redraw
+ }
SshViewAction::ToggleDetect => {
if let Some(form) = self.form.as_mut() {
form.detect_os = !form.detect_os;
@@ -713,6 +852,10 @@ impl SshHostsView {
}
SshViewAction::ToggleMosh => {
if let Some(form) = self.form.as_mut() {
+ if !form.use_mosh && form.network == SshNetwork::Tailnet {
+ form.error = Some(crate::i18n::tr("ssh-error-tailnet-mosh"));
+ return ContentViewResponse::Redraw;
+ }
form.use_mosh = !form.use_mosh;
if form.use_mosh {
// Mosh and ThinkTerm Connect are alternative
@@ -775,6 +918,68 @@ impl SshHostsView {
self.refresh();
ContentViewResponse::Redraw
}
+ SshViewAction::ToggleTailnetGroup => {
+ self.tailnet.collapsed = !self.tailnet.collapsed;
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::TailnetSettings => {
+ if self.tailnet.panel_open {
+ self.close_tailnet_panel();
+ } else {
+ self.open_tailnet_panel();
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::TailnetMachine(index) => self.open_tailnet_machine(index),
+ SshViewAction::TailnetNotice => match self.tailnet.notice {
+ Some(NoticeButton::TurnOn) => {
+ // What was typed into the panel goes first: a control
+ // server is set before the node starts with it.
+ self.commit_tailnet_fields(None);
+ crate::tailnet::turn_on();
+ self.open_tailnet_panel();
+ ContentViewResponse::Redraw
+ }
+ Some(NoticeButton::LogIn) => self.apply(SshViewAction::OpenTailnetLogin),
+ Some(NoticeButton::Settings) => {
+ self.open_tailnet_panel();
+ ContentViewResponse::Redraw
+ }
+ None => ContentViewResponse::Redraw,
+ },
+ SshViewAction::ToggleTailnet => {
+ self.commit_tailnet_fields(None);
+ crate::tailnet::toggle();
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::OpenTailnetLogin => {
+ if let Some(url) = self.tailnet.login_url.as_deref() {
+ wezterm_open_url::open_url(url);
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::CopyTailnetLogin => {
+ let Some(url) = self.tailnet.login_url.clone() else {
+ return ContentViewResponse::Redraw;
+ };
+ self.tailnet.copied_until = Some(Instant::now() + COPIED_FOR);
+ ContentViewResponse::Run(Box::new(move |term_window| {
+ term_window.copy_to_clipboard(
+ config::keyassignment::ClipboardCopyDestination::Clipboard,
+ url,
+ );
+ term_window.invalidate_window();
+ }))
+ }
+ SshViewAction::FocusTailnetField(field) => {
+ self.focus = Focus::Tailnet(field.min(TAILNET_FIELD_COUNT - 1));
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::TailnetLogout => {
+ self.commit_tailnet_fields(None);
+ crate::tailnet::logout();
+ ContentViewResponse::Redraw
+ }
}
}
@@ -960,6 +1165,34 @@ impl SshHostsView {
}
}
+ if self.tailnet.panel_open {
+ if matches!(key, KeyCode::Escape) {
+ // Leaving without sending what was typed: a half-typed key
+ // or address would restart the node on it.
+ self.tailnet.dirty = [false; TAILNET_FIELD_COUNT];
+ self.close_tailnet_panel();
+ return ContentViewResponse::Redraw;
+ }
+ if let Focus::Tailnet(field) = self.focus {
+ match (key, mods) {
+ (KeyCode::Enter, _) => {
+ self.commit_tailnet_field(field);
+ return ContentViewResponse::Redraw;
+ }
+ (KeyCode::Tab, KeyModifiers::NONE) => {
+ self.focus = Focus::Tailnet((field + 1) % TAILNET_FIELD_COUNT);
+ return ContentViewResponse::Redraw;
+ }
+ (KeyCode::Tab, KeyModifiers::SHIFT) => {
+ self.focus =
+ Focus::Tailnet((field + TAILNET_FIELD_COUNT - 1) % TAILNET_FIELD_COUNT);
+ return ContentViewResponse::Redraw;
+ }
+ _ => {}
+ }
+ }
+ }
+
let in_form = self.form.is_some();
match (key, mods) {
(KeyCode::Escape, _) => {
@@ -1205,6 +1438,11 @@ impl SshHostsView {
.then(|| form.options.get(n).map(|(_, value)| value))
.flatten()
}
+ Focus::Tailnet(n) => self
+ .tailnet
+ .panel_open
+ .then(|| self.tailnet.fields.get(n))
+ .flatten(),
}
}
@@ -1234,16 +1472,30 @@ impl SshHostsView {
form.error = None;
form.options.get_mut(n).map(|(_, value)| value)
}
+ Focus::Tailnet(n) => {
+ if !self.tailnet.panel_open {
+ return None;
+ }
+ self.tailnet.fields.get_mut(n)
+ }
}
}
/// Run `f` against the focused field, then re-filter the host list if the
/// search box was the one edited.
fn edit_focused(&mut self, f: impl FnOnce(&mut TextInputState)) {
+ let focus = self.focus;
let Some(input) = self.focused_input_mut() else {
return;
};
+ // A Tailscale field goes out once it is left, and only if what it
+ // says changed: moving the caret through it is no edit.
+ let before = matches!(focus, Focus::Tailnet(_)).then(|| input.text().to_string());
f(input);
+ let changed = before.is_some_and(|before| before != input.text());
+ if let (true, Focus::Tailnet(field)) = (changed, focus) {
+ self.tailnet.dirty[field] = true;
+ }
if matches!(self.focus, Focus::Search) {
// Typing in the search box reshuffles the list under the
// highlight, so the old choice no longer means anything.
@@ -1332,6 +1584,7 @@ impl SshHostsView {
) -> anyhow::Result<()> {
let tokens = UiTokens::for_dpi(ctx.dimensions.dpi);
self.refresh();
+ let tailnet = self.read_tailnet();
self.widgets.clear();
self.card_rects.clear();
@@ -1361,7 +1614,7 @@ impl SshHostsView {
// out in what is left. That is the whole responsive story: widen the
// window and the leftover width becomes more columns, not a wider
// form floating in the middle of the page.
- let inspector_w = if self.form.is_some() {
+ let inspector_w = if self.form.is_some() || self.tailnet.panel_open {
ctx.px(INSPECTOR_W).min(((w - pad * 2.0) * 0.6).max(0.0))
} else {
0.0
@@ -1392,6 +1645,7 @@ impl SshHostsView {
font,
section_font,
palette,
+ &tailnet,
content_x,
content_w,
list_top,
@@ -1434,19 +1688,36 @@ impl SshHostsView {
inspector_w,
(h - pad * 2.0).max(0.0),
);
- self.paint_inspector(
- ctx,
- &title_ctx,
- &section_ctx,
- layers,
- font,
- title_font,
- section_font,
- palette,
- tokens,
- cursor_on,
- inspector,
- )?;
+ if self.tailnet.panel_open {
+ self.paint_tailnet_panel(
+ ctx,
+ &title_ctx,
+ &section_ctx,
+ layers,
+ font,
+ title_font,
+ section_font,
+ palette,
+ tokens,
+ cursor_on,
+ inspector,
+ &tailnet,
+ )?;
+ } else {
+ self.paint_inspector(
+ ctx,
+ &title_ctx,
+ &section_ctx,
+ layers,
+ font,
+ title_font,
+ section_font,
+ palette,
+ tokens,
+ cursor_on,
+ inspector,
+ )?;
+ }
} else {
self.form_area = rect(0.0, 0.0, 0.0, 0.0);
}
@@ -1555,6 +1826,7 @@ impl SshHostsView {
font: &Rc<LoadedFont>,
section_font: &Rc<LoadedFont>,
palette: UiPalette,
+ tailnet: &TailnetView,
content_x: f32,
content_w: f32,
list_top: f32,
@@ -1566,7 +1838,9 @@ impl SshHostsView {
content_w,
(list_bottom - list_top).max(0.0),
);
- if self.filtered.is_empty() && self.system_host_count == 0 {
+ let tailnet_body = self.tailnet_body(tailnet);
+ self.tailnet.notice = None;
+ if self.filtered.is_empty() && self.system_host_count == 0 && tailnet_body.is_none() {
self.scroll.set_extents(viewport.size.height, 0.0);
return self.paint_empty_state(ctx, layers, font, palette, viewport);
}
@@ -1574,9 +1848,15 @@ impl SshHostsView {
let (own, system) = self.grouped_indices();
// A lone "Hosts" caption over the only group on the page is noise;
// the captions earn their place once there is a second group to tell
- // apart from the first.
- let grouped = self.system_host_count > 0;
- let counts = [own.len(), system.len()];
+ // apart from the first -- and the Tailscale group always has one, for
+ // its caption carries the tailnet's state and its gear.
+ let grouped = self.system_host_count > 0 || tailnet_body.is_some();
+ // Its cards, while it shows them.
+ let machines = match &tailnet_body {
+ Some(TailnetBody::Machines) if !self.tailnet.collapsed => self.tailnet.machines.len(),
+ _ => 0,
+ };
+ let counts = [own.len(), machines, system.len()];
let columns = Self::card_columns(ctx, &counts, content_w);
let gap = ctx.px(CARD_GAP);
let card_h = Self::card_height(ctx);
@@ -1584,38 +1864,128 @@ impl SshHostsView {
let max_w = ctx.px(CARD_MAX_W);
let own_grid = card_grid(own.len(), content_w, columns, max_w, gap, card_h);
+ let tailnet_grid = card_grid(machines, content_w, columns, max_w, gap, card_h);
let system_grid = card_grid(system.len(), content_w, columns, max_w, gap, card_h);
let title_gap = ctx.px(GROUP_TITLE_GAP);
- let mut content_h = own_grid.height(gap);
- if grouped {
- content_h += (header_h + title_gap) * 2.0 + ctx.px(GROUP_GAP) + system_grid.height(gap);
+ let caption_h = if grouped { header_h + title_gap } else { 0.0 };
+ // An empty Hosts group has nothing to say under its caption.
+ let show_own = !own.is_empty();
+ let tailnet_h = match &tailnet_body {
+ _ if self.tailnet.collapsed => 0.0,
+ Some(TailnetBody::Machines) => tailnet_grid.height(gap),
+ Some(TailnetBody::Notice(_)) => card_h,
+ Some(TailnetBody::Pending) | None => 0.0,
+ };
+ let mut blocks = Vec::new();
+ if show_own {
+ blocks.push(caption_h + own_grid.height(gap));
+ }
+ if tailnet_body.is_some() {
+ blocks.push(caption_h + tailnet_h);
}
+ if self.system_host_count > 0 {
+ blocks.push(caption_h + system_grid.height(gap));
+ }
+ let content_h =
+ blocks.iter().sum::<f32>() + ctx.px(GROUP_GAP) * blocks.len().saturating_sub(1) as f32;
self.scroll.set_extents(viewport.size.height, content_h);
let mut y = list_top - self.scroll.offset;
- if grouped {
+ let mut first = true;
+ if show_own {
+ first = false;
+ if grouped {
+ self.paint_group_header(
+ section_ctx,
+ layers,
+ section_font,
+ palette,
+ &crate::i18n::tr("ssh-group-hosts"),
+ None,
+ content_x,
+ y,
+ content_w,
+ 0.0,
+ viewport,
+ )?;
+ y += header_h + title_gap;
+ }
+ self.paint_cards(
+ ctx, layers, font, palette, &own, own_grid, content_x, content_w, y, gap, viewport,
+ )?;
+ y += own_grid.height(gap);
+ }
+
+ if let Some(body) = &tailnet_body {
+ if !std::mem::take(&mut first) {
+ y += ctx.px(GROUP_GAP);
+ }
+ let label = match body {
+ TailnetBody::Machines => {
+ let mut args = FluentArgs::new();
+ args.set("count", self.tailnet.machines.len());
+ crate::i18n::tr_args("ssh-group-tailscale-count", &args)
+ }
+ TailnetBody::Notice(_) | TailnetBody::Pending => {
+ crate::i18n::tr("ssh-group-tailscale")
+ }
+ };
+ let status_w = self.tailnet_status_width(ctx, font, tailnet);
self.paint_group_header(
section_ctx,
layers,
section_font,
palette,
- &crate::i18n::tr("ssh-group-hosts"),
- None,
+ &label,
+ Some((SshViewAction::ToggleTailnetGroup, !self.tailnet.collapsed)),
content_x,
y,
content_w,
+ status_w,
viewport,
)?;
+ self.paint_tailnet_status(
+ ctx, layers, font, palette, tailnet, content_x, y, content_w, viewport,
+ )?;
y += header_h + title_gap;
+ if !self.tailnet.collapsed {
+ match body {
+ TailnetBody::Machines => {
+ for slot in 0..machines {
+ let card = card_rect(
+ slot,
+ machines,
+ tailnet_grid,
+ content_x,
+ content_w,
+ y,
+ gap,
+ RowAlign::Justify,
+ );
+ if card_is_warm(card, viewport, 0.0) {
+ self.paint_tailnet_card(
+ ctx, layers, font, palette, slot, card, viewport,
+ )?;
+ }
+ }
+ }
+ TailnetBody::Notice(notice) => {
+ let card = rect(content_x, y, content_w, card_h);
+ self.paint_tailnet_notice(
+ ctx, layers, font, palette, notice, card, viewport,
+ )?;
+ }
+ TailnetBody::Pending => {}
+ }
+ y += tailnet_h;
+ }
}
- self.paint_cards(
- ctx, layers, font, palette, &own, own_grid, content_x, content_w, y, gap, viewport,
- )?;
- y += own_grid.height(gap);
- if grouped {
- y += ctx.px(GROUP_GAP);
+ if self.system_host_count > 0 {
+ if !first {
+ y += ctx.px(GROUP_GAP);
+ }
let mut args = FluentArgs::new();
args.set("count", self.system_host_count);
let label = crate::i18n::tr_args("ssh-system-hosts", &args);
@@ -1625,10 +1995,14 @@ impl SshHostsView {
section_font,
palette,
&label,
- Some(SshViewAction::ToggleSystemHosts),
+ Some((
+ SshViewAction::ToggleSystemHosts,
+ self.system_group_expanded(),
+ )),
content_x,
y,
content_w,
+ 0.0,
viewport,
)?;
y += header_h + title_gap;
@@ -1799,6 +2173,9 @@ impl SshHostsView {
Ok(())
}
+ /// A group's caption. One that folds carries its action and whether it
+ /// is open; `trailing` is kept clear at the right end for what the
+ /// caller draws there.
#[allow(clippy::too_many_arguments)]
fn paint_group_header(
&mut self,
@@ -1807,10 +2184,11 @@ impl SshHostsView {
section_font: &Rc<LoadedFont>,
palette: UiPalette,
label: &str,
- toggle: Option<SshViewAction>,
+ toggle: Option<(SshViewAction, bool)>,
x: f32,
y: f32,
width: f32,
+ trailing: f32,
viewport: RectF,
) -> anyhow::Result<()> {
let height = section_ctx.px(GROUP_HEADER_H);
@@ -1819,7 +2197,7 @@ impl SshHostsView {
}
let line_h = section_ctx.metrics.cell_size.height as f32;
let mut text_x = x;
- if let Some(action) = toggle {
+ if let Some((action, expanded)) = toggle {
let hit_h = (y + height).min(viewport.max_y()) - y.max(viewport.min_y());
self.widgets.push(
rect(x, y.max(viewport.min_y()), width, hit_h.max(0.0)),
@@ -1827,7 +2205,7 @@ impl SshHostsView {
action,
);
let chevron = section_ctx.px(18.0);
- let icon = if self.system_group_expanded() {
+ let icon = if expanded {
SvgIcon::ChevronDown
} else {
SvgIcon::ChevronRight
@@ -1849,7 +2227,7 @@ impl SshHostsView {
y + ((height - line_h) / 2.0).max(0.0),
label,
palette.secondary_text,
- (width - (text_x - x)).max(0.0),
+ (width - trailing - (text_x - x)).max(0.0),
)?;
Ok(())
}
@@ -2049,34 +2427,22 @@ impl SshHostsView {
y: f32,
width: f32,
) -> anyhow::Result<f32> {
- let line_h = ctx.metrics.cell_size.height as f32;
- ctx.draw_text(layers, font, x, y, label, palette.muted_text, width)?;
- let input_y = y + line_h + ctx.px(LABEL_GAP);
- let text_pad = ctx.px(12.0);
- self.resolve_pending_caret_click(ctx, font, Focus::Field(index), shown, x + text_pad);
- let caret = self.caret_for(Focus::Field(index));
- let focused = self.focus == Focus::Field(index);
- draw_text_input(
+ self.paint_input_row(
ctx,
layers,
font,
- &mut self.widgets,
- &self.interaction,
palette,
tokens,
- text_pad,
cursor_on,
- TextInputSpec {
- placeholder,
- text: shown,
- rect: rect(x, input_y, width, ctx.px(INPUT_H)),
- focused,
- selected_all: false,
- action: SshViewAction::FocusField(index),
- },
- caret,
- )?;
- Ok(input_y + ctx.px(INPUT_H))
+ label,
+ Focus::Field(index),
+ SshViewAction::FocusField(index),
+ shown,
+ placeholder,
+ x,
+ y,
+ width,
+ )
}
#[allow(clippy::too_many_arguments)]
@@ -2218,6 +2584,7 @@ impl SshHostsView {
return Ok(());
};
let editing = form.editing.clone();
+ let network = form.network;
let detect_os = form.detect_os;
let use_mosh = form.use_mosh;
let multiplexing = form.multiplexing;
@@ -2301,8 +2668,11 @@ impl SshHostsView {
let mut body_layers = TripleLayerQuadAllocator::Heap(&mut heap);
// ---- Connection
- let conn_h =
- Self::inspector_card_height(ctx, section_h, &[field_h, field_h, field_h, field_h]);
+ let conn_h = Self::inspector_card_height(
+ ctx,
+ section_h,
+ &[field_h, field_h, field_h, field_h, field_h],
+ );
let mut fy = Self::paint_inspector_card(
ctx,
section_ctx,
@@ -2327,6 +2697,52 @@ impl SshHostsView {
fy,
inner,
)? + gap;
+ ctx.draw_text(
+ &mut body_layers,
+ font,
+ x + pad,
+ fy,
+ &crate::i18n::tr("ssh-field-network"),
+ palette.text,
+ inner,
+ )?;
+ let each = (inner - ctx.px(8.0)) / 2.0;
+ for (index, (choice, label)) in [
+ (SshNetwork::System, "ssh-network-system"),
+ (SshNetwork::Tailnet, "ssh-network-tailnet"),
+ ]
+ .iter()
+ .copied()
+ .enumerate()
+ {
+ let action = SshViewAction::SetNetwork(choice);
+ let state = self.button_state(action);
+ draw_button(
+ ctx,
+ &mut body_layers,
+ font,
+ &mut self.widgets,
+ palette,
+ ButtonSpec {
+ label: &crate::i18n::tr(label),
+ action,
+ rect: rect(
+ x + pad + index as f32 * (each + ctx.px(8.0)),
+ fy + line_h + ctx.px(LABEL_GAP),
+ each,
+ ctx.px(INPUT_H),
+ ),
+ state,
+ kind: WidgetKind::Button,
+ variant: if network == choice {
+ ButtonVariant::Primary
+ } else {
+ ButtonVariant::Secondary
+ },
+ },
+ )?;
+ }
+ fy += field_h + gap;
// Host and Port share a row: a port needs four characters, not a
// column of its own.
let port_w = ctx.px(96.0).min(inner * 0.32);
@@ -2901,122 +3317,1359 @@ impl SshHostsView {
}
}
-/// Close the view and open a disconnected remote thread on the main window.
-fn open_thread_response(project_id: String) -> ContentViewResponse {
- ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {
- let window = tw.window.as_ref().cloned();
- if let Some(window) = window {
- if tw.open_ssh_host_thread_without_connecting(project_id, &window) {
- tw.close_content_view();
- }
- }
- }))
+/// How the Tailscale group's caption reads the tailnet.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Tone {
+ Off,
+ Waiting,
+ Up,
+ Trouble,
}
-impl ContentView for SshHostsView {
- fn title(&self) -> String {
- crate::i18n::tr("ssh-hosts-title")
+impl Tone {
+ fn color(self, palette: UiPalette) -> LinearRgba {
+ let (r, g, b) = match self {
+ Self::Off => return palette.muted_text,
+ Self::Trouble => return palette.danger,
+ Self::Waiting => WAITING_ORANGE,
+ Self::Up => ONLINE_GREEN,
+ };
+ LinearRgba::with_srgba(r, g, b, 0xFF)
}
+}
- fn tab_key(&self) -> Option<String> {
- Some(SSH_HOSTS_CONTENT_VIEW_KEY.to_string())
+/// The tailnet in a word or two, for the group's caption: nothing until
+/// the page has read how it is.
+fn tailnet_status(view: &TailnetView) -> Option<(&'static str, Tone)> {
+ if view.error.is_some() {
+ return Some(("ssh-tailscale-not-saved", Tone::Trouble));
}
-
- fn wants_cursor_blink(&self) -> bool {
- // A text field is always focused while this view is open.
- true
+ if view.read_error.is_some() {
+ return Some(("ssh-tailscale-unreadable", Tone::Trouble));
}
-
- fn paint(
- &mut self,
- ctx: &DrawContext,
- layers: &mut TripleLayerQuadAllocator<'_>,
- area: RectF,
- palette: UiPalette,
- font: &Rc<LoadedFont>,
- title_font: &Rc<LoadedFont>,
- section_font: &Rc<LoadedFont>,
- _caption_font: &Rc<LoadedFont>,
- cursor_on: bool,
- ) -> anyhow::Result<()> {
- self.paint_impl(
- ctx,
- layers,
- area,
- palette,
- font,
- title_font,
- section_font,
- cursor_on,
- )
+ if !view.known {
+ return None;
}
-
- fn run_remote_host_command(
- &mut self,
- host_id: &str,
- command: RemoteHostCommand,
- ) -> ContentViewResponse {
- self.run_host_command(host_id, command)
+ if !view.enabled {
+ return Some(("ssh-tailscale-off", Tone::Off));
}
-
- fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
- self.on_mouse_impl(x, y, kind)
+ if !view.server_running {
+ return Some(("ssh-tailscale-starting", Tone::Waiting));
}
+ Some(match &view.state {
+ TailnetState::Connected { .. } => ("ssh-tailscale-connected", Tone::Up),
+ TailnetState::NeedsLogin(_) => ("ssh-tailscale-login", Tone::Waiting),
+ TailnetState::Failed(_) => ("ssh-tailscale-failed", Tone::Trouble),
+ TailnetState::HeldElsewhere => ("ssh-tailscale-elsewhere", Tone::Waiting),
+ TailnetState::Off | TailnetState::Starting => ("ssh-tailscale-starting", Tone::Waiting),
+ })
+}
- fn on_wheel(&mut self, x: f32, y: f32, event: &MouseEvent) -> ContentViewResponse {
- let scale = self.last_ui_scale;
- let scroll = if self.point_in_host_list(x, y) {
- &mut self.scroll
- } else if contains(self.form_area, x, y) {
- &mut self.form_scroll
- } else {
- return ContentViewResponse::Ignored;
- };
- if apply_wheel(event, scroll, scale) {
- ContentViewResponse::Redraw
- } else {
- ContentViewResponse::Ignored
- }
+/// The panel's account of the tailnet: where the node is, or why not.
+fn tailnet_state_text(view: &TailnetView) -> String {
+ if !view.known {
+ return "…".to_string();
}
-
- fn next_frame_time(&self) -> Option<Instant> {
- self.scroll_animating.then(Instant::now)
+ if !view.enabled {
+ return crate::i18n::tr("ssh-tailscale-state-off");
}
-
- fn on_key(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
- self.on_key_impl(key, mods)
+ if !view.server_running {
+ return crate::i18n::tr("ssh-tailscale-server-not-running");
}
-
- fn on_paste(&mut self, text: &str) -> ContentViewResponse {
- self.on_paste_impl(text)
+ match &view.state {
+ TailnetState::Off | TailnetState::Starting => crate::i18n::tr("ssh-tailscale-starting"),
+ TailnetState::NeedsLogin(_) => crate::i18n::tr("ssh-tailscale-login"),
+ TailnetState::Connected {
+ name,
+ address: Some(address),
+ } => tr_named(
+ "ssh-tailscale-state-connected",
+ &[("name", name.clone()), ("address", address.clone())],
+ ),
+ TailnetState::Connected {
+ name,
+ address: None,
+ } => tr_named(
+ "ssh-tailscale-state-connected-no-address",
+ &[("name", name.clone())],
+ ),
+ TailnetState::Failed(error) => {
+ tr_named("ssh-tailscale-state-failed", &[("error", error.clone())])
+ }
+ TailnetState::HeldElsewhere => crate::i18n::tr("ssh-tailscale-state-elsewhere"),
}
+}
- fn begin_new_remote_host(&mut self) {
- // Same reset the `+` button performs; the list refreshes on paint.
- self.open_new_form();
+fn tr_named(id: &str, named: &[(&str, String)]) -> String {
+ let mut args = FluentArgs::new();
+ for (name, value) in named {
+ args.set(*name, value.clone());
}
+ crate::i18n::tr_args(id, &args)
+}
- fn copy_text(&self) -> Option<String> {
- let input = self.focused_input()?;
- let text = input
- .caret_selected_text()
- .unwrap_or_else(|| input.text().to_string());
- (!text.is_empty()).then_some(text)
- }
+/// What a machine of the tailnet is drawn as.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum MachineIcon {
+ /// A maker's mark in its own colours.
+ Brand(BrandIcon),
+ /// A mark tinted like the page's text.
+ Plain(SvgIcon),
+}
- fn cut_text(&mut self) -> Option<String> {
- self.take_focused_selection()
+/// The maker's mark where there is one -- the distribution's, for Linux --
+/// and a plain picture where not.
+fn machine_icon(machine: &TailnetMachine) -> MachineIcon {
+ match machine.device {
+ Device::Mac | Device::IPhone | Device::IPad | Device::AppleTv => {
+ MachineIcon::Plain(SvgIcon::Apple)
+ }
+ Device::Android => MachineIcon::Brand(BrandIcon::Android),
+ Device::Linux => {
+ MachineIcon::Brand(distro_to_icon(&machine.distro).unwrap_or(BrandIcon::Linux))
+ }
+ // The app carries no Windows mark.
+ Device::Windows => MachineIcon::Plain(SvgIcon::Monitor),
+ Device::Unknown => MachineIcon::Plain(SvgIcon::Server),
}
}
-#[cfg(test)]
+/// Under a machine's name: what it is, and whether it is online.
+fn machine_subtitle(machine: &TailnetMachine) -> String {
+ let presence = match machine.online {
+ Some(true) => Some(crate::i18n::tr("ssh-tailscale-online")),
+ Some(false) => Some(crate::i18n::tr("ssh-tailscale-offline")),
+ None => None,
+ };
+ match (machine.device.name(), presence) {
+ (Some(device), Some(presence)) => format!("{device} · {presence}"),
+ (Some(device), None) => device.to_string(),
+ (None, Some(presence)) => presence,
+ (None, None) => machine.target.clone(),
+ }
+}
+
+/// Whether the search box's text, lowercased, finds this machine.
+fn machine_matches(machine: &TailnetMachine, needle: &str) -> bool {
+ let addresses = machine
+ .addresses
+ .iter()
+ .map(|address| address.to_string())
+ .collect::<Vec<_>>()
+ .join(" ");
+ format!(
+ "{} {} {} {addresses}",
+ machine.name,
+ machine.target,
+ machine.device.name().unwrap_or_default()
+ )
+ .to_ascii_lowercase()
+ .contains(needle)
+}
+
+/// Whether a Tailscale field keeps the text it went out with (`change`)
+/// rather than show the file: while that change is saved, and while the
+/// panel says why it could not be. Forgets the change once it is in.
+fn keeps_typed_text(change: &mut Option<u64>) -> bool {
+ match change.map(crate::tailnet::saved) {
+ Some(None) | Some(Some(false)) => true,
+ Some(Some(true)) => {
+ *change = None;
+ false
+ }
+ None => false,
+ }
+}
+
+impl SshHostsView {
+ /// The tailnet as last read -- read again when that is due -- with the
+ /// group's fields and machines brought up to it.
+ fn read_tailnet(&mut self) -> TailnetView {
+ if !crate::tailnet::available() {
+ return TailnetView::default();
+ }
+ if let Some(window) = self.window.clone() {
+ if crate::tailnet::poll_is_due() {
+ crate::tailnet::refresh(window);
+ }
+ }
+ let view = crate::tailnet::view();
+ self.sync_tailnet_fields(&view);
+ self.tailnet.login_url = view.login_url().map(str::to_string);
+ let needle = self.search.text().trim().to_ascii_lowercase();
+ self.tailnet.machines = view
+ .machines
+ .iter()
+ .filter(|machine| needle.is_empty() || machine_matches(machine, &needle))
+ .cloned()
+ .collect();
+ view
+ }
+
+ /// Fields nobody is editing show what the settings file says, which
+ /// `thinkterm tailnet` may have changed meanwhile -- once what was typed
+ /// into them is saved. Text that could not be saved stays, for the
+ /// panel says why, until another change is saved.
+ fn sync_tailnet_fields(&mut self, view: &TailnetView) {
+ for field in 0..TAILNET_FIELD_COUNT {
+ if self.focus == Focus::Tailnet(field)
+ || self.tailnet.dirty[field]
+ || keeps_typed_text(&mut self.tailnet.changes[field])
+ {
+ continue;
+ }
+ let file = match field {
+ // A saved key never shows: the field empties once it is in.
+ TAILNET_AUTH_KEY => "",
+ TAILNET_CONTROL_URL => view.control_url.as_str(),
+ _ => view.hostname.as_str(),
+ };
+ if self.tailnet.fields[field].text() != file {
+ self.tailnet.fields[field].set_text_end(file.to_string());
+ }
+ }
+ }
+
+ /// Sends a Tailscale field that was typed into. The node restarts with
+ /// it once it is saved (see thinkterm_tailnet::update).
+ fn commit_tailnet_field(&mut self, field: usize) {
+ if !std::mem::take(&mut self.tailnet.dirty[field]) {
+ return;
+ }
+ let text = self.tailnet.fields[field].text().to_string();
+ self.tailnet.changes[field] = match field {
+ TAILNET_AUTH_KEY => crate::tailnet::set_auth_key(&text),
+ TAILNET_CONTROL_URL => Some(crate::tailnet::set_control_url(&text)),
+ _ => Some(crate::tailnet::set_hostname(&text)),
+ };
+ }
+
+ /// Sends every Tailscale field typed into but `keep`, the one still
+ /// being typed in.
+ fn commit_tailnet_fields(&mut self, keep: Option<usize>) {
+ for field in 0..TAILNET_FIELD_COUNT {
+ if Some(field) != keep {
+ self.commit_tailnet_field(field);
+ }
+ }
+ }
+
+ /// After a click or a key: a Tailscale field goes out once it is left,
+ /// as Settings' fields did.
+ fn commit_left_tailnet_fields(&mut self) {
+ let keep = match self.focus {
+ Focus::Tailnet(field) if self.tailnet.panel_open => Some(field),
+ _ => None,
+ };
+ self.commit_tailnet_fields(keep);
+ }
+
+ fn open_tailnet_panel(&mut self) {
+ if !crate::tailnet::available() {
+ return;
+ }
+ // One inspector: a host's form gives way, as it does to another
+ // host's.
+ self.close_form();
+ self.tailnet.panel_open = true;
+ self.reset_form_scroll();
+ }
+
+ fn close_tailnet_panel(&mut self) {
+ if !self.tailnet.panel_open {
+ return;
+ }
+ self.commit_tailnet_fields(None);
+ self.tailnet.panel_open = false;
+ if matches!(self.focus, Focus::Tailnet(_)) {
+ self.focus = Focus::Search;
+ }
+ self.reset_form_scroll();
+ }
+
+ /// The saved host that is this machine of the tailnet, if one is: its
+ /// address, or one of its other addresses, names the machine.
+ fn saved_host_for(&self, machine: &TailnetMachine) -> Option<&SshHostEntry> {
+ self.saved_hosts.iter().find(|entry| {
+ entry.spec.network == SshNetwork::Tailnet
+ && (machine.answers_to(&entry.spec.host)
+ || entry
+ .spec
+ .other_addresses
+ .iter()
+ .any(|address| machine.answers_to(address)))
+ })
+ }
+
+ /// A machine of the tailnet: one saved as a host connects the way it
+ /// was saved; another opens a new host's form with its name and address
+ /// filled in, for whom to sign in as -- saved, it is a host like any
+ /// other, in Hosts.
+ fn open_tailnet_machine(&mut self, index: usize) -> ContentViewResponse {
+ let Some(machine) = self.tailnet.machines.get(index).cloned() else {
+ return ContentViewResponse::Redraw;
+ };
+ if let Some(entry) = self.saved_host_for(&machine) {
+ return open_thread_response(entry.id.clone());
+ }
+ self.open_new_form();
+ if let Some(form) = self.form.as_mut() {
+ form.network = SshNetwork::Tailnet;
+ form.fields[FIELD_NAME].set_text_end(machine.name.clone());
+ form.fields[FIELD_HOST].set_text_end(machine.target.clone());
+ }
+ // Where it is, the tailnet said; whom to sign in as is left.
+ self.focus = Focus::Field(FIELD_USER);
+ self.selection_active = false;
+ ContentViewResponse::Redraw
+ }
+
+ /// What the Tailscale group holds, or None when it does not show: in a
+ /// build that cannot join a tailnet, and in a search that finds none of
+ /// its machines.
+ fn tailnet_body(&self, view: &TailnetView) -> Option<TailnetBody> {
+ if !crate::tailnet::available() {
+ return None;
+ }
+ if !self.search.text().trim().is_empty() {
+ return (!self.tailnet.machines.is_empty()).then_some(TailnetBody::Machines);
+ }
+ if !view.known {
+ return Some(TailnetBody::Pending);
+ }
+ let tr = crate::i18n::tr;
+ let notice = |icon, title: &str, subtitle: String, button: Option<(&str, NoticeButton)>| {
+ TailnetBody::Notice(TailnetNotice {
+ icon,
+ title: tr(title),
+ subtitle,
+ button: button.map(|(label, which)| (tr(label), which)),
+ invite: false,
+ })
+ };
+ if !view.enabled {
+ return Some(TailnetBody::Notice(TailnetNotice {
+ icon: SvgIcon::Network,
+ title: tr("ssh-tailscale-off-title"),
+ subtitle: tr("ssh-tailscale-off-subtitle"),
+ button: Some((tr("ssh-tailscale-turn-on"), NoticeButton::TurnOn)),
+ invite: true,
+ }));
+ }
+ if !view.server_running {
+ return Some(notice(
+ SvgIcon::Network,
+ "ssh-tailscale-starting",
+ tr("ssh-tailscale-server-not-running"),
+ None,
+ ));
+ }
+ Some(match &view.state {
+ TailnetState::Connected { .. } if !self.tailnet.machines.is_empty() => {
+ TailnetBody::Machines
+ }
+ TailnetState::Connected { .. } => notice(
+ SvgIcon::Network,
+ "ssh-tailscale-empty-title",
+ tr("ssh-tailscale-empty-subtitle"),
+ None,
+ ),
+ TailnetState::NeedsLogin(_) => notice(
+ SvgIcon::KeyRound,
+ "ssh-tailscale-login",
+ tr("ssh-tailscale-login-description"),
+ Some(("ssh-tailscale-login-button", NoticeButton::LogIn)),
+ ),
+ TailnetState::Failed(error) => notice(
+ SvgIcon::CircleAlert,
+ "ssh-tailscale-failed",
+ error.clone(),
+ Some(("ssh-tailscale-settings-button", NoticeButton::Settings)),
+ ),
+ TailnetState::HeldElsewhere => notice(
+ SvgIcon::Network,
+ "ssh-tailscale-elsewhere",
+ tr("ssh-tailscale-state-elsewhere"),
+ None,
+ ),
+ TailnetState::Off | TailnetState::Starting => notice(
+ SvgIcon::Network,
+ "ssh-tailscale-starting",
+ tr("ssh-tailscale-starting-subtitle"),
+ None,
+ ),
+ })
+ }
+
+ /// The room the caption's status and gear take at its right end.
+ fn tailnet_status_width(
+ &self,
+ ctx: &DrawContext,
+ font: &Rc<LoadedFont>,
+ view: &TailnetView,
+ ) -> f32 {
+ let gear = ctx.px(TAILNET_GEAR + 12.0);
+ match tailnet_status(view) {
+ Some((status, _)) => {
+ gear + ctx.px(10.0 + 7.0 + 8.0)
+ + ctx.measure_text_width(font, &crate::i18n::tr(status))
+ }
+ None => gear,
+ }
+ }
+
+ /// The right end of the Tailscale caption: the tailnet's state by its
+ /// dot, and the gear that opens the panel. Either opens it.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_tailnet_status(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ view: &TailnetView,
+ x: f32,
+ y: f32,
+ width: f32,
+ viewport: RectF,
+ ) -> anyhow::Result<()> {
+ let height = ctx.px(GROUP_HEADER_H);
+ if !row_visible(y, height, viewport) {
+ return Ok(());
+ }
+ let widgets_start = self.widgets.len();
+ let action = SshViewAction::TailnetSettings;
+ let hovered = self.button_state(action) != ControlState::Normal;
+ let gear = ctx.px(TAILNET_GEAR).min(height);
+ let gear_x = x + width - gear;
+ let gear_y = y + (height - gear) / 2.0;
+ let status = tailnet_status(view).map(|(id, tone)| (crate::i18n::tr(id), tone));
+ let line_h = ctx.metrics.cell_size.height as f32;
+ let status_w = status
+ .as_ref()
+ .map(|(text, _)| ctx.measure_text_width(font, text))
+ .unwrap_or_default();
+ let status_x = gear_x - ctx.px(10.0) - status_w;
+ let dot = ctx.px(8.0);
+ let dot_x = status_x - ctx.px(7.0) - dot;
+ let hit_x = if status.is_some() { dot_x } else { gear_x };
+ self.widgets.push(
+ rect(hit_x, y, x + width - hit_x, height),
+ WidgetKind::Button,
+ action,
+ );
+ // A quiet gear, open panel or not: a lit square beside the
+ // caption outshouted everything on the page.
+ if hovered {
+ ctx.draw_rounded_rect(
+ layers,
+ 0,
+ gear_x,
+ gear_y,
+ gear,
+ gear,
+ palette.control_hover_bg,
+ ctx.px(8.0),
+ )?;
+ }
+ // As large as an icon button's, next to the caption's text.
+ let glyph = (line_h + ctx.px(4.0))
+ .clamp(ctx.px(20.0), ctx.px(30.0))
+ .min(gear - ctx.px(6.0))
+ .round();
+ ctx.draw_svg_icon(
+ layers,
+ SvgIcon::Settings,
+ gear_x + (gear - glyph) / 2.0,
+ gear_y + (gear - glyph) / 2.0,
+ glyph,
+ if hovered {
+ palette.text
+ } else {
+ palette.muted_text
+ },
+ )?;
+ if let Some((status, tone)) = &status {
+ ctx.draw_disc(
+ layers,
+ 1,
+ dot_x + dot / 2.0,
+ y + height / 2.0,
+ dot,
+ tone.color(palette),
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ status_x,
+ y + ((height - line_h) / 2.0).max(0.0),
+ status,
+ if *tone == Tone::Trouble {
+ palette.danger
+ } else {
+ palette.secondary_text
+ },
+ status_w,
+ )?;
+ }
+ self.widgets.clip_since(widgets_start, viewport);
+ Ok(())
+ }
+
+ /// One machine of the tailnet: its mark, its name, what it is and
+ /// whether it is online -- and, when it is saved as a host already,
+ /// that it is.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_tailnet_card(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ index: usize,
+ card: RectF,
+ viewport: RectF,
+ ) -> anyhow::Result<()> {
+ let Some(machine) = self.tailnet.machines.get(index).cloned() else {
+ return Ok(());
+ };
+ let action = SshViewAction::TailnetMachine(index);
+ let Some(visible) = card.intersection(&viewport) else {
+ return Ok(());
+ };
+ self.widgets.push(visible, WidgetKind::SidebarRow, action);
+ let hovered = self.interaction.hovered == Some(action);
+ let bg = if hovered {
+ palette.sidebar_row_hover_bg
+ } else {
+ palette.card_bg
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ card.origin.x,
+ card.origin.y,
+ card.size.width,
+ card.size.height,
+ bg,
+ palette.separator,
+ ctx.px(CARD_RADIUS),
+ )?;
+
+ let online = machine.online == Some(true);
+ let offline = machine.online == Some(false);
+ let pad = ctx.px(CARD_PAD);
+ let line_h = ctx.metrics.cell_size.height as f32;
+ // The same size a host's logo gets.
+ let icon = (line_h * 2.2).clamp(ctx.px(50.0), ctx.px(64.0));
+ let icon_x = card.origin.x + pad;
+ let icon_y = card.origin.y + (card.size.height - icon) / 2.0;
+ match machine_icon(&machine) {
+ MachineIcon::Brand(brand) => {
+ ctx.draw_brand_icon(layers, brand, icon_x, icon_y, icon)?
+ }
+ MachineIcon::Plain(mark) => ctx.draw_svg_icon(
+ layers,
+ mark,
+ icon_x,
+ icon_y,
+ icon,
+ if offline {
+ palette.muted_text
+ } else {
+ palette.secondary_text
+ },
+ )?,
+ }
+ if offline {
+ // A machine that is away fades: its mark under a veil of the
+ // card's own colour.
+ ctx.draw_rect(layers, 2, icon_x, icon_y, icon, icon, bg.mul_alpha(0.55))?;
+ }
+
+ let text_x = icon_x + icon + ctx.px(14.0);
+ let right = card.max_x() - pad;
+ let mut title_w = (right - text_x).max(0.0);
+ let stack = line_h * 2.0 + ctx.px(4.0);
+ let title_y = card.origin.y + ((card.size.height - stack) / 2.0).max(ctx.px(8.0));
+ // Saved already: clicking it connects the way it was saved. The
+ // name comes first: where both do not fit, the word goes and the
+ // check stays.
+ if self.saved_host_for(&machine).is_some() {
+ let label = crate::i18n::tr("ssh-tailscale-added");
+ let check = (line_h * 0.85).round();
+ let gap = ctx.px(10.0);
+ let label_w = ctx.measure_text_width(font, &label);
+ let worded = check + ctx.px(4.0) + label_w;
+ let name_w = ctx.measure_text_width(font, &machine.name);
+ let word = name_w + gap + worded <= title_w;
+ let tag_x = right - if word { worded } else { check };
+ ctx.draw_svg_icon(
+ layers,
+ SvgIcon::Check,
+ tag_x,
+ title_y + (line_h - check) / 2.0,
+ check,
+ palette.muted_text,
+ )?;
+ if word {
+ ctx.draw_text(
+ layers,
+ font,
+ tag_x + check + ctx.px(4.0),
+ title_y,
+ &label,
+ palette.muted_text,
+ label_w,
+ )?;
+ }
+ title_w = (tag_x - gap - text_x).max(0.0);
+ }
+ ctx.draw_text(
+ layers,
+ font,
+ text_x,
+ title_y,
+ &machine.name,
+ if offline {
+ palette.secondary_text
+ } else {
+ palette.text
+ },
+ title_w,
+ )?;
+ let subtitle_y = title_y + line_h + ctx.px(4.0);
+ let mut subtitle_x = text_x;
+ if online {
+ let dot = ctx.px(8.0);
+ ctx.draw_disc(
+ layers,
+ 1,
+ subtitle_x + dot / 2.0,
+ subtitle_y + line_h / 2.0,
+ dot,
+ Tone::Up.color(palette),
+ )?;
+ subtitle_x += dot + ctx.px(7.0);
+ }
+ ctx.draw_text(
+ layers,
+ font,
+ subtitle_x,
+ subtitle_y,
+ &machine_subtitle(&machine),
+ palette.muted_text,
+ (right - subtitle_x).max(0.0),
+ )?;
+ Ok(())
+ }
+
+ /// The card the Tailscale group shows instead of machines: the tailnet
+ /// off -- an invitation to turn it on -- or on its way, or waiting.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_tailnet_notice(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ notice: &TailnetNotice,
+ card: RectF,
+ viewport: RectF,
+ ) -> anyhow::Result<()> {
+ if !row_visible(card.origin.y, card.size.height, viewport) {
+ return Ok(());
+ }
+ let widgets_start = self.widgets.len();
+ let (fill, border, mark) = if notice.invite {
+ (
+ palette.accent.mul_alpha(0.06),
+ palette.accent.mul_alpha(0.55),
+ palette.accent,
+ )
+ } else {
+ (palette.card_bg, palette.separator, palette.muted_text)
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ card.origin.x,
+ card.origin.y,
+ card.size.width,
+ card.size.height,
+ fill,
+ border,
+ ctx.px(CARD_RADIUS),
+ )?;
+ let pad = ctx.px(CARD_PAD);
+ let line_h = ctx.metrics.cell_size.height as f32;
+ let icon = (line_h * 1.8).clamp(ctx.px(40.0), ctx.px(52.0));
+ let icon_x = card.origin.x + pad;
+ ctx.draw_svg_icon(
+ layers,
+ notice.icon,
+ icon_x,
+ card.origin.y + (card.size.height - icon) / 2.0,
+ icon,
+ mark,
+ )?;
+
+ let mut right = card.max_x() - pad;
+ if let Some((label, which)) = &notice.button {
+ let button_w = ctx.measure_text_width(font, label) + ctx.px(56.0);
+ let button_h = ctx.px(BTN_H).min(card.size.height - ctx.px(16.0));
+ let button_x = right - button_w;
+ self.tailnet.notice = Some(*which);
+ let state = self.button_state(SshViewAction::TailnetNotice);
+ draw_button(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ palette,
+ ButtonSpec {
+ label,
+ action: SshViewAction::TailnetNotice,
+ rect: rect(
+ button_x,
+ card.origin.y + (card.size.height - button_h) / 2.0,
+ button_w,
+ button_h,
+ ),
+ state,
+ kind: WidgetKind::Button,
+ variant: if *which == NoticeButton::Settings {
+ ButtonVariant::Secondary
+ } else {
+ ButtonVariant::Primary
+ },
+ },
+ )?;
+ right = button_x - ctx.px(14.0);
+ }
+ let text_x = icon_x + icon + ctx.px(16.0);
+ let text_w = (right - text_x).max(0.0);
+ let stack = line_h * 2.0 + ctx.px(4.0);
+ let title_y = card.origin.y + ((card.size.height - stack) / 2.0).max(ctx.px(8.0));
+ ctx.draw_text(
+ layers,
+ font,
+ text_x,
+ title_y,
+ &notice.title,
+ palette.text,
+ text_w,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ text_x,
+ title_y + line_h + ctx.px(4.0),
+ &notice.subtitle,
+ palette.muted_text,
+ text_w,
+ )?;
+ self.widgets.clip_since(widgets_start, viewport);
+ Ok(())
+ }
+
+ /// A labelled text field: the host form's, or the Tailscale panel's.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_input_row(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ tokens: UiTokens,
+ cursor_on: bool,
+ label: &str,
+ focus: Focus,
+ action: SshViewAction,
+ shown: &str,
+ placeholder: &str,
+ x: f32,
+ y: f32,
+ width: f32,
+ ) -> anyhow::Result<f32> {
+ let line_h = ctx.metrics.cell_size.height as f32;
+ ctx.draw_text(layers, font, x, y, label, palette.muted_text, width)?;
+ let input_y = y + line_h + ctx.px(LABEL_GAP);
+ let text_pad = ctx.px(12.0);
+ self.resolve_pending_caret_click(ctx, font, focus, shown, x + text_pad);
+ let caret = self.caret_for(focus);
+ let focused = self.focus == focus;
+ draw_text_input(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ tokens,
+ text_pad,
+ cursor_on,
+ TextInputSpec {
+ placeholder,
+ text: shown,
+ rect: rect(x, input_y, width, ctx.px(INPUT_H)),
+ focused,
+ selected_all: false,
+ action,
+ },
+ caret,
+ )?;
+ Ok(input_y + ctx.px(INPUT_H))
+ }
+
+ /// The Tailscale panel, in the inspector's place: the switch, how the
+ /// node is doing, how it logs in, where it connects and under what
+ /// name, and leaving for good.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_tailnet_panel(
+ &mut self,
+ ctx: &DrawContext,
+ title_ctx: &DrawContext,
+ section_ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ title_font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ tokens: UiTokens,
+ cursor_on: bool,
+ area: RectF,
+ view: &TailnetView,
+ ) -> anyhow::Result<()> {
+ let tr = crate::i18n::tr;
+ self.form_area = area;
+ let x = area.origin.x;
+ let w = area.size.width;
+ let pad = ctx.px(20.0);
+ let inner = (w - pad * 2.0).max(0.0);
+ let line_h = ctx.metrics.cell_size.height as f32;
+ let section_h = section_ctx.metrics.cell_size.height as f32;
+ let title_h = title_ctx.metrics.cell_size.height as f32;
+ let field_h = Self::field_row_height(ctx);
+ let gap = ctx.px(FIELD_GAP);
+ let card_gap = ctx.px(INSPECTOR_CARD_GAP);
+ let toggle_w = ctx.px(64.0);
+ let toggle_h = ctx.px(36.0);
+
+ // The header does not scroll: the switch is what the panel is for.
+ let band = title_h.max(toggle_h);
+ let header_h = band + ctx.px(18.0);
+ let body_top = area.origin.y + header_h;
+ let body_height = (area.max_y() - body_top).max(0.0);
+ self.form_scroll
+ .set_extents(body_height, self.form_content_h);
+ let top = body_top - self.form_scroll.offset;
+ let mut y = top;
+
+ let fields: [String; TAILNET_FIELD_COUNT] =
+ std::array::from_fn(|field| self.tailnet.fields[field].text().to_string());
+ let login = self.tailnet.login_url.is_some();
+ let copied = self
+ .tailnet
+ .copied_until
+ .is_some_and(|until| Instant::now() < until);
+ let wrap = |text: &str, width: f32| -> Vec<String> {
+ if width <= 0.0 {
+ return Vec::new();
+ }
+ wrap_snippet_text_for_width(text, 6, false, |segment| {
+ ctx.measure_text_width(font, segment) / width
+ })
+ };
+ // The state by its dot, then what else holds.
+ let tone = tailnet_status(view).map_or(Tone::Off, |(_, tone)| tone);
+ let dot = ctx.px(9.0);
+ let dot_room = dot + ctx.px(8.0);
+ let state_lines = wrap(&tailnet_state_text(view), inner - dot_room);
+ let mut notes: Vec<(Vec<String>, LinearRgba)> = Vec::new();
+ if view.enabled && view.serves_ssh {
+ notes.push((
+ wrap(&tr("ssh-tailscale-serving-ssh"), inner),
+ palette.muted_text,
+ ));
+ }
+ if let Some(error) = &view.error {
+ notes.push((
+ wrap(
+ &tr_named("ssh-tailscale-save-error", &[("error", error.clone())]),
+ inner,
+ ),
+ palette.danger,
+ ));
+ }
+ if let Some(error) = &view.read_error {
+ notes.push((
+ wrap(
+ &tr_named("ssh-tailscale-read-error", &[("error", error.clone())]),
+ inner,
+ ),
+ palette.danger,
+ ));
+ }
+ let note_gap = ctx.px(6.0);
+ let status_rows = state_lines.len() as f32 * line_h
+ + notes
+ .iter()
+ .map(|(lines, _)| note_gap + lines.len() as f32 * line_h)
+ .sum::<f32>();
+ let login_lines = if login {
+ wrap(&tr("ssh-tailscale-login-description"), inner)
+ } else {
+ Vec::new()
+ };
+ // Only with something to forget.
+ let logout = view.has_identity || view.has_auth_key;
+ let logout_lines = if logout {
+ wrap(&tr("ssh-tailscale-logout-description"), inner)
+ } else {
+ Vec::new()
+ };
+
+ // Recorded and replayed clipped to the body, as the host form is.
+ let mut heap = HeapQuadAllocator::default();
+ let body_widgets_start = self.widgets.len();
+ {
+ let mut body_layers = TripleLayerQuadAllocator::Heap(&mut heap);
+
+ // ---- Status
+ let status_h = Self::inspector_card_height(ctx, section_h, &[status_rows]);
+ let mut fy = Self::paint_inspector_card(
+ ctx,
+ section_ctx,
+ &mut body_layers,
+ section_font,
+ palette,
+ tokens,
+ &tr("ssh-tailscale-status"),
+ rect(x, y, w, status_h),
+ )?;
+ ctx.draw_disc(
+ &mut body_layers,
+ 1,
+ x + pad + dot / 2.0,
+ fy + line_h / 2.0,
+ dot,
+ tone.color(palette),
+ )?;
+ for line in &state_lines {
+ ctx.draw_text(
+ &mut body_layers,
+ font,
+ x + pad + dot_room,
+ fy,
+ line,
+ palette.text,
+ inner - dot_room,
+ )?;
+ fy += line_h;
+ }
+ for (lines, color) in &notes {
+ fy += note_gap;
+ for line in lines {
+ ctx.draw_text(&mut body_layers, font, x + pad, fy, line, *color, inner)?;
+ fy += line_h;
+ }
+ }
+ y += status_h + card_gap;
+
+ // ---- Log in: the link while the control server waits for
+ // someone to approve this machine, and a key instead of it.
+ let mut login_rows = Vec::new();
+ if login {
+ login_rows
+ .push(login_lines.len() as f32 * line_h + ctx.px(LABEL_GAP) + ctx.px(BTN_H));
+ }
+ login_rows.push(field_h);
+ let login_h = Self::inspector_card_height(ctx, section_h, &login_rows);
+ let mut fy = Self::paint_inspector_card(
+ ctx,
+ section_ctx,
+ &mut body_layers,
+ section_font,
+ palette,
+ tokens,
+ &tr("ssh-tailscale-login-section"),
+ rect(x, y, w, login_h),
+ )?;
+ if login {
+ for line in &login_lines {
+ ctx.draw_text(
+ &mut body_layers,
+ font,
+ x + pad,
+ fy,
+ line,
+ palette.muted_text,
+ inner,
+ )?;
+ fy += line_h;
+ }
+ fy += ctx.px(LABEL_GAP);
+ let open_label = tr("ssh-tailscale-login-open");
+ let copy_label = tr(if copied {
+ "ssh-tailscale-copied"
+ } else {
+ "ssh-tailscale-login-copy"
+ });
+ let button_gap = ctx.px(10.0);
+ let open_w = (ctx.measure_text_width(font, &open_label) + ctx.px(56.0)).min(inner);
+ let copy_w = (ctx.measure_text_width(font, &copy_label) + ctx.px(56.0))
+ .min((inner - open_w - button_gap).max(0.0));
+ for (label, action, variant, button_x, button_w) in [
+ (
+ &open_label,
+ SshViewAction::OpenTailnetLogin,
+ ButtonVariant::Primary,
+ x + pad,
+ open_w,
+ ),
+ (
+ &copy_label,
+ SshViewAction::CopyTailnetLogin,
+ ButtonVariant::Secondary,
+ x + pad + open_w + button_gap,
+ copy_w,
+ ),
+ ] {
+ if button_w <= 0.0 {
+ continue;
+ }
+ let state = self.button_state(action);
+ draw_button(
+ ctx,
+ &mut body_layers,
+ font,
+ &mut self.widgets,
+ palette,
+ ButtonSpec {
+ label,
+ action,
+ rect: rect(button_x, fy, button_w, ctx.px(BTN_H)),
+ state,
+ kind: WidgetKind::Button,
+ variant,
+ },
+ )?;
+ }
+ fy += ctx.px(BTN_H) + gap;
+ }
+ // Typed characters show as dots, one each, so the caret and the
+ // selection still land between them.
+ let typed_key = "\u{2022}".repeat(fields[TAILNET_AUTH_KEY].chars().count());
+ let key_hint = tr(if view.has_auth_key {
+ "ssh-tailscale-auth-key-saved"
+ } else {
+ "ssh-tailscale-auth-key-placeholder"
+ });
+ self.paint_input_row(
+ ctx,
+ &mut body_layers,
+ font,
+ palette,
+ tokens,
+ cursor_on,
+ &tr("ssh-tailscale-auth-key"),
+ Focus::Tailnet(TAILNET_AUTH_KEY),
+ SshViewAction::FocusTailnetField(TAILNET_AUTH_KEY),
+ &typed_key,
+ &key_hint,
+ x + pad,
+ fy,
+ inner,
+ )?;
+ y += login_h + card_gap;
+
+ // ---- Connection: where the node signs in, and as what.
+ let connection_h = Self::inspector_card_height(ctx, section_h, &[field_h, field_h]);
+ let mut fy = Self::paint_inspector_card(
+ ctx,
+ section_ctx,
+ &mut body_layers,
+ section_font,
+ palette,
+ tokens,
+ &tr("ssh-group-connection"),
+ rect(x, y, w, connection_h),
+ )?;
+ fy = self.paint_input_row(
+ ctx,
+ &mut body_layers,
+ font,
+ palette,
+ tokens,
+ cursor_on,
+ &tr("ssh-tailscale-control"),
+ Focus::Tailnet(TAILNET_CONTROL_URL),
+ SshViewAction::FocusTailnetField(TAILNET_CONTROL_URL),
+ &fields[TAILNET_CONTROL_URL],
+ &tr("ssh-tailscale-control-placeholder"),
+ x + pad,
+ fy,
+ inner,
+ )? + gap;
+ self.paint_input_row(
+ ctx,
+ &mut body_layers,
+ font,
+ palette,
+ tokens,
+ cursor_on,
+ &tr("ssh-tailscale-hostname"),
+ Focus::Tailnet(TAILNET_HOSTNAME),
+ SshViewAction::FocusTailnetField(TAILNET_HOSTNAME),
+ &fields[TAILNET_HOSTNAME],
+ &tr("ssh-tailscale-hostname-placeholder"),
+ x + pad,
+ fy,
+ inner,
+ )?;
+ y += connection_h + card_gap;
+
+ // ---- Log out
+ if logout {
+ let label = tr("ssh-tailscale-logout");
+ let label_pad = ctx.px(12.0);
+ let label_w = ctx.measure_text_width(font, &label);
+ let action = SshViewAction::TailnetLogout;
+ let hit = rect(
+ x,
+ y,
+ (label_w + label_pad * 2.0).min(w),
+ line_h + ctx.px(14.0),
+ );
+ self.widgets.push(hit, WidgetKind::Button, action);
+ if self.button_state(action) != ControlState::Normal {
+ ctx.draw_rounded_rect(
+ &mut body_layers,
+ 0,
+ hit.origin.x,
+ hit.origin.y,
+ hit.size.width,
+ hit.size.height,
+ palette.control_hover_bg,
+ ctx.px(8.0),
+ )?;
+ }
+ ctx.draw_text(
+ &mut body_layers,
+ font,
+ x + label_pad,
+ y + ctx.px(7.0),
+ &label,
+ palette.danger,
+ label_w,
+ )?;
+ y += hit.size.height + ctx.px(4.0);
+ for line in &logout_lines {
+ ctx.draw_text(
+ &mut body_layers,
+ font,
+ x + label_pad,
+ y,
+ line,
+ palette.muted_text,
+ inner,
+ )?;
+ y += line_h;
+ }
+ }
+ y += ctx.px(PAD);
+ }
+ self.form_content_h = y - top;
+ let clip = QuadClipRect::from_top_left_pixels(
+ area.origin.x,
+ body_top,
+ area.max_x(),
+ area.max_y(),
+ &ctx.dimensions,
+ );
+ self.widgets.clip_since(
+ body_widgets_start,
+ rect(area.origin.x, body_top, area.size.width, body_height),
+ );
+ heap.apply_to_clipped(layers, clip, 1.0)?;
+
+ // The header: the name, and the switch.
+ let hy = area.origin.y;
+ title_ctx.draw_text_on_layer(
+ layers,
+ 2,
+ title_font,
+ x,
+ hy + (band - title_h) / 2.0,
+ &tr("ssh-group-tailscale"),
+ palette.text,
+ (w - toggle_w - ctx.px(12.0)).max(0.0),
+ )?;
+ draw_toggle(
+ ctx,
+ layers,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ rect(
+ x + w - toggle_w,
+ hy + (band - toggle_h) / 2.0,
+ toggle_w,
+ toggle_h,
+ ),
+ view.enabled,
+ SshViewAction::ToggleTailnet,
+ )?;
+ Ok(())
+ }
+}
+
+/// Close the view and open a disconnected remote thread on the main window.
+fn open_thread_response(project_id: String) -> ContentViewResponse {
+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {
+ let window = tw.window.as_ref().cloned();
+ if let Some(window) = window {
+ if tw.open_ssh_host_thread_without_connecting(project_id, &window) {
+ tw.close_content_view();
+ }
+ }
+ }))
+}
+
+impl ContentView for SshHostsView {
+ fn title(&self) -> String {
+ crate::i18n::tr("ssh-hosts-title")
+ }
+
+ fn tab_key(&self) -> Option<String> {
+ Some(SSH_HOSTS_CONTENT_VIEW_KEY.to_string())
+ }
+
+ fn wants_cursor_blink(&self) -> bool {
+ // A text field is always focused while this view is open.
+ true
+ }
+
+ fn paint(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ title_font: &Rc<LoadedFont>,
+ section_font: &Rc<LoadedFont>,
+ _caption_font: &Rc<LoadedFont>,
+ cursor_on: bool,
+ ) -> anyhow::Result<()> {
+ self.paint_impl(
+ ctx,
+ layers,
+ area,
+ palette,
+ font,
+ title_font,
+ section_font,
+ cursor_on,
+ )
+ }
+
+ fn run_remote_host_command(
+ &mut self,
+ host_id: &str,
+ command: RemoteHostCommand,
+ ) -> ContentViewResponse {
+ self.run_host_command(host_id, command)
+ }
+
+ fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
+ let response = self.on_mouse_impl(x, y, kind);
+ self.commit_left_tailnet_fields();
+ response
+ }
+
+ fn on_wheel(&mut self, x: f32, y: f32, event: &MouseEvent) -> ContentViewResponse {
+ let scale = self.last_ui_scale;
+ let scroll = if self.point_in_host_list(x, y) {
+ &mut self.scroll
+ } else if contains(self.form_area, x, y) {
+ &mut self.form_scroll
+ } else {
+ return ContentViewResponse::Ignored;
+ };
+ if apply_wheel(event, scroll, scale) {
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Ignored
+ }
+ }
+
+ fn next_frame_time(&self) -> Option<Instant> {
+ if self.scroll_animating {
+ return Some(Instant::now());
+ }
+ // The tailnet changes elsewhere: the page reads it again every
+ // couple of seconds while it shows. And "Copied" goes back.
+ let poll = (self.window.is_some() && crate::tailnet::available())
+ .then(crate::tailnet::next_poll_at)
+ .flatten();
+ let copied = self
+ .tailnet
+ .copied_until
+ .filter(|until| *until > Instant::now());
+ poll.into_iter().chain(copied).min()
+ }
+
+ fn on_key(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
+ let response = self.on_key_impl(key, mods);
+ self.commit_left_tailnet_fields();
+ response
+ }
+
+ fn on_paste(&mut self, text: &str) -> ContentViewResponse {
+ self.on_paste_impl(text)
+ }
+
+ fn begin_new_remote_host(&mut self) {
+ // Same reset the `+` button performs; the list refreshes on paint.
+ self.open_new_form();
+ }
+
+ fn show_tailscale_panel(&mut self) {
+ self.open_tailnet_panel();
+ }
+
+ fn copy_text(&self) -> Option<String> {
+ // A key typed into the Tailscale panel never leaves it.
+ if self.focus == Focus::Tailnet(TAILNET_AUTH_KEY) {
+ return None;
+ }
+ let input = self.focused_input()?;
+ let text = input
+ .caret_selected_text()
+ .unwrap_or_else(|| input.text().to_string());
+ (!text.is_empty()).then_some(text)
+ }
+
+ fn cut_text(&mut self) -> Option<String> {
+ if self.focus == Focus::Tailnet(TAILNET_AUTH_KEY) {
+ return None;
+ }
+ self.take_focused_selection()
+ }
+}
+
+#[cfg(test)]
mod tests {
use super::{
focus_after_collapsing_advanced, ssh_options_from_rows, tab_stops_for, text_input_with,
ContentViewResponse, Focus, HostForm, RemoteHostCommand, SshHostsView, BASE_FIELD_COUNT,
- FIELD_HOST, FIELD_NAME, FIELD_PORT, FIELD_USER, FIELD_WORKSPACE,
+ FIELD_HOST, FIELD_NAME, FIELD_PORT, FIELD_USER, FIELD_WORKSPACE, TAILNET_AUTH_KEY,
+ TAILNET_CONTROL_URL, TAILNET_FIELD_COUNT, TAILNET_HOSTNAME,
};
- use crate::ssh_hosts::{SshHostEntry, SshHostSource, SshHostSpec};
+ use crate::ssh_hosts::{SshHostEntry, SshHostSource, SshHostSpec, SshNetwork};
+ use wezterm_term::{KeyCode, KeyModifiers};
fn spec(label: &str, host: &str) -> SshHostSpec {
SshHostSpec {
@@ -3024,6 +4677,7 @@ mod tests {
host: host.to_string(),
port: Some(2222),
other_addresses: Vec::new(),
+ network: Default::default(),
username: Some("deploy".to_string()),
identity_file: Some("~/.ssh/id_ed25519".to_string()),
password: None,
@@ -3197,6 +4851,158 @@ mod tests {
assert_eq!(tab_stops_for(&form).len(), BASE_FIELD_COUNT);
}
+ fn tailnet_machine(name: &str, address: &str) -> crate::tailnet::Machine {
+ crate::tailnet::Machine {
+ name: name.to_string(),
+ target: format!("{name}.example.ts.net"),
+ fqdn: format!("{name}.example.ts.net"),
+ addresses: vec![address.parse().unwrap()],
+ online: Some(true),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn a_machine_saved_as_a_host_connects_the_way_it_was_saved() {
+ let mut view = SshHostsView::new();
+ view.saved_hosts = vec![SshHostEntry {
+ id: "ssh-saved".to_string(),
+ source: SshHostSource::ThinkTerm,
+ spec: spec("server-b", "100.64.0.7"),
+ }];
+ view.tailnet.machines = vec![
+ tailnet_machine("server-b", "100.64.0.7"),
+ tailnet_machine("build-box", "100.64.0.8"),
+ ];
+ assert!(view.saved_host_for(&view.tailnet.machines[0]).is_none());
+ view.saved_hosts[0].spec.network = SshNetwork::Tailnet;
+ assert!(view.saved_host_for(&view.tailnet.machines[0]).is_some());
+ assert!(view.saved_host_for(&view.tailnet.machines[1]).is_none());
+
+ // Saved: straight to it, no form to fill in again.
+ assert!(matches!(
+ view.open_tailnet_machine(0),
+ ContentViewResponse::Run(_)
+ ));
+ assert!(view.form.is_none());
+
+ // Not saved: a new host, its name and address filled in, waiting
+ // for whom to sign in as.
+ assert!(matches!(
+ view.open_tailnet_machine(1),
+ ContentViewResponse::Redraw
+ ));
+ let form = view.form.as_ref().expect("a new host's form");
+ assert!(form.editing.is_none());
+ assert_eq!(form.network, SshNetwork::Tailnet);
+ assert_eq!(form.fields[FIELD_NAME].text(), "build-box");
+ assert_eq!(form.fields[FIELD_HOST].text(), "build-box.example.ts.net");
+ assert_eq!(view.focus, Focus::Field(FIELD_USER));
+
+ // A host that reaches it by one of its other addresses is it too.
+ let mut devbox = spec("devbox", "192.0.2.5");
+ devbox.network = SshNetwork::Tailnet;
+ devbox.other_addresses = vec!["build-box".to_string()];
+ view.saved_hosts.push(SshHostEntry {
+ id: "ssh-devbox".to_string(),
+ source: SshHostSource::ThinkTerm,
+ spec: devbox,
+ });
+ assert_eq!(
+ view.saved_host_for(&view.tailnet.machines[1])
+ .map(|entry| entry.id.as_str()),
+ Some("ssh-devbox")
+ );
+ }
+
+ #[test]
+ fn a_new_host_uses_the_system_until_its_network_is_selected() {
+ let mut view = SshHostsView::new();
+ view.open_new_form();
+ assert_eq!(view.form.as_ref().unwrap().network, SshNetwork::System);
+ view.apply(super::SshViewAction::SetNetwork(SshNetwork::Tailnet));
+ assert_eq!(view.form.as_ref().unwrap().network, SshNetwork::Tailnet);
+ view.apply(super::SshViewAction::ToggleMosh);
+ let form = view.form.as_ref().unwrap();
+ assert!(!form.use_mosh);
+ assert!(form.error.is_some());
+ view.apply(super::SshViewAction::SetNetwork(SshNetwork::System));
+ view.apply(super::SshViewAction::ToggleMosh);
+ assert!(view.form.as_ref().unwrap().use_mosh);
+ view.apply(super::SshViewAction::SetNetwork(SshNetwork::Tailnet));
+ assert_eq!(view.form.as_ref().unwrap().network, SshNetwork::System);
+ }
+
+ #[test]
+ fn the_tailscale_panel_and_a_host_form_take_turns() {
+ use super::ContentView;
+ if !crate::tailnet::available() {
+ return;
+ }
+ let mut view = SshHostsView::new();
+ view.open_new_form();
+ view.show_tailscale_panel();
+ assert!(view.tailnet.panel_open);
+ assert!(view.form.is_none());
+ view.open_new_form();
+ assert!(!view.tailnet.panel_open);
+ assert!(view.form.is_some());
+
+ view.show_tailscale_panel();
+ view.focus = Focus::Tailnet(TAILNET_HOSTNAME);
+ // Escape closes the panel, not the page.
+ assert!(matches!(
+ view.on_key(KeyCode::Escape, KeyModifiers::NONE),
+ ContentViewResponse::Redraw
+ ));
+ assert!(!view.tailnet.panel_open);
+ assert_eq!(view.focus, Focus::Search);
+ }
+
+ #[test]
+ fn a_tailscale_field_goes_out_only_once_typed_into() {
+ if !crate::tailnet::available() {
+ return;
+ }
+ let mut view = SshHostsView::new();
+ view.open_tailnet_panel();
+ view.focus = Focus::Tailnet(TAILNET_CONTROL_URL);
+ // Moving the caret through it is no edit.
+ view.edit_focused(|input| input.caret_move_home(false));
+ assert_eq!(view.tailnet.dirty, [false; TAILNET_FIELD_COUNT]);
+ view.edit_focused(|input| input.caret_insert("https://headscale.example", false));
+ assert!(view.tailnet.dirty[TAILNET_CONTROL_URL]);
+ // Escape leaves without sending it.
+ use super::ContentView;
+ view.on_key(KeyCode::Escape, KeyModifiers::NONE);
+ assert!(!view.tailnet.panel_open);
+ assert_eq!(view.tailnet.dirty, [false; TAILNET_FIELD_COUNT]);
+ assert_eq!(view.tailnet.changes, [None; TAILNET_FIELD_COUNT]);
+ }
+
+ #[test]
+ fn an_auth_key_typed_into_the_panel_is_never_copied() {
+ use super::ContentView;
+ if !crate::tailnet::available() {
+ return;
+ }
+ let mut view = SshHostsView::new();
+ view.open_tailnet_panel();
+ view.focus = Focus::Tailnet(TAILNET_AUTH_KEY);
+ view.tailnet.fields[TAILNET_AUTH_KEY].set_text_end("tskey-auth-example".to_string());
+ view.tailnet.fields[TAILNET_AUTH_KEY].caret_select_all();
+ assert_eq!(view.copy_text(), None);
+ assert_eq!(view.cut_text(), None);
+ assert_eq!(
+ view.tailnet.fields[TAILNET_AUTH_KEY].text(),
+ "tskey-auth-example"
+ );
+ // The other fields copy as any field does.
+ view.focus = Focus::Tailnet(TAILNET_HOSTNAME);
+ view.tailnet.fields[TAILNET_HOSTNAME].set_text_end("devbox".to_string());
+ assert_eq!(view.copy_text().as_deref(), Some("devbox"));
+ }
+
#[test]
fn tab_order_covers_option_rows_only_while_advanced_is_open() {
let mut form = HostForm::default();
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index ebb64067..84e517b6 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -118,6 +118,13 @@ pub enum SvgIcon {
Timer,
Type,
Laptop,
+ KeyRound,
+ LogOut,
+ Monitor,
+ Network,
+ /// Apple's mark, tinted like the rest rather than painted in its own
+ /// black: drawn white, it vanishes on a light theme.
+ Apple,
QrCode,
Smartphone,
Upload,
@@ -386,6 +393,11 @@ impl SvgIcon {
Self::Timer => include_bytes!("../../../../third_party/lucide/icons/timer.svg"),
Self::Type => include_bytes!("../../../../third_party/lucide/icons/type.svg"),
Self::Laptop => include_bytes!("../../../../third_party/lucide/icons/laptop.svg"),
+ Self::KeyRound => include_bytes!("../../../../third_party/lucide/icons/key-round.svg"),
+ Self::LogOut => include_bytes!("../../../../third_party/lucide/icons/log-out.svg"),
+ Self::Monitor => include_bytes!("../../../../third_party/lucide/icons/monitor.svg"),
+ Self::Apple => include_bytes!("../../../../third_party/simple-icons/icons/apple.svg"),
+ Self::Network => include_bytes!("../../../../third_party/lucide/icons/network.svg"),
Self::QrCode => include_bytes!("../../../../third_party/lucide/icons/qr-code.svg"),
Self::Smartphone => {
include_bytes!("../../../../third_party/lucide/icons/smartphone.svg")
@@ -415,7 +427,11 @@ impl SvgIcon {
pub fn rasterize_with_rotation(self, size: usize, degrees: f32) -> Result<Image> {
let svg = std::str::from_utf8(self.bytes()).context("SVG asset is not UTF-8")?;
// Lucide icons use `currentColor`; tint them white for the dark UI.
- let svg = svg.replace("currentColor", "#ffffff");
+ let mut svg = svg.replace("currentColor", "#ffffff");
+ // A simple-icons mark names no colour at all, which is black.
+ if self == Self::Apple {
+ svg = svg.replacen("<path ", "<path fill=\"#ffffff\" ", 1);
+ }
rasterize_svg_str(&svg, size, degrees)
}
}
@@ -541,6 +557,7 @@ pub enum BrandIcon {
AgentCopilot,
AgentKimi,
Alpine,
+ Android,
Anthropic,
Apple,
ArchLinux,
@@ -592,6 +609,9 @@ impl BrandIcon {
Self::Alpine => {
include_bytes!("../../../../third_party/simple-icons/icons/alpinelinux.svg")
}
+ Self::Android => {
+ include_bytes!("../../../../third_party/simple-icons/icons/android.svg")
+ }
Self::Anthropic => {
include_bytes!("../../../../third_party/simple-icons/icons/anthropic.svg")
}
@@ -649,6 +669,7 @@ impl BrandIcon {
Self::AgentCopilot => (0x24, 0x96, 0xED),
Self::AgentKimi => (0x17, 0x83, 0xFF),
Self::Alpine => (0x0D, 0x59, 0x7F),
+ Self::Android => (0x3D, 0xDC, 0x84),
Self::Anthropic => (0x19, 0x19, 0x19),
Self::Apple => (0x00, 0x00, 0x00),
Self::ArchLinux => (0x17, 0x93, 0xD1),
@@ -888,6 +909,10 @@ mod tests {
SvgIcon::Terminal,
SvgIcon::Trash2,
SvgIcon::X,
+ // Remote Hosts' Tailscale group: the tailnet and its machines.
+ SvgIcon::Apple,
+ SvgIcon::Monitor,
+ SvgIcon::Network,
// What a plugin's panel is shown by in the selector.
SvgIcon::Activity,
SvgIcon::Bug,
@@ -917,6 +942,15 @@ mod tests {
}
}
+ #[test]
+ fn the_apple_mark_is_white_to_be_tinted() {
+ // Black, the tint it is drawn in would not show.
+ let data: Vec<u8> = SvgIcon::Apple.rasterize(24).unwrap().into();
+ assert!(data
+ .chunks_exact(4)
+ .any(|pixel| pixel.iter().all(|channel| *channel > 200)));
+ }
+
#[test]
fn brand_icons_rasterize() {
for icon in [
@@ -927,6 +961,7 @@ mod tests {
BrandIcon::AgentCopilot,
BrandIcon::AgentKimi,
BrandIcon::Alpine,
+ BrandIcon::Android,
BrandIcon::Anthropic,
BrandIcon::Apple,
BrandIcon::ArchLinux,
diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rs
index 07022883..3ac9f085 100644
--- a/wezterm-gui/src/ui/icons.rs
+++ b/wezterm-gui/src/ui/icons.rs
@@ -19,6 +19,7 @@ pub(crate) enum SettingsIcon {
Archived,
Backup,
Web,
+ Tailscale,
CommandPalette,
Search,
Clear,
@@ -45,6 +46,7 @@ impl SettingsIcon {
Self::Archived => SvgIcon::Archive,
Self::Backup => SvgIcon::Save,
Self::Web => SvgIcon::Globe,
+ Self::Tailscale => SvgIcon::Network,
Self::CommandPalette => SvgIcon::SquareTerminal,
Self::Search => SvgIcon::Search,
Self::Clear => SvgIcon::X,
diff --git a/wezterm-gui/src/web_settings.rs b/wezterm-gui/src/web_settings.rs
index 446299de..0091cf15 100644
--- a/wezterm-gui/src/web_settings.rs
+++ b/wezterm-gui/src/web_settings.rs
@@ -8,6 +8,7 @@
//! One cache for the process: there is one mux connection, and a second
//! settings window would be asking the same server the same questions.
+use crate::page_poll::PollTimer;
use codec::{WebServerStatus, WebTokenInfo};
use mux::Mux;
use std::sync::Mutex;
@@ -47,9 +48,6 @@ pub struct WebState {
pub loaded: bool,
/// When the last answer landed, so the page can go and ask again.
pub refreshed_at: Option<Instant>,
- /// A wake-up is already scheduled; a second would double the rate
- /// every time the window repainted for an unrelated reason.
- pub poll_armed: bool,
/// Bumped by every user action that lands. A poll that was already in
/// flight when it did carries a picture from before the click, and is
/// thrown away rather than painted over the result.
@@ -214,8 +212,12 @@ pub fn arm_poll(window: Window) {
// would wake, paint, find the poll not due, and arm again at display
// rate for as long as the request took. `finish` repaints when the
// answer lands, and that paint arms the next wait.
+ //
+ // One wake-up at a time: a second would double the rate every time the
+ // window repainted for an unrelated reason.
+ static POLL: PollTimer = PollTimer::new();
let due_in = with_state(|s| {
- if s.busy || s.polling || std::mem::replace(&mut s.poll_armed, true) {
+ if s.busy || s.polling {
return None;
}
Some(
@@ -224,15 +226,9 @@ pub fn arm_poll(window: Window) {
.unwrap_or(POLL_INTERVAL),
)
});
- let Some(due_in) = due_in else {
- return;
- };
- promise::spawn::spawn_into_main_thread(async move {
- smol::Timer::after(due_in).await;
- with_state(|s| s.poll_armed = false);
- window.invalidate();
- })
- .detach();
+ if let Some(due_in) = due_in {
+ POLL.arm(window, due_in);
+ }
}
/// Read the listener's state and the token list.
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index 42449809..5c99422e 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -1726,6 +1726,7 @@ pub fn create_space_on_domain(domain_name: &str, name: Option<String>) -> Result
remote_tree_mutation_allowed(Some(domain_name)),
"{domain_name} is disconnected"
);
+ let project_name = crate::ssh_hosts::connect_domain_label(domain_name);
let mut store = THREAD_STORE.lock();
store.normalize_after_load();
let name = name.unwrap_or_else(|| next_space_name(&store.spaces));
@@ -1737,7 +1738,7 @@ pub fn create_space_on_domain(domain_name: &str, name: Option<String>) -> Result
store.projects.push(Project {
id: project_id.clone(),
space_id: space_id.clone(),
- name: domain_name.to_string(),
+ name: project_name,
path: PathBuf::from(format!("wezterm-mux://{domain_name}")),
threads: vec![thread],
active_thread_id: Some(thread_id),
@@ -9485,7 +9486,9 @@ fn is_remote_project(project: &Project, spaces: &[Space]) -> bool {
/// misses it — same three-way test as `is_remote_project`), or this device.
fn origin_machine_for_project(project: &Project, spaces: &[Space]) -> (String, bool) {
let host_id = match project_machine(project, spaces) {
- ProjectMachine::Domain(domain) => return (domain, false),
+ ProjectMachine::Domain(domain) => {
+ return (crate::ssh_hosts::connect_domain_label(&domain), false)
+ }
ProjectMachine::Local => return ("Local".to_string(), true),
ProjectMachine::Ssh(host_id) => host_id,
};
@@ -9835,6 +9838,7 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {
}
let mux_project_id = remote_project_id_for_space(space_id, &mux_domain_host_id(&domain_name));
+ let mux_project_name = crate::ssh_hosts::connect_domain_label(&domain_name);
let mut store = THREAD_STORE.lock();
let mut changed = false;
@@ -9896,7 +9900,7 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {
store.projects.push(Project {
id: mux_project_id.clone(),
space_id: space_id.to_string(),
- name: domain_name.clone(),
+ name: mux_project_name.clone(),
path: PathBuf::from(format!("wezterm-mux://{domain_name}")),
threads: vec![],
active_thread_id: None,
@@ -10010,6 +10014,7 @@ pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {
impl WorkspaceThreadStore {
fn ensure_mux_domain_space(&mut self, domain_name: &str) -> MuxDomainSpacePlan {
let store = self;
+ let label = crate::ssh_hosts::connect_domain_label(domain_name);
// A server can host several Spaces. Land on the one this device was last
// using; failing that its first Space; and only create one when we have
@@ -10017,10 +10022,7 @@ impl WorkspaceThreadStore {
let space_id = store
.preferred_space_for_domain(domain_name)
.unwrap_or_else(|| {
- store.create_space_record_for_domain(
- domain_name.to_string(),
- Some(domain_name.to_string()),
- )
+ store.create_space_record_for_domain(label.clone(), Some(domain_name.to_string()))
});
let host_id = mux_domain_host_id(domain_name);
@@ -10029,7 +10031,7 @@ impl WorkspaceThreadStore {
store.projects.push(Project {
id: project_id.clone(),
space_id: space_id.clone(),
- name: domain_name.to_string(),
+ name: label,
path: PathBuf::from(format!("wezterm-mux://{domain_name}")),
threads: vec![],
active_thread_id: None,