A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(web): Remote Hosts, other machines, tab icons and a phone layout
RoversXe24c09bc143d
diff --git a/Cargo.lock b/Cargo.lockindex 011bf46c..05803e14 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8867,6 +8867,7 @@ dependencies = ["thinkterm-render","thinkterm-session","thinkterm-snippets",+ "thinkterm-tab-icons","wasm-bindgen","wasm-bindgen-futures","web-sys",diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 6eda6e0c..63ad919a 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -1151,3 +1151,66 @@ session-import-check-result = Importergebnis prüfensession-import-still-running = Der Import läuft noch auf dem Zielrechner. Prüfen Sie das Ergebnis später erneut.session-import-result-interrupted = Der Dienst wurde unterbrochen oder die Anfrage ist abgelaufen. Das Ergebnis lässt sich nicht automatisch bestätigen. Prüfen Sie den Ziel-Space vor einem neuen Import.session-import-result-unavailable = Die Verbindung wurde unterbrochen. Prüfen Sie das Importergebnis, um die Verbindung wiederherzustellen und diese Anfrage abzurufen. Starten Sie keinen zweiten Import.++web-machines-title = Remote-Hosts+web-machines-here = Dieser Server+web-machines-connected = Verbunden+web-machines-others = Andere Rechner+web-machines-empty = Noch keine anderen Rechner. Fügen Sie hier einen hinzu oder tragen Sie ihn auf diesem Server in ~/.ssh/config ein.+web-machines-connect = Verbinden+web-machines-show = Anzeigen+web-machines-disconnect = Trennen+web-machines-forget = Entfernen+web-machines-retry = Erneut versuchen+web-machines-plain-ssh = Einfaches SSH-Terminal öffnen+web-machines-name = Name+web-machines-host = Host+web-machines-port = Port+web-machines-user = Benutzer+web-machines-password = Passwort+web-machines-optional = optional+web-machines-add-connect = Hinzufügen und verbinden+web-machines-cancel = Abbrechen+web-machines-from-ssh-config = ~/.ssh/config+web-machines-from-desktop = Desktop+web-machines-from-web = Hier hinzugefügt+web-machines-password-kept = Passwort gespeichert+web-machines-step-connecting = Verbinde…+web-machines-step-authenticating = Melde an…+web-machines-step-checking = Prüfe ThinkTerm dort…+web-machines-step-installing = Installiere ThinkTerm…+web-machines-step-updating = Aktualisiere ThinkTerm…+web-machines-step-starting = Starte ThinkTerm…+web-machines-reconnecting = Verbinde erneut…+web-machines-needs-you = Wartet auf Ihre Antwort+web-machines-not-connected = Nicht verbunden+web-machines-ask-host-key = Diesem Rechner vertrauen?+web-machines-ask-host-key-hint = Dieser Server war noch nie mit ihm verbunden. Prüfen Sie den Fingerabdruck, bevor Sie ihm vertrauen.+web-machines-ask-password = Passwort+web-machines-ask-code = Code+web-machines-ask-answer = Antwort+web-machines-ask-install = ThinkTerm dort installieren?+web-machines-ask-install-hint = Es wird für Ihren Benutzer in ~/.local/bin installiert, ohne root. Sie werden pro Rechner nur einmal gefragt.+web-machines-ask-replace = Das neuere ThinkTerm dort ersetzen?+web-machines-ask-replace-hint = Dort läuft ein neueres ThinkTerm als auf diesem Server. Die Version dieses Servers wird installiert und übernimmt die Sitzungen.+web-machines-ask-stop = Den alten ThinkTerm-Server dort beenden?+web-machines-ask-stop-hint = Er konnte seine Sitzungen nicht an die neue Version übergeben. Beenden schließt alle Sitzungen darin.+web-machines-remember = Auf diesem Server merken+web-machines-trust = Vertrauen+web-machines-install = Installieren+web-machines-replace = Ersetzen+web-machines-stop = Beenden+web-machines-not-now = Nicht jetzt+web-machines-continue = Weiter+web-machines-failed-unreachable = Nicht erreichbar+web-machines-failed-host-key = Sein Host-Schlüssel hat sich geändert+web-machines-failed-auth = Anmeldung fehlgeschlagen+web-machines-failed-cancelled = Abgebrochen+web-machines-failed-declined = ThinkTerm ist dort nicht eingerichtet+web-machines-failed-cannot-install = ThinkTerm kann dort nicht installiert werden+web-machines-failed-same-server = Das ist dieser Server+web-machines-failed-failed = Verbindung fehlgeschlagen+web-machines-failed-desktop = Die Desktop-App dort muss zuerst aktualisiert werden+web-machines-failed-gone = Nicht mehr in der Liste dieses Servers+web-machines-bad-port = Ein Port ist eine Zahl von 1 bis 65535+web-machines-details = Detailsdiff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex e4deaab8..b462d328 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -1151,3 +1151,66 @@ session-import-check-result = Check import resultsession-import-still-running = The import is still running on the target. Check again to retrieve its result.session-import-result-interrupted = The service was interrupted or the request expired. Its result cannot be confirmed automatically. Check the target Space before starting another import.session-import-result-unavailable = The connection was interrupted. Check the import result to reconnect and recover this request; do not start a second import.++web-machines-title = Remote Hosts+web-machines-here = This server+web-machines-connected = Connected+web-machines-others = Other machines+web-machines-empty = No other machines yet. Add one here, or list it in ~/.ssh/config on this server.+web-machines-connect = Connect+web-machines-show = Show+web-machines-disconnect = Disconnect+web-machines-forget = Forget+web-machines-retry = Try again+web-machines-plain-ssh = Open a plain SSH terminal+web-machines-name = Name+web-machines-host = Host+web-machines-port = Port+web-machines-user = User+web-machines-password = Password+web-machines-optional = optional+web-machines-add-connect = Add and connect+web-machines-cancel = Cancel+web-machines-from-ssh-config = ~/.ssh/config+web-machines-from-desktop = Desktop+web-machines-from-web = Added here+web-machines-password-kept = password kept+web-machines-step-connecting = Connecting…+web-machines-step-authenticating = Signing in…+web-machines-step-checking = Checking ThinkTerm there…+web-machines-step-installing = Installing ThinkTerm…+web-machines-step-updating = Updating ThinkTerm…+web-machines-step-starting = Starting ThinkTerm…+web-machines-reconnecting = Reconnecting…+web-machines-needs-you = Waiting for you+web-machines-not-connected = Not connected+web-machines-ask-host-key = Trust this machine?+web-machines-ask-host-key-hint = This server has not connected to it before. Check the fingerprint before you trust it.+web-machines-ask-password = Password+web-machines-ask-code = Code+web-machines-ask-answer = Answer+web-machines-ask-install = Install ThinkTerm there?+web-machines-ask-install-hint = It goes into ~/.local/bin for your user, with no root. You are asked only once for this machine.+web-machines-ask-replace = Replace the newer ThinkTerm there?+web-machines-ask-replace-hint = It runs a newer ThinkTerm than this server. This server's version is installed in its place and takes its sessions over.+web-machines-ask-stop = Stop the old ThinkTerm server there?+web-machines-ask-stop-hint = It could not hand its sessions to the new version. Stopping it ends every session in it.+web-machines-remember = Remember on this server+web-machines-trust = Trust+web-machines-install = Install+web-machines-replace = Replace+web-machines-stop = Stop it+web-machines-not-now = Not now+web-machines-continue = Continue+web-machines-failed-unreachable = Could not reach it+web-machines-failed-host-key = Its host key has changed+web-machines-failed-auth = Sign-in failed+web-machines-failed-cancelled = Cancelled+web-machines-failed-declined = ThinkTerm is not set up there+web-machines-failed-cannot-install = ThinkTerm cannot be installed there+web-machines-failed-same-server = That is this server+web-machines-failed-failed = Could not connect+web-machines-failed-desktop = The desktop app there needs updating first+web-machines-failed-gone = No longer on this server’s list+web-machines-bad-port = A port is a number from 1 to 65535+web-machines-details = Detailsdiff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 74b7a713..6d5274dc 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -1148,3 +1148,66 @@ session-import-check-result = Vérifier le résultatsession-import-still-running = L’importation est toujours en cours sur la machine cible. Vérifiez à nouveau son résultat dans un instant.session-import-result-interrupted = Le service a été interrompu ou la demande a expiré. Le résultat ne peut pas être confirmé automatiquement. Vérifiez le Space cible avant de lancer une nouvelle importation.session-import-result-unavailable = La connexion a été interrompue. Vérifiez le résultat pour vous reconnecter et récupérer cette demande, sans lancer une seconde importation.++web-machines-title = Hôtes distants+web-machines-here = Ce serveur+web-machines-connected = Connectées+web-machines-others = Autres machines+web-machines-empty = Aucune autre machine pour l’instant. Ajoutez-en une ici, ou indiquez-la dans ~/.ssh/config sur ce serveur.+web-machines-connect = Se connecter+web-machines-show = Afficher+web-machines-disconnect = Déconnecter+web-machines-forget = Retirer+web-machines-retry = Réessayer+web-machines-plain-ssh = Ouvrir un terminal SSH simple+web-machines-name = Nom+web-machines-host = Hôte+web-machines-port = Port+web-machines-user = Utilisateur+web-machines-password = Mot de passe+web-machines-optional = facultatif+web-machines-add-connect = Ajouter et se connecter+web-machines-cancel = Annuler+web-machines-from-ssh-config = ~/.ssh/config+web-machines-from-desktop = Bureau+web-machines-from-web = Ajoutée ici+web-machines-password-kept = mot de passe enregistré+web-machines-step-connecting = Connexion…+web-machines-step-authenticating = Authentification…+web-machines-step-checking = Vérification de ThinkTerm…+web-machines-step-installing = Installation de ThinkTerm…+web-machines-step-updating = Mise à jour de ThinkTerm…+web-machines-step-starting = Démarrage de ThinkTerm…+web-machines-reconnecting = Reconnexion…+web-machines-needs-you = En attente de votre réponse+web-machines-not-connected = Non connectée+web-machines-ask-host-key = Faire confiance à cette machine ?+web-machines-ask-host-key-hint = Ce serveur ne s’y est jamais connecté. Vérifiez l’empreinte avant de lui faire confiance.+web-machines-ask-password = Mot de passe+web-machines-ask-code = Code+web-machines-ask-answer = Réponse+web-machines-ask-install = Installer ThinkTerm sur cette machine ?+web-machines-ask-install-hint = Il est installé dans ~/.local/bin pour votre utilisateur, sans root. La question n’est posée qu’une fois par machine.+web-machines-ask-replace = Remplacer le ThinkTerm plus récent ?+web-machines-ask-replace-hint = Cette machine exécute un ThinkTerm plus récent que ce serveur. La version de ce serveur y est installée et reprend ses sessions.+web-machines-ask-stop = Arrêter l’ancien serveur ThinkTerm ?+web-machines-ask-stop-hint = Il n’a pas pu transmettre ses sessions à la nouvelle version. L’arrêter met fin à toutes ses sessions.+web-machines-remember = Mémoriser sur ce serveur+web-machines-trust = Faire confiance+web-machines-install = Installer+web-machines-replace = Remplacer+web-machines-stop = L’arrêter+web-machines-not-now = Pas maintenant+web-machines-continue = Continuer+web-machines-failed-unreachable = Machine injoignable+web-machines-failed-host-key = Sa clé d’hôte a changé+web-machines-failed-auth = Échec de l’authentification+web-machines-failed-cancelled = Annulé+web-machines-failed-declined = ThinkTerm n’y est pas installé+web-machines-failed-cannot-install = Impossible d’y installer ThinkTerm+web-machines-failed-same-server = C’est ce serveur+web-machines-failed-failed = Connexion impossible+web-machines-failed-desktop = L’application de bureau doit d’abord y être mise à jour+web-machines-failed-gone = N’est plus dans la liste de ce serveur+web-machines-bad-port = Un port est un nombre de 1 à 65535+web-machines-details = Détailsdiff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 2989f91e..39437bb4 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -1123,3 +1123,66 @@ session-import-check-result = インポート結果を確認session-import-still-running = 対象のマシンでインポートを実行中です。後でもう一度結果を確認してください。session-import-result-interrupted = サービスが中断されたか、リクエストの有効期限が切れたため、結果を自動確認できません。新しいインポートを始める前に対象の Space を確認してください。session-import-result-unavailable = 接続が中断されました。「インポート結果を確認」で再接続し、このリクエストの結果を取得してください。別のインポートを開始しないでください。++web-machines-title = リモートホスト+web-machines-here = このサーバー+web-machines-connected = 接続済み+web-machines-others = ほかのマシン+web-machines-empty = ほかのマシンはまだありません。ここで追加するか、このサーバーの ~/.ssh/config に書いてください。+web-machines-connect = 接続+web-machines-show = 表示+web-machines-disconnect = 切断+web-machines-forget = 削除+web-machines-retry = 再試行+web-machines-plain-ssh = 通常の SSH ターミナルを開く+web-machines-name = 名前+web-machines-host = ホスト+web-machines-port = ポート+web-machines-user = ユーザー+web-machines-password = パスワード+web-machines-optional = 任意+web-machines-add-connect = 追加して接続+web-machines-cancel = キャンセル+web-machines-from-ssh-config = ~/.ssh/config+web-machines-from-desktop = デスクトップ+web-machines-from-web = ここで追加+web-machines-password-kept = パスワード保存済み+web-machines-step-connecting = 接続しています…+web-machines-step-authenticating = サインインしています…+web-machines-step-checking = ThinkTerm を確認しています…+web-machines-step-installing = ThinkTerm をインストールしています…+web-machines-step-updating = ThinkTerm を更新しています…+web-machines-step-starting = ThinkTerm を起動しています…+web-machines-reconnecting = 再接続しています…+web-machines-needs-you = 回答を待っています+web-machines-not-connected = 未接続+web-machines-ask-host-key = このマシンを信頼しますか?+web-machines-ask-host-key-hint = このサーバーはまだ接続したことがありません。フィンガープリントを確認してから信頼してください。+web-machines-ask-password = パスワード+web-machines-ask-code = コード+web-machines-ask-answer = 回答+web-machines-ask-install = そのマシンに ThinkTerm をインストールしますか?+web-machines-ask-install-hint = あなたのユーザーで ~/.local/bin に入ります。root は不要です。マシンごとに一度だけ確認します。+web-machines-ask-replace = より新しい ThinkTerm を置き換えますか?+web-machines-ask-replace-hint = そのマシンの ThinkTerm はこのサーバーより新しいバージョンです。このサーバーのバージョンを入れ、セッションを引き継ぎます。+web-machines-ask-stop = 古い ThinkTerm サーバーを停止しますか?+web-machines-ask-stop-hint = セッションを新しいバージョンに引き継げませんでした。停止すると、その中のすべてのセッションが終了します。+web-machines-remember = このサーバーに保存+web-machines-trust = 信頼する+web-machines-install = インストール+web-machines-replace = 置き換える+web-machines-stop = 停止する+web-machines-not-now = 今はしない+web-machines-continue = 続ける+web-machines-failed-unreachable = 接続できませんでした+web-machines-failed-host-key = ホスト鍵が変わっています+web-machines-failed-auth = サインインに失敗しました+web-machines-failed-cancelled = キャンセルしました+web-machines-failed-declined = ThinkTerm が用意されていません+web-machines-failed-cannot-install = ThinkTerm をインストールできません+web-machines-failed-same-server = このサーバー自身です+web-machines-failed-failed = 接続できませんでした+web-machines-failed-desktop = そのマシンのデスクトップ版を先に更新してください+web-machines-failed-gone = このサーバーの一覧にもうありません+web-machines-bad-port = ポートは 1 から 65535 までの数字です+web-machines-details = 詳細diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex c27fcbc2..de7e343a 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -1123,3 +1123,66 @@ session-import-check-result = 检查导入结果session-import-still-running = 目标机器仍在导入。稍后再次检查,即可取回本次结果。session-import-result-interrupted = 服务曾中断或请求已过期,无法自动确认结果。请检查目标 Space 后再决定是否发起新的导入。session-import-result-unavailable = 连接已中断。请使用“检查导入结果”重新连接并查询本次请求,不要另行发起导入。++web-machines-title = 远程主机+web-machines-here = 这台服务器+web-machines-connected = 已连接+web-machines-others = 其他机器+web-machines-empty = 还没有其他机器。可以在这里添加,或写进这台服务器的 ~/.ssh/config。+web-machines-connect = 连接+web-machines-show = 显示+web-machines-disconnect = 断开+web-machines-forget = 移除+web-machines-retry = 重试+web-machines-plain-ssh = 打开普通 SSH 终端+web-machines-name = 名称+web-machines-host = 主机+web-machines-port = 端口+web-machines-user = 用户+web-machines-password = 密码+web-machines-optional = 可选+web-machines-add-connect = 添加并连接+web-machines-cancel = 取消+web-machines-from-ssh-config = ~/.ssh/config+web-machines-from-desktop = 桌面版+web-machines-from-web = 在这里添加+web-machines-password-kept = 已记住密码+web-machines-step-connecting = 正在连接…+web-machines-step-authenticating = 正在登录…+web-machines-step-checking = 正在检查那边的 ThinkTerm…+web-machines-step-installing = 正在安装 ThinkTerm…+web-machines-step-updating = 正在更新 ThinkTerm…+web-machines-step-starting = 正在启动 ThinkTerm…+web-machines-reconnecting = 正在重连…+web-machines-needs-you = 等你回答+web-machines-not-connected = 未连接+web-machines-ask-host-key = 信任这台机器?+web-machines-ask-host-key-hint = 这台服务器以前没连过它。请先核对指纹再信任。+web-machines-ask-password = 密码+web-machines-ask-code = 验证码+web-machines-ask-answer = 回答+web-machines-ask-install = 在那台机器上安装 ThinkTerm?+web-machines-ask-install-hint = 会以你的用户装进 ~/.local/bin,不需要 root。每台机器只问这一次。+web-machines-ask-replace = 替换那边更新的 ThinkTerm?+web-machines-ask-replace-hint = 那台机器的 ThinkTerm 比这台服务器的新。会装上这台服务器的版本,并接管它的会话。+web-machines-ask-stop = 停掉那边旧的 ThinkTerm 服务?+web-machines-ask-stop-hint = 它没能把会话交给新版本。停掉它会结束里面的所有会话。+web-machines-remember = 在这台服务器上记住+web-machines-trust = 信任+web-machines-install = 安装+web-machines-replace = 替换+web-machines-stop = 停掉+web-machines-not-now = 暂不+web-machines-continue = 继续+web-machines-failed-unreachable = 连不上这台机器+web-machines-failed-host-key = 它的主机密钥变了+web-machines-failed-auth = 登录失败+web-machines-failed-cancelled = 已取消+web-machines-failed-declined = 那边还没装 ThinkTerm+web-machines-failed-cannot-install = 那边装不了 ThinkTerm+web-machines-failed-same-server = 这就是当前这台服务器+web-machines-failed-failed = 连接失败+web-machines-failed-desktop = 那台机器上的桌面版需要先更新+web-machines-failed-gone = 这台服务器的列表里已经没有它了+web-machines-bad-port = 端口是 1 到 65535 之间的数字+web-machines-details = 详情diff --git a/thinkterm-mobile/src/core.rs b/thinkterm-mobile/src/core.rsindex 448f2061..7746c066 100644--- a/thinkterm-mobile/src/core.rs+++ b/thinkterm-mobile/src/core.rs@@ -971,6 +971,7 @@ impl State {rows,font_pinned: true,languages: vec![],+ server_version: attached.server_version.clone(),});host.events.set_wake(app.wake());{diff --git a/thinkterm-mobile/src/platform.rs b/thinkterm-mobile/src/platform.rsindex c66e9528..5c52d112 100644--- a/thinkterm-mobile/src/platform.rs+++ b/thinkterm-mobile/src/platform.rs@@ -234,6 +234,10 @@ impl Platform for MobilePlatform {true}+ fn bare_lone_pane(&self) -> bool {+ true+ }+fn set_title(&self, title: &str) {self.notify.on_title(title.to_string());}diff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rsindex 1cda8c4c..f2ef4d7c 100644--- a/thinkterm-session/src/pane.rs+++ b/thinkterm-session/src/pane.rs@@ -196,6 +196,12 @@ impl<H: SessionHost> PaneSession<H> {self.state().dimensions}+ /// The dimensions the server last reported, while `dimensions` may+ /// still be a frontend preview of another size.+ pub fn server_dimensions(&self) -> RenderableDimensions {+ self.state().server_dimensions+ }+pub fn cursor_position(&self) -> StableCursorPosition {self.state().cursor_position}diff --git a/thinkterm-web/Cargo.toml b/thinkterm-web/Cargo.tomlindex 67fab0af..2af0e3f6 100644--- a/thinkterm-web/Cargo.toml+++ b/thinkterm-web/Cargo.toml@@ -36,6 +36,7 @@ thinkterm-proto.workspace = truethinkterm-render = { workspace = true, features = ["wgpu"] }thinkterm-session.workspace = truethinkterm-snippets.workspace = true+thinkterm-tab-icons.workspace = truewezterm-color-types.workspace = truewezterm-term = { workspace = true, features = ["use_serde"] }wgpu.workspace = truediff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 527794e8..d02b72d1 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -207,6 +207,8 @@ pub struct Setup<P: Platform, L: Link> {pub font_pinned: bool,/// The browser's languages, for switching the locale by preference.pub languages: Vec<String>,+ /// The server's version, as it answered the handshake.+ pub server_version: String,}/// One pane on the page: its session and the state that is the page's@@ -304,6 +306,14 @@ pub struct Inner<P: Platform, L: Link> {/// The size the page started with: what "follow" goes back to.boot_size_pt: f64,languages: Vec<String>,+ /// What Settings › About names as the version: the server's, as it+ /// answered when the page attached.+ server_version: String,+ /// What leads each pane's terminal, as the server pushes it, for the+ /// tab icons. A pane the listing no longer has is let go with it.+ programs: std::collections::HashMap<PaneId, thinkterm_proto::ForegroundProgram>,+ /// The cards the page's server sent for its tabs (`tab_icons`).+ tab_icons: Option<crate::tab_icons::TabIcons>,/// Palette picks, most recent first; the page keeps them across loads.recent: Vec<String>,/// The page's preferences, as it handed them over.@@ -346,6 +356,9 @@ pub struct Inner<P: Platform, L: Link> {last_click_ms: f64,focused: bool,composing: bool,+ /// What the input method has composed so far, drawn at the cursor+ /// until it is committed or dropped (`emit::LineParams::composing`).+ preedit: String,/// Refreshed on layout/scroll changes, avoiding layout reads per glyph/// or per frame. The IME field itself uses fixed CSS positioning.canvas_rect: [f64; 4],@@ -653,6 +666,7 @@ impl<P: Platform, L: Link> App<P, L> {last_click_ms: 0.0,focused: true,composing: false,+ preedit: String::new(),canvas_rect: [0.0; 4],ime_anchor: None,disconnected: None,@@ -665,6 +679,9 @@ impl<P: Platform, L: Link> App<P, L> {capacity: Capacity::new(),font_pinned: setup.font_pinned,languages: setup.languages,+ server_version: setup.server_version,+ programs: std::collections::HashMap::new(),+ tab_icons: None,recent: Vec::new(),settings: crate::settings::WebSettings::default(),server_palette: None,@@ -942,13 +959,11 @@ impl<P: Platform, L: Link> App<P, L> {}/// The footer the desktop's sidebar ends with: the gear and its label,- /// then Live Overview, Remote Hosts and the thread search. The first- /// two need windows the browser has not got, so they are shown and- /// refused rather than hidden -- the panel is the shape the desktop's- /// is either way.+ /// then Live Overview, Remote Hosts and the thread search.fn side_footer() -> Vec<crate::sidebar::FooterAction> {- // Only what the page can do: the desktop's Live Overview and- // Remote Hosts have no browser counterpart, so no button for them.+ // Only what the page can do: the desktop's Live Overview has no+ // browser counterpart, so no button for it. Remote Hosts is the+ // page's own machines panel.vec![crate::sidebar::FooterAction {id: "settings".into(),@@ -958,6 +973,14 @@ impl<P: Platform, L: Link> App<P, L> {enabled: true,trailing: false,},+ crate::sidebar::FooterAction {+ id: "machines".into(),+ icon: "globe".into(),+ label: None,+ tip: thinkterm_i18n::tr("tooltip-sidebar-ssh-hosts"),+ enabled: true,+ trailing: true,+ },crate::sidebar::FooterAction {id: "search".into(),icon: "search".into(),@@ -1042,7 +1065,32 @@ impl<P: Platform, L: Link> App<P, L> {pub fn tabs_view(&self) -> crate::views::TabsView {let inner = self.inner.borrow();let (tabs, controls) = Self::strip_model(&inner).unwrap_or_default();- crate::views::TabsView { tabs, controls }+ let icon = Self::tab_icons(&inner).and_then(|icons| icons.terminal()).map(str::to_string);+ crate::views::TabsView { tabs, controls, icon }+ }++ /// The cards to dress the tabs with: none until the page has handed+ /// them over, or with tab icons off.+ fn tab_icons(inner: &Inner<P, L>) -> Option<&crate::tab_icons::TabIcons> {+ inner.tab_icons.as_ref().filter(|_| inner.settings.tab_icons)+ }++ /// The card heading a pane's tab: its agent's, else its program's,+ /// else the terminal's.+ fn pane_icon(inner: &Inner<P, L>, pane_id: PaneId) -> Option<String> {+ Self::tab_icons(inner)?+ .card(inner.tree.agent_id(pane_id), inner.programs.get(&pane_id))+ .map(str::to_string)+ }++ /// The cards this page's server sent for its tabs, as the page read+ /// them off the relay.+ pub fn set_tab_icons(self: &Rc<Self>, json: &str) -> Result<(), String> {+ let icons = crate::tab_icons::TabIcons::parse(json)?;+ let mut inner = self.inner.borrow_mut();+ inner.tab_icons = Some(icons);+ Self::notify(&inner);+ Ok(())}pub fn navs_view(&self) -> crate::views::NavsView {@@ -1071,7 +1119,7 @@ impl<P: Platform, L: Link> App<P, L> {if cols == 0 || rows == 0 {return None;}- let dims = cell.session.dimensions();+ let dims = Self::shown_dims(&cell.session);let visible = visible_rows(&dims, rows, cell.scroll_from_bottom);let (first, lines) = cell.session.get_lines(visible.clone());let mut text = String::with_capacity(rows * (cols + 1));@@ -1148,7 +1196,7 @@ impl<P: Platform, L: Link> App<P, L> {let Some(cell) = inner.panes.get_mut(&place.pane_id) else {return;};- let dims = cell.session.dimensions();+ let dims = Self::shown_dims(&cell.session);let visible = visible_rows(&dims, rows, cell.scroll_from_bottom);cell.selection = Some(Selection {anchor: (visible.start + anchor.0 as StableRowIndex, anchor.1),@@ -1413,6 +1461,19 @@ impl<P: Platform, L: Link> App<P, L> {self.inner.borrow_mut().tree.apply_agent(pane_id, status.as_ref());Self::render_strip(&self.inner.borrow());}+ Pdu::ForegroundProgramChanged(codec::ForegroundProgramChanged { pane_id, program }) => {+ drop(inner);+ let mut inner = self.inner.borrow_mut();+ match program {+ Some(program) => {+ inner.programs.insert(pane_id, program);+ }+ None => {+ inner.programs.remove(&pane_id);+ }+ }+ Self::notify(&inner);+ }Pdu::ClientViewportState(_) | Pdu::FrontendAccessState(_) => {drop(inner);// The desktop may have resized: the panes are listed again@@ -1536,7 +1597,8 @@ impl<P: Platform, L: Link> App<P, L> {self.platform.set_timeout(delay_ms.max(0.0),Box::new(move || {- let Some(app) = weak.upgrade() else { return };+ // A client the page has closed does not come back.+ let Some(app) = weak.upgrade().filter(|app| !app.retired.get()) else { return };app.inner.borrow_mut().reconnect_pending = false;let task = Rc::clone(&app).try_reconnect();app.spawn(task);@@ -1820,8 +1882,32 @@ impl<P: Platform, L: Link> App<P, L> {true}- pub fn composing(&self, composing: bool) {- self.inner.borrow_mut().composing = composing;+ pub fn composing(self: &Rc<Self>, composing: bool) {+ {+ let mut inner = self.inner.borrow_mut();+ inner.composing = composing;+ if inner.preedit.is_empty() {+ return;+ }+ // A composition that starts afresh, or ends either way, leaves+ // nothing drawn at the cursor.+ inner.preedit.clear();+ }+ self.request_frame();+ }++ /// The input method's text so far, to draw at the cursor as the+ /// desktop does; the keys it took are not the terminal's yet.+ pub fn preedit(self: &Rc<Self>, text: &str) {+ {+ let mut inner = self.inner.borrow_mut();+ if inner.preedit == text {+ return;+ }+ inner.preedit.clear();+ inner.preedit.push_str(text);+ }+ self.request_frame();}/// Whether input may go out at all. In Handoff mode with the@@ -1893,6 +1979,32 @@ impl<P: Platform, L: Link> App<P, L> {})}+ /// A finger is no pointer: a press within a finger's width of a divider+ /// starts dragging it, as a press right on it does for a mouse. The+ /// drag is measured from the finger, so the line follows it from where+ /// it landed. The moves and the release are the pointer's own.+ pub fn touch_divider(&self, client_x: f64, client_y: f64) -> bool {+ const NEAR: [f64; 7] = [0.0, -6.0, 6.0, -12.0, 12.0, -18.0, 18.0];+ let mut inner = self.inner.borrow_mut();+ let dpr = inner.dpr;+ let hit = NEAR.iter().find_map(|d| {+ Self::divider_under(&inner, client_x, client_y + d)+ .filter(|(i, _)| matches!(inner.tab_layout.as_ref().and_then(|l| l.dividers.get(*i)), Some(crate::layout::Divider::Row { .. })))+ .map(|(i, at)| (i, at - d * dpr))+ .or_else(|| {+ Self::divider_under(&inner, client_x + d, client_y)+ .filter(|(i, _)| matches!(inner.tab_layout.as_ref().and_then(|l| l.dividers.get(*i)), Some(crate::layout::Divider::Col { .. })))+ .map(|(i, at)| (i, at - d * dpr))+ })+ });+ let Some((idx, at)) = hit else {+ return false;+ };+ inner.drag_divider = Some((idx, at, 0));+ inner.drag_layout = inner.tab_layout.clone();+ true+ }+/// A press on a divider starts dragging it; moves send whole cells/// to the server as they accrue; the release ends it. A move over a/// divider shows the resize cursor.@@ -2450,7 +2562,7 @@ impl<P: Platform, L: Link> App<P, L> {};let session = Arc::clone(&cell.session);let scroll = cell.scroll_from_bottom;- let dims = session.dimensions();+ let dims = Self::shown_dims(&session);let rows_shown = Self::placements(&inner).into_iter().find(|p| p.pane_id == hit.pane_id)@@ -2646,7 +2758,7 @@ impl<P: Platform, L: Link> App<P, L> {let session = Arc::clone(&cell.session);if session.is_alt_screen() || session.is_mouse_grabbed() {let button = if lines < 0.0 { MouseButton::WheelUp(notches) } else { MouseButton::WheelDown(notches) };- let dims = session.dimensions();+ let dims = Self::shown_dims(&session);let visible = visible_rows(&dims, rows_shown, cell.scroll_from_bottom);let event = MouseEvent {kind: MouseEventKind::Press,@@ -2676,7 +2788,7 @@ impl<P: Platform, L: Link> App<P, L> {self.step_font(step);return true;}- let max = max_scroll(&session.dimensions(), rows_shown);+ let max = max_scroll(&Self::shown_dims(&session), rows_shown);if smooth {// Down the page (a positive delta) is towards the newest row,// which is the way `normalize_scroll_px` counts. A trackpad or@@ -2734,10 +2846,12 @@ impl<P: Platform, L: Link> App<P, L> {.map(|s| s.pixel_height as f64 / s.rows as f64 * inner.platform.units_per_inch() / s.dpi as f64).unwrap_or(0.0);let mut json = format!(- "{{\"tab\":{},\"canvas\":[{},{}],\"cell\":[{cw:.3},{ch:.3}],\"font_pt\":{},\"desktop_cell\":{desktop_cell:.3},\"focused\":{},\"owner\":{},\"may_type\":{},\"fit\":{},\"following\":{}",+ "{{\"tab\":{},\"canvas\":[{},{}],\"cell\":[{cw:.3},{ch:.3}],\"pad\":[{:.3},{:.3}],\"font_pt\":{},\"desktop_cell\":{desktop_cell:.3},\"focused\":{},\"owner\":{},\"may_type\":{},\"fit\":{},\"following\":{}",inner.tab_id,inner.cols,inner.rows,+ Self::pad(inner).0 as f64 / dpr,+ Self::pad(inner).1 as f64 / dpr,inner.glyphs.size_pt,inner.focused_pane,lease.owns_viewport(),@@ -2753,7 +2867,7 @@ impl<P: Platform, L: Link> App<P, L> {.map(|place| Self::shown_in(inner, place).1),None => Self::focused_placement(inner).as_ref().map(|place| Self::shown_in(inner, place).1),}.unwrap_or(inner.rows);- let max = max_scroll(&cell.session.dimensions(), rows);+ let max = max_scroll(&Self::shown_dims(&cell.session), rows);// With the fraction of a row a smooth scroll is part way// through, so a bar following it moves as the rows do rather// than a row at a time.@@ -2849,8 +2963,16 @@ impl<P: Platform, L: Link> App<P, L> {// prompt: the rows sit flush with the bottom of the canvas,// and whatever part of a row the height cannot fit is the gap// under the tab row instead, where it reads as a margin.+ // Flush with the tab's own rows while the server has yet to+ // give it the canvas's: the soft keyboard coming or going cuts+ // the canvas a round trip before the new layout arrives, and+ // the old one drawn from the top jumped the prompt away from+ // the keyboard's edge and back.let height = inner.gpu.size().1 as f32;- let rows = (height / ch.max(1.0)).floor();+ let rows = match &inner.tab_layout {+ Some(layout) if layout.rows > 0 => layout.rows as f32,+ _ => (height / ch.max(1.0)).floor(),+ };return (cw, height - rows * ch);}(cw, ch / 2.0)@@ -2872,11 +2994,14 @@ impl<P: Platform, L: Link> App<P, L> {Self::nav_rows_for(inner, inner.tab_layout.as_ref().map_or(1, |l| l.panes.len()))}- /// The bar's rows for a tab of `panes` panes. A phone shows a lone- /// pane bare, as its terminal apps do; the bar appears with a split,- /// when there is something to tell apart.+ /// The bar's rows for a tab of `panes` panes. The phone app shows a+ /// lone pane bare, as its terminal apps do, the bar appearing with a+ /// split, when there is something to tell apart; a page on a phone+ /// keeps the bar, as the desktop does (`Platform::bare_lone_pane`).fn nav_rows_for(inner: &Inner<P, L>, panes: usize) -> usize {- if inner.platform.is_mobile() && (panes <= 1 || !inner.settings.pane_bars) {+ if inner.platform.is_mobile()+ && (!inner.settings.pane_bars || (panes <= 1 && inner.platform.bare_lone_pane()))+ {return 0;}crate::navbar::nav_rows(Self::nav_css(inner) * inner.dpr, inner.glyphs.metrics.cell_size.height as f64)@@ -2885,6 +3010,12 @@ impl<P: Platform, L: Link> App<P, L> {/// One bar per drawn pane, as the page shows them.fn nav_views(inner: &Inner<P, L>) -> Vec<crate::navbar::NavView> {let mut views = Vec::new();+ // No rows for the bars, no bars: a phone shows a lone pane bare.+ // A bar's height is its rows plus the padding above the pane, so+ // without this the padding alone drew a sliver of one.+ if Self::nav_rows(inner) == 0 {+ return views;+ }if let Some(layout) = &inner.tab_layout {let dpr = inner.dpr.max(0.1);let cell_css = (@@ -2919,6 +3050,7 @@ impl<P: Platform, L: Link> App<P, L> {title: title.to_string(),busy,current: m.pane_id == place.pane_id,+ icon: Self::pane_icon(inner, m.pane_id),}}).collect();@@ -2985,6 +3117,15 @@ impl<P: Platform, L: Link> App<P, L> {}Err(err) => log::warn!("fetching agent statuses: {err:#}"),}+ let programs = thinkterm_session::host::request(&link, Pdu::GetForegroundPrograms(codec::GetForegroundPrograms {}), |p| match p {+ Pdu::GetForegroundProgramsResponse(r) => Ok(r.programs),+ other => Err(other),+ })+ .await;+ match programs {+ Ok(entries) => app.inner.borrow_mut().programs = entries.into_iter().map(|e| (e.pane_id, e.program)).collect(),+ Err(err) => log::warn!("fetching foreground programs: {err:#}"),+ }app.fetch_session().await;Self::render_strip(&app.inner.borrow());});@@ -3550,6 +3691,12 @@ impl<P: Platform, L: Link> App<P, L> {let (fresh, changed, first_layout) = {let mut inner = self.inner.borrow_mut();inner.tree.apply_panes(&list);+ let listed: std::collections::HashSet<PaneId> = list+ .tabs+ .iter()+ .flat_map(|node| crate::layout::leaves(node).into_iter().map(|e| e.pane_id))+ .collect();+ inner.programs.retain(|pane, _| listed.contains(pane));inner.layout = Some(list);let first_layout = inner.tab_layout.is_none();let before = (inner.focused_pane, inner.tab_layout.clone());@@ -3625,7 +3772,12 @@ impl<P: Platform, L: Link> App<P, L> {// by the next listing.let claim = {let mut inner = self.inner.borrow_mut();- let showing = inner.auto_claimed != Some(tab_id) && inner.disconnected.is_none();+ // A machine's terminal behind another's on the page is not on+ // show: it takes nothing from the host's own desktop. It claims+ // when it comes on show (the page lists it again then).+ let showing = inner.platform.shown()+ && inner.auto_claimed != Some(tab_id)+ && inner.disconnected.is_none();if showing {inner.auto_claimed = Some(tab_id);}@@ -3896,6 +4048,13 @@ impl<P: Platform, L: Link> App<P, L> {/// A new tab in the window this tab is in, at the tab's own size.pub fn new_tab(self: &Rc<Self>) {+ self.new_tab_in(None);+ }++ /// A new tab in the named domain of the server, rather than the one+ /// the focused pane is in: a plain ssh terminal on a machine the page+ /// could not reach with ThinkTerm.+ pub fn new_tab_in(self: &Rc<Self>, domain: Option<String>) {let (window_id, workspace, size) = {let inner = self.inner.borrow();let size = inner@@ -3909,7 +4068,10 @@ impl<P: Platform, L: Link> App<P, L> {self.act("web-act-new-tab",Pdu::SpawnV2(codec::SpawnV2 {- domain: thinkterm_proto::SpawnTabDomain::CurrentPaneDomain,+ domain: match domain {+ Some(name) => thinkterm_proto::SpawnTabDomain::DomainName(name),+ None => thinkterm_proto::SpawnTabDomain::CurrentPaneDomain,+ },window_id: Some(window_id),command: None,command_dir: None,@@ -4051,6 +4213,18 @@ impl<P: Platform, L: Link> App<P, L> {true}+ /// Whether the connection is up: false from a drop until the reconnect+ /// that ends it.+ pub fn connected(&self) -> bool {+ self.inner.borrow().disconnected.is_none()+ }++ /// Every Space of this server, for a page that lists several servers'+ /// Spaces in one menu.+ pub fn spaces(&self) -> Vec<crate::tree::SpaceEntry> {+ self.inner.borrow().tree.spaces()+ }+/// A context menu for something on the page: `kind` names what was/// clicked, `id` which one. Empty when there is nothing to offer.pub fn context_menu(&self, kind: &str, id: &str) -> Vec<crate::menu::MenuItem> {@@ -5151,12 +5325,16 @@ impl<P: Platform, L: Link> App<P, L> {inner.recompute_palettes()};self.repaint_palettes(&changed);- // The pane in use takes the new scheme on the server too.- let (link, pane, palette) = {- let inner = self.inner.borrow();- (inner.link.clone(), inner.focused_pane, inner.configured())- };- Self::advise_focus(&self.platform, link, pane, palette);+ // The pane in use takes the new scheme on the server too -- on show+ // only: telling a host's server which pane has focus moves its+ // desktop's tab when the desktop follows the page.+ if self.platform.shown() {+ let (link, pane, palette) = {+ let inner = self.inner.borrow();+ (inner.link.clone(), inner.focused_pane, inner.configured())+ };+ Self::advise_focus(&self.platform, link, pane, palette);+ }Self::notify(&self.inner.borrow());}@@ -5165,6 +5343,11 @@ impl<P: Platform, L: Link> App<P, L> {self.inner.borrow().settings.clone()}+ /// The server's version, as it answered when the page attached.+ pub fn server_version(&self) -> String {+ self.inner.borrow().server_version.clone()+ }+/// The page's stored preferences, at boot: applied whole.pub fn apply_settings(self: &Rc<Self>, json: &str) -> Result<(), String> {let settings = crate::settings::WebSettings::parse(json)?;@@ -5409,7 +5592,9 @@ impl<P: Platform, L: Link> App<P, L> {("cmd", "close-pane") => self.close_pane(),("cmd", "take-over") => self.take_over(),("cmd", "follow") => self.on_chrome_click(crate::chrome::Click::Follow),- ("cmd", "toggle-sidebar") | ("cmd", "settings") => outcome.page = Some(arg.to_string()),+ ("cmd", "toggle-sidebar") | ("cmd", "settings") | ("cmd", "remote-hosts") | ("cmd", "add-remote-host") => {+ outcome.page = Some(arg.to_string())+ }("cmd", "font-up") => self.step_font(1.0),("cmd", "font-down") => self.step_font(-1.0),("cmd", "font-reset") => self.step_font(0.0),@@ -5976,7 +6161,9 @@ impl<P: Platform, L: Link> App<P, L> {/// tab fit the canvas. `None` when the size is right or pinned by/// `?font=`.fn desired_size_pt(inner: &Inner<P, L>, dev_w: u32, dev_h: u32) -> Option<f64> {- if inner.font_pinned {+ // A canvas with no room -- one machine's terminal behind another's+ // -- says nothing about the size anyone wants.+ if inner.font_pinned || dev_w <= 1 || dev_h <= 1 {return None;}// Holding the tab, the page shows its own size; the desktop is@@ -6254,7 +6441,7 @@ impl<P: Platform, L: Link> App<P, L> {let Some(cell) = inner.panes.get(&place.pane_id) else {continue;};- let dims = cell.session.dimensions();+ let dims = Self::shown_dims(&cell.session);// The extra row a fractional scroll draws is one whose fetch can// stall like any other; asking about the range that was painted// is what keeps a dropped `GetLines` for it being retried.@@ -6376,7 +6563,7 @@ impl<P: Platform, L: Link> App<P, L> {return layout.panes.clone();}let cell = inner.focused();- let size = cell.session.dimensions();+ let size = Self::shown_dims(&cell.session);vec![crate::layout::PanePlacement {pane_id: inner.focused_pane,tab_id: inner.tab_id,@@ -6394,6 +6581,18 @@ impl<P: Platform, L: Link> App<P, L> {}]}+ /// A pane's dimensions as it is drawn and pointed at: a preview of+ /// another height placed where the server will put its rows+ /// (`viewport::previewed`).+ fn shown_dims(session: &PaneSession<AppHost<P, L>>) -> thinkterm_proto::RenderableDimensions {+ crate::viewport::previewed(+ session.dimensions(),+ &session.server_dimensions(),+ session.cursor_position().y,+ session.is_alt_screen(),+ )+ }+/// The grid a placement shows: its frame, or less when the pane's own/// grid is smaller (the desktop reserves rows of a frame for chrome).fn shown(place: &crate::layout::PanePlacement) -> (usize, usize) {@@ -6433,7 +6632,7 @@ impl<P: Platform, L: Link> App<P, L> {continue;};let session = Arc::clone(&cell.session);- let dims = session.dimensions();+ let dims = Self::shown_dims(&session);let max = max_scroll(&dims, rows_shown);if cell.scroll_from_bottom > max {cell.scroll_from_bottom = max;@@ -6602,6 +6801,7 @@ impl<P: Platform, L: Link> App<P, L> {},cursor_hidden: inner.settings.cursor_blink && !inner.blink_shown,min_contrast: inner.settings.min_contrast,+ composing: (inner.composing && !inner.preedit.is_empty()).then_some(inner.preedit.as_str()),};if line.has_images() && inner.frame_control.get(&place.pane_id).is_some_and(|(_, revision)| revision.is_some()) {inner.graphics.collect_line(diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rsindex e874d2be..f64fd7ab 100644--- a/thinkterm-web/src/bridge.rs+++ b/thinkterm-web/src/bridge.rs@@ -79,6 +79,41 @@ impl Client {self.app.resize();}+ /// The page put this machine's terminal on show (`true`) or behind+ /// another machine's. Hidden, it keeps its sessions but does not paint.+ pub fn set_shown(&self, shown: bool) {+ self.app.platform.set_shown(shown);+ if shown {+ self.app.resize();+ self.app.request_frame();+ // Listed again now, so a tab it shows is claimed as on any+ // showing rather than at the next poll.+ self.app.refresh_layout();+ }+ }++ /// Let this client go: its connection closes, and nothing it set going+ /// does anything more. The page frees it after.+ pub fn close(&self) {+ self.app.retire();+ self.app.platform.release();+ }++ /// Whether the connection is up; a change comes with a view change.+ pub fn connected(&self) -> bool {+ self.app.connected()+ }++ /// This server's Spaces: JSON `[{id, name, current, default}]`.+ pub fn spaces(&self) -> String {+ json(&self.app.spaces())+ }++ /// A new tab in the named domain of this server (a plain ssh one).+ pub fn new_tab_in(&self, domain: String) {+ self.app.new_tab_in(Some(domain));+ }+/// The card's button, or a press on the card: ask for the terminal/// another device holds. What comes of it is the card's next state.pub fn take_over(&self) {@@ -357,6 +392,12 @@ impl Client {json(&self.app.settings_view())}+ /// The version of the ThinkTerm at the other end, as it answered when+ /// the page attached: what Settings › About shows.+ pub fn server_version(&self) -> String {+ self.app.server_version()+ }+/// The stored preferences, whole, at boot. Returns an error text or "".pub fn apply_settings(&self, json: String) -> String {self.app.apply_settings(&json).err().unwrap_or_default()@@ -368,6 +409,18 @@ impl Client {self.app.set_setting(&key, &value).err().unwrap_or_default()}+ /// A finger came down at a point: whether that starts dragging a+ /// divider near it (`App::touch_divider`).+ pub fn touch_divider(&self, x: f64, y: f64) -> bool {+ self.app.touch_divider(x, y)+ }++ /// The tab icon cards the page's server sent over the relay (a+ /// `WireCatalog`, as JSON). Returns an error text or "".+ pub fn set_tab_icons(&self, json: String) -> String {+ self.app.set_tab_icons(&json).err().unwrap_or_default()+ }+/// The colours of the scheme named by `terminal-scheme`, as the page/// read them out of `schemes.json`; `None` follows the server's/// configuration. Returns an error text or "".diff --git a/thinkterm-web/src/emit.rs b/thinkterm-web/src/emit.rsindex 9160916a..68678f16 100644--- a/thinkterm-web/src/emit.rs+++ b/thinkterm-web/src/emit.rs@@ -10,7 +10,7 @@ use crate::glyphs::{CachedGlyph, GlyphCache};use anyhow::{Context, Result};use std::ops::Range;use std::rc::Rc;-use termwiz::cell::{Intensity, Underline};+use termwiz::cell::{unicode_column_width, Intensity, Underline};use termwiz::surface::{CursorShape, CursorVisibility, Line};use thinkterm_font_core::PresentationWidth;use thinkterm_font_web::GlyphRole;@@ -52,6 +52,10 @@ pub struct LineParams<'a> {/// A WCAG contrast ratio text is lifted to against its background;/// under 1 is off.pub min_contrast: f32,+ /// What an input method is composing, drawn over the row at the cursor+ /// as the desktop draws it (`screen_line.rs`): in the cursor's colours,+ /// the cursor a block as wide as the text.+ pub composing: Option<&'a str>,}/// A flat rectangle at `at` of `size`, both in device pixels from the@@ -142,22 +146,41 @@ pub fn emit_line(if p.line.is_double_height_bottom() {return Ok(());}+ let cursor_on_row = p.stable_row == p.cursor.y;+ // The text being composed, over a copy of the row from the cursor on;+ // only where the cursor is drawn, as only one pane has the keys.+ let composing = p+ .composing+ .filter(|text| cursor_on_row && p.draw_cursor && !text.is_empty());+ let composed;+ let line = match composing {+ Some(text) => {+ let mut copy = p.line.clone();+ let seqno = copy.current_seqno();+ copy.overlay_text_with_attribute(p.cursor.x, text, CellAttributes::blank(), seqno);+ composed = copy;+ &composed+ }+ None => p.line,+ };+ let composing_width = composing.map_or(0, |text| unicode_column_width(text, None));let metrics = cache.metrics;- let width_scale: f32 = if p.line.is_single_width() { 1.0 } else { 2.0 };- let height_scale: f32 = if p.line.is_double_height_top() { 2.0 } else { 1.0 };+ let width_scale: f32 = if line.is_single_width() { 1.0 } else { 2.0 };+ let height_scale: f32 = if line.is_double_height_top() { 2.0 } else { 1.0 };let cell_width = metrics.cell_size.width as f32 * width_scale;let cell_height = metrics.cell_size.height as f32 * height_scale;let gl_x = -p.surface.0 / 2.0 + p.origin.0;let pos_y = -p.surface.1 / 2.0 + p.origin.1 + p.top_pixel_y;let pixel_width = p.clip.0;- let cursor_on_row = p.stable_row == p.cursor.y;let cursor_cell = if cursor_on_row {- p.line.get_cell(p.cursor.x)+ line.get_cell(p.cursor.x)} else {None};- let cursor_range = if cursor_on_row {+ let cursor_range = if composing_width > 0 {+ p.cursor.x..p.cursor.x + composing_width+ } else if cursor_on_row {p.cursor.x..p.cursor.x + cursor_cell.as_ref().map(|c| c.width()).unwrap_or(1)} else {0..0@@ -169,12 +192,19 @@ pub fn emit_line(} else {p.selection.start as f32 * cell_width..p.selection.end as f32 * cell_width};- let cursor_visible = p.draw_cursor- && cursor_on_row- && !p.cursor_hidden- && p.cursor.visibility == CursorVisibility::Visible;- let cursor_shape = p.cursor_shape.unwrap_or(p.cursor.shape);- let filled_cursor = cursor_visible && p.focused && is_block(cursor_shape);+ // Composing, the text is on show whatever the blink or the program+ // asked of the cursor, in a block, as on the desktop.+ let cursor_visible = composing.is_some()+ || (p.draw_cursor+ && cursor_on_row+ && !p.cursor_hidden+ && p.cursor.visibility == CursorVisibility::Visible);+ let cursor_shape = if composing.is_some() {+ CursorShape::Default+ } else {+ p.cursor_shape.unwrap_or(p.cursor.shape)+ };+ let filled_cursor = cursor_visible && (p.focused || composing.is_some()) && is_block(cursor_shape);let selection_fg = p.palette.selection_fg.to_linear();let selection_bg = p.palette.selection_bg.to_linear();@@ -210,7 +240,7 @@ pub fn emit_line(underline: Option<(thinkterm_render::bitmaps::TextureRect, LinearRgba)>,glyphs: Vec<(u8, Rc<CachedGlyph>)>,}- let clusters = p.line.cluster(None);+ let clusters = line.cluster(None);let mut shaped: Vec<Shaped> = Vec::with_capacity(clusters.len());for cluster in &clusters {let attrs = &cluster.attrs;@@ -357,14 +387,14 @@ pub fn emit_line(// The cursor: filled when this page has focus and the shape is a// block, an outline when it does not, bar and underline as themselves.if cursor_visible {- let (shape, color) = if !p.focused {+ let (shape, color) = if !p.focused && composing.is_none() {(CursorShape::SteadyBlock, cursor_border)} else if is_block(cursor_shape) {(CursorShape::Default, cursor_bg)} else {(cursor_shape, cursor_bg)};- let width_cells = (cursor_range.end - cursor_range.start).max(1) as u8;+ let width_cells = (cursor_range.end - cursor_range.start).clamp(1, u8::MAX as usize) as u8;let sprite = cache.cursor_sprite(Some(shape), width_cells)?;let x = gl_x + cursor_range_pixels.start;let mut quad = layers.allocate(2).context("allocate")?;diff --git a/thinkterm-web/src/graphics_check.rs b/thinkterm-web/src/graphics_check.rsindex 411d7733..3bd3c5a6 100644--- a/thinkterm-web/src/graphics_check.rs+++ b/thinkterm-web/src/graphics_check.rs@@ -123,6 +123,7 @@ async fn run(names: Vec<String>, fonts: Vec<js_sys::Uint8Array>, size: f64) -> Rcursor_shape: None,cursor_hidden: false,min_contrast: 0.0,+ composing: None,},)?;}@@ -249,6 +250,7 @@ async fn image_atlas_check(gpu: &mut Gpu, surface: (u32, u32), cell: (u32, u32))origin: (0.0, 0.0), clip: (w, h), hsv: None,draw_cursor: false, cursor_shape: None, cursor_hidden: true,min_contrast: 0.0,+ composing: None,};graphics.collect_line(gpu, 0, ¶ms, (cw, ch), (1.0, 1.0), [0.0, 0.0, w, h])?;}@@ -380,6 +382,7 @@ async fn image_check(cursor_shape: None,cursor_hidden: true,min_contrast: 0.0,+ composing: None,};let mut graphics = Graphics::default();for _ in 0..3 {diff --git a/thinkterm-web/src/input.rs b/thinkterm-web/src/input.rsindex f995f0a2..6a725b46 100644--- a/thinkterm-web/src/input.rs+++ b/thinkterm-web/src/input.rs@@ -7,31 +7,11 @@ use crate::page::WebApp;use crate::platform::{PointerInput, WheelDelta, WheelInput};use wezterm_term::KeyModifiers;use std::rc::Rc;-use wasm_bindgen::prelude::*;-use wasm_bindgen::JsCast;use web_sys::{ClipboardEvent, CompositionEvent, Event, HtmlCanvasElement, HtmlTextAreaElement, InputEvent,KeyboardEvent, PointerEvent, WheelEvent,};-pub(crate) fn listen<E: JsCast + 'static>(- target: &web_sys::EventTarget,- name: &str,- handler: impl FnMut(E) + 'static,-) {- let mut handler = handler;- let closure = Closure::<dyn FnMut(Event)>::new(move |ev: Event| {- if let Ok(ev) = ev.dyn_into::<E>() {- handler(ev);- }- });- target- .add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())- .expect("addEventListener");- // The listeners live as long as the page.- closure.forget();-}-fn mouse_modifiers(ev: &web_sys::MouseEvent) -> KeyModifiers {let mut m = KeyModifiers::NONE;if ev.shift_key() {@@ -77,18 +57,27 @@ fn wheel_input(ev: &WheelEvent) -> WheelInput {}}+/// Every listener holds the App weakly, and is held by the platform rather+/// than leaked: the page can close a machine's terminal (machines.svelte.ts)+/// and stay open, and then `WebPlatform::release` takes them all down.pub fn install(app: Rc<WebApp>, canvas: &HtmlCanvasElement, textarea: &HtmlTextAreaElement) {+ let platform = Rc::clone(&app.platform);if let Some(document) = web_sys::window().and_then(|window| window.document()) {app.visibility_changed(!document.hidden());- let app = Rc::clone(&app);+ let app = Rc::downgrade(&app);let target = document.clone();- listen::<Event>(&target, "visibilitychange", move |_| app.visibility_changed(!document.hidden()));+ platform.listen::<Event>(&target, "visibilitychange", move |_| {+ if let Some(app) = app.upgrade() {+ app.visibility_changed(!document.hidden());+ }+ });}let window = web_sys::window().expect("window");{- let app = app.clone();- listen::<KeyboardEvent>(textarea, "keydown", move |ev| {+ let app = Rc::downgrade(&app);+ platform.listen::<KeyboardEvent>(textarea, "keydown", move |ev| {+ let Some(app) = app.upgrade() else { return };let key = ev.key();let code = ev.code();let dom = DomKey {@@ -117,13 +106,28 @@ pub fn install(app: Rc<WebApp>, canvas: &HtmlCanvasElement, textarea: &HtmlTextA});}{- let app = app.clone();- listen::<CompositionEvent>(textarea, "compositionstart", move |_| app.composing(true));+ let app = Rc::downgrade(&app);+ platform.listen::<CompositionEvent>(textarea, "compositionstart", move |_| {+ if let Some(app) = app.upgrade() {+ app.composing(true);+ }+ });+ }+ {+ // What the input method has so far ("ni hao" before it is 你好),+ // drawn at the cursor: the field it is typed into is out of sight.+ let app = Rc::downgrade(&app);+ platform.listen::<CompositionEvent>(textarea, "compositionupdate", move |ev| {+ if let Some(app) = app.upgrade() {+ app.preedit(&ev.data().unwrap_or_default());+ }+ });}{- let app = app.clone();+ let app = Rc::downgrade(&app);let textarea = textarea.clone();- listen::<CompositionEvent>(&textarea.clone(), "compositionend", move |ev| {+ platform.listen::<CompositionEvent>(&textarea.clone(), "compositionend", move |ev| {+ let Some(app) = app.upgrade() else { return };app.composing(false);if let Some(text) = ev.data() {if !text.is_empty() {@@ -134,9 +138,10 @@ pub fn install(app: Rc<WebApp>, canvas: &HtmlCanvasElement, textarea: &HtmlTextA});}{- let app = app.clone();+ let app = Rc::downgrade(&app);let textarea = textarea.clone();- listen::<InputEvent>(&textarea.clone(), "input", move |ev| {+ platform.listen::<InputEvent>(&textarea.clone(), "input", move |ev| {+ let Some(app) = app.upgrade() else { return };// Composition text arrives through compositionend; anything// else typed straight into the textarea (a virtual keyboard,// autocorrect) is sent as bytes.@@ -151,8 +156,9 @@ pub fn install(app: Rc<WebApp>, canvas: &HtmlCanvasElement, textarea: &HtmlTextA});}{- let app = app.clone();- listen::<ClipboardEvent>(textarea, "paste", move |ev| {+ let app = Rc::downgrade(&app);+ platform.listen::<ClipboardEvent>(textarea, "paste", move |ev| {+ let Some(app) = app.upgrade() else { return };ev.prevent_default();if let Some(data) = ev.clipboard_data() {if let Ok(text) = data.get_data("text/plain") {@@ -164,66 +170,89 @@ pub fn install(app: Rc<WebApp>, canvas: &HtmlCanvasElement, textarea: &HtmlTextA});}{- let app = app.clone();+ let app = Rc::downgrade(&app);let canvas = canvas.clone();- listen::<PointerEvent>(&canvas.clone(), "pointerdown", move |ev| {+ platform.listen::<PointerEvent>(&canvas.clone(), "pointerdown", move |ev| {+ let Some(app) = app.upgrade() else { return };let _ = canvas.set_pointer_capture(ev.pointer_id());app.pointer(&pointer_input(&ev), crate::app::Pointer::Down);ev.prevent_default();});}{- let app = app.clone();- listen::<PointerEvent>(canvas, "pointermove", move |ev| {- app.pointer(&pointer_input(&ev), crate::app::Pointer::Move);+ let app = Rc::downgrade(&app);+ platform.listen::<PointerEvent>(canvas, "pointermove", move |ev| {+ if let Some(app) = app.upgrade() {+ app.pointer(&pointer_input(&ev), crate::app::Pointer::Move);+ }});}{- let app = app.clone();- listen::<PointerEvent>(canvas, "pointerup", move |ev| {- app.pointer(&pointer_input(&ev), crate::app::Pointer::Up);+ let app = Rc::downgrade(&app);+ platform.listen::<PointerEvent>(canvas, "pointerup", move |ev| {+ if let Some(app) = app.upgrade() {+ app.pointer(&pointer_input(&ev), crate::app::Pointer::Up);+ }});}{- let app = app.clone();- listen::<PointerEvent>(canvas, "pointercancel", move |ev| {- app.pointer(&pointer_input(&ev), crate::app::Pointer::Up);+ let app = Rc::downgrade(&app);+ platform.listen::<PointerEvent>(canvas, "pointercancel", move |ev| {+ if let Some(app) = app.upgrade() {+ app.pointer(&pointer_input(&ev), crate::app::Pointer::Up);+ }});}{- let app = app.clone();- listen::<WheelEvent>(canvas, "wheel", move |ev| {- if app.wheel(&wheel_input(&ev)) {+ let app = Rc::downgrade(&app);+ platform.listen::<WheelEvent>(canvas, "wheel", move |ev| {+ if app.upgrade().is_some_and(|app| app.wheel(&wheel_input(&ev))) {ev.prevent_default();}});}{- listen::<Event>(canvas, "contextmenu", move |ev| ev.prevent_default());+ platform.listen::<Event>(canvas, "contextmenu", move |ev| ev.prevent_default());}{- let app = app.clone();- listen::<Event>(&window, "focus", move |_| app.focus(true));+ let app = Rc::downgrade(&app);+ platform.listen::<Event>(&window, "focus", move |_| {+ if let Some(app) = app.upgrade() {+ app.focus(true);+ }+ });}{- let app = app.clone();- listen::<Event>(&window, "blur", move |_| app.focus(false));+ let app = Rc::downgrade(&app);+ platform.listen::<Event>(&window, "blur", move |_| {+ if let Some(app) = app.upgrade() {+ app.focus(false);+ }+ });}{- let app = app.clone();- listen::<Event>(&window, "resize", move |_| app.resize());+ let app = Rc::downgrade(&app);+ platform.listen::<Event>(&window, "resize", move |_| {+ if let Some(app) = app.upgrade() {+ app.resize();+ }+ });}{- let app = app.clone();- listen::<Event>(&window, "scroll", move |_| app.resize());+ let app = Rc::downgrade(&app);+ platform.listen::<Event>(&window, "scroll", move |_| {+ if let Some(app) = app.upgrade() {+ app.resize();+ }+ });}{// The canvas's own box, not just the window: CSS can resize it.- let app = app.clone();- let closure = Closure::<dyn FnMut(js_sys::Array)>::new(move |_entries: js_sys::Array| app.resize());- if let Ok(observer) = web_sys::ResizeObserver::new(closure.as_ref().unchecked_ref()) {- observer.observe(canvas);- closure.forget();- }+ let app = Rc::downgrade(&app);+ platform.observe_resize(canvas, move || {+ if let Some(app) = app.upgrade() {+ app.resize();+ }+ });}}diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex 2e367658..20478956 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -34,6 +34,7 @@ pub mod raster;pub mod settings;pub mod sidebar;pub mod snippets;+pub mod tab_icons;pub mod tree;pub mod viewport;pub mod views;diff --git a/thinkterm-web/src/link.rs b/thinkterm-web/src/link.rsindex 37872a75..9f098ac8 100644--- a/thinkterm-web/src/link.rs+++ b/thinkterm-web/src/link.rs@@ -22,6 +22,8 @@ use web_sys::{BinaryType, MessageEvent, WebSocket};pub const SUBPROTOCOL: &str = "thinkterm.v1";pub const TOKEN_PROTOCOL_PREFIX: &str = "tt-token.";+/// Another machine, reached through the page's server (`web_relay` there).+pub const RELAY_SUBPROTOCOL: &str = "thinkterm.relay.v1";// Allow one maximum codec payload plus its three varint header fields.// Independent chunk accounting bounds overhead for tiny WebSocket messages.@@ -141,6 +143,11 @@ struct Inner {pub lease: RefCell<Lease>,url: String,token: String,+ /// For another machine: the page's own code opens the socket and+ /// answers the relay's questions (a password, a host key), and hands+ /// it back ready to carry the mux connection. Used in place of `url`+ /// for every connect, reconnects included.+ opener: Option<js_sys::Function>,}/// A handle on the connection; clone freely.@@ -152,6 +159,16 @@ impl WsLink {/// the server to accept it.pub async fn connect(url: &str, token: &str) -> Result<Self> {let socket = Self::open(url, token).await?;+ Ok(Self::around(socket, url, token, None))+ }++ /// Reach another machine through `opener`; see `Inner::opener`.+ pub async fn connect_via(opener: js_sys::Function) -> Result<Self> {+ let socket = Self::open_via(&opener).await?;+ Ok(Self::around(socket, "", "", Some(opener)))+ }++ fn around(socket: Rc<Socket>, url: &str, token: &str, opener: Option<js_sys::Function>) -> Self {let link = Self(Rc::new(Inner {socket: RefCell::new(socket),serials: RefCell::new(SerialTable::new()),@@ -162,9 +179,42 @@ impl WsLink {lease: RefCell::new(Lease::default()),url: url.to_string(),token: token.to_string(),+ opener,}));link.spawn_reader();- Ok(link)+ link+ }++ /// Ask the page for a socket to the other machine, already past the+ /// relay's questions.+ async fn open_via(opener: &js_sys::Function) -> Result<Rc<Socket>> {+ fn text(value: &JsValue) -> String {+ value+ .as_string()+ .or_else(|| value.dyn_ref::<js_sys::Error>().map(|e| String::from(e.message())))+ .unwrap_or_else(|| format!("{value:?}"))+ }+ let promise: js_sys::Promise = opener+ .call0(&JsValue::NULL)+ .map_err(|e| anyhow!("{}", text(&e)))?+ .dyn_into()+ .map_err(|_| anyhow!("the page did not hand back a promise for the socket"))?;+ let ws: WebSocket = wasm_bindgen_futures::JsFuture::from(promise)+ .await+ .map_err(|e| anyhow!("{}", text(&e)))?+ .dyn_into()+ .map_err(|_| anyhow!("the page did not hand back a socket"))?;+ let socket = Self::adopt(ws);+ // Closed between the relay's "ready" and here: nothing to adopt.+ if socket.ws.ready_state() != WebSocket::OPEN {+ socket.retire();+ anyhow::bail!("the connection to the machine closed as it opened");+ }+ if socket.ws.protocol() != RELAY_SUBPROTOCOL {+ socket.retire();+ anyhow::bail!("the server did not select the {RELAY_SUBPROTOCOL} subprotocol");+ }+ Ok(socket)}/// Open a socket and wait for the server to accept the token.@@ -174,12 +224,24 @@ impl WsLink {protocols.push(&JsValue::from_str(&format!("{TOKEN_PROTOCOL_PREFIX}{token}")));let ws = WebSocket::new_with_str_sequence(url, &protocols).map_err(|e| anyhow!("WebSocket::new: {e:?}"))?;+ let socket = Self::adopt(ws);+ Self::opened(&socket).await?;+ if socket.ws.protocol() != SUBPROTOCOL {+ socket.retire();+ anyhow::bail!("the server did not select the {SUBPROTOCOL} subprotocol");+ }+ Ok(socket)+ }++ /// The socket's events, wired to a `Socket`; it may be open already.+ fn adopt(ws: WebSocket) -> Rc<Socket> {ws.set_binary_type(BinaryType::Arraybuffer);+ let open = ws.ready_state() == WebSocket::OPEN;let socket = Rc::new(Socket {ws,incoming: RefCell::new(ByteQueue::new(MAX_RECEIVE_BYTES, MAX_RECEIVE_CHUNKS)),waker: RefCell::new(None),- open: Cell::new(false),+ open: Cell::new(open),closed: Cell::new(false),close_reason: RefCell::new(String::new()),_closures: RefCell::new(Vec::new()),@@ -253,7 +315,11 @@ impl WsLink {closures.push(c);}*socket._closures.borrow_mut() = closures;+ socket+ }+ /// Wait for the server to accept the socket.+ async fn opened(socket: &Rc<Socket>) -> Result<()> {let opened = futures::future::poll_fn(|cx| {if socket.open.get() {Poll::Ready(Ok(()))@@ -281,12 +347,7 @@ impl WsLink {socket.retire();return Err(err);}- if socket.ws.protocol() != SUBPROTOCOL {- socket.retire();- anyhow::bail!("the server did not select the {SUBPROTOCOL} subprotocol");- }-- Ok(socket)+ Ok(())}/// Put a fresh socket under this handle.@@ -296,7 +357,10 @@ impl WsLink {/// swapping the socket underneath them is what makes a reconnect/// invisible to everything above.pub async fn reconnect_to(&self) -> Result<()> {- let socket = Self::open(&self.0.url, &self.0.token).await?;+ let socket = match &self.0.opener {+ Some(opener) => Self::open_via(opener).await?,+ None => Self::open(&self.0.url, &self.0.token).await?,+ };// Anything still waiting was waiting on the old socket and will// never be answered; the new server has never heard of those// serials.diff --git a/thinkterm-web/src/navbar.rs b/thinkterm-web/src/navbar.rsindex 4a3785e5..0fb10fad 100644--- a/thinkterm-web/src/navbar.rs+++ b/thinkterm-web/src/navbar.rs@@ -150,6 +150,8 @@ pub struct CapsuleView {pub title: String,pub busy: bool,pub current: bool,+ /// The card heading it (`tab_icons`); none with tab icons off.+ pub icon: Option<String>,}diff --git a/thinkterm-web/src/page.rs b/thinkterm-web/src/page.rsindex 3e96221d..59c69db9 100644--- a/thinkterm-web/src/page.rs+++ b/thinkterm-web/src/page.rs@@ -79,11 +79,15 @@ pub async fn start(// The language: a preference ("system" or a tag) and the browser's list.locale: String,languages: Vec<String>,+ // Another machine, reached through this page's server: hands back a+ // socket ready for its mux connection (`WsLink::connect_via`); `url`+ // and `token` are then unused.+ opener: Option<js_sys::Function>,) -> Result<crate::bridge::Client, JsValue> {thinkterm_i18n::activate_preference(&locale, &languages);run(canvas_id, textarea_id, url, token, font_names, fonts, size_pt, glyph_font, font_pinned,- languages,+ languages, opener,).await.map(crate::bridge::Client::new)@@ -110,6 +114,7 @@ async fn run(glyph_font: String,font_pinned: bool,languages: Vec<String>,+ opener: Option<js_sys::Function>,) -> Result<Rc<WebApp>> {let canvas: web_sys::HtmlCanvasElement = element(&canvas_id)?;let textarea: web_sys::HtmlTextAreaElement = element(&textarea_id)?;@@ -136,11 +141,21 @@ async fn run(let dpi = (96.0 * dpr) as u32;set_status("connecting…");- let link = WsLink::connect(&url, &token).await?;+ let link_is_relay = opener.is_some();+ let link = match opener {+ Some(opener) => WsLink::connect_via(opener).await?,+ None => WsLink::connect(&url, &token).await?,+ };// From here on a failure must hand the socket back: without this the// server keeps a registered client and a TCP session for a page that// gave up, and the reader keeps answering its pings.let platform = Rc::new(WebPlatform::new(canvas.clone(), textarea.clone()));+ // Another machine starts behind the one on show; the page brings it on+ // show. Hidden from the first moment, so nothing in its start-up takes+ // a terminal from that host's own desktop.+ if link_is_relay {+ platform.set_shown(false);+ }let outcome = start_attached(&link, platform, &canvas, &textarea, fonts, size_pt, &glyph_font, dpr, dpi, font_pinned,languages,@@ -253,6 +268,7 @@ async fn start_attached(rows,font_pinned,languages,+ server_version: attached.server_version.clone(),});host.events.set_wake(app.wake());{@@ -268,7 +284,8 @@ async fn start_attached(app.hide_status();app.refresh_layout();app.poll_layout(5_000);- let _ = textarea.focus();+ // Through the platform, which leaves a phone's soft keyboard down.+ platform.focus_input();app.match_desktop_cell();app.resize();app.request_frame();diff --git a/thinkterm-web/src/palette.rs b/thinkterm-web/src/palette.rsindex 12c3c701..70251033 100644--- a/thinkterm-web/src/palette.rs+++ b/thinkterm-web/src/palette.rs@@ -74,6 +74,10 @@ const COMMANDS: &[(&str, &str, &str, &str)] = &[("follow", "web-cmd-follow", "eye", ""),("toggle-sidebar", "web-cmd-toggle-sidebar", "panel-left", ""),("settings", "sidebar-settings", "settings", ""),+ // The desktop's Shell › Remote Hosts… and Add Remote Host…: the page's+ // own, as Settings is.+ ("remote-hosts", "web-machines-title", "network", ""),+ ("add-remote-host", "menu-add-remote-host", "plus", ""),("font-up", "web-cmd-font-up", "zoom-in", "Cmd+="),("font-down", "web-cmd-font-down", "zoom-out", "Cmd+-"),("font-reset", "web-cmd-font-reset", "rotate-ccw", "Cmd+0"),diff --git a/thinkterm-web/src/platform.rs b/thinkterm-web/src/platform.rsindex 83c0858c..16d44942 100644--- a/thinkterm-web/src/platform.rs+++ b/thinkterm-web/src/platform.rs@@ -137,6 +137,18 @@ pub trait Platform: 'static {fn set_backing_size(&self, width: u32, height: u32) -> bool;/// The phone shape: no margin above and below the grid.fn is_mobile(&self) -> bool;+ /// Whether a lone pane goes without its bar on a phone: the phone+ /// app's way, as its terminal apps show one. A page keeps the+ /// desktop's two rows of tabs.+ fn bare_lone_pane(&self) -> bool {+ false+ }+ /// Whether this client's terminal is on show. A page with several+ /// machines shows one; the others keep their sessions but act on+ /// nothing a person did not ask them to.+ fn shown(&self) -> bool {+ true+ }// ----- the shell -----diff --git a/thinkterm-web/src/settings.rs b/thinkterm-web/src/settings.rsindex a2f66969..3544d944 100644--- a/thinkterm-web/src/settings.rs+++ b/thinkterm-web/src/settings.rs@@ -60,6 +60,9 @@ pub struct WebSettings {pub auto_reconnect: bool,/// The bars over the panes; a phone can do without them.pub pane_bars: bool,+ /// The program's icon at the head of each tab, as the desktop draws+ /// it from that machine's cards.+ pub tab_icons: bool,}/// A colour scheme as the page hands it over, straight out of@@ -126,6 +129,7 @@ impl Default for WebSettings {resize_mode: ResizeMode::Live,auto_reconnect: true,pane_bars: true,+ tab_icons: true,}}}diff --git a/thinkterm-web/src/tab_icons.rs b/thinkterm-web/src/tab_icons.rsnew file mode 100644index 00000000..79918727--- /dev/null+++ b/thinkterm-web/src/tab_icons.rs@@ -0,0 +1,98 @@+//! The icons heading the tabs, as the desktop draws them: a coloured+//! circle carrying the mark of what a pane runs. The cards are the+//! desktop's, as its settings make them on the machine this page reached+//! (`thinkterm_tab_icons::WireCatalog`, sent over the relay's control+//! socket); which card a pane gets is the desktop's own rule (`Matcher`):+//! its agent's, else its program's, else the terminal's. A window tab+//! always gets the terminal's, as it holds panes that may each run+//! something else. The page draws a card from its id.++use thinkterm_proto::ForegroundProgram;+use thinkterm_tab_icons::{Matcher, WireCatalog};++pub struct TabIcons {+ /// The cards' ids, in the catalog's order: what `Matcher` indexes.+ ids: Vec<String>,+ /// The machine's own switch: off, no tab gets an icon.+ enabled: bool,+ matcher: Matcher,+}++impl TabIcons {+ pub fn parse(json: &str) -> Result<Self, String> {+ let catalog: WireCatalog = serde_json::from_str(json).map_err(|e| e.to_string())?;+ Ok(Self::new(&catalog))+ }++ pub fn new(catalog: &WireCatalog) -> Self {+ Self {+ ids: catalog.cards.iter().map(|card| card.id.clone()).collect(),+ enabled: catalog.enabled,+ matcher: catalog.matcher(),+ }+ }++ /// The card for a pane running `agent` and led by `program`.+ pub fn card(&self, agent: Option<&str>, program: Option<&ForegroundProgram>) -> Option<&str> {+ self.id(self.matcher.find(agent, program))+ }++ /// The terminal's card, for a window tab.+ pub fn terminal(&self) -> Option<&str> {+ self.id(self.matcher.terminal())+ }++ fn id(&self, index: usize) -> Option<&str> {+ if !self.enabled {+ return None;+ }+ self.ids.get(index).map(String::as_str)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn catalog(enabled: bool) -> String {+ serde_json::json!({+ "enabled": enabled,+ "terminal": "terminal",+ "cards": [+ { "id": "terminal", "circle": "#333333", "glyph": "#ffffff", "svg": "<svg/>", "programs": [], "agents": [] },+ { "id": "vim", "circle": "#22aa44", "glyph": "#ffffff", "svg": "<svg/>", "programs": ["vim", "nvim"], "agents": [] },+ { "id": "claude", "circle": "#cc7744", "glyph": "#ffffff", "svg": "<svg/>", "programs": [], "agents": ["claude"] },+ ],+ })+ .to_string()+ }++ fn program(executable: &str) -> ForegroundProgram {+ ForegroundProgram {+ executable: executable.to_string(),+ runs: None,+ }+ }++ #[test]+ fn a_pane_gets_its_agents_card_then_its_programs_then_the_terminals() {+ let icons = TabIcons::parse(&catalog(true)).unwrap();+ assert_eq!(icons.card(Some("claude"), Some(&program("node"))), Some("claude"));+ assert_eq!(icons.card(None, Some(&program("nvim"))), Some("vim"));+ assert_eq!(icons.card(None, Some(&program("zsh"))), Some("terminal"));+ assert_eq!(icons.card(None, None), Some("terminal"));+ assert_eq!(icons.terminal(), Some("terminal"));+ }++ #[test]+ fn the_machines_switch_turns_every_icon_off() {+ let icons = TabIcons::parse(&catalog(false)).unwrap();+ assert_eq!(icons.card(None, Some(&program("vim"))), None);+ assert_eq!(icons.terminal(), None);+ }++ #[test]+ fn a_catalog_that_does_not_parse_is_refused() {+ assert!(TabIcons::parse("{}").is_err());+ }+}diff --git a/thinkterm-web/src/tree.rs b/thinkterm-web/src/tree.rsindex 3cddd28c..65e81831 100644--- a/thinkterm-web/src/tree.rs+++ b/thinkterm-web/src/tree.rs@@ -90,7 +90,7 @@ pub struct TreeProject {}/// A Space as the Space menu lists it.-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pub struct SpaceEntry {pub id: String,pub name: String,@@ -105,6 +105,8 @@ pub struct TreeModel {pub agents: HashMap<PaneId, AgentState>,/// The agent's id and the pane's title as the server reported them.agent_details: HashMap<PaneId, (String, String)>,+ /// Panes whose agent reported its own end.+ agents_ended: HashSet<PaneId>,pub collapsed: HashSet<String>,pub archived_open: bool,/// The Space the sidebar shows; the first one until chosen.@@ -169,14 +171,29 @@ impl TreeModel {self.agents.insert(pane_id, s.state);let title = self.agent_details.get(&pane_id).map(|(_, t)| t.clone()).unwrap_or_default();self.agent_details.insert(pane_id, (s.agent_id.clone(), title));+ if s.ended {+ self.agents_ended.insert(pane_id);+ } else {+ self.agents_ended.remove(&pane_id);+ }}None => {self.agents.remove(&pane_id);self.agent_details.remove(&pane_id);+ self.agents_ended.remove(&pane_id);}}}+ /// The agent a pane runs, by id, until it reports its own end: what+ /// picks the pane's tab icon, as on the desktop.+ pub fn agent_id(&self, pane_id: PaneId) -> Option<&str> {+ if !self.agents.contains_key(&pane_id) || self.agents_ended.contains(&pane_id) {+ return None;+ }+ self.agent_details.get(&pane_id).map(|(id, _)| id.as_str())+ }+/// The windows the server has, for the ones no thread claims.pub fn apply_panes(&mut self, list: &ListPanesResponse) {let mut seen = HashSet::new();diff --git a/thinkterm-web/src/viewport.rs b/thinkterm-web/src/viewport.rsindex a2c16f5b..9c23b741 100644--- a/thinkterm-web/src/viewport.rs+++ b/thinkterm-web/src/viewport.rs@@ -42,6 +42,37 @@ pub fn choose_size_pt(((pt - current).abs() >= 0.125).then_some(pt)}+/// Where a pane's rows sit while it previews a grid of another height than+/// the server has given it yet: the preview's row count, placed as the+/// server's resize will place them. Taller, the bottom stays on the newest+/// row and the rows above come out of the scrollback, as far as it goes;+/// shorter, the blank rows under the cursor go first, then the top rows+/// into the scrollback. The preview itself keeps the old top: a phone's+/// pane growing as its soft keyboard went away showed rows past the newest+/// one, not written yet -- blank but for its last rows until the server+/// answered, and then everything moved. The alternate screen, a program's+/// own grid, is left as the preview has it.+pub fn previewed(+ dims: RenderableDimensions,+ server: &RenderableDimensions,+ cursor_row: StableRowIndex,+ alt_screen: bool,+) -> RenderableDimensions {+ if alt_screen || dims.cols != server.cols || dims.viewport_rows == server.viewport_rows {+ return dims;+ }+ let rows = dims.viewport_rows as StableRowIndex;+ let old = server.viewport_rows as StableRowIndex;+ let bottom = server.physical_top + old;+ let physical_top = if rows > old {+ (bottom - rows).max(dims.scrollback_top)+ } else {+ let blank_below = (bottom - 1).saturating_sub(cursor_row).clamp(0, old - rows);+ bottom - blank_below - rows+ };+ RenderableDimensions { physical_top, ..dims }+}+/// Rows the page shows: the last `rows` of the screen, moved up into the/// scrollback by `scroll_from_bottom` lines.pub fn visible_rows(@@ -168,6 +199,36 @@ mod tests {assert_eq!(visible_rows(&dims(100, 0, 24), 24, 0), 100..124);}+ #[test]+ fn a_taller_preview_keeps_the_newest_row_at_the_bottom() {+ // The server has rows 384..400 on show, the cursor on the last; a+ // keyboard going away previews 32 rows.+ let server = dims(384, 0, 16);+ let preview = dims(384, 0, 32);+ let shown = previewed(preview, &server, 399, false);+ assert_eq!(visible_rows(&shown, 32, 0), 368..400);+ // Without that much scrollback, blank rows go under the newest one.+ let short = previewed(dims(5, 0, 32), &dims(5, 0, 16), 20, false);+ assert_eq!(visible_rows(&short, 32, 0), 0..32);+ // The alternate screen is left as previewed.+ assert_eq!(previewed(preview, &server, 399, true).physical_top, 384);+ }++ #[test]+ fn a_shorter_preview_drops_the_blank_rows_under_the_cursor_first() {+ let server = dims(368, 0, 32);+ // The cursor on the last row: the top rows go into the scrollback.+ let full = previewed(dims(368, 0, 16), &server, 399, false);+ assert_eq!(visible_rows(&full, 16, 0), 384..400);+ // The cursor near the top of a fresh screen: the blank rows under+ // it go, and the top stays.+ let fresh = previewed(dims(368, 0, 16), &server, 370, false);+ assert_eq!(visible_rows(&fresh, 16, 0), 368..384);+ // In between: as many blank rows as there are, then the top.+ let partial = previewed(dims(368, 0, 16), &server, 390, false);+ assert_eq!(visible_rows(&partial, 16, 0), 375..391);+ }+#[test]fn scrolling_moves_up_and_stops_at_the_oldest_row() {assert_eq!(visible_rows(&dims(100, 0, 24), 24, 10), 90..114);diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rsindex 47b0db3a..287c011f 100644--- a/thinkterm-web/src/views.rs+++ b/thinkterm-web/src/views.rs@@ -30,6 +30,9 @@ pub struct SidebarView {pub struct TabsView {pub tabs: Vec<TabView>,pub controls: Controls,+ /// The card heading every window tab: the terminal's, as on the+ /// desktop (`tab_icons`); none with tab icons off.+ pub icon: Option<String>,}pub type NavsView = Vec<NavView>;@@ -85,6 +88,78 @@ pub struct Card {/// The static labels the page draws itself (tooltips, headers, the/// confirmation words), keyed by their catalogue id, in the active locale.pub const STRING_KEYS: &[&str] = &[+ "web-machines-title",+ "web-machines-here",+ "web-machines-connected",+ "web-machines-others",+ "web-machines-empty",+ "web-machines-connect",+ "web-machines-show",+ "web-machines-disconnect",+ "web-machines-forget",+ "web-machines-retry",+ "web-machines-plain-ssh",+ "web-machines-name",+ "web-machines-host",+ "web-machines-port",+ "web-machines-user",+ "web-machines-password",+ "web-machines-optional",+ "web-machines-add-connect",+ "web-machines-cancel",+ "web-machines-from-ssh-config",+ "web-machines-from-desktop",+ "web-machines-from-web",+ "web-machines-password-kept",+ "web-machines-step-connecting",+ "web-machines-step-authenticating",+ "web-machines-step-checking",+ "web-machines-step-installing",+ "web-machines-step-updating",+ "web-machines-step-starting",+ "web-machines-reconnecting",+ "web-machines-needs-you",+ "web-machines-not-connected",+ "web-machines-ask-host-key",+ "web-machines-ask-host-key-hint",+ "web-machines-ask-password",+ "web-machines-ask-code",+ "web-machines-ask-answer",+ "web-machines-ask-install",+ "web-machines-ask-install-hint",+ "web-machines-ask-replace",+ "web-machines-ask-replace-hint",+ "web-machines-ask-stop",+ "web-machines-ask-stop-hint",+ "web-machines-remember",+ "web-machines-trust",+ "web-machines-install",+ "web-machines-replace",+ "web-machines-stop",+ "web-machines-not-now",+ "web-machines-continue",+ "web-machines-failed-unreachable",+ "web-machines-failed-host-key",+ "web-machines-failed-auth",+ "web-machines-failed-cancelled",+ "web-machines-failed-declined",+ "web-machines-failed-cannot-install",+ "web-machines-failed-same-server",+ "web-machines-failed-failed",+ "web-machines-failed-desktop",+ "web-machines-failed-gone",+ "web-machines-bad-port",+ "web-machines-details",+ // The add form's card, as the desktop's host form heads it.+ "ssh-group-connection",+ // The page's toolbar, as the desktop's Remote Hosts page has it.+ "ssh-new-host",+ "ssh-search",+ // The desktop's Tab Icons switch.+ "settings-tab-icons-enabled",+ "settings-tab-icons-enabled-description",+ "menu-add-remote-host",+ "menu-new-space-here","sidebar-new-thread","sidebar-pinned","sidebar-workspaces",@@ -135,6 +210,8 @@ pub const STRING_KEYS: &[&str] = &["web-settings-sidebar-reset","web-settings-about","web-settings-close",+ // The way back to the sections, on a phone.+ "sidebar-settings","language-system","settings-section-general","settings-section-appearance",@@ -143,6 +220,12 @@ pub const STRING_KEYS: &[&str] = &["settings-section-about","web-settings-search","web-settings-build",+ // Settings › About, in the desktop's words.+ "settings-about-version",+ "settings-about-license",+ "settings-about-copy",+ "settings-about-copied",+ "ssh-field-host","web-settings-language-description","web-settings-hotkey-description","web-settings-theme-description",@@ -302,8 +385,10 @@ mod tests {panes: vec![],}],controls: Controls { following: true, fit: false, closing_tab: Some(7), clipped: Some((80, 24)) },+ icon: Some("terminal".into()),}).unwrap();+ assert_eq!(v["icon"], "terminal");assert_eq!(v["tabs"][0]["tab"], 7);assert_eq!(v["tabs"][0]["window"], 0);assert_eq!(v["tabs"][0]["target"], 9);diff --git a/thinkterm-web/src/web_platform.rs b/thinkterm-web/src/web_platform.rsindex 9c0645c3..fc296c78 100644--- a/thinkterm-web/src/web_platform.rs+++ b/thinkterm-web/src/web_platform.rs@@ -14,6 +14,27 @@ pub struct WebPlatform {performance: Option<web_sys::Performance>,frame: RefCell<Option<Closure<dyn FnMut()>>>,ime_anchor: RefCell<Option<crate::ime::Anchor>>,+ /// The page shows this canvas. One page can hold several machines'+ /// terminals, one on show at a time; the others keep their sessions+ /// but neither paint nor name the document.+ shown: Cell<bool>,+ /// A frame asked for while hidden, owed once shown again.+ frame_owed: Cell<bool>,+ /// The title last asked for, for when this is shown again.+ title: RefCell<Option<String>>,+ /// The frame asked for and not yet called back.+ frame_pending: Cell<Option<i32>>,+ /// Listeners, timers and observers this client set up on the page,+ /// held rather than leaked so `release` can take them down when the+ /// page closes this client while the page itself stays.+ held: RefCell<Held>,+}++#[derive(Default)]+struct Held {+ listeners: Vec<(web_sys::EventTarget, String, Closure<dyn FnMut(web_sys::Event)>)>,+ intervals: Vec<(i32, Closure<dyn FnMut()>)>,+ observers: Vec<(web_sys::ResizeObserver, Closure<dyn FnMut(js_sys::Array)>)>,}impl WebPlatform {@@ -24,6 +45,88 @@ impl WebPlatform {performance: web_sys::window().and_then(|w| w.performance()),frame: RefCell::new(None),ime_anchor: RefCell::new(None),+ shown: Cell::new(true),+ frame_owed: Cell::new(false),+ title: RefCell::new(None),+ frame_pending: Cell::new(None),+ held: RefCell::new(Held::default()),+ }+ }++ /// `handler` for `name` events on `target`, until `release`.+ pub fn listen<E: JsCast + 'static>(+ &self,+ target: &web_sys::EventTarget,+ name: &str,+ mut handler: impl FnMut(E) + 'static,+ ) {+ let closure = Closure::<dyn FnMut(web_sys::Event)>::new(move |ev: web_sys::Event| {+ if let Ok(ev) = ev.dyn_into::<E>() {+ handler(ev);+ }+ });+ if target+ .add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())+ .is_ok()+ {+ self.held+ .borrow_mut()+ .listeners+ .push((target.clone(), name.to_string(), closure));+ }+ }++ /// `cb` whenever `element`'s box changes size, until `release`.+ pub fn observe_resize(&self, element: &web_sys::Element, mut cb: impl FnMut() + 'static) {+ let closure = Closure::<dyn FnMut(js_sys::Array)>::new(move |_entries: js_sys::Array| cb());+ if let Ok(observer) = web_sys::ResizeObserver::new(closure.as_ref().unchecked_ref()) {+ observer.observe(element);+ self.held.borrow_mut().observers.push((observer, closure));+ }+ }++ /// Take down everything this client set up on the page: its listeners,+ /// timers and observers, and the frame it asked for. The page calls it+ /// when it closes a machine's terminal and stays open itself; without+ /// it the canvas, its GPU context and the client stayed reachable from+ /// the page for as long as the page lived.+ pub fn release(&self) {+ self.shown.set(false);+ let held = std::mem::take(&mut *self.held.borrow_mut());+ let window = web_sys::window();+ for (target, name, closure) in held.listeners {+ let _ = target.remove_event_listener_with_callback(&name, closure.as_ref().unchecked_ref());+ }+ for (id, _closure) in held.intervals {+ if let Some(window) = &window {+ window.clear_interval_with_handle(id);+ }+ }+ for (observer, _closure) in held.observers {+ observer.disconnect();+ }+ if let (Some(window), Some(id)) = (&window, self.frame_pending.take()) {+ let _ = window.cancel_animation_frame(id);+ }+ }++ /// Put this canvas on show, or take it off; see `shown`.+ pub fn set_shown(&self, shown: bool) {+ self.shown.set(shown);+ if !shown {+ return;+ }+ if let Some(title) = self.title.borrow().as_deref() {+ Self::write_title(title);+ }+ if self.frame_owed.replace(false) {+ self.request_frame();+ }+ }++ fn write_title(title: &str) {+ if let Some(doc) = web_sys::window().and_then(|w| w.document()) {+ doc.set_title(&format!("{title} — ThinkTerm"));}}@@ -78,15 +181,12 @@ impl Platform for WebPlatform {fn set_interval(&self, every_ms: f64, cb: Box<dyn FnMut()>) {let closure = Closure::<dyn FnMut()>::new(cb);if let Some(window) = web_sys::window() {- if window- .set_interval_with_callback_and_timeout_and_arguments_0(- closure.as_ref().unchecked_ref(),- every_ms.clamp(0.0, i32::MAX as f64) as i32,- )- .is_ok()- {- // One per page, for the life of the page.- closure.forget();+ if let Ok(id) = window.set_interval_with_callback_and_timeout_and_arguments_0(+ closure.as_ref().unchecked_ref(),+ every_ms.clamp(0.0, i32::MAX as f64) as i32,+ ) {+ // For the life of this client; see `release`.+ self.held.borrow_mut().intervals.push((id, closure));}}}@@ -118,10 +218,20 @@ impl Platform for WebPlatform {*self.frame.borrow_mut() = Some(Closure::<dyn FnMut()>::new(move || cb()));}+ fn shown(&self) -> bool {+ self.shown.get()+ }+fn request_frame(&self) {+ if !self.shown.get() {+ self.frame_owed.set(true);+ return;+ }let frame = self.frame.borrow();if let (Some(window), Some(closure)) = (web_sys::window(), frame.as_ref()) {- let _ = window.request_animation_frame(closure.as_ref().unchecked_ref());+ if let Ok(id) = window.request_animation_frame(closure.as_ref().unchecked_ref()) {+ self.frame_pending.set(Some(id));+ }}}@@ -156,8 +266,9 @@ impl Platform for WebPlatform {}fn set_title(&self, title: &str) {- if let Some(doc) = web_sys::window().and_then(|w| w.document()) {- doc.set_title(&format!("{title} — ThinkTerm"));+ *self.title.borrow_mut() = Some(title.to_string());+ if self.shown.get() {+ Self::write_title(title);}}@@ -186,6 +297,11 @@ impl Platform for WebPlatform {if body.has_attribute("data-mobile") && !body.has_attribute("data-keyboard") {return;}+ // A page in the terminal's place (the Remote Hosts tab) keeps+ // the keys: the terminal behind it is not on show.+ if body.has_attribute("data-page") {+ return;+ }}let el: &web_sys::HtmlElement = self.textarea.as_ref();let _ = el.focus();diff --git a/thinkterm-web/ui/index.html b/thinkterm-web/ui/index.htmlindex 6e4537b7..e51b1d35 100644--- a/thinkterm-web/ui/index.html+++ b/thinkterm-web/ui/index.html@@ -2,7 +2,7 @@<html lang="en"><head><meta charset="utf-8">-<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content"><meta name="mobile-web-app-capable" content="yes"><title>ThinkTerm</title></head>diff --git a/thinkterm-web/ui/package.json b/thinkterm-web/ui/package.jsonindex e994c837..534de2ad 100644--- a/thinkterm-web/ui/package.json+++ b/thinkterm-web/ui/package.json@@ -5,7 +5,8 @@"scripts": {"dev": "vite","build": "vite build",- "check": "svelte-check --tsconfig ./tsconfig.json"+ "check": "svelte-check --tsconfig ./tsconfig.json",+ "test": "node --conditions=browser --experimental-vm-modules --test tests/*.test.mjs"},"devDependencies": {"@sveltejs/vite-plugin-svelte": "^7.3.0",diff --git a/thinkterm-web/ui/src/AgentsPanel.svelte b/thinkterm-web/ui/src/AgentsPanel.svelteindex b86d4f66..5daec4b9 100644--- a/thinkterm-web/ui/src/AgentsPanel.svelte+++ b/thinkterm-web/ui/src/AgentsPanel.svelte@@ -37,9 +37,13 @@// What the panel shows is followed only while it is up: the snippets,// and the server's connection to the plugin host for them, go with it.+ // The client is the one on show when the panel came up: with several+ // machines the panel comes up afresh for each, and puts down what the+ // last one followed.$effect(() => {- handle.client?.set_right_panel_shown(true);- return () => handle.client?.set_right_panel_shown(false);+ const client = handle.client;+ client?.set_right_panel_shown(true);+ return () => client?.set_right_panel_shown(false);});// A click anywhere in a row is that row's, as it is on the desktop: thediff --git a/thinkterm-web/ui/src/App.svelte b/thinkterm-web/ui/src/App.svelteindex afe6c78f..1498bdcc 100644--- a/thinkterm-web/ui/src/App.svelte+++ b/thinkterm-web/ui/src/App.svelte@@ -3,6 +3,7 @@// and the remark are drawn here from the views the wasm publishes; the// canvas and the keyboard field are the wasm's, and it finds them by id.import AgentsPanel from './AgentsPanel.svelte';+ import Boot from './Boot.svelte';import Card from './Card.svelte';import ContextMenu from './ContextMenu.svelte';import DragLayer from './DragLayer.svelte';@@ -14,6 +15,8 @@import Status from './Status.svelte';import TabRow from './TabRow.svelte';import { views } from './client.svelte';+ import { HERE, machines } from './machines.svelte';+ import MachinesPanel from './MachinesPanel.svelte';import { openMenu } from './menu.svelte';import { mobile, openSide } from './mobile.svelte';import { paneAt } from './pane';@@ -47,17 +50,31 @@<Sidebar /><TabRow />-<canvas id="term" data-layout={views.layout} oncontextmenu={onCanvasMenu} use:touch></canvas>+<!-- One canvas and one keyboard field per machine; the one on show is+ #term and #kbd, which is how everything else finds it. -->+<canvas id={machines.active === HERE ? 'term' : 'term-0'} class:off={machines.active !== HERE} data-layout={machines.active === HERE ? views.layout : undefined} oncontextmenu={onCanvasMenu} use:touch></canvas>+{#each machines.open as m (m.n)}+ <canvas id={machines.active === m.id ? 'term' : `term-${m.n}`} class:off={machines.active !== m.id} data-layout={machines.active === m.id ? views.layout : undefined} oncontextmenu={onCanvasMenu} use:touch></canvas>+{/each}<NavBars /><!-- svelte-ignore a11y_click_events_have_key_events --><!-- svelte-ignore a11y_no_static_element_interactions -->{#if drawn}<div id="scrim" onclick={closeDrawers}></div>{/if}<Card />-<textarea id="kbd" wrap="off" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>+<textarea id={machines.active === HERE ? 'kbd' : 'kbd-0'} class:off={machines.active !== HERE} wrap="off" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>+{#each machines.open as m (m.n)}+ <textarea id={machines.active === m.id ? 'kbd' : `kbd-${m.n}`} class:off={machines.active !== m.id} wrap="off" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea>+{/each}<Status />-{#if views.settings['agents-panel']}<AgentsPanel />{/if}-{#if mobile.on}<KeyBar />{/if}+<!-- Each machine's own: they follow its client and its #term and #kbd,+ so they come up afresh when another machine comes on show. -->+{#key machines.active}+ {#if views.settings['agents-panel']}<AgentsPanel />{/if}+ {#if mobile.on}<KeyBar />{/if}+{/key}<ContextMenu /><DragLayer /><SearchPalette /><SettingsPanel />+<MachinesPanel />+<Boot />diff --git a/thinkterm-web/ui/src/Boot.svelte b/thinkterm-web/ui/src/Boot.sveltenew file mode 100644index 00000000..fc13dff1--- /dev/null+++ b/thinkterm-web/ui/src/Boot.svelte@@ -0,0 +1,69 @@+<script lang="ts">+ // The page while it starts: the app's mark with a ring turning round it,+ // its name, and the start's steps as a terminal would list them -- a+ // tick and the time each took once done, a spinner on the one under way+ // -- until the client is attached; then it fades away. A start that+ // fails stays, the step it failed on crossed, why under it and a way to+ // try again. Not drawn for the probes (`?check=`), which read their one+ // line from #status.+ import { views } from './client.svelte';+ import { fade, fly } from 'svelte/transition';+ import { cubicInOut, cubicOut } from 'svelte/easing';+ import appIcon from '../../../assets/icon/ThinkTerm_simple_128.png';++ /** Leaving: a fade with the slightest lift towards the viewer. It waits+ a moment first: the client draws its first frame as it attaches, and+ that holds the page for a while -- a fade started at once lost its+ first half to it and read as a jump to half gone. */+ function away(_node: Element, { duration, delay }: { duration: number; delay: number }) {+ return { duration, delay, easing: cubicInOut, css: (t: number) => `opacity: ${t}; transform: scale(${1 + (1 - t) * 0.03})` };+ }++ const probe = new URLSearchParams(location.search).has('check');++ /** The steps, in the order `views.bootStage` counts them (main.ts). */+ const STEPS = ['runtime', 'fonts', 'connect'];+ /** When each step began, to say how long the finished ones took. */+ const began: number[] = [performance.now()];+ let took = $state<string[]>([]);+ $effect(() => {+ const stage = views.ready ? STEPS.length : views.bootStage;+ const now = performance.now();+ for (let i = took.length; i < stage; i++) {+ took[i] = `${((now - (began[i] ?? now)) / 1000).toFixed(1)}s`;+ began[i + 1] = now;+ }+ });+ const stage = $derived(views.ready ? STEPS.length : views.bootStage);++</script>++{#if !views.ready && !probe}+ <div id="boot" class:failed={views.bootFailed} out:away={{ duration: 520, delay: 180 }} role="status" aria-live="polite">+ <div class="dots"></div>+ <div class="dots lit"></div>+ <div class="dots wave"></div>+ <div class="mid">+ <div class="orb">+ {#if !views.bootFailed}<div class="ring" aria-hidden="true"></div>{/if}+ <img class="mark" src={appIcon} alt="" width="64" height="64" draggable="false" />+ </div>+ <div class="name">ThinkTerm</div>+ <div class="log">+ {#each STEPS.slice(0, Math.min(stage + 1, STEPS.length)) as step, i (step)}+ <div class="ln" class:done={i < stage} class:bad={views.bootFailed && i === stage} in:fly={{ y: 6, duration: 280, easing: cubicOut }}>+ <span class="st">+ {#if i < stage}<span class="tick">✓</span>{:else if views.bootFailed}<span class="cross">✗</span>{:else}<span class="spin" aria-hidden="true"></span>{/if}+ </span>+ <span class="what">{step}</span>+ <span class="t">{i < stage ? (took[i] ?? '') : ''}</span>+ </div>+ {/each}+ </div>+ {#if views.bootFailed}+ <div class="why" in:fade={{ duration: 200 }}>{views.boot}</div>+ <button class="again" type="button" onclick={() => location.reload()}>Try again</button>+ {/if}+ </div>+ </div>+{/if}diff --git a/thinkterm-web/ui/src/Card.svelte b/thinkterm-web/ui/src/Card.svelteindex d102ad17..505aa0c2 100644--- a/thinkterm-web/ui/src/Card.svelte+++ b/thinkterm-web/ui/src/Card.svelte@@ -6,6 +6,7 @@// and the model's next state says how that went.import { handle } from './client';import { views } from './client.svelte';+ import { focusTerminal } from './mobile.svelte';const card = $derived(views.status.card);const taking = $derived(card?.state === 'taking');@@ -27,7 +28,7 @@handle.client?.take_over();// The keyboard stays the terminal's: a button that took focus would// keep the keys once the card is gone.- document.getElementById('kbd')?.focus({ preventScroll: true });+ focusTerminal();}</script>diff --git a/thinkterm-web/ui/src/ContextMenu.svelte b/thinkterm-web/ui/src/ContextMenu.svelteindex 1eb01400..ef1f1f97 100644--- a/thinkterm-web/ui/src/ContextMenu.svelte+++ b/thinkterm-web/ui/src/ContextMenu.svelte@@ -3,7 +3,7 @@// offers and what a row does are the wasm's (thinkterm-web/src/menu.rs);// drawn here, clamped into the viewport, walked with the pointer or the// keyboard, and closed by anything that means the page moved on.- import { closeInnermost, closeMenu, menu, runItem } from './menu.svelte';+ import { closeInnermost, closeMenu, menu, menuTrigger, runItem } from './menu.svelte';import { chevronRight, iconByName } from './icons';import { mobile } from './mobile.svelte';import type { MenuItem } from './model';@@ -99,10 +99,23 @@if (menu.items.length === 0) return;const inside = (target: EventTarget | null) =>target instanceof Node && boxes.some((b) => !!b && b.contains(target));+ // The button the menu came from closes it itself, on its click:+ // closing here as well had the click open it again, a flash.const down = (ev: Event) => {+ const from = menuTrigger();+ if (from && ev.target instanceof Node && from.contains(ev.target)) return;if (!inside(ev.target)) closeMenu();};const away = () => closeMenu();+ // A wheel is the page moving on only outside the menu, and only once+ // the menu has been up a moment: a trackpad's scroll coasts on after+ // the fingers lift, and a menu opened just after scrolling the sidebar+ // used to close itself on the coast.+ const opened = performance.now();+ const wheel = (ev: Event) => {+ if (inside(ev.target) || performance.now() - opened < 400) return;+ closeMenu();+ };// On a phone a resize is the soft keyboard coming or going, which is// not the page moving on; the menu that opened the keyboard's owner// must not vanish because of it.@@ -112,12 +125,12 @@window.addEventListener('pointerdown', down, true);window.addEventListener('blur', away);window.addEventListener('resize', resized);- window.addEventListener('wheel', away, { capture: true, passive: true });+ window.addEventListener('wheel', wheel, { capture: true, passive: true });return () => {window.removeEventListener('pointerdown', down, true);window.removeEventListener('blur', away);window.removeEventListener('resize', resized);- window.removeEventListener('wheel', away, { capture: true });+ window.removeEventListener('wheel', wheel, { capture: true });};});diff --git a/thinkterm-web/ui/src/KeyBar.svelte b/thinkterm-web/ui/src/KeyBar.svelteindex cdb8e86c..af55d33e 100644--- a/thinkterm-web/ui/src/KeyBar.svelte+++ b/thinkterm-web/ui/src/KeyBar.svelte@@ -7,6 +7,7 @@// the next key from the bar or from the soft keyboard, whichever comes.import { handle } from './client';import { KEYBAR, toggleKeyboard } from './mobile.svelte';+ import { keyboard } from './icons';/** A key: `name` is the DOM name the wasm maps, `label` what it says. */type Key = { name: string; label: string };@@ -112,6 +113,15 @@if (REPEATS.has(name)) startRepeat(name);}+ // iOS does not stop at pointerdown: once the finger lifts it plays the+ // tap as mouse events and a click, and focuses what was tapped -- the bar+ // itself, which has a tabindex -- so #kbd lost focus and the keyboard the+ // button had just brought up went straight back down. Cancelling the+ // touch's end cancels all of that; the press was handled already.+ function onTouchEnd(ev: TouchEvent) {+ if (ev.target instanceof Element && ev.target.closest('.k')) ev.preventDefault();+ }+// An armed modifier applies to the soft keyboard's next key too. #kbd's// own listener is the wasm's and sits on the same element without// capture, so this one runs first and takes the key instead.@@ -157,6 +167,19 @@const vv = window.visualViewport;let settle: ReturnType<typeof setTimeout> | null = null;let applied = 0;+ /** The bar's height when the canvas was last cut to fit above it. */+ let appliedMine = 0;+ const root = document.documentElement;+ /** Until the canvas is cut to the viewport's new height, it rides with+ the bar (--term-shift in tokens.css): its last row -- the prompt --+ stays on the bar's edge while the keyboard comes or goes, and the+ rows the cut adds or takes are at the top, where the server will+ put them. Left where it was, the prompt fell behind the keyboard as+ it came up, and the terminal jumped down once it went. */+ const ride = (barTop: number) => {+ const shift = applied > 0 ? barTop - (applied - appliedMine) : 0;+ root.style.setProperty('--term-shift', `${Math.round(shift)}px`);+ };/** The height the canvas is cut to, once the viewport has stoppedmoving. The soft keyboard slides in over a few hundred millisecondsand the viewport reports every step of it; cutting the canvas at@@ -165,22 +188,36 @@up. The bar itself still follows every step, so it never floatsaway from the keyboard's edge. */const apply = (height: number, mine: number) => {- document.documentElement.style.setProperty('--keybar', `${mine}px`);+ root.style.setProperty('--keybar', `${mine}px`);+ appliedMine = mine;+ // Cut to fit, the canvas sits where the bar is: nothing to ride.+ root.style.setProperty('--term-shift', '0px');if (height === applied) return;applied = height;- document.documentElement.style.setProperty('--vvh', `${height}px`);+ root.style.setProperty('--vvh', `${height}px`);};const read = () => {+ // The page never pans: a browser that moves the view up to show the+ // focused field (which sits at the terminal's cursor) took the tab+ // rows off the top and left a gap over the bar. Where the browser+ // resizes the page for the keyboard instead (interactive-widget in+ // index.html) this never fires.+ if (vv && (vv.offsetTop > 0 || window.scrollY > 0)) window.scrollTo(0, 0);const height = vv ? vv.height : window.innerHeight;const mine = bar?.offsetHeight || KEYBAR;- top = (vv ? vv.offsetTop : 0) + height - mine;+ // Kept in a local: read back from `top`, the state would make this+ // effect depend on it, and run again -- cutting the canvas at once+ // -- every time the bar moved.+ const barTop = (vv ? vv.offsetTop : 0) + height - mine;+ top = barTop;+ ride(barTop);if (settle !== null) clearTimeout(settle);settle = setTimeout(() => {settle = null;apply(height, mine);}, SETTLE);};- document.documentElement.style.setProperty('--keybar', `${KEYBAR}px`);+ root.style.setProperty('--keybar', `${KEYBAR}px`);// The first cut is immediate: nothing is moving yet, and the terminal// must not sit at the window's height for SETTLE before it fits.apply(vv ? vv.height : window.innerHeight, bar?.offsetHeight || KEYBAR);@@ -196,8 +233,29 @@vv?.removeEventListener('resize', read);vv?.removeEventListener('scroll', read);window.removeEventListener('resize', read);- document.documentElement.style.removeProperty('--keybar');- document.documentElement.style.removeProperty('--vvh');+ root.style.removeProperty('--keybar');+ root.style.removeProperty('--vvh');+ root.style.removeProperty('--term-shift');+ };+ });++ // The ground around the bar is the terminal's own (tokens.css,+ // --term-bg), so the capsule floats on the terminal rather than on a+ // strip of the page's colour. It is the colour the client on show clears+ // its canvas to (`data-bg`); showing another machine moves `#term` to+ // that machine's canvas.+ $effect(() => {+ const root = document.documentElement;+ const read = () => {+ const bg = document.getElementById('term')?.dataset.bg ?? '';+ if (/^#[0-9a-fA-F]{6}$/.test(bg)) root.style.setProperty('--term-bg', bg);+ };+ const watch = new MutationObserver(read);+ watch.observe(document.body, { subtree: true, attributes: true, attributeFilter: ['data-bg', 'id'] });+ read();+ return () => {+ watch.disconnect();+ root.style.removeProperty('--term-bg');};});@@ -207,7 +265,12 @@<!-- The keys are the bar's, delegated, as the tab row's and the sidebar'sare; a release anywhere ends a repeat. --><svelte:window onpointerup={stopRepeat} onpointercancel={stopRepeat} />-<div bind:this={bar} id="keybar" role="toolbar" aria-label="Terminal keys" tabindex="-1" style="top:{top.toFixed(2)}px" onpointerdown={onDown}>+<div bind:this={bar} id="keybar" role="toolbar" aria-label="Terminal keys" tabindex="-1" style="top:{top.toFixed(2)}px" onpointerdown={onDown} ontouchend={onTouchEnd}>+ <!-- The soft keyboard's own button stays put at the start; the keys+ scroll beside it. -->+ <div class="pill">+ <button class="k kbd" type="button" data-key="kbd" aria-label="Keyboard">{@html keyboard}</button>+ <div class="keys">{#each HEAD as k (k.name)}<button class="k" type="button" data-key={k.name} aria-label={k.label}>{k.label}</button>{/each}@@ -216,5 +279,6 @@{#each REST as k (k.name)}<button class="k" type="button" data-key={k.name} aria-label={k.name}>{k.label}</button>{/each}- <button class="k" type="button" data-key="kbd" aria-label="Keyboard">⌨</button>+ </div>+ </div></div>diff --git a/thinkterm-web/ui/src/MachinesPanel.svelte b/thinkterm-web/ui/src/MachinesPanel.sveltenew file mode 100644index 00000000..f775b331--- /dev/null+++ b/thinkterm-web/ui/src/MachinesPanel.svelte@@ -0,0 +1,338 @@+<script lang="ts">+ // The Remote Hosts page: the machines this page's server can reach, the+ // ones open here, and -- while one opens -- how far it got and what the+ // relay needs answered (machines.svelte.ts). The desktop's Remote Hosts+ // page, for a page whose only way out is its server, and a tab of its+ // own as that one is: in the terminal's place while it is on show, kept+ // as it was while another tab is.+ import { s } from './client.svelte';+ import { check, chevronRight, download, house, keyRound, plus, search, server, shieldAlert, unplug, x } from './icons';+ import {+ addMachine, answer, close, closePanel, connect, forgetMachine, HERE, machines, openPlainSsh, showMachine,+ stateText, type Ask, type MachineEntry, type OpenMachine,+ } from './machines.svelte';++ /** What the toolbar's search field holds. */+ let query = $state('');+ /** A machine the search leaves on show: its name or where it is. */+ function found(label: string, endpoint: string): boolean {+ const q = query.trim().toLowerCase();+ return q === '' || label.toLowerCase().includes(q) || endpoint.toLowerCase().includes(q);+ }++ /** The machines open here, and the ones not, in the server's order. */+ const opened = $derived(machines.open.filter((m) => found(m.label, endpointOf(m.id))));+ const others = $derived(machines.list.filter((m) => !machines.open.some((o) => o.id === m.id) && found(m.label, m.endpoint)));++ const SOURCE: Record<string, string> = {+ 'ssh-config': 'web-machines-from-ssh-config',+ saved: 'web-machines-from-desktop',+ web: 'web-machines-from-web',+ };++ let saving = $state(false);+ let form = $state({ label: '', host: '', port: '', user: '', password: '' });+ /** What is typed into the question on show, per machine. */+ let typed = $state<Record<string, string>>({});+ let remember = $state<Record<string, boolean>>({});+ /** The machines whose details are unfolded. */+ let unfolded = $state<Record<string, boolean>>({});+ let page = $state<HTMLElement>();++ // What is typed belongs to the question it was typed for. One that ends+ // any other way than by its answer -- the socket lost, the machine+ // closed or tried again -- takes it along: a half-typed password is not+ // offered to the next question, which may show its answer in clear.+ let askedLast = new Map<string, Ask | null>();+ $effect(() => {+ const now = new Map<string, Ask | null>();+ for (const m of machines.open) {+ now.set(m.id, m.ask);+ if (askedLast.get(m.id) !== m.ask) typed[m.id] = '';+ }+ askedLast = now;+ });++ // A form put away -- or closed with the tab -- takes what was typed in it.+ $effect(() => {+ if (machines.adding) return;+ form = { label: '', host: '', port: '', user: '', password: '' };+ });++ // A tab closed starts the next one afresh: no search left in its field.+ $effect(() => {+ if (!machines.tab) query = '';+ });++ // On show, the page takes the keys -- unless a field in it already has+ // them (a question's answer).+ $effect(() => {+ if (!machines.panel || !page) return;+ if (!page.contains(document.activeElement)) page.focus({ preventScroll: true });+ });++ async function submit(ev: Event) {+ ev.preventDefault();+ if (form.host.trim() === '' || saving) return;+ saving = true;+ const ok = await addMachine(form);+ saving = false;+ if (ok) machines.adding = false;+ }++ /** Connect, or try again. The button takes the keys as it is pressed+ (Safari leaves them where they were): the field they came from --+ the blank form Add Remote Host opens on -- is no longer being typed+ in, and the machine comes on show when it is ready. */+ function go(ev: MouseEvent, id: string) {+ (ev.currentTarget as HTMLElement).focus();+ void connect(id, true);+ }++ function reply(m: OpenMachine, value: string | null) {+ answer(m.id, value, remember[m.id] ?? true);+ typed[m.id] = '';+ }++ function onAnswerKey(ev: KeyboardEvent, m: OpenMachine) {+ if (ev.key === 'Enter') {+ ev.preventDefault();+ reply(m, typed[m.id] ?? '');+ }+ }++ // Escape puts the form away, and closes the page when there is none, as+ // on the desktop.+ function onKeydown(ev: KeyboardEvent) {+ // Nothing typed here reaches the terminal's keyboard field.+ ev.stopPropagation();+ if (ev.key !== 'Escape') return;+ ev.preventDefault();+ if (machines.adding) {+ machines.adding = false;+ page?.focus({ preventScroll: true });+ } else {+ closePanel();+ }+ }++ // A field that comes up takes the keys, but not from another field the+ // person is typing in: a question for another machine waits its turn.+ function typeHere(node: HTMLInputElement) {+ const typing = document.activeElement;+ if (typing instanceof HTMLInputElement && typing !== node && typing.closest('#machines')) return;+ node.focus();+ }++ /** The form comes into view whole, its buttons too, when it opens under+ a long list. */+ function reveal(node: HTMLElement) {+ node.scrollIntoView({ block: 'nearest' });+ }++ /** The question's heading. */+ function askTitle(m: OpenMachine): string {+ switch (m.ask?.kind) {+ case 'host-key': return s('web-machines-ask-host-key');+ case 'install': return s('web-machines-ask-install');+ case 'replace': return s('web-machines-ask-replace');+ case 'stop-server': return s('web-machines-ask-stop');+ case 'password': return m.ask.prompt || s('web-machines-ask-password');+ case 'secret': return m.ask.prompt || s('web-machines-ask-code');+ default: return m.ask?.prompt || s('web-machines-ask-answer');+ }+ }++ /** The yes of a yes-or-no question, and its explanation. */+ const CONFIRM: Record<string, [string, string]> = {+ 'host-key': ['web-machines-trust', 'web-machines-ask-host-key-hint'],+ install: ['web-machines-install', 'web-machines-ask-install-hint'],+ replace: ['web-machines-replace', 'web-machines-ask-replace-hint'],+ 'stop-server': ['web-machines-stop', 'web-machines-ask-stop-hint'],+ };++ function sourceOf(m: MachineEntry): string {+ return s(SOURCE[m.source] ?? 'web-machines-from-web');+ }++ function endpointOf(id: string): string {+ return machines.list.find((m) => m.id === id)?.endpoint ?? '';+ }++ /** Where the form would connect, as the desktop's host form heads itself+ with it: user@host, and the port when it is not 22. */+ const formEndpoint = $derived.by(() => {+ const host = form.host.trim();+ if (host === '') return '';+ const port = form.port.trim();+ const user = form.user.trim();+ return `${user !== '' ? `${user}@` : ''}${host}${port !== '' && port !== '22' ? `:${port}` : ''}`;+ });++ /** An open machine's card takes the grid's full width while it has more+ to say than its row: a question, a failure or its progress log. */+ function wide(m: OpenMachine): boolean {+ return !!m.ask || (m.state === 'failed' && !!m.failure) || (m.log.length > 0 && (m.state !== 'ready' || !!unfolded[m.id]));+ }+</script>++<!-- The desktop's Remote Hosts page (ssh_hosts_view.rs) where it puts it,+ in the terminal's place (`#machines` in tokens.css): New Host and the+ search field in the toolbar, a grid of host cards under their group+ captions, and the host form as an inspector on the right. A card says+ what the machine is and how far it got; its question, failure and log+ open the card to the grid's full width, at its text. Kept while its+ tab is behind another, so a half-typed form or answer waits there. -->+<!-- svelte-ignore a11y_no_static_element_interactions -->+{#if machines.tab}+ <div id="machines" class:adding={machines.adding} hidden={!machines.panel} tabindex="-1" onkeydown={onKeydown} bind:this={page}>+ <div class="lists">+ <div class="tools">+ <button class="pillbtn primary addbtn" type="button" data-action="add-machine" onclick={() => (machines.adding = true)}>{@html plus}<span>{s('ssh-new-host')}</span></button>+ <label class="find">{@html search}<input type="search" bind:value={query} placeholder={s('ssh-search')} spellcheck="false" autocapitalize="off" autocomplete="off" /></label>+ </div>+ <div class="body">+ <div class="label">{s('web-machines-connected')}</div>+ <div class="grid">+ <div class="hcard" class:on={machines.active === HERE}>+ <div class="mrow" data-machine={HERE}>+ <span class="logo">{@html house}<span class="dot ok"></span></span>+ <div class="tx"><div class="lab">{s('web-machines-here')}</div>{#if machines.here}<div class="desc">{machines.here}</div>{/if}</div>+ <div class="ctl">+ {#if machines.active !== HERE}<button class="pillbtn" type="button" onclick={() => { showMachine(HERE); closePanel(); }}>{s('web-machines-show')}</button>{:else}<span class="shown">{@html check}</span>{/if}+ </div>+ </div>+ </div>+ {#each opened as m (m.n)}+ {@const state = stateText(m)}+ {@const endpoint = endpointOf(m.id)}+ <div class="group hcard" class:on={machines.active === m.id} class:wide={wide(m)}>+ <div class="mrow" data-machine={m.id} data-state={m.ask ? 'asking' : m.state}>+ <span class="logo">{@html server}<span class="dot" class:ok={m.state === 'ready' && !m.ask} class:busy={(m.state === 'connecting' || m.state === 'reconnecting') && !m.ask} class:wait={!!m.ask} class:bad={m.state === 'failed'}></span></span>+ <div class="tx">+ <div class="lab">{m.label}</div>+ <div class="desc">{#if endpoint}<span>{endpoint}</span>{/if}{#if state !== ''}<span class="st">{state}</span>{#if m.percent !== null}<span class="st">{m.percent}%</span>{/if}{/if}</div>+ {#if m.percent !== null && !m.ask}+ <div class="bar"><span style={`width: ${m.percent}%`}></span></div>+ {/if}+ </div>+ <div class="ctl">+ {#if m.state === 'ready' || m.state === 'reconnecting'}+ {#if machines.active !== m.id}<button class="pillbtn" type="button" onclick={() => { showMachine(m.id); closePanel(); }}>{s('web-machines-show')}</button>{:else}<span class="shown">{@html check}</span>{/if}+ {:else if m.state === 'failed'}+ <button class="pillbtn" type="button" data-action="retry" onclick={(ev) => go(ev, m.id)}>{s('web-machines-retry')}</button>+ {/if}+ <button class="iconbtn" type="button" title={s('web-machines-disconnect')} onclick={() => close(m.id)}>{@html unplug}</button>+ </div>+ </div>+ {#if m.ask}+ {@const confirm = CONFIRM[m.ask.kind]}+ <div class="ask" data-ask={m.ask.kind}>+ <div class="ask-title">{@html confirm ? (m.ask.kind === 'host-key' ? shieldAlert : download) : keyRound}<span>{askTitle(m)}</span></div>+ {#if confirm}+ <div class="hint">{s(confirm[1])}</div>+ {#if m.ask.detail}<pre class="detail">{m.ask.detail}</pre>{/if}+ <div class="btns">+ <button class="pillbtn" type="button" data-answer="no" onclick={() => reply(m, null)}>{s('web-machines-not-now')}</button>+ <button class="pillbtn primary" type="button" data-answer="yes" onclick={() => reply(m, 'yes')}>{s(confirm[0])}</button>+ </div>+ {:else}+ {#if m.ask.detail}<div class="hint">{m.ask.detail}</div>{/if}+ <input+ class="field"+ type={m.ask.kind === 'text' ? 'text' : 'password'}+ autocomplete="off"+ spellcheck="false"+ value={typed[m.id] ?? ''}+ oninput={(ev) => (typed[m.id] = (ev.currentTarget as HTMLInputElement).value)}+ onkeydown={(ev) => onAnswerKey(ev, m)}+ use:typeHere+ />+ <div class="foot">+ {#if m.ask.remember}+ <!-- The settings window's switch, before its label. -->+ <label class="check"><span class="switch"><input type="checkbox" checked={remember[m.id] ?? true} onchange={(ev) => (remember[m.id] = (ev.currentTarget as HTMLInputElement).checked)} /><span class="knob"></span></span><span>{s('web-machines-remember')}</span></label>+ {/if}+ <div class="btns">+ <button class="pillbtn" type="button" data-answer="cancel" onclick={() => reply(m, null)}>{s('web-machines-cancel')}</button>+ <button class="pillbtn primary" type="button" data-answer="submit" onclick={() => reply(m, typed[m.id] ?? '')}>{s('web-machines-continue')}</button>+ </div>+ </div>+ {/if}+ </div>+ {/if}+ {#if m.state === 'failed' && m.failure}+ <div class="fail">+ <!-- A refusal or a cancel says all there is in its own words;+ anything else carries what the server found. -->+ {#if m.failure.message && m.failure.reason !== 'declined' && m.failure.reason !== 'cancelled'}<div class="hint">{m.failure.message}</div>{/if}+ {#if m.failure.ssh_domain}+ <div class="btns"><button class="pillbtn" type="button" data-action="plain-ssh" onclick={() => openPlainSsh(m.id)}>{s('web-machines-plain-ssh')}</button></div>+ {/if}+ </div>+ {/if}+ {#if m.log.length > 0 && (m.state !== 'ready' || unfolded[m.id])}+ <button class="more" class:open={unfolded[m.id]} type="button" aria-expanded={!!unfolded[m.id]} onclick={() => (unfolded[m.id] = !unfolded[m.id])}>{@html chevronRight}<span>{s('web-machines-details')}</span></button>+ {#if unfolded[m.id]}<pre class="log">{m.log.join('\n')}</pre>{/if}+ {/if}+ </div>+ {/each}+ </div>++ {#if others.length > 0 || (machines.listed && machines.list.length === 0)}<div class="label">{s('web-machines-others')}</div>{/if}+ {#if others.length > 0}+ <div class="grid">+ {#each others as m (m.id)}+ <div class="hcard">+ <div class="mrow" data-machine={m.id}>+ <span class="logo">{@html server}</span>+ <div class="tx">+ <div class="lab">{m.label}</div>+ <div class="desc"><span>{m.endpoint}</span><span>{sourceOf(m)}</span>{#if m.password}<span>{s('web-machines-password-kept')}</span>{/if}</div>+ </div>+ <div class="ctl">+ <button class="pillbtn" type="button" data-action="connect" onclick={(ev) => go(ev, m.id)}>{s('web-machines-connect')}</button>+ {#if m.forgettable}+ <button class="iconbtn" type="button" title={s('web-machines-forget')} data-action="forget" onclick={() => void forgetMachine(m.id)}>{@html x}</button>+ {/if}+ </div>+ </div>+ </div>+ {/each}+ </div>+ {:else if machines.listed && machines.list.length === 0}+ <!-- The desktop's empty page: the server glyph over one line. -->+ <div class="empty">{@html server}<span>{s('web-machines-empty')}</span></div>+ {/if}+ {#if machines.error !== ''}<div class="err">{machines.error}</div>{/if}+ </div>+ </div>++ {#if machines.adding}+ <!-- The desktop's inspector: the host's name (or what this is) and+ where it would connect, over one card of fields, with the way+ through at its foot. "optional" is said in the field, as a+ placeholder. -->+ <form class="add" onsubmit={submit} use:reveal>+ <div class="ihead">+ <div class="ititle">{form.label.trim() !== '' ? form.label.trim() : s('ssh-new-host')}</div>+ {#if formEndpoint !== ''}<div class="iend">{formEndpoint}</div>{/if}+ </div>+ <div class="card">+ <div class="cap">{s('ssh-group-connection')}</div>+ <div class="pair">+ <label class="fld"><span>{s('web-machines-host')}</span><input bind:value={form.host} spellcheck="false" autocapitalize="off" autocomplete="off" use:typeHere /></label>+ <label class="fld port"><span>{s('web-machines-port')}</span><input bind:value={form.port} inputmode="numeric" placeholder="22" autocomplete="off" /></label>+ </div>+ <label class="fld"><span>{s('web-machines-user')}</span><input bind:value={form.user} spellcheck="false" autocapitalize="off" autocomplete="off" /></label>+ <label class="fld"><span>{s('web-machines-name')}</span><input bind:value={form.label} placeholder={s('web-machines-optional')} spellcheck="false" autocomplete="off" /></label>+ <label class="fld"><span>{s('web-machines-password')}</span><input type="password" bind:value={form.password} placeholder={s('web-machines-optional')} autocomplete="new-password" /></label>+ </div>+ <div class="btns">+ <button class="pillbtn" type="button" onclick={() => (machines.adding = false)}>{s('web-machines-cancel')}</button>+ <button class="pillbtn primary" type="submit" disabled={saving || form.host.trim() === ''}>{s('web-machines-add-connect')}</button>+ </div>+ </form>+ {/if}+ </div>+{/if}diff --git a/thinkterm-web/ui/src/NavBars.svelte b/thinkterm-web/ui/src/NavBars.svelteindex 2cd1819e..f7e5df69 100644--- a/thinkterm-web/ui/src/NavBars.svelte+++ b/thinkterm-web/ui/src/NavBars.svelte@@ -3,13 +3,51 @@// pane's capsules and the buttons that split, zoom and close it. What// `navbar::NavBars::html` drew.import { onChromeClick } from './chrome';+ import { handle } from './client';import { s, views } from './client.svelte';import { loaderCircle, maximize2, minimize2, plus, squareSplitHorizontal, squareSplitVertical, squareTerminal, x } from './icons';import { armDrag } from './drag.svelte';+ import { iconClass } from './tabicons.svelte';+ import { mobile } from './mobile.svelte';++ type Divider = { row?: number; left?: number; cols?: number; col?: number; top?: number; rows?: number };+ /** Where each divider's handle goes on a phone, in the canvas's CSS px:+ a finger takes hold of a divider anywhere near it (touch.ts), and the+ handle says that it can. */+ const handles = $derived.by(() => {+ if (!mobile.on) return [];+ try {+ const layout = JSON.parse(views.layout || '{}') as { cell?: [number, number]; pad?: [number, number]; dividers?: Divider[] };+ const [cw, ch] = layout.cell ?? [0, 0];+ const [padX, padY] = layout.pad ?? [0, 0];+ if (!(cw > 0) || !(ch > 0)) return [];+ return (layout.dividers ?? []).map((d) =>+ d.row !== undefined+ ? { across: true, x: padX + ((d.left ?? 0) + (d.cols ?? 0) / 2) * cw, y: padY + (d.row + 0.5) * ch, length: (d.cols ?? 0) * cw }+ : { across: false, x: padX + ((d.col ?? 0) + 0.5) * cw, y: padY + ((d.top ?? 0) + (d.rows ?? 0) / 2) * ch, length: (d.rows ?? 0) * ch },+ );+ } catch {+ return [];+ }+ });const px = (n: number) => n.toFixed(2);+ /** A finger on a divider's strip takes hold of the divider: the wasm+ drags it from the line's middle, and the rest of the gesture is the+ canvas's, as a mouse's on the line would be. */+ function grab(ev: PointerEvent, h: { x: number; y: number }) {+ const canvas = document.getElementById('term');+ const panes = document.getElementById('panes');+ if (!canvas || !panes) return;+ const box = panes.getBoundingClientRect();+ if (!handle.client?.touch_divider(box.left + h.x, box.top + h.y)) return;+ ev.preventDefault();+ ev.stopPropagation();+ canvas.setPointerCapture(ev.pointerId);+ }+// A press on a capsule may be its drag onto another pane; the close// button is its own, and a press that stays put still focuses the pane.function onPointerDown(ev: PointerEvent) {@@ -31,6 +69,7 @@<divclass="nav"class:focused={bar.focused}+ class:lower={bar.rect.top > 0}data-nav={bar.rect.pane}style="left:{px(bar.rect.left)}px;top:{px(bar.rect.top)}px;width:min({px(bar.rect.width)}px, calc(100% - {px(bar.rect.left)}px));height:{px(bar.rect.height)}px"><span class="caps">{#each bar.members as m (m.pane)}<span@@ -38,7 +77,7 @@class:current={m.current}data-pane={m.pane}title={m.title}- >{#if m.busy}<span class="spin">{@html loaderCircle}</span>{:else}{@html squareTerminal}{/if}<span class="t">{m.title}</span><span+ >{#if iconClass(m.icon)}<span class="ticon {iconClass(m.icon)}">{#if m.busy}<span class="spin">{@html loaderCircle}</span>{:else}<i></i>{/if}</span>{:else if m.busy}<span class="spin">{@html loaderCircle}</span>{:else}{@html squareTerminal}{/if}<span class="t">{m.title}</span><spanclass="x"class:danger={bar.closing && m.current}data-action="close-pane"@@ -59,4 +98,8 @@title={bar.zoomed ? s('web-tip-unzoom') : s('web-tip-zoom')}>{#if bar.zoomed}{@html minimize2}{:else}{@html maximize2}{/if}</span></span></div>{/each}+ {#each handles as h, i (i)}+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <span class="grip" class:across={h.across} style="left:{px(h.x)}px;top:{px(h.y)}px;{h.across ? 'width' : 'height'}:{px(h.length)}px" onpointerdown={(ev) => grab(ev, h)}></span>+ {/each}</div>diff --git a/thinkterm-web/ui/src/SettingsPanel.svelte b/thinkterm-web/ui/src/SettingsPanel.svelteindex aabb4d64..80c132bc 100644--- a/thinkterm-web/ui/src/SettingsPanel.svelte+++ b/thinkterm-web/ui/src/SettingsPanel.svelte@@ -3,10 +3,20 @@// holds them (thinkterm-web/src/settings.rs) and applies the language and// the font itself; the theme is painted here, and the rest is read by// whatever it concerns.- import { handle } from './client';+ import { clients, handle } from './client';import { s, views } from './client.svelte';- import { info, minus, palette, panelLeft, plus, rotateCcw, search, slidersHorizontal, x } from './icons';+ import {+ aLargeSmall, arrowLeft, bot, braces, contrast, gitBranch, globe, grid2x2, info, minus, mouse, packageIcon, palette, panelLeft,+ panelLeftOpen, panelRightOpen, plus, puzzle, rotateCcw, rotateCw, scale as scaleIcon, search, server,+ slidersHorizontal, squareTerminal, x,+ } from './icons';+ import { HERE } from './machines.svelte';+ import { mobile } from './mobile.svelte';import { applyTheme, closeSettings, FOLLOW_DESKTOP, loadSchemes, panel, pickScheme, previewScheme, schemes, setSetting, storedScheme } from './settings.svelte';+ // About's hero shows the app's own icon, as the desktop's does, from its+ // small copy; the maker's logo under it is an alpha mask tinted by CSS.+ import appIcon from '../../../assets/icon/ThinkTerm_simple_128.png';+ import closexSvg from '../../../assets/icon/CloseX.svg?raw';import type { Hotkey, Scheme, ScrollMode, Theme } from './model';import { POP, WINDOW, ms } from './motion';import { fade, scale } from 'svelte/transition';@@ -29,15 +39,39 @@// on the left; the page has fewer rows, so fewer sections.// The panels and the plugins are both under Sidebar: whatever a plugin// shows, it shows in a panel.+ // Each heads its row with the desktop's square: its glyph, in white, on+ // its colour (`SettingsSection::tile_color`, `TileColor`).type Section = 'general' | 'appearance' | 'sidebar' | 'about';- const SECTIONS: [Section, string, string][] = [- ['general', 'settings-section-general', slidersHorizontal],- ['appearance', 'settings-section-appearance', palette],- ['sidebar', 'settings-section-sidebar', panelLeft],- ['about', 'settings-section-about', info],+ /** The squares' colours (`TileColor`): Apple's system colours. The rows+ inside a section are headed the same way, each by the square the+ desktop gives the same setting (`paint_row_tile`); a row the desktop+ has no square for takes its nearest neighbour's. */+ const TILE = {+ blue: '#0A84FF',+ indigo: '#5E5CE6',+ purple: '#BF5AF2',+ pink: '#FF375F',+ orange: '#FF9F0A',+ green: '#30D158',+ teal: '#30B0C7',+ gray: '#636366',+ slate: '#5A6478',+ } as const;+ const SECTIONS: [Section, string, string, string][] = [+ ['general', 'settings-section-general', slidersHorizontal, TILE.gray],+ ['appearance', 'settings-section-appearance', palette, TILE.purple],+ ['sidebar', 'settings-section-sidebar', panelRightOpen, TILE.blue],+ ['about', 'settings-section-about', info, TILE.gray],];let section = $state<Section>('general');+ /** On a phone the settings are two pages, as a phone's own are: the+ sections, then the one picked, with a way back. */+ let picked = $state(false);+ $effect(() => {+ if (!panel.open) picked = false;+ });let query = $state('');+ const listing = $derived(mobile.on && !picked && query.trim() === '');/** A description: its catalogue text, or nothing while the key is missing. */const d = (id: string) => (views.strings[id] === undefined ? '' : views.strings[id]);@@ -96,6 +130,17 @@const snippetsRow = $derived(plugins.rows.find((row) => row.builtin && row.id === 'snippets'));let reloading = $state(false);+ // A plugin's square (`plugin_tile`): Snippets takes its panel's; any other+ // the puzzle piece in a colour picked from its id by the desktop's own+ // hash (FNV-1a over the id's bytes), so it wears the same colour there.+ const PLUGIN_TILES = [TILE.green, TILE.teal, TILE.blue, TILE.indigo, TILE.pink, TILE.orange];+ function pluginTile(builtin: boolean, id: string): [string, string] {+ if (builtin && id === 'snippets') return [braces, TILE.purple];+ let hash = 0xcbf29ce484222325n;+ for (const byte of new TextEncoder().encode(id)) hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100000001b3n);+ return [puzzle, PLUGIN_TILES[Number(hash % BigInt(PLUGIN_TILES.length))]];+ }+function onPlugin(id: string, ev: Event) {const field = ev.currentTarget;if (field instanceof HTMLInputElement) void handle.client?.plugin_set_enabled(id, field.checked);@@ -174,14 +219,60 @@setSetting('sidebar-width', 220);}- // The locale the language preference actually came to, and where the- // page is served from. Re-read when the language changes.- const about = $derived.by(() => {+ // The locale the language preference actually came to. Re-read when the+ // language changes.+ const locale = $derived.by(() => {void settings.language;- const locale = document.documentElement.lang;- return locale ? `${locale} · ${location.host}` : location.host;+ return document.documentElement.lang;});+ /** The version of the ThinkTerm this page came from: the server it+ booted with, whichever machine is on show. */+ function serverVersion(): string {+ return (clients.get(HERE) ?? handle.client)?.server_version() ?? '';+ }++ /** About's facts, a line each: the desktop's Version, Build and License,+ with where the page is served from and the language it came to in+ place of the desktop's Platform. */+ function facts(version: string): [string, string, string, string][] {+ return [+ [packageIcon, TILE.blue, s('settings-about-version'), version || '—'],+ [gitBranch, TILE.indigo, s('web-settings-build'), import.meta.env.MODE],+ [server, TILE.slate, s('ssh-field-host'), location.host],+ [globe, TILE.blue, s('settings-language'), locale],+ // As the desktop's: what the packages declare.+ [scaleIcon, TILE.orange, s('settings-about-license'), 'GPL-3.0-only'],+ ];+ }++ // About's Copy button says "Copied" for as long as the desktop's does.+ let copied = $state(false);+ let copiedTimer = 0;++ /** What a bug report needs on its first lines, as About's Copy on the+ desktop puts it, with the browser in place of the OS. */+ function copyInfo(version: string) {+ const text = [+ `ThinkTerm ${version}`,+ `Build: ${import.meta.env.MODE}`,+ `Language: ${locale}`,+ `Browser: ${navigator.userAgent}`,+ ].join('\n');+ // A clipboard the browser refuses is not worth a remark, as for a+ // menu's Copy.+ navigator.clipboard+ ?.writeText(text)+ .then(() => {+ copied = true;+ clearTimeout(copiedTimer);+ copiedTimer = window.setTimeout(() => (copied = false), 1400);+ })+ .catch(() => {});+ }++ const closexLogo = `url("data:image/svg+xml,${encodeURIComponent(closexSvg)}")`;+// The panel takes the keyboard while it is up, so nothing typed into it// reaches the terminal; closing hands focus back.function onKeydown(ev: KeyboardEvent) {@@ -272,6 +363,7 @@rise, at the length a window takes rather than a menu's. --><divid="settings"+ class:listingrole="dialog"aria-modal="true"tabindex="-1"@@ -284,18 +376,20 @@<div class="app">ThinkTerm</div><label class="find">{@html search}<input placeholder={s('web-settings-search')} bind:value={query} spellcheck="false" /></label><div class="secs">- {#each SECTIONS as [id, label, icon] (id)}- <div class="sec" class:on={query.trim() === '' && section === id} data-section={id} onclick={() => { section = id; query = ''; }}>{@html icon}<span>{s(label)}</span></div>+ {#each SECTIONS as [id, label, icon, tile] (id)}+ <div class="sec" class:on={query.trim() === '' && section === id} data-section={id} onclick={() => { section = id; query = ''; picked = true; }}><span class="tile" style:--tile={tile}>{@html icon}</span><span class="sl">{s(label)}</span></div>{/each}</div></div><div class="body">+ <button class="back" type="button" onclick={() => (picked = false)}>{@html arrowLeft}<span>{s('sidebar-settings')}</span></button><div class="title">{query.trim() === '' ? s(SECTIONS.find(([id]) => id === section)?.[1] ?? '') : s('web-settings-search')}</div>{#if shows('general', s('settings-language')) || shows('general', s('web-settings-palette-hotkey')) || shows('general', s('web-settings-scroll-mode'))}<div class="card">{#if shows('general', s('settings-language'))}<div class="srow">+ <span class="tile" style:--tile={TILE.blue}>{@html globe}</span><div class="tx"><div class="lab">{s('settings-language')}</div><div class="desc">{d('web-settings-language-description')}</div></div><select class="pillsel" data-setting="language" value={settings.language} onchange={onLanguage}>{#each panel.languages as option (option.preference)}@@ -307,7 +401,9 @@</div>{/if}{#if shows('general', s('web-settings-scroll-mode'))}+ <!-- The desktop's Terminal › Scroll mode. --><div class="srow">+ <span class="tile" style:--tile={TILE.teal}>{@html mouse}</span><div class="tx"><div class="lab">{s('web-settings-scroll-mode')}</div><div class="desc">{d('web-settings-scroll-mode-description')}</div></div><select class="pillsel" data-setting="scroll-mode" value={settings['scroll-mode']} onchange={(ev) => setSetting('scroll-mode', (ev.currentTarget as HTMLSelectElement).value)}>{#each SCROLL_MODES as [value, label] (value)}@@ -317,7 +413,10 @@</div>{/if}{#if shows('general', s('web-settings-palette-hotkey'))}+ <!-- The desktop keeps its hotkey on the Command Palette page,+ whose square this takes. --><div class="srow">+ <span class="tile" style:--tile={TILE.blue}>{@html squareTerminal}</span><div class="tx"><div class="lab">{s('web-settings-palette-hotkey')}</div><div class="desc">{d('web-settings-hotkey-description')}</div></div><select class="pillsel" data-setting="palette-hotkey" value={settings['palette-hotkey']} onchange={onHotkey}>{#each HOTKEYS as [value, label] (value)}@@ -333,12 +432,17 @@<div class="card">{#if shows('appearance', s('web-settings-scheme'))}<div class="srow">+ <span class="tile" style:--tile={TILE.purple}>{@html palette}</span><div class="tx"><div class="lab">{s('web-settings-scheme')}</div><div class="desc">{d('web-settings-scheme-description')}</div></div><button class="pillsel" type="button" data-setting="terminal-scheme" data-scheme={chosen} onclick={openPicker}>{schemeLabel}</button></div>{/if}{#if shows('appearance', s('web-settings-theme'))}+ <!-- The desktop shows its theme modes as pictures, without a+ square; this takes its Window opacity row's half-dark+ circle. --><div class="srow">+ <span class="tile" style:--tile={TILE.blue}>{@html contrast}</span><div class="tx"><div class="lab">{s('web-settings-theme')}</div><div class="desc">{d('web-settings-theme-description')}</div></div><select class="pillsel" data-setting="theme" value={settings.theme} onchange={(ev) => setSetting('theme', (ev.currentTarget as HTMLSelectElement).value)}>{#each THEMES as [value, label] (value)}@@ -348,7 +452,9 @@</div>{/if}{#if shows('appearance', s('web-settings-font'))}+ <!-- The desktop's Terminal › Font size. --><div class="srow">+ <span class="tile" style:--tile={TILE.indigo}>{@html aLargeSmall}</span><div class="tx"><div class="lab">{s('web-settings-font')}</div><div class="desc">{d('web-settings-font-description')}</div></div><div class="ctl"><span class="seg">@@ -367,16 +473,33 @@</div>{/if}+ {#if shows('appearance', s('settings-tab-icons-enabled'))}+ <!-- The desktop's Tab Icons switch, under that page's square. The+ cards themselves are set on the desktop, and come from it. -->+ <div class="card">+ <div class="srow">+ <span class="tile" style:--tile={TILE.pink}>{@html grid2x2}</span>+ <div class="tx"><div class="lab">{s('settings-tab-icons-enabled')}</div><div class="desc">{d('settings-tab-icons-enabled-description')}</div></div>+ <label class="switch"><input type="checkbox" data-setting="tab-icons" checked={settings['tab-icons']} onchange={(ev) => onFlag('tab-icons', ev)} /><span class="knob"></span></label>+ </div>+ </div>+ {/if}+{#if shows('sidebar', s('web-settings-hover-reveal')) || shows('sidebar', s('web-settings-sidebar-reset'))}<div class="card">+ <!-- The desktop sets these two from the sidebar itself, so has no+ squares for them: the left sidebar's own glyphs, in the+ page's blue and in the grey of a row that only acts. -->{#if shows('sidebar', s('web-settings-hover-reveal'))}<div class="srow">+ <span class="tile" style:--tile={TILE.blue}>{@html panelLeftOpen}</span><div class="tx"><div class="lab">{s('web-settings-hover-reveal')}</div><div class="desc">{d('web-settings-hover-reveal-description')}</div></div><label class="switch"><input type="checkbox" data-setting="hover-reveal" checked={settings['hover-reveal']} onchange={(ev) => onFlag('hover-reveal', ev)} /><span class="knob"></span></label></div>{/if}{#if shows('sidebar', s('web-settings-sidebar-reset'))}<div class="srow">+ <span class="tile" style:--tile={TILE.gray}>{@html panelLeft}</span><div class="tx"><div class="lab">{s('web-settings-sidebar-reset')}</div><div class="desc">{d('web-settings-sidebar-reset-description')}</div></div><button class="pillbtn" type="button" data-action="reset-sidebar" onclick={resetSidebar}>{s('common-reset')}</button></div>@@ -384,21 +507,31 @@</div>{/if}- <!-- The right panel's panels, a switch each. Snippets is a built-in- plugin, and its switch is the plugin's. -->+ <!-- The right panel's panels, as the desktop lays them out+ (`paint_panel_cards`): a card each, two across where there is+ room, its square grey while the panel is off. Snippets is a+ built-in plugin, and its switch is the plugin's. -->{#if shows('sidebar', s('web-settings-agents-panel')) || shows('sidebar', s('right-mode-snippets'))}{#if query.trim() === ''}<div class="sdesc">{d('settings-sidebar-description')}</div>{/if}- <div class="card">+ <div class="pcards">{#if shows('sidebar', s('web-settings-agents-panel'))}- <div class="srow">- <div class="tx"><div class="lab">{s('web-settings-agents-panel')}</div><div class="desc">{d('web-settings-agents-panel-description')}</div></div>- <label class="switch"><input type="checkbox" data-setting="agents-panel" checked={settings['agents-panel']} onchange={(ev) => onFlag('agents-panel', ev)} /><span class="knob"></span></label>+ {@const on = settings['agents-panel']}+ <div class="pcard" class:off={!on}>+ <div class="phead">+ <span class="tile" style:--tile={on ? TILE.orange : TILE.gray}>{@html bot}</span>+ <label class="switch"><input type="checkbox" data-setting="agents-panel" checked={settings['agents-panel']} onchange={(ev) => onFlag('agents-panel', ev)} /><span class="knob"></span></label>+ </div>+ <div class="lab">{s('web-settings-agents-panel')}</div><div class="desc">{d('web-settings-agents-panel-description')}</div></div>{/if}{#if shows('sidebar', s('right-mode-snippets'))}- <div class="srow">- <div class="tx"><div class="lab">{s('right-mode-snippets')}</div><div class="desc">{d('settings-sidebar-snippets-description')}</div></div>- <label class="switch"><input type="checkbox" data-panel-switch="snippets" checked={snippetsRow?.enabled ?? false} disabled={!snippetsRow?.switchable} onchange={(ev) => onPlugin('snippets', ev)} /><span class="knob"></span></label>+ {@const on = snippetsRow?.enabled ?? false}+ <div class="pcard" class:off={!on}>+ <div class="phead">+ <span class="tile" style:--tile={on ? TILE.purple : TILE.gray}>{@html braces}</span>+ <label class="switch"><input type="checkbox" data-panel-switch="snippets" checked={snippetsRow?.enabled ?? false} disabled={!snippetsRow?.switchable} onchange={(ev) => onPlugin('snippets', ev)} /><span class="knob"></span></label>+ </div>+ <div class="lab">{s('right-mode-snippets')}</div><div class="desc">{d('settings-sidebar-snippets-description')}</div></div>{/if}</div>@@ -408,6 +541,7 @@{#if query.trim() === ''}<div class="sdesc">{d('settings-plugins-description')}</div>{/if}<div class="card"><div class="srow">+ <span class="tile" style:--tile={TILE.green}>{@html rotateCw}</span><div class="tx"><div class="lab">{s('settings-plugins-reload')}</div><div class="desc">{d('settings-plugins-reload-description')}</div></div><button class="pillbtn" type="button" data-action="reload-plugins" disabled={reloading} onclick={reloadPlugins}>{s('settings-plugins-reload-button')}</button></div>@@ -415,7 +549,9 @@{#if plugins.state === 'ready' && plugins.status !== ''}<div class="err">{plugins.status}</div>{/if}<div class="card" data-plugins={plugins.state}>{#each pluginRows as row (row.key)}+ {@const [glyph, tile] = pluginTile(row.builtin, row.id)}<div class="srow" data-plugin={row.id}>+ <span class="tile" style:--tile={tile}>{@html glyph}</span><div class="tx"><div class="lab">{row.name}</div><div class="desc">{row.detail}</div></div>{#if row.builtin}<!-- Its switch is its panel's, above. -->@@ -443,15 +579,29 @@{#if plugins.refused}<div class="err">{plugins.refused}</div>{/if}{/if}+ <!-- About as the desktop's opens (`paint_about`): the app's icon, its+ name and version and Copy in a card of their own, then its facts+ a line each, and who makes it at the foot of the page. -->{#if shows('about', s('settings-section-about'))}- <div class="card">- <div class="srow">- <div class="tx"><div class="lab">{s('settings-section-about')}</div><div class="desc">{about}</div></div>- </div>- <div class="srow">- <div class="tx"><div class="lab">{s('web-settings-build')}</div><div class="desc">{import.meta.env.MODE}</div></div>+ {@const version = serverVersion()}+ <div class="card hero">+ <img class="mark" src={appIcon} alt="" width="54" height="54" draggable="false" />+ <div class="ht">+ <div class="hl">ThinkTerm</div>+ <!-- The desktop's version line, which every catalogue words as+ the word and the number. -->+ <div class="sl">{version === '' ? location.host : `${s('settings-about-version')} ${version}`}</div></div>+ <button class="pillbtn" type="button" data-action="copy-version" onclick={() => copyInfo(version)}>{s(copied ? 'settings-about-copied' : 'settings-about-copy')}</button>+ </div>+ <div class="card facts">+ {#each facts(version) as [glyph, tile, label, value] (label)}+ <div class="srow fact"><span class="tile" style:--tile={tile}>{@html glyph}</span><div class="lab">{label}</div><div class="val">{value}</div></div>+ {/each}</div>+ {#if query.trim() === ''}+ <div class="maker"><span class="logo" role="img" aria-label="CloseX" style:--logo={closexLogo}></span><span class="yr">© 2026</span></div>+ {/if}{/if}{#if panel.error !== ''}<div class="err">{panel.error}</div>{/if}diff --git a/thinkterm-web/ui/src/Sidebar.svelte b/thinkterm-web/ui/src/Sidebar.svelteindex 7e543a47..c973cf5c 100644--- a/thinkterm-web/ui/src/Sidebar.svelte+++ b/thinkterm-web/ui/src/Sidebar.svelte@@ -6,9 +6,9 @@import {archive, archiveRestore, chevronDown, chevronRight, circleAlert, circleCheck, circlePlus,bell, ellipsis, folder, folderOpen, folderPlus, layers, loaderCircle, panelLeft, pin, pinOff, plus,- trash2,+ server, trash2,} from './icons';- import { menu, openMenu } from './menu.svelte';+ import { menu, openMenu, toggleMenu } from './menu.svelte';import { armDrag } from './drag.svelte';import { handle } from './client';import { toggleSidebar } from './chrome';@@ -18,6 +18,7 @@import { mobile, openSide } from './mobile.svelte';import { palette } from './palette.svelte';import { followSpace, panel } from './settings.svelte';+ import { activeLabel, addWorkspaceOn, HERE, hidePanel, machines, stateText, togglePanel, workspaceMachines } from './machines.svelte';import type { FooterAction, SideRow } from './model';const rows = $derived(views.sidebar.rows);@@ -45,9 +46,19 @@// The Space on show is this browser's; the next load opens on it, and// this is where that load asks for it back.+ // Only this server's: another machine's Spaces are not this server's to+ // reopen on.$effect(() => {const space = views.sidebar.space;- if (space) followSpace(space);+ if (space && machines.active === HERE) followSpace(space);+ });+ /** The machine on show, when it is not this server, and how it is. */+ const machine = $derived(activeLabel());+ /** Another machine, behind the one on show, waits on an answer. */+ const waiting = $derived(machines.open.find((o) => o.ask && o.id !== machines.active) ?? null);+ const machineState = $derived.by(() => {+ const m = machines.open.find((o) => o.id === machines.active);+ return m ? stateText(m) : '';});// One row is one element, so a re-listing keeps the DOM it already has --@@ -106,8 +117,9 @@const action = hit.getAttribute('data-action');let handled = false;switch (action) {- // The footer's two: the page's own panels, not the model's.+ // The footer's three: the page's own panels, not the model's.case 'settings': openSettings(); handled = true; break;+ case 'machines': togglePanel(); handled = true; break;case 'search': openPalette('threads'); handled = true; break;case 'new-thread': handled = sideClick('new-thread', project); break;case 'new-project': handled = sideClick('new-project'); break;@@ -122,13 +134,13 @@// hangs under it.case 'space-menu': {const box = hit.getBoundingClientRect();- openMenu('space', '', box.left, box.bottom + 4);+ toggleMenu('space', '', box.left, box.bottom + 4, hit);handled = true;break;}case 'notifications': {const box = hit.getBoundingClientRect();- openMenu('notifications', '', box.left, box.bottom + 4);+ toggleMenu('notifications', '', box.left, box.bottom + 4, hit);handled = true;break;}@@ -136,7 +148,7 @@// so the menu is anchored under the button rather than at a point.case 'sidebar-options': {const box = hit.getBoundingClientRect();- openMenu('sidebar-options', '', box.left, box.bottom + 4);+ toggleMenu('sidebar-options', '', box.left, box.bottom + 4, hit);handled = true;break;}@@ -150,9 +162,13 @@break;}if (handled) ev.preventDefault();- // On a phone the panel is a drawer over the canvas: picking a terminal- // is what it was opened for, so it goes away again.- if (handled && mobile.on && (thread !== null || hit.hasAttribute('data-window'))) openSide(false);+ // Picking a terminal -- a thread, a window, a new thread -- puts the+ // Remote Hosts page behind it, as the desktop's sidebar does.+ const picked = action === 'new-thread' || (action === 'rename-thread' && ev.detail < 2) || (action === null && (thread !== null || hit.hasAttribute('data-window')));+ if (handled && picked) hidePanel();+ // On a phone the drawer goes away to reveal the chosen terminal or+ // the Remote Hosts page.+ if (handled && mobile.on && (thread !== null || hit.hasAttribute('data-window') || action === 'machines')) openSide(false);}// A press on a row is that row's menu: a thread's, a project's, or an@@ -425,7 +441,7 @@<div class="list">{#each rows as row (key(row))}{#if row.kind === 'space'}- <div class="row space" data-action={editingSpace(row.id) ? undefined : 'space-menu'} title={s('web-tip-space')}>{@html layers}{#if editingSpace(row.id)}<input class="rename" value={row.name} spellcheck="false" use:typeHere>{:else}<span class="t">{row.name}</span>{/if}<span class="act">{@html ellipsis}</span></div>+ <div class="row space" class:remote={machine !== ''} class:down={machineState !== '' || waiting !== null} data-action={editingSpace(row.id) ? undefined : 'space-menu'} title={machineState !== '' ? `${machine} · ${machineState}` : waiting ? `${waiting.label} · ${s('web-machines-needs-you')}` : s('web-tip-space')}>{@html machineState !== '' || waiting ? circleAlert : machine === '' ? layers : server}{#if editingSpace(row.id)}<input class="rename" value={row.name} spellcheck="false" use:typeHere>{:else}<span class="t">{#if machine !== ''}<span class="machine">{machine}</span><span class="sn">{row.name}</span>{:else}{row.name}{/if}</span>{/if}<span class="act">{@html ellipsis}</span></div>{:else if row.kind === 'new-thread'}<div class="top"><div class="pill" data-action="new-thread" title={s('web-tip-new-thread')}>{@html circlePlus}<span>{s('sidebar-new-thread')}</span></div><span class="act round" data-action="notifications" title={s('tooltip-sidebar-notifications')}>{@html bell}</span></div>{:else if row.kind === 'pinned'}@@ -435,6 +451,12 @@{#if addingWorkspace}<div class="path" class:bad={!!addError}><div class="lb">{@html folderPlus}<span>{s('web-add-workspace')}</span></div>+ <!-- Which machine it goes on, once there is more than one. -->+ {#if workspaceMachines().length > 1}+ <select class="on" value={machines.active} title={s('web-machines-title')} onchange={(ev) => addWorkspaceOn((ev.currentTarget as HTMLSelectElement).value)}>+ {#each workspaceMachines() as m (m.key)}<option value={m.key}>{m.label}</option>{/each}+ </select>+ {/if}<inputplaceholder={s('web-path-placeholder')}spellcheck="false"diff --git a/thinkterm-web/ui/src/Status.svelte b/thinkterm-web/ui/src/Status.svelteindex 0728e8d3..7c1f1460 100644--- a/thinkterm-web/ui/src/Status.svelte+++ b/thinkterm-web/ui/src/Status.svelte@@ -24,7 +24,9 @@});const text = $derived.by(() => {- if (!views.ready) return views.boot;+ // Before the client, the boot screen says how the start is going; the+ // probes (`?check=`) still read their one line here.+ if (!views.ready) return new URLSearchParams(location.search).has('check') ? views.boot : '';if (!toast) return '';return toast.sticky || now < toast.at + LIFE ? toast.text : '';});diff --git a/thinkterm-web/ui/src/TabRow.svelte b/thinkterm-web/ui/src/TabRow.svelteindex 9b9ea458..6bd478f0 100644--- a/thinkterm-web/ui/src/TabRow.svelte+++ b/thinkterm-web/ui/src/TabRow.svelte@@ -1,21 +1,48 @@<script lang="ts">// The window's tab row: the sidebar toggle, a capsule per tab of this- // window, the new-tab button and the right panel's toggle. What- // `chrome::TabStrip::render` drew.+ // window, the Remote Hosts tab when it is open, the new-tab button and the+ // right panel's toggle. What `chrome::TabStrip::render` drew.import { onChromeClick } from './chrome';import { s, views } from './client.svelte';- import { panelLeft, panelRight, plus, squareTerminal, x } from './icons';+ import { link2, panelLeft, panelRight, plus, squareTerminal, x } from './icons';+ import { closePanel, hidePanel, machines, openPanel } from './machines.svelte';+ import { iconClass } from './tabicons.svelte';import { openMenu } from './menu.svelte';import { armDrag } from './drag.svelte';import { short } from './title';const tabs = $derived(views.tabs?.tabs ?? []);const controls = $derived(views.tabs?.controls ?? null);+ /** The card heading every tab, the terminal's; none with icons off. */+ const icon = $derived(iconClass(views.tabs?.icon));++ // The Remote Hosts tab is the page's own, not the wasm's: its capsule+ // puts the page on show and its close button closes it. Any other tab --+ // or a new one -- puts the page behind the terminal and keeps its tab, as+ // the desktop's tab row does.+ function onClick(ev: MouseEvent) {+ const target = ev.target;+ if (target instanceof Element) {+ if (target.closest('[data-page-tab]')) {+ if (target.closest('.x')) closePanel();+ else if (!machines.panel) openPanel();+ ev.preventDefault();+ return;+ }+ if (target.closest('.tab, [data-action=new-tab]') && !target.closest('.x')) hidePanel();+ }+ onChromeClick(ev);+ }// A press on a capsule -- its close button included -- is that tab's.+ // The Remote Hosts tab has none.function onMenu(ev: MouseEvent) {const target = ev.target;if (!(target instanceof Element)) return;+ if (target.closest('[data-page-tab]')) {+ ev.preventDefault();+ return;+ }const tab = target.closest('.tab')?.getAttribute('data-tab');if (tab === null || tab === undefined) return;ev.preventDefault();@@ -38,11 +65,14 @@are the controls, not the container. --><!-- svelte-ignore a11y_click_events_have_key_events --><!-- svelte-ignore a11y_no_static_element_interactions -->-<div id="tabs" onclick={onChromeClick} oncontextmenu={onMenu} onpointerdown={onPointerDown}>- <span class="act" data-action="sidebar" title={s('web-tip-sidebar')}>{@html panelLeft}</span>+<div id="tabs" onclick={onClick} oncontextmenu={onMenu} onpointerdown={onPointerDown}>+ <span class="lead"><span class="act" data-action="sidebar" title={s('web-tip-sidebar')}>{@html panelLeft}</span></span>+ <!-- What scrolls on a phone, under the buttons at either end, which stay+ put; elsewhere it is no box of its own, and the row scrolls. -->+ <span class="strip">{#each tabs as tab (tab.tab)}- <span class="tab" class:current={tab.current} data-pane={tab.target} data-tab={tab.tab} title={tab.title}>- {@html squareTerminal}<span class="t">{short(tab.label)}</span><span+ <span class="tab" class:current={tab.current && !machines.panel} data-pane={tab.target} data-tab={tab.tab} title={tab.title}>+ {#if icon}<span class="ticon {icon}"><i></i></span>{:else}{@html squareTerminal}{/if}<span class="t">{short(tab.label)}</span><spanclass="x"class:danger={controls?.closing === tab.tab}data-action="close-tab"@@ -51,7 +81,15 @@>{#if controls?.closing === tab.tab}{s('web-confirm-close')}{:else}{@html x}{/if}</span></span>{/each}+ <!-- After the terminal's tabs, as the desktop places its Remote Hosts+ page's: a link glyph, the title, and a close button. -->+ {#if machines.tab}+ <span class="tab" class:current={machines.panel} data-page-tab="machines" title={s('web-machines-title')}>+ {@html link2}<span class="t">{s('web-machines-title')}</span><span class="x" title={s('web-tip-close-tab')}>{@html x}</span>+ </span>+ {/if}<span class="act" data-action="new-tab" title={s('web-tip-new-tab')}>{@html plus}</span>+ </span><!-- The row's right end, as the desktop's tab bar has it: the rightpanel's toggle. --><span class="trail">diff --git a/thinkterm-web/ui/src/client.svelte.ts b/thinkterm-web/ui/src/client.svelte.tsindex 691c296e..50615936 100644--- a/thinkterm-web/ui/src/client.svelte.ts+++ b/thinkterm-web/ui/src/client.svelte.ts@@ -3,7 +3,7 @@// shows, kept in runes so the components follow it.import { flushSync } from 'svelte';-import { handle, type Client } from './client';+import { everyClient, handle, type Client } from './client';import type { AgentsView, NavsView, PluginsView, SidebarView, SnippetsView, StatusView, Strings, TabsView, WebSettings } from './model';export const views = $state({@@ -42,8 +42,11 @@ export const views = $state({/** The page's own labels in the active language; empty until attached. */strings: {} as Strings,/** What the page says before the client exists: the boot, or its failure. */- boot: 'loading…',+ boot: 'Loading…',bootFailed: false,+ /** Which step of the start the page is on: 0 the client's own code,+ 1 the fonts, 2 the connection; the boot screen's bar. */+ bootStage: 0,/** The client is attached; the views below are its, not the boot's. */ready: false,});@@ -54,32 +57,59 @@ export function s(id: string): string {}/** The boot's progress, and the probes' one-line results. */-export function setBoot(text: string, failed = false) {+export function setBoot(text: string, failed = false, stage?: number) {views.boot = text;views.bootFailed = failed;+ if (stage !== undefined) views.bootStage = stage;}-/** Re-read every view now. Set by `attach`; a no-op before it. */+/** Re-read every view now. Set by `activate`; a no-op before it. */let refresh: () => void = () => {};-/** Follow a client's views. Called once, right after `start()` resolves. */-export function attach(client: Client) {- // The views are re-listed every frame something moved and are mostly the- // same string as last time; parsing only what changed keeps the whole- // chrome from being diffed for a cursor blink.- let lastTabs = '';- let lastNavs = '';- let lastStatus = '';- let lastStrings = '';- let lastSidebar = '';- let lastAgents = '';- // The snippets can be long; their view is read only when it moved.- let lastSnippets = -1;- let lastPlugins = -1;- let lastPanel = -1;- let lastExtended = -1;- let lastSettings = '';- const read = () => {+// The views are re-listed every frame something moved and are mostly the+// same string as last time; parsing only what changed keeps the whole+// chrome from being diffed for a cursor blink. Kept for the client on show+// and forgotten when another comes on.+let lastTabs = '';+let lastNavs = '';+let lastStatus = '';+let lastStrings = '';+let lastSidebar = '';+let lastAgents = '';+// The snippets can be long; their view is read only when it moved.+let lastSnippets = -1;+let lastPlugins = -1;+let lastPanel = -1;+let lastExtended = -1;+let lastSettings = '';++function forget() {+ lastTabs = lastNavs = lastStatus = lastStrings = lastSidebar = lastAgents = lastSettings = '';+ lastSnippets = lastPlugins = lastPanel = lastExtended = -1;+}++/** Follow a client: its views are read whenever they change while it is+ the one on show, and `also` hears of every change regardless. */+export function attach(client: Client, also: () => void = () => {}) {+ client.on_change(() => {+ also();+ if (handle.client === client) read();+ });+}++/** Put a client's views on show: the chrome draws it from here on. */+export function activate(client: Client) {+ handle.client = client;+ forget();+ refresh = read;+ views.ready = true;+ read();+}++function read() {+ const client = handle.client;+ if (!client) return;+ {const strings = client.strings();if (strings !== lastStrings) {lastStrings = strings;@@ -140,11 +170,7 @@ export function attach(client: Client) {views.settings = JSON.parse(settings) as WebSettings;}views.layout = client.layout();- };- refresh = read;- views.ready = true;- // Registering calls it once, so the first frame is the client's.- client.on_change(read);+ }}/** Re-read every view and put it on show now, for a caller that went to@@ -157,7 +183,9 @@ export function refreshViews() {/** Switch the interface language; returns the locale it resolved to. */export function setLocale(preference: string): string {if (!handle.client) return '';- const code = handle.client.set_locale(preference, Array.from(navigator.languages ?? [navigator.language]));+ const languages = Array.from(navigator.languages ?? [navigator.language]);+ for (const other of everyClient()) if (other !== handle.client) other.set_locale(preference, languages);+ const code = handle.client.set_locale(preference, languages);refresh();flushSync();return code;diff --git a/thinkterm-web/ui/src/client.ts b/thinkterm-web/ui/src/client.tsindex 250d98b6..4441dd15 100644--- a/thinkterm-web/ui/src/client.ts+++ b/thinkterm-web/ui/src/client.ts@@ -6,6 +6,15 @@ export type { Client };export const handle: { client: Client | null } = { client: null };+/** Every client the page holds, by machine (machines.svelte.ts): this+ server's and one per other machine it has open. */+export const clients = new Map<string, Client>();++/** Each of them, for what applies to all: a preference, the language. */+export function everyClient(): Client[] {+ return clients.size > 0 ? [...clients.values()] : handle.client ? [handle.client] : [];+}+// For probes and the smoke tests, which drive the page from outside.declare global {interface Window {diff --git a/thinkterm-web/ui/src/drag.svelte.ts b/thinkterm-web/ui/src/drag.svelte.tsindex 663f27bc..01b6c3aa 100644--- a/thinkterm-web/ui/src/drag.svelte.ts+++ b/thinkterm-web/ui/src/drag.svelte.ts@@ -10,6 +10,7 @@import { handle } from './client';import { refreshViews, views } from './client.svelte';+import { focusTerminal } from './mobile.svelte';/** How far a press travels before it is a drag (the desktop's ~5px). */const THRESHOLD = 5;@@ -201,13 +202,21 @@ function retarget(x: number, y: number) {drag.zone = target && target.kind === 'pane' ? target.zone : null;}+/** What scrolls the tab row: its strip on a phone, where the buttons at+ either end stay put over it; elsewhere the strip is no box of its own,+ and the row scrolls. */+function tabScroller(): HTMLElement | null {+ const strip = document.querySelector<HTMLElement>('#tabs .strip');+ return strip && getComputedStyle(strip).display !== 'contents' ? strip : document.getElementById('tabs');+}+/** The list under the pointer scrolls while the drag rests at its edge; aparked pointer sends no more moves, so each applied step queues the next. */function autoscroll(x: number, y: number) {if (!spec || spec.kind === 'pane') return;const el =spec.kind === 'tab'- ? document.getElementById('tabs')+ ? tabScroller(): document.querySelector<HTMLElement>('#side .list');if (!el) return;const bounds = box(el);@@ -278,7 +287,7 @@ function finish(commit: boolean, clickFollows = false) {else handle.client.drop(picked.kind, picked.id, landed.before ?? null, null, null);refreshViews();// The terminal keeps the keyboard, as it had it before the press.- document.getElementById('kbd')?.focus();+ focusTerminal();}function onMove(ev: PointerEvent) {diff --git a/thinkterm-web/ui/src/icons.ts b/thinkterm-web/ui/src/icons.tsindex 7b5bc411..d84591b9 100644--- a/thinkterm-web/ui/src/icons.ts+++ b/thinkterm-web/ui/src/icons.ts@@ -5,7 +5,10 @@import archive from '../../../third_party/lucide/icons/archive.svg?raw';import arrowLeft from '../../../third_party/lucide/icons/arrow-left.svg?raw';import archiveRestore from '../../../third_party/lucide/icons/archive-restore.svg?raw';+import aLargeSmall from '../../../third_party/lucide/icons/a-large-small.svg?raw';import bell from '../../../third_party/lucide/icons/bell.svg?raw';+import braces from '../../../third_party/lucide/icons/braces.svg?raw';+import contrast from '../../../third_party/lucide/icons/contrast.svg?raw';import info from '../../../third_party/lucide/icons/info.svg?raw';import minus from '../../../third_party/lucide/icons/minus.svg?raw';import notebookTabs from '../../../third_party/lucide/icons/notebook-tabs.svg?raw';@@ -27,6 +30,14 @@ import folder from '../../../third_party/lucide/icons/folder.svg?raw';import folderOpen from '../../../third_party/lucide/icons/folder-open.svg?raw';import folderPlus from '../../../third_party/lucide/icons/folder-plus.svg?raw';import globe from '../../../third_party/lucide/icons/globe.svg?raw';+import keyRound from '../../../third_party/lucide/icons/key-round.svg?raw';+import keyboard from '../../../third_party/lucide/icons/keyboard.svg?raw';+import link2 from '../../../third_party/lucide/icons/link-2.svg?raw';+import network from '../../../third_party/lucide/icons/network.svg?raw';+import server from '../../../third_party/lucide/icons/server.svg?raw';+import shieldAlert from '../../../third_party/lucide/icons/shield-alert.svg?raw';+import unplug from '../../../third_party/lucide/icons/unplug.svg?raw';+import download from '../../../third_party/lucide/icons/download.svg?raw';import grid2x2 from '../../../third_party/lucide/icons/grid-2x2.svg?raw';import house from '../../../third_party/lucide/icons/house.svg?raw';import languages from '../../../third_party/lucide/icons/languages.svg?raw';@@ -35,13 +46,20 @@ import loaderCircle from '../../../third_party/lucide/icons/loader-circle.svg?raimport mail from '../../../third_party/lucide/icons/mail.svg?raw';import maximize2 from '../../../third_party/lucide/icons/maximize-2.svg?raw';import minimize2 from '../../../third_party/lucide/icons/minimize-2.svg?raw';+import mouse from '../../../third_party/lucide/icons/mouse.svg?raw';+// `package` is a reserved word.+import packageIcon from '../../../third_party/lucide/icons/package.svg?raw';import panelLeft from '../../../third_party/lucide/icons/panel-left.svg?raw';+import panelLeftOpen from '../../../third_party/lucide/icons/panel-left-open.svg?raw';import panelRight from '../../../third_party/lucide/icons/panel-right.svg?raw';+import panelRightOpen from '../../../third_party/lucide/icons/panel-right-open.svg?raw';import pencil from '../../../third_party/lucide/icons/pencil.svg?raw';import pin from '../../../third_party/lucide/icons/pin.svg?raw';import pinOff from '../../../third_party/lucide/icons/pin-off.svg?raw';import plus from '../../../third_party/lucide/icons/plus.svg?raw';import rotateCcw from '../../../third_party/lucide/icons/rotate-ccw.svg?raw';+import rotateCw from '../../../third_party/lucide/icons/rotate-cw.svg?raw';+import scale from '../../../third_party/lucide/icons/scale.svg?raw';import search from '../../../third_party/lucide/icons/search.svg?raw';import settings from '../../../third_party/lucide/icons/settings.svg?raw';import slidersHorizontal from '../../../third_party/lucide/icons/sliders-horizontal.svg?raw';@@ -75,9 +93,19 @@ import brandCopilot from '../../../third_party/simple-icons/icons/githubcopilot.export {archive,arrowLeft,+ download,+ keyRound,+ keyboard,+ link2,+ network,+ server,+ shieldAlert,+ unplug,archiveRestore,+ aLargeSmall,bell,bot,+ braces,brandClaude,brandCopilot,check,@@ -88,12 +116,14 @@ export {circlePlus,clipboardPaste,codeXml,+ contrast,copy,ellipsis,eye,folder,folderOpen,folderTree,+ gitBranch,globe,grid2x2,folderPlus,@@ -106,15 +136,22 @@ export {maximize2,minimize2,minus,+ mouse,notebookTabs,+ packageIcon,palette,panelLeft,+ panelLeftOpen,panelRight,+ panelRightOpen,pencil,pin,pinOff,plus,+ puzzle,rotateCcw,+ rotateCw,+ scale,search,settings,slidersHorizontal,@@ -179,6 +216,8 @@ const BY_NAME: Record<string, string> = {x,'zoom-in': zoomIn,'zoom-out': zoomOut,+ network,+ server,};/** A lucide icon by its name; nothing for a name the page has not inlined. */diff --git a/thinkterm-web/ui/src/machines.svelte.ts b/thinkterm-web/ui/src/machines.svelte.tsnew file mode 100644index 00000000..65f167a9--- /dev/null+++ b/thinkterm-web/ui/src/machines.svelte.ts@@ -0,0 +1,699 @@+// Other machines, reached through this page's server (web_relay.rs there):+// the ones that server knows, the ones this page has open, and the one on+// show. Every open machine is a client of its own -- its own canvas, its+// own keyboard field, its own connection -- and the chrome draws whichever+// is active: `handle.client` is always that one. This server is `HERE`,+// the client the page booted with.+//+// The relay asks its questions (a password, a host key, whether to+// install) before the mux connection starts; this module answers them from+// the Remote Hosts page, for the first connect and for every reconnect.+// That page is a tab of its own, as the desktop's is: after the terminal's+// in the tab row, in the terminal's place while it is on show.++import { flushSync } from 'svelte';+import { clients, handle, type Client } from './client';+import { activate, attach, refreshViews, s } from './client.svelte';+import { focusTerminal, openSide } from './mobile.svelte';+import type { MenuItem } from './model';++export const HERE = 'here';+const RELAY = 'thinkterm.relay.v1';+/** The machines this browser had open, reopened on the next load. */+const OPEN_STORE = 'thinkterm.machines';+/** Lines of a machine's progress kept for the page. */+const LOG_LINES = 40;+/** What a reconnect may meet and still try again: the network, or the+ host being in the middle of something. Anything else -- a refused key,+ a declined install -- would only be asked again and again. */+const RETRYABLE = new Set(['unreachable', 'failed']);++export type MachineSource = 'ssh-config' | 'saved' | 'web';+export type MachineEntry = {+ id: string;+ label: string;+ endpoint: string;+ source: MachineSource;+ /** A password is kept for it on the server. */+ password: boolean;+ /** ThinkTerm may be installed there without asking. */+ install: boolean;+ /** Forgetting it changes something here. */+ forgettable: boolean;+};+export type Step = 'connecting' | 'authenticating' | 'checking' | 'installing' | 'updating' | 'starting';+export type AskKind = 'host-key' | 'password' | 'secret' | 'text' | 'install' | 'replace' | 'stop-server';+export type Ask = { id: number; kind: AskKind; prompt: string; detail: string; remember: boolean };+export type Failure = { reason: string; message: string; ssh_domain: string | null };++export type OpenMachine = {+ id: string;+ label: string;+ /** Names its canvas and keyboard field while it is not on show. */+ n: number;+ state: 'connecting' | 'ready' | 'reconnecting' | 'failed';+ step: Step | null;+ percent: number | null;+ /** The relay's question on show, until it is answered. */+ ask: Ask | null;+ log: string[];+ failure: Failure | null;+ /** Shown once it is ready: the person asked for it, not a reload. */+ showWhenReady: boolean;+ /** Reopened on the next load: it came from the last one, or it has been+ up. A machine that only ever failed is not tried again on every load. */+ remembered: boolean;+};++export const machines = $state({+ /** This server's own name. */+ here: '',+ list: [] as MachineEntry[],+ listed: false,+ /** Why the list or the last change to it failed; empty when it did not. */+ error: '',+ open: [] as OpenMachine[],+ /** `HERE`, or the id of the open machine on show. */+ active: HERE,+ /** The Remote Hosts tab is in the tab row. */+ tab: false,+ /** It is the tab on show: the page is in the terminal's place. */+ panel: false,+ /** The page's host form is open. */+ adding: false,+});++/** What starting another client takes; set by the boot (`configure`). */+export type Boot = {+ start: (canvas: string, textarea: string, opener: () => Promise<WebSocket>) => Promise<Client>;+ token: string;+ /** Brings a new client to this browser's preferences. */+ prepare: (client: Client) => void;+};+let boot: Boot | null = null;+let counter = 0;+/** The sockets still in their questions, by machine. */+const asking = new Map<string, { socket: WebSocket; cancel: () => void }>();++function relaySocket(): WebSocket {+ const scheme = location.protocol === 'https:' ? 'wss' : 'ws';+ return new WebSocket(`${scheme}://${location.host}/relay`, [RELAY, `tt-token.${boot?.token ?? ''}`]);+}++/** The page booted with this server's client: open the machines it had+ open last time, in the background. */+export function configure(next: Boot, hub: Client) {+ boot = next;+ clients.set(HERE, hub);+ const reopen = storedOpen();+ if (reopen.length === 0) return;+ // The list first: it names them. Without one (the relay down for a+ // moment) nothing is opened, and nothing is forgotten either.+ void refreshList().then(() => {+ if (!machines.listed || machines.error !== '') return;+ for (const id of reopen) if (machines.list.some((m) => m.id === id)) void connect(id, false, true);+ storeOpen();+ });+}++function storedOpen(): string[] {+ try {+ const value: unknown = JSON.parse(localStorage.getItem(OPEN_STORE) ?? '[]');+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [];+ } catch {+ return [];+ }+}++function storeOpen() {+ try {+ localStorage.setItem(OPEN_STORE, JSON.stringify(machines.open.filter((m) => m.remembered).map((m) => m.id)));+ } catch {+ // A browser that blocks storage reopens nothing next time.+ }+}++/** One request to the relay that ends with the list: it opens a socket,+ asks, and closes. Resolves with the id a save came to, if it was one. */+function request(message: object): Promise<string | null> {+ return new Promise((resolve) => {+ const ws = relaySocket();+ let done = false;+ let saved: string | null = null;+ const finish = (error: string) => {+ if (done) return;+ done = true;+ machines.error = error;+ ws.close();+ resolve(error === '' ? saved : null);+ };+ ws.onopen = () => ws.send(JSON.stringify(message));+ ws.onmessage = (ev) => {+ if (typeof ev.data !== 'string') return;+ const reply = JSON.parse(ev.data);+ if (reply.op === 'machines') {+ machines.here = reply.here;+ machines.list = reply.machines;+ machines.listed = true;+ for (const m of machines.open) m.label = machines.list.find((e) => e.id === m.id)?.label ?? m.label;+ finish('');+ } else if (reply.op === 'saved') {+ saved = reply.id;+ } else if (reply.op === 'error') {+ finish(reply.message);+ }+ };+ ws.onerror = () => finish(s('web-machines-failed-failed'));+ ws.onclose = () => finish(done ? '' : s('web-machines-failed-failed'));+ });+}++export async function refreshList(): Promise<void> {+ await request({ op: 'list' });+}++/** The cards this server dresses its tabs with (`tab-icons`), as its+ desktop settings make them; null when the relay could not say. */+export function fetchTabIcons(): Promise<unknown> {+ return new Promise((resolve) => {+ const ws = relaySocket();+ const finish = (catalog: unknown) => {+ ws.onmessage = null;+ ws.onerror = null;+ ws.onclose = null;+ ws.close();+ resolve(catalog);+ };+ ws.onopen = () => ws.send(JSON.stringify({ op: 'tab-icons' }));+ ws.onmessage = (ev) => {+ if (typeof ev.data !== 'string') return;+ const reply = JSON.parse(ev.data);+ finish(reply.op === 'tab-icons' ? reply : null);+ };+ ws.onerror = () => finish(null);+ ws.onclose = () => finish(null);+ });+}++export type NewMachine = { label: string; host: string; port: string; user: string; password: string };++/** Add a machine to the server's list and connect to it. */+export async function addMachine(form: NewMachine): Promise<boolean> {+ const port = form.port.trim() === '' ? null : Number(form.port.trim());+ // Never quietly 22: that would be another machine, or the same one's+ // kept password answering for it.+ if (port !== null && !(Number.isInteger(port) && port > 0 && port < 65536)) {+ machines.error = s('web-machines-bad-port');+ return false;+ }+ // The server keys a machine by its address: one typed in again is the+ // one already listed, and that is the one opened.+ const id = await request({+ op: 'save',+ machine: {+ label: form.label.trim() || null,+ host: form.host.trim(),+ port: port !== null && Number.isInteger(port) && port > 0 && port < 65536 ? port : null,+ user: form.user.trim() || null,+ password: form.password === '' ? null : form.password,+ },+ });+ if (id === null) return false;+ void connect(id, true);+ return true;+}++export async function forgetMachine(id: string): Promise<void> {+ await request({ op: 'forget', id });+}++/** The page in the terminal's place, for what hands the keys back to the+ terminal (focusTerminal, the wasm's own): `body[data-page]` names it,+ and the keys stay with it. Set at once, not when the page is next+ drawn: the terminal is often focused in the same task. */+function mark() {+ const body = globalThis.document?.body;+ if (!body) return;+ if (machines.panel) body.dataset.page = 'machines';+ else delete body.dataset.page;+}++function present() {+ machines.tab = true;+ machines.panel = true;+ mark();+ // On a phone the drawer it was opened from (the sidebar's globe, the+ // Space menu's rows) would cover it: the drawer goes.+ openSide(false);+}++/** Open the Remote Hosts tab and put it on show. `form` opens it on a+ blank host form, as the desktop's Add Remote Host does. */+export function openPanel(form = false) {+ present();+ if (form) machines.adding = true;+ void refreshList();+}++/** The sidebar's globe, as the desktop's: the page on show is closed, and+ one behind the terminal comes back. */+export function togglePanel() {+ if (machines.panel) closePanel();+ else openPanel();+}++/** Put the page behind the terminal and keep its tab, as picking another+ tab -- or a terminal anywhere else -- does on the desktop. */+export function hidePanel() {+ if (!machines.panel) return;+ machines.panel = false;+ mark();+ focusTerminal();+}++/** Close the Remote Hosts tab; the terminal comes back. */+export function closePanel() {+ if (!machines.tab) return;+ const shown = machines.panel;+ machines.tab = false;+ machines.panel = false;+ machines.adding = false;+ mark();+ if (shown) focusTerminal();+}++function find(id: string): OpenMachine | undefined {+ return machines.open.find((m) => m.id === id);+}++/** The socket the relay hands over once a machine is reached, after its+ questions are answered here. Called for the first connect and again by+ the client for every reconnect. */+function opener(id: string, n: number): () => Promise<WebSocket> {+ return () =>+ new Promise<WebSocket>((resolve, reject) => {+ const m = find(id);+ if (!m || m.n !== n || m.state === 'failed') {+ reject(new Error('closed'));+ return;+ }+ const ws = relaySocket();+ ws.binaryType = 'arraybuffer';+ let settled = false;+ const settle = () => {+ settled = true;+ if (asking.get(id)?.socket === ws) asking.delete(id);+ ws.onmessage = null;+ ws.onclose = null;+ ws.onerror = null;+ ws.onopen = null;+ };+ const cancel = () => {+ if (settled) return;+ settle();+ ws.close();+ reject(new Error('closed'));+ };+ asking.set(id, { socket: ws, cancel });+ ws.onopen = () => {+ if (find(id)?.n !== n) return cancel();+ ws.send(JSON.stringify({ op: 'open', id }));+ };+ ws.onmessage = (ev) => {+ if (settled) return;+ if (typeof ev.data !== 'string') return;+ const reply = JSON.parse(ev.data);+ const m = find(id);+ if (!m || m.n !== n) return cancel();+ switch (reply.op) {+ case 'step':+ m.step = reply.step;+ m.percent = reply.percent ?? null;+ break;+ case 'log':+ m.log = [...m.log, reply.text].slice(-LOG_LINES);+ break;+ case 'ask':+ m.ask = reply as Ask;+ // The page comes on show for a machine the person just asked+ // to open. One reconnecting behind the scenes waits to be+ // noticed (the Space row says so): taking the terminal's place+ // would take the keys being typed there.+ if (m.showWhenReady) present();+ break;+ case 'ready':+ m.ask = null;+ m.step = null;+ m.percent = null;+ m.failure = null;+ settle();+ resolve(ws);+ break;+ case 'failed':+ m.ask = null;+ m.percent = null;+ m.failure = reply as Failure;+ settle();+ ws.close();+ reject(new Error(reply.message));+ if (!RETRYABLE.has(reply.reason)) {+ // Not worth opening on the next load either.+ m.remembered = false;+ storeOpen();+ if (clients.has(id)) giveUp(id);+ }+ break;+ case 'error':+ m.log = [...m.log, reply.message].slice(-LOG_LINES);+ break;+ }+ };+ // A question left on show after its socket went is one nobody can+ // answer any more.+ const lost = () => {+ if (settled) return;+ settle();+ const m = find(id);+ if (m?.n === n) {+ m.ask = null;+ m.percent = null;+ }+ reject(new Error(s('web-machines-failed-failed')));+ };+ ws.onerror = lost;+ ws.onclose = lost;+ });+}++/** A machine whose reconnect cannot succeed by trying again: it stays in+ the list, failed, where Try again starts it afresh. */+function giveUp(id: string) {+ const m = find(id);+ const client = clients.get(id);+ if (!m || !client) return;+ m.state = 'failed';+ if (machines.active === id) showMachine(HERE);+ clients.delete(id);+ // Once the reconnect that asked has its answer.+ setTimeout(() => {+ client.close();+ client.free();+ }, 0);+}++/** Answer the question on show: a value, or null to decline it. */+export function answer(id: string, value: string | null, remember = false) {+ const m = find(id);+ const ws = asking.get(id)?.socket;+ if (!m || !m.ask || !ws) return;+ ws.send(JSON.stringify({ op: 'answer', id: m.ask.id, value, remember }));+ m.ask = null;+}++/** Open a machine: its own client, on a canvas of its own. `show` brings it+ on show once it is ready. */+export async function connect(id: string, show: boolean, remembered = false): Promise<void> {+ if (!boot) return;+ const existing = find(id);+ if (existing) {+ if (existing.state === 'failed') {+ // Again, from the start.+ close(id);+ } else {+ if (show) {+ // One with a terminal already -- up, or reconnecting behind the+ // scenes -- comes on show now; one on its first connect, once it+ // is ready. (Only a first connect ever reads the flag again: set+ // for a reconnecting one, it stayed set, and brought the page up+ // for some later reconnect's question.)+ if (clients.has(id)) showMachine(id);+ else existing.showWhenReady = true;+ }+ return;+ }+ }+ const known = machines.list.find((m) => m.id === id);+ const n = ++counter;+ machines.open.push({+ id,+ label: known?.label ?? id,+ n,+ state: 'connecting',+ step: 'connecting',+ percent: null,+ ask: null,+ log: [],+ failure: null,+ showWhenReady: show,+ remembered,+ });+ storeOpen();+ // The canvas and the field have to be in the page before the client+ // looks them up.+ flushSync();+ let client: Client;+ try {+ client = await boot.start(`term-${n}`, `kbd-${n}`, opener(id, n));+ } catch (e) {+ const m = find(id);+ if (m?.n === n) {+ m.state = 'failed';+ m.step = null;+ m.failure ??= { reason: 'failed', message: String((e as { message?: string })?.message ?? e), ssh_domain: null };+ }+ return;+ }+ const m = find(id);+ if (!m || m.n !== n) {+ // Closed while it was opening.+ client.close();+ client.free();+ return;+ }+ clients.set(id, client);+ client.set_shown(false);+ boot.prepare(client);+ attach(client, () => onChange(id, n));+ m.state = 'ready';+ m.step = null;+ m.remembered = true;+ storeOpen();+ // Brought on show as asked -- unless the person is in the middle of+ // answering something else, whose keys would land in this terminal.+ if (m.showWhenReady && !typingElsewhere() && !machines.open.some((o) => o.ask)) {+ showMachine(id);+ closePanel();+ }+ m.showWhenReady = false;+}++/** The person is typing an answer or a path, not at a terminal. (No+ document at all where the module runs on its own, in its tests.) */+function typingElsewhere(): boolean {+ const active = globalThis.document?.activeElement;+ return !!active?.closest('#machines input, #machines textarea, #machines select, #side .path');+}++/** A client's views moved, which is also how a dropped connection, and+ the reconnect that ends it, reach the page. */+function onChange(id: string, n: number) {+ const m = find(id);+ const client = clients.get(id);+ if (!m || m.n !== n || !client) return;+ const up = client.connected();+ if (!up && m.state === 'ready') m.state = 'reconnecting';+ else if (up && m.state === 'reconnecting') m.state = 'ready';+}++/** Put a machine's terminal on show, and the chrome with it; the keys go+ to it too unless `focus` says otherwise. */+export function showMachine(key: string, focus = true) {+ const next = clients.get(key);+ if (!next || machines.active === key) {+ if (next && focus) focusTerminal();+ return;+ }+ const previous = handle.client;+ previous?.set_shown(false);+ machines.active = key;+ // The keyed panels capture this client when they come up again.+ activate(next);+ // The ids move with the machine on show: `#term` and `#kbd` are its.+ flushSync();+ next.set_shown(true);+ if (focus) focusTerminal();+}++/** Close a machine's connection and let its client go. */+export function close(id: string) {+ const m = find(id);+ if (!m) return;+ asking.get(id)?.cancel();+ asking.delete(id);+ if (machines.active === id) showMachine(HERE);+ const client = clients.get(id);+ clients.delete(id);+ machines.open = machines.open.filter((o) => o.id !== id);+ storeOpen();+ if (client) {+ client.close();+ client.free();+ }+}++/** A plain ssh terminal on this server, for a machine ThinkTerm could not+ be set up on: a new tab here, in that machine's ssh domain. */+export function openPlainSsh(id: string) {+ const m = find(id);+ const domain = m?.failure?.ssh_domain;+ const hub = clients.get(HERE);+ if (!m || !domain || !hub) return;+ close(id);+ showMachine(HERE);+ hub.new_tab_in(domain);+ closePanel();+}++/** Where a machine stands, in a few words; empty when it is simply up. */+export function stateText(m: OpenMachine): string {+ if (m.ask) return s('web-machines-needs-you');+ switch (m.state) {+ case 'ready':+ return '';+ case 'reconnecting':+ return s('web-machines-reconnecting');+ case 'failed':+ return m.failure ? s(`web-machines-failed-${m.failure.reason}`) : s('web-machines-not-connected');+ case 'connecting':+ return m.step ? s(`web-machines-step-${m.step}`) : s('web-machines-step-connecting');+ }+}++/** Add a workspace on another machine: its tree comes on show with the+ field open there, and the one open here is put away. */+export function addWorkspaceOn(key: string) {+ const next = clients.get(key);+ if (!next || machines.active === key) return;+ handle.client?.side_key('Escape', '');+ // The path is typed next: the keys stay in the field, not the terminal.+ showMachine(key, false);+ next.side_click('new-project');+ refreshViews();+ document.querySelector<HTMLInputElement>('#side .path input')?.focus();+}++/** The machines a workspace can be added on: this server and every open+ one that is up. */+export function workspaceMachines(): { key: string; label: string }[] {+ return [+ { key: HERE, label: s('web-machines-here') },+ ...machines.open.filter((m) => m.state === 'ready').map((m) => ({ key: m.id, label: m.label })),+ ];+}++/** What the Space button calls the machine on show; empty for this one. */+export function activeLabel(): string {+ if (machines.active === HERE) return '';+ return find(machines.active)?.label ?? '';+}++// ---- the Space menu ---------------------------------------------------------++/** The page's own rows in the Space menu, by their place in it. */+let pageActions: (() => void)[] = [];++type SpaceEntry = { id: string; name: string; current: boolean; default: boolean };++/** A machine's Spaces; one that has none yet has the one its sidebar+ shows, which is where switching to it lands. */+function spacesOf(client: Client): SpaceEntry[] {+ try {+ const spaces = JSON.parse(client.spaces()) as SpaceEntry[];+ if (spaces.length > 0) return spaces;+ const row = (JSON.parse(client.sidebar()) as { rows: { kind: string; name?: string }[] }).rows.find((r) => r.kind === 'space');+ return row ? [{ id: '', name: row.name ?? '', current: true, default: true }] : [];+ } catch {+ return [];+ }+}++function pageItem(label: string, icon: string | null, run: () => void, checked = false, enabled = true): MenuItem {+ pageActions.push(run);+ return { id: `page:${pageActions.length - 1}`, label, icon, kind: 'item', enabled, checked, submenu: [] };+}++function header(label: string): MenuItem {+ return { id: '', label, icon: null, kind: 'header', enabled: false, checked: false, submenu: [] };+}++function separator(): MenuItem {+ return { id: '', label: '', icon: null, kind: 'separator', enabled: false, checked: false, submenu: [] };+}++/** Switch to `space` on machine `key`: the machine comes on show with it,+ and its terminal in front of the Remote Hosts page. An empty `space` is+ the machine's only one. */+function switchSpace(key: string, space: string) {+ const client = clients.get(key);+ if (!client) return;+ // On a phone the drawer the menu was opened from would cover it.+ openSide(false);+ hidePanel();+ showMachine(key);+ if (space !== '') client.set_space(space);+ refreshViews();+}++/** The Space menu the way the desktop lays it out: this server's Spaces,+ then each other machine under its name with its own, then Add Remote+ Host, then what the active machine's menu offers for its current Space+ (New, Rename, Delete). `own` is the active client's menu. */+export function spaceMenu(own: MenuItem[]): MenuItem[] {+ pageActions = [];+ const items: MenuItem[] = [];+ const spaceRow = (key: string, space: SpaceEntry) =>+ pageItem(space.name, space.default ? 'house' : 'layers', () => switchSpace(key, space.id), machines.active === key && space.current);+ const hub = clients.get(HERE);+ // With other machines in the list, this server's Spaces are headed too.+ if (machines.open.length > 0) items.push(header(machines.here ? `${s('web-machines-here')} · ${machines.here}` : s('web-machines-here')));+ if (hub) for (const space of spacesOf(hub)) items.push(spaceRow(HERE, space));+ for (const m of machines.open) {+ items.push(separator());+ const state = stateText(m);+ items.push(header(state === '' ? m.label : `${m.label} · ${state}`));+ const client = clients.get(m.id);+ if (client && m.state !== 'failed') {+ for (const space of spacesOf(client)) items.push(spaceRow(m.id, space));+ items.push(+ pageItem(s('menu-new-space-here'), 'plus', () => {+ // Looked up now: the machine may have been closed meanwhile.+ const now = clients.get(m.id);+ if (!now) return;+ openSide(false);+ hidePanel();+ showMachine(m.id);+ now.menu_action('new-space');+ refreshViews();+ }),+ );+ } else {+ items.push(pageItem(s('web-machines-show'), 'server', () => openPanel()));+ }+ }+ items.push(separator());+ items.push(pageItem(s('menu-add-remote-host'), 'network', () => openPanel(true)));+ // The active machine's own actions on its current Space.+ const cut = own.findIndex((item) => item.kind === 'separator');+ if (cut >= 0) items.push(...own.slice(cut));+ return items;+}++/** Run one of the page's own rows; false for any other id. */+export function runPageItem(id: string): boolean {+ if (!id.startsWith('page:')) return false;+ pageActions[Number(id.slice(5))]?.();+ return true;+}++// For probes and the smoke tests, beside `window.thinkterm.client`.+(window as unknown as { thinkterm: Record<string, unknown> }).thinkterm.machines = machines;diff --git a/thinkterm-web/ui/src/main.ts b/thinkterm-web/ui/src/main.tsindex 73a184f8..b683a974 100644--- a/thinkterm-web/ui/src/main.ts+++ b/thinkterm-web/ui/src/main.ts@@ -2,10 +2,12 @@import { flushSync, mount } from 'svelte';import App from './App.svelte';import { handle } from './client';-import { attach, setBoot } from './client.svelte';+import { activate, attach, setBoot, views } from './client.svelte';+import { configure as configureMachines, fetchTabIcons } from './machines.svelte';+import { dress, setTabIcons } from './tabicons.svelte';import { watchMobile } from './mobile.svelte';import { storedPicks, watchHotkey } from './palette.svelte';-import { applyTheme, previewScheme, storedScheme, storedSettings, storedSpace } from './settings.svelte';+import { applyTheme, FOLLOW_DESKTOP, previewScheme, storedScheme, storedSettings, storedSpace } from './settings.svelte';import type { Theme } from './model';import './tokens.css';@@ -95,6 +97,7 @@ async function fetchFont(url: string): Promise<Uint8Array> {}try {+ setBoot("Loading ThinkTerm…", false, 0);const glueUrl = new URL("pkg/thinkterm_web.js", document.baseURI).href;const mod = await import(/* @vite-ignore */ glueUrl) as Glue;await mod.default();@@ -117,10 +120,13 @@ try {setBoot("GRAPHICS " + await mod.graphics_check(names, data, fontSize));} else {if (!token) throw new Error("no token: open the URL that `thinkterm cli web-token mint` printed");+ setBoot("Loading fonts…", false, 1);const names = FONTS.map(([n]) => n);const data = await Promise.all(FONTS.map(([, u]) => fetchFont(u)));+ setBoot("Connecting…", false, 2);const scheme = location.protocol === "https:" ? "wss" : "ws";- handle.client = await mod.start("term", "kbd", `${scheme}://${location.host}/ws`, token, names, data, fontSize, glyphFont, fontPinned, locale, languages);+ const hub = await mod.start("term", "kbd", `${scheme}://${location.host}/ws`, token, names, data, fontSize, glyphFont, fontPinned, locale, languages, undefined);+ handle.client = hub;// The preferences go over whole: the wasm checks them and applies the// language and the font itself. A refusal is worth a line in the// console, not a failed boot -- the defaults are perfectly usable.@@ -129,7 +135,8 @@ try {// The picked scheme's colours were stored with its name, so the first// frame is already in it and nothing waits on schemes.json.if (settings["terminal-scheme"] && settings["terminal-scheme"] !== "desktop") previewScheme(storedScheme());- attach(handle.client);+ attach(hub);+ activate(hub);// Which locale the preference came to, for the settings panel to name.document.documentElement.lang = handle.client.set_locale(locale, languages);handle.client.set_recent(storedPicks());@@ -137,6 +144,30 @@ try {// and the sidebar simply stays where it landed.const space = storedSpace();if (space !== "") handle.client.set_space(space);+ // Other machines, through this server: each a client of its own, with+ // this browser's preferences as they stand when it opens.+ configureMachines({+ // The language as it stands now, not as this load began: start()+ // activates the one it is given, for the whole page.+ start: (canvas, textarea, opener) =>+ mod.start(canvas, textarea, "", token as string, names, data, fontSize, glyphFont, fontPinned, String(views.settings.language || "system"), languages, opener),+ token: token as string,+ prepare: (client) => {+ client.apply_settings(JSON.stringify(views.settings));+ client.set_locale(String(views.settings.language), languages);+ if (views.settings["terminal-scheme"] !== FOLLOW_DESKTOP) {+ const picked = storedScheme();+ if (picked) client.set_terminal_palette(JSON.stringify(picked));+ }+ client.set_recent(storedPicks());+ dress(client);+ },+ }, hub);+ // The cards this server's desktop dresses its tabs with; without them+ // (a relay that cannot say) the tabs keep the plain terminal mark.+ void fetchTabIcons().then((catalog) => {+ if (catalog !== null) setTabIcons(catalog);+ });}} catch (e) {const err = e as { message?: string } | null;diff --git a/thinkterm-web/ui/src/menu.svelte.ts b/thinkterm-web/ui/src/menu.svelte.tsindex fe8adb0d..cc73f1a0 100644--- a/thinkterm-web/ui/src/menu.svelte.ts+++ b/thinkterm-web/ui/src/menu.svelte.ts@@ -6,8 +6,9 @@import { handle } from './client';import { refreshViews } from './client.svelte';+import { hidePanel, runPageItem, spaceMenu } from './machines.svelte';import type { MenuItem, MenuOutcome } from './model';-import { focusTerminal } from './mobile.svelte';+import { focusTerminal, openSide } from './mobile.svelte';export const menu = $state({/** The root list; empty when no menu is open. */@@ -24,8 +25,25 @@ export const menu = $state({selected: -1,});+/** The button a menu was opened from, if it was one: a press on it is+ not a press elsewhere, but the same button again (`toggleMenu`). */+let trigger: Element | null = null;++export function menuTrigger(): Element | null {+ return trigger;+}++/** A button's menu: opened by the button, closed by the same button. */+export function toggleMenu(kind: string, id: string, clientX: number, clientY: number, from: Element) {+ if (menu.items.length > 0 && trigger === from) {+ closeMenu();+ return;+ }+ openMenu(kind, id, clientX, clientY, from);+}+/** The menu for `kind`/`id` at a point, if the wasm has one to offer. */-export function openMenu(kind: string, id: string, clientX: number, clientY: number) {+export function openMenu(kind: string, id: string, clientX: number, clientY: number, from: Element | null = null) {if (!handle.client) return;let items: MenuItem[];try {@@ -35,7 +53,10 @@ export function openMenu(kind: string, id: string, clientX: number, clientY: num}// Nothing to offer is not an empty menu: the page shows none at all.if (!Array.isArray(items) || items.length === 0) return;+ // The Space menu lists every machine's Spaces, as the desktop's does.+ if (kind === 'space') items = spaceMenu(items);menu.items = items;+ trigger = from;menu.kind = kind;menu.id = id;menu.x = clientX;@@ -47,6 +68,7 @@ export function openMenu(kind: string, id: string, clientX: number, clientY: num/** Close the whole thing; the keyboard goes back to the terminal. */export function closeMenu() {if (menu.items.length === 0) return;+ trigger = null;menu.items = [];menu.path = [];menu.selected = -1;@@ -69,6 +91,10 @@ export function closeInnermost() {that is disabled, and a header or separator do nothing. */export function runItem(item: MenuItem) {if (item.kind !== 'item' || !item.enabled || item.submenu.length > 0 || item.id === '') return;+ if (runPageItem(item.id)) {+ closeMenu();+ return;+ }const client = handle.client;if (!client) return;let outcome: MenuOutcome;@@ -80,6 +106,13 @@ export function runItem(item: MenuItem) {}closeMenu();if (!outcome.handled) return;+ // Another Space, or a new one, puts the Remote Hosts page behind its+ // terminal, as switching Spaces does on the desktop -- and on a phone,+ // the drawer the menu was opened from.+ if (item.id === 'new-space' || item.id.startsWith('space:')) {+ openSide(false);+ hidePanel();+ }// What the row changed is on show before this returns, as it is for a// click on the chrome: the client's own notice is a frame away.refreshViews();diff --git a/thinkterm-web/ui/src/mobile.svelte.ts b/thinkterm-web/ui/src/mobile.svelte.tsindex d1221dc0..c9647d8f 100644--- a/thinkterm-web/ui/src/mobile.svelte.ts+++ b/thinkterm-web/ui/src/mobile.svelte.ts@@ -11,7 +11,7 @@ const NARROW = 720;and below, so every key clears the 44px a thumb needs. The bar reportswhat it really measures as `--keybar`, which is this plus whatever thehome indicator takes; the canvas and the drawers leave room for that. */-export const KEYBAR = 52;+export const KEYBAR = 62;export const mobile = $state({/** The page is in its phone shape. */@@ -35,21 +35,32 @@ export function wantKeyboard(): boolean {/** Put focus back on the field the terminal types through, where that iswanted (see `wantKeyboard`). Every "hand focus back to the terminal"site goes through here, so a phone never gets the soft keyboard from a- panel closing under it. */+ panel closing under it. A page in the terminal's place (`body[data-page]`+ names it, machines.svelte.ts) gets the keys instead: the terminal+ behind it is not on show to type into. */export function focusTerminal() {if (!wantKeyboard()) return;- document.getElementById('kbd')?.focus();+ const page = document.body.dataset.page;+ if (page !== undefined) {+ const el = document.getElementById(page);+ if (el && !el.contains(document.activeElement)) el.focus({ preventScroll: true });+ return;+ }+ document.getElementById('kbd')?.focus({ preventScroll: true });}/** The keyboard button: ask for the soft keyboard, or send it away. */export function toggleKeyboard() {const kbd = document.getElementById('kbd');if (!(kbd instanceof HTMLTextAreaElement)) return;- const up = document.activeElement === kbd;+ // Up only if it was asked for: the field can hold focus with no+ // keyboard on show (a desktop-shaped load, a focus iOS would not raise+ // the keyboard for), and reading that as "up" put a first tap to waste.+ const up = mobile.keyboard && document.activeElement === kbd;mobile.keyboard = !up;paintKeyboard();if (up) kbd.blur();- else kbd.focus();+ else kbd.focus({ preventScroll: true });}/** The wasm asks the same question through `body[data-keyboard]`, since@@ -85,8 +96,10 @@ export function watchMobile() {// #kbd with nothing else taking focus; from then on the keyboard is not// wanted until the button asks again. A blur that moves focus into a// panel is that panel's, and the flag stays for when it closes.- document.getElementById('kbd')?.addEventListener('blur', () => {- if (!mobile.on) return;+ // Listened for on the document: #kbd is not there yet when this runs,+ // and it is a different field for each machine's terminal.+ document.addEventListener('focusout', (ev) => {+ if (!mobile.on || (ev.target as Element | null)?.id !== 'kbd') return;setTimeout(() => {if (document.activeElement === document.body || document.activeElement === null) {mobile.keyboard = false;diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.tsindex 4c0aa48f..4ed638b1 100644--- a/thinkterm-web/ui/src/model.ts+++ b/thinkterm-web/ui/src/model.ts@@ -25,11 +25,15 @@ export type Controls = {clipped: [number, number] | null;};-export type TabsView = { tabs: TabView[]; controls: Controls };+/** `icon`: the card heading every tab (tabicons.svelte.ts), the+ terminal's; null with tab icons off. */+export type TabsView = { tabs: TabView[]; controls: Controls; icon: string | null };export type NavRect = { pane: number; left: number; top: number; width: number; height: number };-export type CapsuleView = { pane: number; title: string; busy: boolean; current: boolean };+/** `icon`: the card heading it, for what the pane runs; null with tab+ icons off. */+export type CapsuleView = { pane: number; title: string; busy: boolean; current: boolean; icon: string | null };export type NavView = {rect: NavRect;@@ -354,6 +358,8 @@ export type WebSettings = {'scroll-mode': ScrollMode;/** `"desktop"` follows the server's configuration; else a scheme's name. */'terminal-scheme': string;+ /** The program's icon at the head of each tab (tabicons.svelte.ts). */+ 'tab-icons': boolean;};/** One entry of `schemes.json`, built by `thinkterm cli color-schemesdiff --git a/thinkterm-web/ui/src/palette.svelte.ts b/thinkterm-web/ui/src/palette.svelte.tsindex f38ab6f4..35619a65 100644--- a/thinkterm-web/ui/src/palette.svelte.ts+++ b/thinkterm-web/ui/src/palette.svelte.ts@@ -7,9 +7,10 @@import { handle } from './client';import { refreshViews, views } from './client.svelte';import { toggleSidebar } from './chrome';+import { hidePanel, openPanel, togglePanel } from './machines.svelte';import type { Hotkey, PaletteEntry, PaletteOutcome, PaletteResults } from './model';import { openSettings, setSetting } from './settings.svelte';-import { focusTerminal } from './mobile.svelte';+import { focusTerminal, openSide } from './mobile.svelte';/** Where this browser keeps the picks, most recent first. */const RECENT = 'thinkterm.recent';@@ -107,6 +108,14 @@ export function run(id: string) {}closePalette();if (!outcome.handled) return;+ // Every pick but the page's own acts on a terminal -- a thread, a tab, a+ // pane, a Space, a command -- and that terminal comes in front of the+ // Remote Hosts page, as it does on the desktop, and of the drawer the+ // palette may have been opened from on a phone.+ if (outcome.page === null) {+ openSide(false);+ hidePanel();+ }// What the pick changed is on show before this returns, as it is for a// menu row: the client's own notice is a frame away.refreshViews();@@ -114,6 +123,8 @@ export function run(id: string) {const page = outcome.page;if (page === 'toggle-sidebar') toggleSidebar();else if (page === 'settings') openSettings();+ else if (page === 'remote-hosts') togglePanel();+ else if (page === 'add-remote-host') openPanel(true);else if (page !== null && page.startsWith('lang:')) {// The wasm activated the language; the preference is the page's to// keep, and storing it is what makes the next load open in it.diff --git a/thinkterm-web/ui/src/settings.svelte.ts b/thinkterm-web/ui/src/settings.svelte.tsindex fa357365..461173ea 100644--- a/thinkterm-web/ui/src/settings.svelte.ts+++ b/thinkterm-web/ui/src/settings.svelte.ts@@ -4,7 +4,7 @@// show, and the palette's recent picks. The wasm applies what concerns it// -- the language and the font -- and the page applies the rest.-import { handle } from './client';+import { everyClient, handle } from './client';import { refreshViews, setLocale, views } from './client.svelte';import type { LanguageOption, Scheme, Theme } from './model';import { focusTerminal } from './mobile.svelte';@@ -82,6 +82,9 @@ export function setSetting(key: string, value: unknown) {const client = handle.client;if (!client) return;panel.error = client.set_setting(key, JSON.stringify(value));+ // The preferences are this browser's, so every machine's terminal takes+ // them; what the one on show said about them is what the panel shows.+ for (const other of everyClient()) if (other !== client) other.set_setting(key, JSON.stringify(value));// The wasm activated the language itself; this is how the page learns// which locale that came to, for the About line.if (key === 'language' && panel.error === '') {@@ -202,9 +205,7 @@ export function storedScheme(): Scheme | null {/** Draw with `scheme` without keeping it: what a hover shows. `null` goesback to the server's own scheme. */export function previewScheme(scheme: Scheme | null) {- const client = handle.client;- if (!client) return;- client.set_terminal_palette(scheme ? JSON.stringify(scheme) : undefined);+ for (const client of everyClient()) client.set_terminal_palette(scheme ? JSON.stringify(scheme) : undefined);}/** Keep `scheme` for this browser: the colours beside the name, so the nextdiff --git a/thinkterm-web/ui/src/tabicons.svelte.ts b/thinkterm-web/ui/src/tabicons.svelte.tsnew file mode 100644index 00000000..96c2c1ae--- /dev/null+++ b/thinkterm-web/ui/src/tabicons.svelte.ts@@ -0,0 +1,70 @@+// The icons heading the tabs (thinkterm-web/src/tab_icons.rs): the cards+// this page's server sent over the relay, drawn here as one stylesheet --+// each card's colours and its mark, as a mask cut out of its SVG -- and+// the class that picks a card by its id. Which card a tab gets is the+// wasm's to say; every client is handed the same cards, other machines'+// tabs included, as the desktop dresses them with its own.++import { everyClient, type Client } from './client';++type WireCard = { id: string; circle: string; glyph: string; svg: string };++export const icons = $state({+ /** Each card's class, by its id. */+ classes: {} as Record<string, string>,+});++/** The cards as the server sent them, for a client that starts later. */+let sent: string | null = null;++const HEX = /^#[0-9a-fA-F]{6}$/;++/** A card's mark as a mask. An SVG drawn as an image runs nothing, which+ is what makes an imported one safe to show. A card sent without one+ (its file unreadable there) shows its circle alone, as the desktop's+ does: a mask that hides the whole glyph. */+function mask(svg: string): string {+ if (svg === '') return 'linear-gradient(transparent, transparent)';+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;+}++/** Take the server's cards: draw them, and hand them to every client. A+ card whose colours are not colours is left out, and draws as the+ terminal's mark would without icons. */+export function setTabIcons(catalog: unknown) {+ const cards = (catalog as { cards?: unknown })?.cards;+ if (!Array.isArray(cards)) return;+ const rules: string[] = [];+ const classes: Record<string, string> = {};+ cards.forEach((card: WireCard, i) => {+ if (typeof card?.id !== 'string' || typeof card.svg !== 'string' || !HEX.test(card.circle) || !HEX.test(card.glyph)) return;+ classes[card.id] = `k${i}`;+ rules.push(`.ticon.k${i} { --c: ${card.circle}; --g: ${card.glyph}; --m: ${mask(card.svg)}; }`);+ });+ let style = document.getElementById('tab-icons');+ if (!(style instanceof HTMLStyleElement)) {+ style = document.createElement('style');+ style.id = 'tab-icons';+ document.head.append(style);+ }+ style.textContent = rules.join('\n');+ icons.classes = classes;+ sent = JSON.stringify(catalog);+ for (const client of everyClient()) dress(client);+}++/** A client that starts after the cards came gets them too. */+export function dress(client: Client) {+ if (sent === null) return;+ const refused = client.set_tab_icons(sent);+ if (refused !== '') console.warn('tab icons: ' + refused);+}++/** The class drawing card `id`; empty for none, or one the page has no+ picture of. */+export function iconClass(id: string | null | undefined): string {+ return id ? (icons.classes[id] ?? '') : '';+}++// For probes, beside `window.thinkterm.client`.+(window as unknown as { thinkterm: Record<string, unknown> }).thinkterm.tabIcons = icons;diff --git a/thinkterm-web/ui/src/tokens.css b/thinkterm-web/ui/src/tokens.cssindex 6813b5bc..4547b9a4 100644--- a/thinkterm-web/ui/src/tokens.css+++ b/thinkterm-web/ui/src/tokens.css@@ -18,6 +18,12 @@--btn: #262628; --btn-hover: #313134; --btn-border: rgba(118,118,128,.35);--row-hover: #232326; --row-sel: #3E3E41;--card: #1D1D1F; --card-border: rgba(118,118,128,.22); --card-line: rgba(118,118,128,.24); --dot: rgba(242,242,247,.16);+ /* The settings window's nav rows and squares (`sidebar_row_*`,+ `paint_active_row_shadow`, `ROW_TILE`). */+ --nav-hover: rgba(42,42,44,.98); --nav-sel: rgba(54,54,57,.98); --nav-sel-border: rgba(118,118,128,.22);+ --nav-shadow: .18; --tile-shadow: .35;+ /* How dark a tab icon's shadow is (tab_icons.rs PLATE). */+ --ticon-shadow: 50%;--fade: background-color .12s ease, border-color .12s ease, color .12s ease, box-shadow .12s ease;}body[data-side=off] { --side-w: 0px; }@@ -38,6 +44,9 @@ body:not([data-agents]), body:not([data-extended]) { --ext-w: 0px; }--row-hover: rgba(28,28,30,.06); --row-sel: rgba(255,255,255,.94);--card: rgba(255,255,255,.72); --card-border: rgba(60,60,67,.16); --card-line: rgba(60,60,67,.14);--dot: rgba(28,28,30,.22);+ --nav-hover: rgba(60,60,67,.08); --nav-sel: rgba(255,255,255,.78); --nav-sel-border: rgba(60,60,67,.18);+ --nav-shadow: .05; --tile-shadow: .18;+ --ticon-shadow: 32%;}html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text2); font: 500 14px var(--ui); overflow: hidden; }/* The page is mounted into #app; it generates no box of its own, so the@@ -51,6 +60,9 @@ svg { width: 16px; height: 16px; flex: none; }#tabs .tab { display: inline-flex; align-items: center; flex: 0 0 auto; width: 128px; height: 30px; box-sizing: border-box; padding: 0 9px; border-radius: 999px; border: 1px solid transparent; color: var(--text2); cursor: default; transition: var(--fade); }#tabs .tab:hover { background: var(--ctl-hover); }#tabs .tab.current { background: var(--ctl); border-color: var(--ctl-border); box-shadow: var(--shadow); color: var(--text); }+/* The Remote Hosts tab takes the width its title needs: in a terminal+ tab's 128px it read "Remot…". */+#tabs .tab[data-page-tab] { width: auto; min-width: 128px; }.t { margin-left: 4px; flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.x { display: none; margin-left: 4px; width: 22px; height: 22px; border-radius: 999px; align-items: center; justify-content: center; opacity: .82; flex: none; }.current .x, .tab:hover .x, .cap:hover .x { display: inline-flex; }@@ -67,6 +79,8 @@ svg { width: 16px; height: 16px; flex: none; }/* Its own layer: the sidebar's edge moves the canvas on every drag frame,and a promoted layer moves instead of being laid out again. */canvas#term { will-change: transform; }+/* Another machine's terminal, behind the one on show (machines.svelte.ts). */+canvas.off, textarea.off { display: none; }/* One bar over each pane, laid out from the canvas's cells. */#panes { position: absolute; inset: var(--tabs) calc(var(--agents-w) + var(--ext-w)) 0 var(--side-w); pointer-events: none; overflow: hidden; }/* The desktop's left sidebar: Spaces, Projects, Threads. Every row's box@@ -90,19 +104,20 @@ body[data-side=off]:not([data-mobile]) #side.revealed {}#side .list { position: absolute; inset: 26px 10px 44px 10px; overflow-y: auto; scrollbar-width: thin; display: flex; flex-direction: column; gap: 5px; padding-bottom: 8px; }/* The footer as the desktop ends its sidebar: a row of icons, the gear at- the left inset and the thread search at the right, no rule above. */+ the left inset and Remote Hosts and the thread search at the right, no+ rule above. */#side .foot { position: absolute; left: 13px; right: 13px; bottom: 0; height: 58px; display: flex; align-items: center; justify-content: space-between; }#side .foot .act { width: 28px; height: 28px; color: var(--text2); border-radius: 8px; }/* The gear carries its label, as the desktop's footer does; the row is the- label's own width, and the search stays at the right inset. */-#side .foot .act.lbl { width: auto; min-width: 28px; max-width: calc(100% - 34px); padding: 0 7px; gap: 6px; justify-content: flex-start; font-size: 14px; }+ label's own width, and gives way before the right-hand actions do. */+#side .foot .act.lbl { width: auto; min-width: 28px; flex: 0 1 auto; overflow: hidden; padding: 0 7px; gap: 6px; justify-content: flex-start; font-size: 14px; }#side .foot .act.lbl .tl { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }/* Under the width the model says the label needs, the gear is a lonebutton again -- `.narrow` is set from that number, not from a mediaquery with a number of its own. */#side.narrow .foot .act.lbl .tl { display: none; }-#side .foot .act svg { width: 16px; height: 16px; }-#side .foot .acts { display: inline-flex; align-items: center; gap: 3px; }+#side .foot .act svg { width: 16px; height: 16px; flex: none; }+#side .foot .acts { display: inline-flex; flex: none; align-items: center; gap: 3px; }#side .foot .act:hover { color: var(--text); background: var(--row-hover); }/* Nothing behind them yet: shown, as the desktop shows them, and inert. */#side .foot .act.off { color: var(--muted); opacity: .5; }@@ -110,6 +125,7 @@ body[data-side=off]:not([data-mobile]) #side.revealed {/* The tab row's toggle stays above the revealed panel: a quick press pinsthe panel open without the reveal getting in the way. */#tabs [data-action=sidebar] { position: relative; z-index: 18; }+#tabs .lead, #tabs .strip { display: contents; }/* Pinned open, the panel carries the toggle itself at its top-left, as thedesktop's titlebar does; the tab row's copy shows only while it is away. */body:not([data-side=off]):not([data-mobile]) #tabs [data-action=sidebar] { display: none; }@@ -135,6 +151,15 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }/* The Space row is the pill's height plus 6 design px, not a list row. */#side .row.space { min-height: 32px; cursor: default; }#side .row.space .act { width: 29px; height: 29px; margin-left: auto; color: var(--text2); }+/* Another machine on show: its name ahead of the Space's, as the desktop+ heads a server's Spaces in the menu, and the one that gives way when the+ row is short. Not connected, the icon is the desktop's amber alert,+ swapped in place so the row never moves. */+#side .row.space.remote .t { display: flex; min-width: 0; }+#side .row.space .machine { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; color: var(--text); font-weight: 500; }+#side .row.space .sn { flex: 0 0 auto; max-width: 60%; overflow: hidden; text-overflow: ellipsis; }+#side .row.space .sn::before { content: '·'; margin: 0 6px; color: var(--muted); }+#side .row.space.down > svg { color: var(--warn); }#side .row:hover { background: var(--row-hover); }#side .row.selected { background: var(--row-sel); border-color: rgba(118,118,128,.22); box-shadow: var(--shadow); }#side .row.selected .t { color: var(--text); }@@ -186,6 +211,12 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#side .path input::placeholder { color: var(--muted); }#side .path input:focus { border-color: var(--accent); }#side .path .hint { color: var(--muted); font-size: 12px; font-weight: 500; line-height: 1.35; word-break: break-word; }+/* The machine it goes on: the field's own box and height, with the settings+ window's drawn chevron rather than the browser's, which a dark ground+ hides. */+#side .path select.on { width: 100%; box-sizing: border-box; font: 400 14px var(--ui); color: var(--text); background-color: var(--ctl); border: 1px solid var(--ctl-border); border-radius: 7px; padding: 6px 26px 6px 8px; outline: none; appearance: none; -webkit-appearance: none; background-image: linear-gradient(45deg, transparent 50%, var(--text2) 50%), linear-gradient(135deg, var(--text2) 50%, transparent 50%); background-position: calc(100% - 15px) 55%, calc(100% - 10px) 55%; background-size: 5px 5px, 5px 5px; background-repeat: no-repeat; transition: var(--fade); }+#side .path select.on:hover { background-color: var(--ctl-hover); }+#side .path select.on:focus { border-color: var(--accent); }#side .path.bad input { border-color: var(--danger); }#side .path.bad .hint { color: var(--danger); }/* With no workspace yet, the header's round button is the only way in and@@ -317,7 +348,13 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#agents .se-field:focus { border-color: var(--edge); }#agents .se-body { min-height: 180px; flex: none; resize: vertical; font: 400 13px ui-monospace, "SF Mono", Menlo, monospace; line-height: 1.45; white-space: pre; overflow: auto; }#agents .se-body.want { border-color: var(--danger); }-.nav { position: absolute; pointer-events: auto; box-sizing: border-box; display: flex; align-items: center; gap: 9px; padding: 0 5px; background: var(--bg); color: var(--text2); user-select: none; overflow: hidden; }+.nav { position: absolute; pointer-events: auto; box-sizing: border-box; display: flex; align-items: flex-start; gap: 9px; padding: 0 5px; background: var(--bg); color: var(--text2); user-select: none; overflow: hidden; }+/* The bar is the desktop's 47px, but the pane pays for it in whole rows+ (and a pane at the top in its padding too): the capsules sit where they+ would in a 47px bar at its top, and what the rounding adds is left+ under them, as the desktop leaves it -- not split above and below. */+.nav > .caps, .nav > .acts { margin-top: 8.5px; height: 30px; align-items: center; }+body[data-mobile] .nav > .caps, body[data-mobile] .nav > .acts { margin-top: 6px; height: 40px; }.nav.focused { color: var(--text); }.nav .caps { display: flex; gap: 9px; flex: 1 1 auto; min-width: 0; overflow: hidden; }.nav .cap { display: inline-flex; align-items: center; flex: 0 0 auto; width: 128px; height: 30px; box-sizing: border-box; padding: 0 9px; border-radius: 999px; border: 1px solid transparent; background: var(--wash); color: var(--text2); cursor: default; }@@ -330,6 +367,23 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }.nav .act svg { width: 13px; height: 13px; }.spin { display: inline-flex; animation: spin .96s steps(12) infinite; }@keyframes spin { to { transform: rotate(360deg); } }+/* A tab's icon (tabicons.svelte.ts), as the desktop draws it (tab_icons.rs+ PLATE, paint_tab_circle_icon): the card's circle, concentric with the+ capsule's rounded end (TAB_ICON_CIRCLE_INSET) -- lighter at the top,+ darker at the foot, its rim the same more strongly, its shadow in its+ own hue -- carrying the card's mark, or the spinner while the pane+ works, at TAB_ICON_GLYPH_RATIO of its width. The card gives `--c` (the+ circle), `--g` (the mark) and `--m` (the mark's shape). */+.ticon {+ flex: none; display: inline-flex; align-items: center; justify-content: center;+ height: calc(100% - 4px); aspect-ratio: 1; margin-left: -7px; border-radius: 50%;+ background: linear-gradient(color-mix(in srgb, var(--c), #fff 18%), color-mix(in srgb, var(--c), #000 13%));+ box-shadow: inset 0 1px 0 color-mix(in srgb, var(--c), #fff 42%), inset 0 -1px 0 color-mix(in srgb, var(--c), #000 25%),+ 0 1.25px 1.75px color-mix(in srgb, color-mix(in srgb, var(--c), #000 55%) var(--ticon-shadow), transparent);+}+.ticon > i { width: 56%; height: 56%; background: var(--g); -webkit-mask: var(--m) center / contain no-repeat; mask: var(--m) center / contain no-repeat; }+.ticon .spin { width: 56%; height: 56%; color: var(--g); }+.ticon .spin svg { width: 100%; height: 100%; }/* What the desktop shows over a terminal another device holds. */@keyframes card-in { from { opacity: 0; } to { opacity: 1; } }#card:not([hidden]) { animation: card-in .16s cubic-bezier(0,0,.2,1); }@@ -354,8 +408,7 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }/* The panel arrives at the point it was asked for: a 120ms fade and ahair of scale from that corner. Its own measuring reads offsetWidth,which a transform does not move. */-@keyframes menu-in { from { opacity: 0; transform: scale(.97); } to { opacity: 1; transform: scale(1); } }-.menu { animation: menu-in .12s cubic-bezier(0,0,.2,1); transform-origin: top left; position: fixed; z-index: 20; min-width: 168px; max-width: 340px; box-sizing: border-box; padding: 5px; border-radius: 10px; background: var(--ctl); border: 1px solid var(--ctl-border); box-shadow: 0 8px 28px rgba(0,0,0,.42); color: var(--text); font: 500 13px var(--ui); user-select: none; outline: none; }+.menu { position: fixed; z-index: 20; min-width: 168px; max-width: 340px; box-sizing: border-box; padding: 5px; border-radius: 10px; background: var(--ctl); border: 1px solid var(--ctl-border); box-shadow: 0 8px 28px rgba(0,0,0,.42); color: var(--text); font: 500 13px var(--ui); user-select: none; outline: none; }.menu .mi { display: flex; align-items: center; gap: 8px; height: 28px; box-sizing: border-box; padding: 0 8px; border-radius: 6px; white-space: nowrap; }.menu .mi:hover, .menu .mi.on { background: var(--ctl-hover); }.menu .mi.disabled { color: var(--muted); }@@ -405,36 +458,60 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }control pills right-aligned to the card's 18px inset. */#settings { --settings-tf: translate(-50%, -50%); position: fixed; z-index: 31; left: 50%; top: 50%; transform: var(--settings-tf); width: min(960px, 94vw); height: min(602px, 90vh); box-sizing: border-box; display: flex; background: var(--bg); border: 1px solid var(--ctl-border); border-radius: 20px; box-shadow: 0 24px 80px rgba(0,0,0,.55); color: var(--text); font: 500 14px var(--ui); overflow: hidden; outline: none; }#settings .sc { position: absolute; right: 12px; top: 12px; z-index: 1; display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: 999px; background: transparent; border: 0; color: var(--muted); transition: var(--fade); }+#settings .back { display: none; }#settings .sc:hover { color: var(--text); background: var(--row-hover); }#settings .sc svg { width: 15px; height: 15px; }-#settings .snav { flex: 0 0 220px; box-sizing: border-box; padding: 18px 14px; background: var(--side-bg); border-right: 1px solid var(--sep); display: flex; flex-direction: column; }-#settings .app { font-size: 17px; font-weight: 700; color: var(--text); padding: 18px 3px 15px 3px; }-#settings .find { display: flex; align-items: center; gap: 7px; height: 28px; box-sizing: border-box; padding: 0 10px; border-radius: 999px; background: var(--ctl); border: 1px solid var(--ctl-border); color: var(--muted); }+#settings .snav { flex: 0 0 220px; box-sizing: border-box; padding: 36px 14px 16px 14px; background: var(--side-bg); border-right: 1px solid var(--sep); display: flex; flex-direction: column; }+#settings .app { font-size: 17px; font-weight: 750; line-height: 22px; color: var(--text); padding: 0 3px 13px 3px; }+#settings .find { display: flex; align-items: center; gap: 7px; flex: none; height: 28px; box-sizing: border-box; padding: 0 10px; border-radius: 999px; background: var(--ctl); border: 1px solid var(--ctl-border); color: var(--muted); }#settings .find svg { width: 14px; height: 14px; flex: none; }#settings .find input { flex: 1 1 auto; min-width: 0; background: transparent; border: 0; outline: none; color: var(--text); font: 500 13px var(--ui); }-#settings .secs { display: flex; flex-direction: column; gap: 4px; margin-top: 11px; }-/* 68 device px tall on a 76 px pitch at 2x, and the selected row is the- sidebar's own #3E3E41. A shadow rather than a border: a border on the- selected row alone would move the text by a pixel. */-#settings .sec { display: flex; align-items: center; gap: 7px; height: 34px; box-sizing: border-box; padding: 0 9px; border-radius: 10px; color: var(--text); cursor: default; transition: var(--fade); }-#settings .sec svg { width: 15px; height: 15px; flex: none; color: var(--text2); }-#settings .sec:hover { background: var(--row-hover); }-#settings .sec.on { background: var(--row-sel); box-shadow: var(--shadow); }-#settings .body { flex: 1 1 auto; min-width: 0; overflow-y: auto; scrollbar-width: thin; padding: 28px 26px 24px 22px; }-#settings .title { font-size: 19px; font-weight: 700; margin: 0 0 20px 0; }-#settings .card { background: var(--card); border: 1px solid var(--card-border); border-radius: 17px; padding: 0 18px; margin-bottom: 18px; }-#settings .srow { display: flex; align-items: center; gap: 18px; padding: 11px 0; border-bottom: 1px solid var(--card-line); }-#settings .srow:last-child { border-bottom: 0; }+#settings .secs { display: flex; flex-direction: column; gap: 5px; margin-top: 12px; min-height: 0; overflow-y: auto; scrollbar-width: none; margin-left: -4px; margin-right: -4px; padding: 0 4px 4px 4px; }+/* The desktop's nav rows (`NAV_ROW_*`, 2x): 66 device px tall on a 76 px+ pitch, a 46 px square 12 px in, the label 16 px after it in the secondary+ text, the text colour once selected. The selected row is the sidebar's+ active one, fill, hairline and shadow; the hairline is drawn inside, so+ the label does not move by a pixel when the row is chosen. */+#settings .sec { display: flex; align-items: center; gap: 8px; flex: none; height: 33px; box-sizing: border-box; padding: 0 7px; border-radius: 10px; color: var(--text2); cursor: default; transition: var(--fade); }+#settings .sec .sl { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#settings .sec:hover { background: var(--nav-hover); }+#settings .sec.on { background: var(--nav-sel); color: var(--text); box-shadow: inset 0 0 0 1px var(--nav-sel-border), 0 1px 1px 1px rgba(0,0,0,var(--nav-shadow)); }+/* A section's square (`paint_tile`, `ROW_TILE`): its colour lit from above+ and a step darker below, a faint light rim on top and a soft drop shadow,+ with the glyph in white at 58% of the side. */+#settings .tile { --tile: #636366; display: inline-flex; align-items: center; justify-content: center; flex: none; width: 23px; height: 23px; border-radius: 6px; color: #FFFFFF; background: linear-gradient(to bottom, color-mix(in srgb, var(--tile), #FFFFFF 16%), color-mix(in srgb, var(--tile), #000000 10%)); box-shadow: inset 0 .5px 0 rgba(255,255,255,.30), 0 1px 2px rgba(0,0,0,var(--tile-shadow)); }+#settings .tile svg { width: 13px; height: 13px; }+#settings .body { flex: 1 1 auto; min-width: 0; overflow-y: auto; scrollbar-width: thin; padding: 36px 24px 24px 23px; display: flex; flex-direction: column; }+/* A column, so About's maker can sit at the foot; nothing in it shrinks. */+#settings .body > * { flex: none; }+/* The page's name on the brand's line, as large as the settings text plus+ four, at its weight. */+#settings .title { font-size: 19px; font-weight: 600; line-height: 22px; margin: 0 0 28px 0; }+#settings .card { background: var(--card); border: 1px solid var(--card-border); border-radius: 18px; padding: 0 18px; margin-bottom: 18px; }+/* A two-line row is 128 device px at 2x: the label, then its description+ in the secondary text at the label's size. Its square comes first, the+ text 12px after it and the control 12px after that (ROW_TILE_GAP); the+ rule between two rows starts where their text does. */+#settings .srow { position: relative; display: flex; align-items: center; gap: 12px; min-height: 30px; padding: 13px 0; }+#settings .srow:not(:last-child)::after { content: ""; position: absolute; left: 40px; right: 0; bottom: 0; height: 1px; background: var(--card-line); }+#settings .srow:has(> .tx:first-child)::after { left: 0; }#settings .tx { flex: 1 1 auto; min-width: 0; }-#settings .lab { font-weight: 600; color: var(--text); }-#settings .desc { margin-top: 4px; color: var(--muted); font-size: 13px; font-weight: 500; }+#settings .lab { font-weight: 600; color: var(--text); line-height: 18px; }+#settings .desc { margin-top: 4px; color: var(--text2); font-size: 14px; font-weight: 400; line-height: 19px; }+/* A row's square (`paint_row_tile`, ROW_TILE_SIDE 28pt): the section's+ square at 28px, its glyph 16px, centred on the label and the first line+ of the description however many lines that runs to. */+#settings .srow > .tile { width: 28px; height: 28px; border-radius: 7.5px; align-self: flex-start; margin-top: 6.5px; }+#settings .srow > .tile svg { width: 16px; height: 16px; }#settings .ctl { display: flex; align-items: center; gap: 8px; flex: none; }/* The desktop's control pill: 280x54 device px at 2x, flush with the card'sright inset. */#settings .pillsel, #settings .pillbtn { flex: none; box-sizing: border-box; height: 28px; font: 500 13px var(--ui); color: var(--text); background: var(--ctl); border: 1px solid var(--btn-border); border-radius: 8px; padding: 0 12px; min-width: 140px; transition: var(--fade); }#settings .pillsel { appearance: none; -webkit-appearance: none; padding-right: 28px; background-image: linear-gradient(45deg, transparent 50%, var(--text2) 50%), linear-gradient(135deg, var(--text2) 50%, transparent 50%); background-position: calc(100% - 16px) 55%, calc(100% - 11px) 55%; background-size: 5px 5px, 5px 5px; background-repeat: no-repeat; }#settings .pillsel:hover, #settings .pillbtn:hover { background-color: var(--ctl-hover); }-#settings .pillbtn { min-width: 0; }+/* A button is fully round (`draw_button`), which tells it from the value+ pills of the same height. */+#settings .pillbtn { min-width: 0; border-radius: 999px; }#settings .seg { display: inline-flex; height: 28px; box-sizing: border-box; border: 1px solid var(--btn-border); border-radius: 8px; overflow: hidden; background: var(--ctl); }#settings .sg { display: inline-flex; align-items: center; gap: 6px; padding: 0 11px; color: var(--text2); font: 500 13px var(--ui); cursor: default; transition: var(--fade); }#settings .sg input { position: absolute; opacity: 0; width: 0; height: 0; }@@ -458,10 +535,177 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#settings .switch input:checked + .knob { background: var(--accent); }#settings .switch input:checked + .knob::after { transform: translateX(16px); }#settings .err { padding: 0 2px 8px 2px; color: var(--danger); font-size: 12px; }-/* A section's own sentence above its cards, and a row's state where it- has no control. */-#settings .sdesc { padding: 0 2px 12px 2px; color: var(--muted); font-size: 13px; font-weight: 500; }-#settings .pilltag { flex: none; color: var(--muted); font: 500 12px var(--ui); }+/* A section's own sentence above its cards, in the description's face,+ and a row's state where it has no control, in a pill as the desktop+ shows a value (`paint_setting_row`). */+#settings .sdesc { padding: 0 2px 12px 2px; color: var(--text2); font-size: 14px; font-weight: 400; line-height: 19px; }+#settings .pilltag { flex: none; box-sizing: border-box; display: inline-flex; align-items: center; height: 28px; min-width: 140px; padding: 0 12px; border-radius: 8px; background: var(--ctl); border: 1px solid var(--btn-border); color: var(--text); font: 500 13px var(--ui); white-space: nowrap; }+/* The right panel's panels as cards (`paint_panel_cards`): two across once+ each can be 219px, a 32px square with the switch level with it, then the+ name 10px under it and two lines of what it is for. Off, the square is+ grey and the words are a step dimmer. */+#settings .pcards { display: grid; grid-template-columns: repeat(auto-fill, minmax(max(219px, calc((100% - 12px) / 2)), 1fr)); gap: 12px; margin-bottom: 18px; }+#settings .pcard { min-width: 0; padding: 15px; border-radius: 14px; background: var(--card); border: 1px solid var(--card-border); }+#settings .pcard .phead { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }+#settings .pcard .tile { width: 32px; height: 32px; border-radius: 8.5px; }+#settings .pcard .tile svg { width: 18.5px; height: 18.5px; }+#settings .pcard .desc { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }+#settings .pcard.off .lab { color: var(--text2); }+#settings .pcard.off .desc { color: var(--muted); }+/* About's hero (`paint_hero`): the app's icon at 54px, its name in the+ title's face and its version under it, Copy on the right, in a card of+ its own at least 90px tall and 26px over the next. */+#settings .hero { display: flex; align-items: center; gap: 12px; min-height: 90px; box-sizing: border-box; padding: 18px; margin-bottom: 26px; }+#settings .hero .mark { flex: none; width: 54px; height: 54px; }+#settings .hero .ht { flex: 1 1 auto; min-width: 0; }+#settings .hero .hl { font-size: 19px; font-weight: 600; line-height: 22px; color: var(--text); }+#settings .hero .sl { margin-top: 6px; color: var(--text2); font-weight: 400; line-height: 19px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#settings .hero .pillbtn { min-width: 115px; }+/* Its facts (`paint_compact_row`): a line each on a 42px pitch, the value+ flush right in the secondary text; the card adds 6px above and below. */+#settings .facts { padding: 6px 18px; }+#settings .fact { box-sizing: border-box; min-height: 42px; padding: 0; }+#settings .fact > .tile { align-self: center; margin-top: 0; }+#settings .fact .lab { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#settings .fact .val { flex: 0 1 auto; max-width: 62%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text2); font-weight: 400; text-align: right; }+/* Who makes it, at the foot of the page when there is room for it there+ (`draw_closex_logo`): the logo 32px tall in the text colour, the year+ after it on the wordmark's baseline, small and muted. */+#settings .maker { margin-top: auto; padding-top: 24px; display: flex; align-items: flex-start; gap: 6px; }+#settings .maker .logo { flex: none; width: calc(32px * 876 / 234); height: 32px; background: var(--text); -webkit-mask: var(--logo) center / contain no-repeat; mask: var(--logo) center / contain no-repeat; }+#settings .maker .yr { margin-top: 16.5px; color: var(--muted); font-size: 11px; font-weight: 500; line-height: 13px; }+/* The Remote Hosts page (MachinesPanel.svelte): the desktop's+ (ssh_hosts_view.rs, 2x design px halved) where the desktop puts it, in+ the terminal's place while its tab is on show -- over the canvas, the+ pane bars and the card, under the drawers and the menus. PAD at the+ sides; the toolbar (New Host, then the search pill, SEARCH_W) heads a+ grid of cards (CARD_MIN_W, CARD_GAP, CARD_RADIUS, CARD_PAD) under their+ group captions, and the form is the inspector beside them at its fixed+ width (INSPECTOR_W), up to 60% of the page. */+#machines { position: absolute; inset: var(--tabs) calc(var(--agents-w) + var(--ext-w)) 0 var(--side-w); z-index: 13; box-sizing: border-box; display: flex; gap: 10px; padding: 0 12px; background: var(--bg); color: var(--text); font: 500 14px var(--ui); outline: none; }+#machines[hidden] { display: none; }+#machines .lists { flex: 1 1 auto; min-width: 0; min-height: 0; display: flex; flex-direction: column; }+#machines .tools { flex: none; display: flex; align-items: center; gap: 6px; margin-top: 12px; }+#machines .find { flex: 0 1 180px; min-width: 0; box-sizing: border-box; display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 12px 0 9px; border-radius: 999px; border: 1px solid var(--btn-border); background: var(--ctl); color: var(--muted); transition: var(--fade); }+#machines .find:focus-within { border-color: var(--accent); }+#machines .find svg { width: 14px; height: 14px; }+#machines .find input { flex: 1 1 auto; min-width: 0; height: 100%; padding: 0; border: 0; background: transparent; color: var(--text); font: 400 14px var(--ui); outline: none; }+#machines .find input::placeholder { color: var(--muted); }+#machines .find input::-webkit-search-cancel-button { -webkit-appearance: none; }+/* What scrolls fades out at the top and the foot rather than being cut off+ at a hard edge. At rest the padding covers the fades. */+#machines .body, #machines form.add { min-height: 0; overflow-y: auto; scrollbar-width: thin; -webkit-mask-image: linear-gradient(to bottom, transparent, #000 12px, #000 calc(100% - 16px), transparent); mask-image: linear-gradient(to bottom, transparent, #000 12px, #000 calc(100% - 16px), transparent); }+#machines .body { flex: 1 1 auto; padding: 12px 0 16px 0; }+/* A group's caption: the section font in the secondary text (GROUP_HEADER_H,+ GROUP_TITLE_GAP), GROUP_GAP above the next. */+#machines .label { margin: 0 2px 6px 2px; color: var(--text2); font-size: 13px; font-weight: 600; line-height: 19px; }+#machines .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 9px; margin-bottom: 18px; }+/* A host card: the card ground with a hairline, the row hover's fill under+ the pointer, and the machine on show ringed in the accent as the desktop+ rings its selected card. */+#machines .hcard { box-sizing: border-box; min-width: 0; min-height: 56px; padding: 10px 11px 10px 12px; background: var(--card); border: 1px solid var(--card-border); border-radius: 18px; transition: var(--fade); }+#machines .hcard:hover { background: color-mix(in srgb, var(--card), var(--text) 3%); }+#machines .hcard.on { border-color: var(--accent); box-shadow: inset 0 0 0 .5px var(--accent); }+#machines .hcard.wide { grid-column: 1 / -1; }+#machines .mrow { display: flex; align-items: center; gap: 10px; min-height: 34px; }+/* The logo is how a machine is picked out without reading: the server+ glyph, large and muted, with the machine's state as a dot on its corner --+ green when it is up, the sidebar's live blue while it connects, amber+ while it waits on you, red once it has failed. */+#machines .logo { position: relative; display: inline-flex; flex: none; color: var(--muted); }+#machines .logo > svg { width: 28px; height: 28px; stroke-width: 1.6; }+#machines .dot { position: absolute; right: -3px; bottom: -3px; width: 10px; height: 10px; border-radius: 50%; background: var(--muted); box-shadow: 0 0 0 2px var(--card); }+#machines .dot.ok { background: var(--done); }+#machines .dot.busy { background: var(--open); animation: machines-pulse 1.2s ease-in-out infinite; }+#machines .dot.wait { background: var(--warn); }+#machines .dot.bad { background: var(--danger); }+@keyframes machines-pulse { 50% { opacity: .35; } }+#machines .tx { flex: 1 1 auto; min-width: 0; }+#machines .lab { font-weight: 600; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#machines .desc { margin-top: 3px; color: var(--muted); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#machines .desc > span:not(:last-child)::after { content: '·'; margin: 0 6px; color: var(--muted); }+#machines .desc .st { color: var(--text2); }+#machines .bar { height: 4px; margin-top: 7px; border-radius: 999px; background: var(--card-line); overflow: hidden; }+#machines .bar span { display: block; height: 100%; border-radius: inherit; background: var(--accent); transition: width .2s; }+#machines .ctl { display: flex; align-items: center; justify-content: flex-end; gap: 4px; flex: none; }+/* The machine on show: a check where its Show button would be. */+#machines .shown { display: inline-flex; align-items: center; justify-content: center; min-width: 28px; color: var(--accent); }+#machines .shown svg { width: 16px; height: 16px; }+/* The desktop's buttons are pills, as its toolbar's New Host is. */+#machines .pillbtn { flex: none; box-sizing: border-box; height: 28px; font: 500 13px var(--ui); color: var(--text); background: var(--ctl); border: 1px solid var(--btn-border); border-radius: 999px; padding: 0 13px; white-space: nowrap; transition: var(--fade); }+#machines .pillbtn:hover:not(:disabled) { background-color: var(--ctl-hover); }+/* The one action a question or the form exists for, filled as the desktop+ fills it: a step lighter on hover in the dark, a step darker in the light. */+#machines .pillbtn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }+#machines .pillbtn.primary:hover:not(:disabled) { background: color-mix(in srgb, var(--accent) 86%, var(--text)); border-color: transparent; }+#machines .pillbtn:disabled { opacity: .45; }+#machines .iconbtn { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border-radius: 999px; border: 0; background: transparent; color: var(--muted); transition: var(--fade); }+#machines .iconbtn:hover { background: var(--row-hover); color: var(--text); }+#machines .iconbtn svg { width: 15px; height: 15px; }+/* What a machine has under its row starts at its text. */+#machines .ask, #machines .fail, #machines .log, #machines .more { margin-left: 38px; }+#machines .ask { margin-top: 10px; margin-bottom: 4px; padding: 12px 14px; border-radius: 12px; background: var(--row-hover); }+#machines .ask-title { display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text); overflow-wrap: anywhere; }+#machines .ask-title svg { width: 16px; height: 16px; flex: none; color: var(--warn); }+#machines .hint { margin-top: 6px; color: var(--muted); font-size: 13px; line-height: 1.4; white-space: pre-wrap; overflow-wrap: anywhere; }+#machines .detail, #machines .log { padding: 8px 10px; border-radius: 8px; background: var(--bg); border: 1px solid var(--card-line); color: var(--text2); font: 12px/1.45 ui-monospace, "SF Mono", Menlo, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 160px; overflow-y: auto; }+#machines .detail { margin: 10px 0 0 0; }+#machines .log { margin-top: 0; margin-bottom: 4px; }+#machines .btns { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }+#machines .ask .btns, #machines .ask .foot { margin-top: 12px; }+#machines .foot { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; }+#machines .ask .foot .btns { margin: 0 0 0 auto; }+#machines .field, #machines form.add input { display: block; width: 100%; min-width: 0; box-sizing: border-box; height: 28px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--btn-border); background: var(--ctl); color: var(--text); font: 400 14px var(--ui); outline: none; transition: var(--fade); }+#machines .field { margin-top: 10px; }+#machines .field:focus, #machines form.add input:focus { border-color: var(--accent); }+#machines .field::placeholder, #machines form.add input::placeholder { color: var(--muted); }+#machines .check { display: inline-flex; align-items: center; gap: 8px; color: var(--text2); font-size: 13px; cursor: default; }+#machines .switch { position: relative; display: inline-block; width: 40px; height: 24px; flex: none; }+#machines .switch input { position: absolute; inset: 0; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: default; }+#machines .switch .knob { position: absolute; inset: 0; border-radius: 999px; background: rgba(118,118,128,.32); transition: background .15s; pointer-events: none; }+#machines .switch .knob::after { content: ""; position: absolute; top: 2px; left: 2px; width: 20px; height: 20px; border-radius: 999px; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.4); transition: transform .15s; }+#machines .switch input:checked + .knob { background: var(--accent); }+#machines .switch input:checked + .knob::after { transform: translateX(16px); }+#machines .switch input:focus-visible + .knob { box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 35%, transparent); }+/* A failure reads on from the row's own state line. */+#machines .fail .hint { margin: 8px 0 0 0; }+#machines .fail .btns { justify-content: flex-start; margin-top: 10px; }+/* Details: a disclosure, its chevron on the text's edge. */+#machines .more { display: inline-flex; align-items: center; gap: 4px; margin-top: 8px; margin-bottom: 4px; padding: 2px 6px 2px 0; border: 0; border-radius: 6px; background: transparent; color: var(--muted); font: 500 12px var(--ui); transition: var(--fade); }+#machines .more:hover { color: var(--text); }+#machines .more svg { width: 13px; height: 13px; transition: transform .15s; }+#machines .more.open svg { transform: rotate(90deg); }+/* The desktop's empty page: its server glyph over the one line. */+#machines .empty { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 28px 24px 34px 24px; color: var(--muted); font-size: 13px; line-height: 1.4; text-align: center; }+#machines .empty svg { width: 28px; height: 28px; stroke-width: 1.6; }+#machines .err { margin: -8px 2px 16px 2px; color: var(--danger); font-size: 12px; }+#machines .addbtn { display: inline-flex; align-items: center; gap: 6px; padding: 0 14px 0 11px; }+#machines .addbtn svg { width: 14px; height: 14px; }+/* The inspector: the host's name as its heading and where it connects under+ it, then the Connection card of labelled fields (label over input, Host+ beside a narrow Port), then the way through. */+#machines form.add { flex: 0 0 min(240px, 60%); box-sizing: border-box; display: flex; flex-direction: column; padding: 12px 0 16px 0; scroll-margin: 12px 0; }+#machines .ihead { padding: 2px 4px 12px 4px; min-width: 0; }+#machines .ititle { font-size: 16px; font-weight: 600; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#machines .iend { margin-top: 3px; color: var(--muted); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+#machines form.add .card { display: flex; flex-direction: column; gap: 9px; padding: 12px 14px 14px 14px; margin-bottom: 12px; background: var(--card); border: 1px solid var(--card-border); border-radius: 18px; }+#machines .cap { color: var(--text2); font-size: 13px; font-weight: 600; }+#machines .pair { display: flex; gap: 8px; }+#machines .fld { display: flex; flex-direction: column; gap: 4px; flex: 1 1 0; min-width: 0; }+#machines .fld.port { flex: 0 0 72px; }+#machines .fld > span { color: var(--muted); font-size: 13px; }+#machines form.add .btns { flex: none; }+/* Too narrow for the inspector beside the grid: the form goes over it,+ and the page scrolls as one. */+@media (max-width: 720px) {+ #machines { flex-direction: column; gap: 0; overflow-y: auto; }+ #machines .lists { flex: none; }+ #machines .body, #machines form.add { overflow: visible; -webkit-mask-image: none; mask-image: none; }+ #machines form.add { order: -1; flex: none; padding: 12px 0 4px 0; }+}+@media (prefers-reduced-motion: reduce) {+ #machines .dot.busy { animation: none; }+}/* Focus lives here so the IME composes into a real text field; thefield itself stays out of sight. */#kbd { position: fixed; left: 0; top: 0; width: 1px; height: 1px; opacity: 0; border: 0; padding: 0; margin: 0; resize: none; overflow: hidden; pointer-events: none; }@@ -519,18 +763,76 @@ body[data-mobile] canvas#term { touch-action: none; -webkit-tap-highlight-color:body[data-mobile] #tabs {height: calc(var(--tabs) + var(--safe-t));padding: calc(2px + var(--safe-t)) calc(8px + var(--safe-r)) 0 calc(8px + var(--safe-l));- gap: 7px; -webkit-overflow-scrolling: touch; overscroll-behavior-x: contain;+ /* The row itself stands still: its strip scrolls (below). */+ overflow: hidden;+}+/* The capsules scroll in a strip of their own, the whole width of the row,+ under the two buttons at its ends, which stay where they are: nothing+ they are in moves. Room is left at either end for the capsules to come+ out from under them. No -webkit-overflow-scrolling: iOS scrolls with+ momentum anyway, and that property makes its box a stacking context in+ WebKit -- on the row, it kept the drawers' buttons under the drawers. */+body[data-mobile] #tabs .strip {+ position: absolute; left: 0; right: 0; top: calc(2px + var(--safe-t)); bottom: 0;+ display: flex; align-items: center; gap: 7px; box-sizing: border-box;+ padding-left: calc(8px + var(--safe-l) + 38px + 7px);+ overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: none; white-space: nowrap;}+body[data-mobile] #tabs .strip::-webkit-scrollbar { display: none; }+/* The room at the end, as an item: a scroller's end padding is not always+ counted in what it scrolls. */+body[data-mobile] #tabs .strip::after { content: ''; flex: 0 0 calc(8px + var(--safe-r) + 38px); height: 1px; }body[data-mobile] #term, body[data-mobile] #panes { top: calc(var(--tabs) + var(--safe-t)); }+/* While the soft keyboard comes or goes, the canvas rides with the key bar+ until it is cut to the new height (--term-shift, KeyBar.svelte), so its+ last row stays on the bar's edge. What rides up past its own top is cut+ off rather than drawn over the tab row, which cannot be lifted above it:+ a z-index there would trap the drawers' buttons under the drawers. The+ top pane's bar stays under the tab row, as it will be once the canvas is+ cut; the bars and dividers lower down ride with the rows they belong to.+ `translate`, not `transform`: a divider's own transform centres it. */+body[data-mobile] #term {+ translate: 0 var(--term-shift, 0px);+ clip-path: inset(max(0px, calc(-1 * var(--term-shift, 0px))) 0 0 0);+}+body[data-mobile] #panes .nav.lower, body[data-mobile] #panes .grip { translate: 0 var(--term-shift, 0px); }body[data-mobile] #term, body[data-mobile] #panes { height: calc(var(--vvh, 100%) - var(--tabs) - var(--safe-t) - var(--keybar)); }/* A capsule takes what its title needs, up to under half the screen, sotwo or three tabs share a 390px row instead of one 150px box pushing therest off the edge; the same rule the pane capsules got below. */-body[data-mobile] #tabs .tab { height: 36px; flex: 0 1 auto; width: auto; min-width: 88px; max-width: min(150px, 44vw); padding: 0 6px 0 10px; }+/* A capsule on a phone, in either row, is as wide as its title needs+ between the same two bounds (--cap-min, --cap-max): the tab row keeps+ its titles and scrolls sideways rather than squeezing them to three+ letters, and a pane's capsule no longer runs the width of the screen. */+body[data-mobile] { --cap-min: 128px; --cap-max: min(200px, 56vw); }+body[data-mobile] #tabs .tab { height: 36px; flex: 0 0 auto; width: auto; min-width: var(--cap-min); max-width: var(--cap-max); padding: 0 6px 0 10px; }+body[data-mobile] #tabs .tab .ticon { margin-left: -8px; }/* The drawer toggle and the trailing buttons stay put while the capsulesscroll under them, so neither end is ever out of reach. */-body[data-mobile] #tabs [data-action=sidebar] { position: sticky; left: 0; background: var(--bg); box-shadow: 4px 0 6px -2px var(--bg); }-body[data-mobile] #tabs .trail { position: sticky; right: 0; margin-left: auto; padding-left: 6px; background: var(--bg); box-shadow: -4px 0 6px -2px var(--bg); z-index: 1; }+/* The two ends float over the tabs, which slide under them: round+ buttons on a frosted ground with a shadow, not a strip of the bar's+ colour. */+body[data-mobile] #tabs [data-action=sidebar],+body[data-mobile] #tabs .trail .act {+ background: color-mix(in srgb, var(--ctl) 78%, transparent);+ border-color: var(--ctl-border);+ -webkit-backdrop-filter: blur(12px) saturate(1.4); backdrop-filter: blur(12px) saturate(1.4);+ box-shadow: 0 1px 3px rgba(0,0,0,.22);+}+/* The two buttons, fixed at the row's ends over the strip. Each sits on a+ short fade of the bar's ground, so a tab passing under it dissolves+ there instead of running into it: the fade starts under the button and+ reaches only a little past it. */+body[data-mobile] #tabs .lead, body[data-mobile] #tabs .trail {+ position: absolute; top: calc(2px + var(--safe-t)); bottom: 0; display: inline-flex; align-items: center; margin: 0;+}+body[data-mobile] #tabs .lead { left: calc(8px + var(--safe-l)); z-index: 18; }+body[data-mobile] #tabs .trail { right: calc(8px + var(--safe-r)); z-index: 2; padding: 0; background: transparent; }+body[data-mobile] #tabs .lead::before, body[data-mobile] #tabs .trail::before {+ content: ''; position: absolute; top: 0; bottom: 0; z-index: -1; pointer-events: none;+}+body[data-mobile] #tabs .lead::before { left: calc(-8px - var(--safe-l)); right: -10px; background: linear-gradient(to right, var(--bg) calc(100% - 28px), transparent); }+body[data-mobile] #tabs .trail::before { right: calc(-8px - var(--safe-r)); left: -10px; background: linear-gradient(to left, var(--bg) calc(100% - 28px), transparent); }body[data-mobile] .act { width: 38px; height: 38px; }/* A close button between two capsules is easy to hit by mistake; on aphone it is only on the tab in front, and big enough to mean it. */@@ -543,8 +845,15 @@ body[data-mobile] .nav .act[data-action=split-right],body[data-mobile] .nav .act[data-action=split-below] { display: none; }/* The pane's own capsule has the width the tab row's has not: a 160px boxon a 390px screen left two thirds of the bar empty. */-body[data-mobile] .nav .cap { width: auto; flex: 1 1 auto; min-width: 0; max-width: 100%; }+body[data-mobile] .nav .cap { width: auto; flex: 0 1 auto; min-width: min(var(--cap-min), 100%); max-width: var(--cap-max); height: 36px; padding: 0 6px 0 10px; }+body[data-mobile] .nav .cap .ticon { margin-left: -8px; }body[data-mobile] .nav .acts .act { width: 40px; height: 40px; }+/* A split's divider on a phone: a short pill on the line, where a finger+ takes hold of it (touch.ts). Only a mark: the press goes to the canvas. */+.grip { position: absolute; width: 24px; transform: translate(-50%, -50%); pointer-events: auto; touch-action: none; z-index: 1; }+.grip.across { height: 24px; }+.grip::after { content: ''; position: absolute; left: 50%; top: 50%; width: 4px; height: 36px; transform: translate(-50%, -50%); border-radius: 999px; background: var(--muted); opacity: .7; }+.grip.across::after { width: 36px; height: 4px; }/* The two panels are drawers: over the canvas, resizing nothing, or notthere at all. */body[data-mobile] #side,@@ -557,7 +866,11 @@ body[data-mobile] #agents {box-shadow: 0 8px 28px rgba(0,0,0,.42);overscroll-behavior: contain;}+/* The left one is the whole screen, the tab row included: a page of its+ own, as a phone's are, with the sidebar's button left where it was over+ it (it stays above everything) to put it away again. */body[data-mobile] #side {+ top: 0; width: 100%; height: var(--vvh, 100%); z-index: 17; box-shadow: none; border-right: 0;padding-left: var(--safe-l);transform: translateX(-101%); visibility: hidden; pointer-events: none; will-change: transform;transition: transform .15s cubic-bezier(.4,0,1,1), visibility 0s linear .15s;@@ -571,6 +884,19 @@ body[data-mobile] #side.open {@keyframes drawer-in { from { transform: translateX(101%); } to { transform: translateX(0); } }body[data-mobile] #agents { animation: drawer-in .15s cubic-bezier(0,0,.2,1); }body[data-mobile] #agents { padding-right: var(--safe-r); }+/* The right one is the whole screen too, as the left is: its own button+ stays over it, top right, to put it away; the left one stands down. */+body[data-mobile] #agents {+ top: 0; width: 100%; height: var(--vvh, 100%); z-index: 17; box-shadow: none; border-left: 0; padding-bottom: var(--safe-b);+}+body[data-mobile] #agents .hd { top: calc(var(--tabs) + var(--safe-t)); padding: 4px calc(14px + var(--safe-r)) 0 14px; }+body[data-mobile] #agents .list { top: calc(110px + var(--tabs) + var(--safe-t)); left: 14px; right: calc(14px + var(--safe-r)); }+body[data-mobile] #agents .list.snippets, body[data-mobile] #agents .list.snippet-editor { top: calc(122px + var(--tabs) + var(--safe-t)); }+body[data-mobile]:has(#agents) #tabs .trail { z-index: 18; }+body[data-mobile]:has(#agents) #tabs .lead { visibility: hidden; }+/* Over the open drawer the button stands alone, without the bar's fade. */+body[data-mobile]:has(#side.open) #tabs .lead::before,+body[data-mobile]:has(#agents) #tabs .trail::before { display: none; }/* Their edges are dragged with a pointer, which a phone has not got. */body[data-mobile] #side .handle,body[data-mobile] #agents .handle { display: none; }@@ -584,14 +910,25 @@ body[data-mobile] #side .hdr { min-height: 36px; }body[data-mobile] #side .top .pill, body[data-mobile] #side .pill { height: 38px; }body[data-mobile] #side .act.round { width: 38px; height: 38px; }body[data-mobile] #side .act { width: 40px; height: 40px; }-body[data-mobile] #side .foot { height: 52px; left: 12px; right: 12px; }+body[data-mobile] #side .foot { height: 52px; left: 16px; right: calc(16px + var(--safe-r)); bottom: var(--safe-b); }+/* Settings keeps its word on a phone too: the 40px every footer button+ gets there is a square, and cut its label to one letter. */+body[data-mobile] #side .foot .act.lbl { width: auto; padding: 0 10px; }body[data-mobile] #side .foot .act { width: 40px; height: 40px; }-body[data-mobile] #side .list { inset: 12px 10px 52px 10px; }+body[data-mobile] #side .list { inset: calc(var(--tabs) + var(--safe-t) + 8px) calc(14px + var(--safe-r)) 56px 14px; }/* A finger has no hover, so a thread's pin and delete would never appear. */body[data-mobile] #side .hov { display: inline-flex; }body[data-mobile] #side .path input { padding: 9px 10px; }+body[data-mobile] #side .path select.on { padding: 9px 28px 9px 10px; font-size: 16px; }/* Behind whichever drawer is out: a press here puts it away. */#scrim { position: fixed; inset: 0; z-index: 14; background: rgba(0,0,0,.34); }+/* On a phone a drawer is what is on show: what is behind it goes dark+ enough not to read as part of it, the pane bars' buttons included. */+body[data-mobile] #scrim { background: rgba(0,0,0,.6); }+/* The key bar types into the terminal: not while a drawer or the+ settings are over it. */+body:has(#scrim) #keybar, body:has(#settings) #keybar { display: none; }+body[data-mobile] #side { padding-bottom: var(--safe-b); box-sizing: border-box; }/* A menu row a finger can hit, clear of the corners and the indicator. */body[data-mobile] .menu {min-width: 200px; padding: 6px;@@ -607,37 +944,109 @@ body[data-mobile] #palette {body[data-mobile] #palette .pl { max-height: none; flex: 1 1 auto; }body[data-mobile] #palette .pe { height: 44px; }body[data-mobile] #palette .st { display: none; }-/* The settings window has no room for its 220px nav column beside the- cards: on a phone it fills the window and the sections become a strip- of chips over one column of rows. */+/* The settings on a phone are two pages, as a phone's own are: the+ sections as a list of rows (`listing`), then the one picked, full width,+ with the way back at its top. Nothing of the other page shows. */body[data-mobile] #settings {left: 0; top: 0; --settings-tf: translate(0, 0); transform: var(--settings-tf); width: 100%;- height: calc(var(--vvh, 100%) - var(--keybar));+ height: var(--vvh, 100%);border-radius: 0; border: 0; flex-direction: column;}+body[data-mobile] #settings.listing .body { display: none; }+body[data-mobile] #settings:not(.listing) .snav { display: none; }body[data-mobile] #settings .snav {- flex: none; padding: calc(var(--safe-t) + 10px) calc(12px + var(--safe-r)) 10px calc(12px + var(--safe-l));- border-right: 0; border-bottom: 1px solid var(--sep);+ flex: 1 1 auto; width: auto; min-height: 0; overflow-y: auto;+ padding: calc(var(--safe-t) + 16px) calc(16px + var(--safe-r)) 24px calc(16px + var(--safe-l));+ border-right: 0;}-body[data-mobile] #settings .app { padding: 0 2px 10px 2px; font-size: 16px; }+body[data-mobile] #settings .app { padding: 4px 4px 16px 4px; font-size: 26px; }body[data-mobile] #settings .find { display: none; }body[data-mobile] #settings .secs {- flex-direction: row; margin-top: 0; gap: 6px;- overflow-x: auto; scrollbar-width: none; padding-bottom: 2px;-}-body[data-mobile] #settings .secs::-webkit-scrollbar { display: none; }-body[data-mobile] #settings .sec { flex: 0 0 auto; height: 38px; border-radius: 999px; background: var(--ctl); }-body[data-mobile] #settings .sec.on { background: var(--row-sel); }-body[data-mobile] #settings .body { padding: 18px calc(14px + var(--safe-r)) 24px calc(14px + var(--safe-l)); }-body[data-mobile] #settings .title { font-size: 20px; margin-bottom: 14px; }+ flex-direction: column; margin-top: 0; gap: 0; padding: 0;+ background: var(--card); border: 1px solid var(--card-border); border-radius: 14px; overflow: hidden;+}+body[data-mobile] #settings .sec { height: 52px; padding: 0 14px; gap: 12px; border-radius: 0; background: transparent; box-shadow: none; border-bottom: 1px solid var(--card-line); }+body[data-mobile] #settings .sec:last-child { border-bottom: 0; }+body[data-mobile] #settings .sec .sl { flex: 1 1 auto; font-size: 16px; }+body[data-mobile] #settings .sec::after { content: '›'; color: var(--muted); font-size: 22px; line-height: 1; }+body[data-mobile] #settings .sec.on { background: transparent; }+body[data-mobile] #settings .back { display: inline-flex; align-items: center; gap: 6px; height: 36px; margin: 0 0 6px -6px; padding: 0 8px; border: 0; border-radius: 8px; background: transparent; color: var(--accent); font: 500 16px var(--ui); }+body[data-mobile] #settings .back svg { width: 18px; height: 18px; }+body[data-mobile] #settings .body { padding: calc(var(--safe-t) + 8px) calc(14px + var(--safe-r)) 24px calc(14px + var(--safe-l)); }+body[data-mobile] #settings .title { font-size: 24px; margin-bottom: 14px; }body[data-mobile] #settings .card { padding: 0 14px; }-/* Label over control, so a description never squeezes into one word a line. */-body[data-mobile] #settings .srow { flex-direction: column; align-items: stretch; gap: 10px; padding: 14px 0; }-body[data-mobile] #settings .ctl { justify-content: flex-start; flex-wrap: wrap; }+/* A row says what it is in a line or two of small print, not a paragraph+ that pushes its control off the screen. */+body[data-mobile] #settings .desc { font-size: 13px; line-height: 17px; color: var(--muted); }+body[data-mobile] #settings .seg .sg { padding: 0 10px; font-size: 13px; }+/* The square, the label and a switch share the first line; any other+ control goes under the text, in the text's column, so a description+ never squeezes into one word a line. */+/* A row is one line, as a phone's own settings are: the square and the+ name on the left, the value -- a switch, or what is chosen, in grey with+ its chevron -- on the right. The paragraph that explains a row on the+ desktop does not fit beside it, and goes. A control too wide for the+ line (the font size's) takes the line under the name. */+body[data-mobile] #settings .srow { display: flex; flex-wrap: wrap; align-items: center; column-gap: 12px; row-gap: 10px; min-height: 50px; padding: 8px 0; box-sizing: border-box; }+body[data-mobile] #settings .srow > .tx { flex: 1 1 0; min-width: 0; }+body[data-mobile] #settings .srow .desc { display: none; }+body[data-mobile] #settings .srow .lab { font-size: 16px; font-weight: 500; }+body[data-mobile] #settings .srow > .pillsel {+ flex: 0 1 auto; min-width: 0; max-width: 58%; height: 36px; padding: 0 30px 0 6px;+ background-color: transparent; border-color: transparent; color: var(--muted); font-size: 15px; text-align: right; text-align-last: right;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+/* The panel cards are rows here too: the square, the name, the switch. */+body[data-mobile] #settings .pcards { grid-template-columns: 1fr; gap: 8px; }+body[data-mobile] #settings .pcard { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; column-gap: 12px; padding: 9px 14px; min-height: 50px; box-sizing: border-box; }+body[data-mobile] #settings .pcard .phead { display: contents; }+body[data-mobile] #settings .pcard .tile { grid-area: 1 / 1; width: 28px; height: 28px; border-radius: 7px; }+body[data-mobile] #settings .pcard .tile svg { width: 16px; height: 16px; }+body[data-mobile] #settings .pcard .lab { grid-area: 1 / 2; font-size: 16px; font-weight: 500; }+body[data-mobile] #settings .pcard .switch { grid-area: 1 / 3; }+body[data-mobile] #settings .pcard .desc { display: none; }+body[data-mobile] #settings .srow > .ctl { flex: 1 0 100%; padding-left: 40px; box-sizing: border-box; justify-content: flex-start; flex-wrap: wrap; }+body[data-mobile] #settings .stepper.off, body[data-mobile] #settings .reset:disabled { display: none; }+/* About keeps its lines whole: a long version wraps rather than being+ cut, and Copy goes under the name. */+body[data-mobile] #settings .hero { display: grid; grid-template-columns: 54px minmax(0, 1fr); gap: 12px; padding: 14px; }+body[data-mobile] #settings .hero .pillbtn { grid-column: 2; justify-self: start; }+body[data-mobile] #settings .hero .sl { white-space: normal; overflow-wrap: anywhere; }+body[data-mobile] #settings .facts { padding: 6px 14px; }+body[data-mobile] #settings .srow.fact { display: flex; padding: 7px 0; }+body[data-mobile] #settings .fact .val { white-space: normal; overflow-wrap: anywhere; }body[data-mobile] #settings .pillsel, body[data-mobile] #settings .pillbtn,-body[data-mobile] #settings .seg, body[data-mobile] #settings .stepper { height: 38px; }+body[data-mobile] #settings .seg, body[data-mobile] #settings .stepper { height: 36px; }body[data-mobile] #settings .pillsel { flex: 1 1 auto; min-width: 0; }body[data-mobile] #settings .sc { top: calc(var(--safe-t) + 10px); right: calc(10px + var(--safe-r)); width: 40px; height: 40px; }+/* The Remote Hosts page has the terminal's place on a phone too, under+ the tab row, and the key bar's as well: those keys type into the+ terminal, which is behind it. It scrolls as one, with controls a thumb+ can hit; a card takes the full width, its address and state wrap rather+ than being cut, and the form goes over the list. */+body[data-mobile] #machines {+ top: calc(var(--tabs) + var(--safe-t)); bottom: auto; height: calc(var(--vvh, 100%) - var(--tabs) - var(--safe-t));+ padding: 0 calc(12px + var(--safe-r)) var(--safe-b) calc(12px + var(--safe-l));+ flex-direction: column; gap: 0; overflow-y: auto;+}+body[data-page] #keybar { display: none; }+body[data-mobile] #machines .lists { flex: none; }+body[data-mobile] #machines .find { flex: 1 1 auto; height: 38px; }+body[data-mobile] #machines .find input { font-size: 16px; }+body[data-mobile] #machines .body, body[data-mobile] #machines form.add { overflow: visible; -webkit-mask-image: none; mask-image: none; }+body[data-mobile] #machines .body { padding: 12px 0 24px 0; }+body[data-mobile] #machines form.add { order: -1; flex: none; padding: 12px 0 4px 0; }+body[data-mobile] #machines .grid { grid-template-columns: 1fr; }+body[data-mobile] #machines .hcard { padding: 12px; }+body[data-mobile] #machines .desc { white-space: normal; overflow-wrap: break-word; }+/* Each part whole: a line breaks between an address and its state. */+body[data-mobile] #machines .desc > span { display: inline-block; }+body[data-mobile] #machines form.add .card { padding: 14px; }+body[data-mobile] #machines .pillbtn { height: 38px; }+body[data-mobile] #machines .iconbtn { width: 38px; height: 38px; }+body[data-mobile] #machines .field, body[data-mobile] #machines form.add input { height: 40px; font-size: 16px; }+body[data-mobile] #machines .ask, body[data-mobile] #machines .fail, body[data-mobile] #machines .log, body[data-mobile] #machines .more { margin-left: 0; }+body[data-mobile] #machines .more, body[data-mobile] #machines .check { min-height: 38px; }/* The remark and the takeover card sit clear of the key bar. */body[data-mobile] #status {right: calc(10px + var(--safe-r)); left: calc(10px + var(--safe-l)); max-width: none;@@ -652,23 +1061,44 @@ body[data-mobile] #card .go { height: 38px; }leaves room for. */#keybar {position: fixed; left: 0; right: 0; z-index: 16; box-sizing: border-box;- height: calc(52px + env(safe-area-inset-bottom, 0px));- padding: 0 6px env(safe-area-inset-bottom, 0px) 6px;- display: flex; align-items: center; gap: 5px;- background: var(--ctl); border-top: 1px solid var(--ctl-border);- overflow-x: auto; overflow-y: hidden; white-space: nowrap; overscroll-behavior-x: contain;- scrollbar-width: none; user-select: none; -webkit-user-select: none; touch-action: manipulation;+ height: calc(62px + env(safe-area-inset-bottom, 0px));+ padding: 4px calc(18px + var(--safe-r, 0px)) calc(12px + env(safe-area-inset-bottom, 0px)) calc(18px + var(--safe-l, 0px));+ background: transparent;+ user-select: none; -webkit-user-select: none; touch-action: manipulation;-webkit-tap-highlight-color: transparent;}-#keybar::-webkit-scrollbar { display: none; }+/* What shows around the bar, and under the home indicator, is the+ terminal's ground (--term-bg, from KeyBar.svelte), not a strip of the+ page's colour: the capsule floats on the terminal. The rows still end+ above it, so nothing typed is ever under it. */+body[data-mobile] { background: var(--term-bg, var(--bg)); }+/* A capsule floating over the foot of the screen, as rounded as a phone's+ own corners: frosted glass the terminal's ground shows through, with a+ shadow, the keys pills inside it. */+#keybar .pill {+ height: 100%; box-sizing: border-box; display: flex; align-items: center; gap: 4px; padding: 0 5px;+ border-radius: 999px; border: 1px solid var(--ctl-border);+ background: color-mix(in srgb, var(--ctl) 55%, transparent);+ -webkit-backdrop-filter: blur(16px) saturate(1.4); backdrop-filter: blur(16px) saturate(1.4);+ box-shadow: 0 6px 22px rgba(0,0,0,.4);+}+/* The keys scroll; the keyboard's button before them does not. */+#keybar .keys {+ flex: 1 1 auto; min-width: 0; height: 100%; display: flex; align-items: center; gap: 4px; padding-right: 10px;+ overflow-x: auto; overflow-y: hidden; white-space: nowrap; overscroll-behavior-x: contain; scrollbar-width: none;+ -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 18px), transparent); mask-image: linear-gradient(to right, #000 calc(100% - 18px), transparent);+}+#keybar .keys::-webkit-scrollbar { display: none; }#keybar .k {- flex: 0 0 auto; min-width: 44px; height: 44px; margin: 0; padding: 0 10px;+ flex: 0 0 auto; min-width: 40px; height: 34px; margin: 0; padding: 0 9px;display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box;- border-radius: 10px; border: 1px solid var(--ctl-border); background: var(--ctl-hover);- color: var(--text); font: 500 14px var(--ui);+ border-radius: 999px; border: 0; background: transparent;+ color: var(--text2); font: 500 13px var(--ui);touch-action: manipulation; -webkit-tap-highlight-color: transparent; -webkit-user-select: none; user-select: none;}-#keybar .k:active { background: var(--ctl-pressed); }+#keybar .k.kbd { min-width: 48px; background: color-mix(in srgb, var(--ctl-hover) 75%, transparent); color: var(--text); }+#keybar .k.kbd svg { width: 20px; height: 20px; pointer-events: none; }+#keybar .k:active { background: var(--ctl-pressed); color: var(--text); }/* An armed modifier: it is spent on the next key, from here or from thesoft keyboard. The ring says so from across the bar, not only the fill. */#keybar .k.armed {@@ -681,12 +1111,85 @@ body[data-mobile] #card .go { height: 38px; }body[data-mobile] { --tabs: 40px; }body[data-mobile] #tabs .tab { height: 30px; }body[data-mobile] .act { width: 32px; height: 32px; }- #keybar { height: calc(44px + env(safe-area-inset-bottom, 0px)); }- #keybar .k { height: 36px; min-width: 40px; }- body[data-mobile] #settings .srow { flex-direction: row; align-items: center; gap: 14px; }+ #keybar { height: calc(48px + env(safe-area-inset-bottom, 0px)); padding-bottom: calc(4px + env(safe-area-inset-bottom, 0px)); }+ #keybar .k { height: 30px; min-width: 36px; }+ body[data-mobile] #settings .srow, body[data-mobile] #settings .hero { display: flex; align-items: center; gap: 12px; }body[data-mobile] #settings .pillsel { flex: none; min-width: 140px; }}+/* The boot screen (Boot.svelte): over everything until the client is+ attached, the app's mark and name centred a little above the middle, a+ thin bar under them and the step in small print. */+/* Black and white, and cold: a fine grid of dots fading out towards the+ edges, drifting; a soft patch of light wandering over it, waking the+ dots it passes; in the middle the mark, the name, a turning ring and+ the step in small print. */+#boot { --boot-ink: #fff; position: fixed; inset: 0; z-index: 60; display: flex; align-items: center; justify-content: center; overflow: hidden; background: #0b0b0c; color: #f2f2f2; font: 400 13px var(--ui); user-select: none; }+:root[data-theme=light] #boot { --boot-ink: #000; background: #f4f4f4; color: #111; }+/* The grid: fine, even dots on a 24px pitch, fading out well before the+ edges, drifting a little; over it the same grid brighter and a touch+ bigger, seen only where a soft light passes. */+#boot .dots {+ position: absolute; inset: -48px; pointer-events: none;+ background-image: radial-gradient(circle at center, color-mix(in srgb, var(--boot-ink) 13%, transparent) 0.9px, transparent 1.3px);+ background-size: 24px 24px;+ -webkit-mask-image: radial-gradient(ellipse 55% 50% at 50% 46%, #000 30%, transparent 100%); mask-image: radial-gradient(ellipse 55% 50% at 50% 46%, #000 30%, transparent 100%);+ animation: boot-drift 10s linear infinite;+}+#boot .dots.lit {+ background-image: radial-gradient(circle at center, color-mix(in srgb, var(--boot-ink) 75%, transparent) 1.2px, transparent 1.8px);+ -webkit-mask-image: radial-gradient(circle closest-side, rgba(0,0,0,.9), rgba(0,0,0,.35) 45%, transparent); mask-image: radial-gradient(circle closest-side, rgba(0,0,0,.9), rgba(0,0,0,.35) 45%, transparent);+ -webkit-mask-size: 520px 520px; mask-size: 520px 520px; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat;+ animation: boot-drift 10s linear infinite, boot-wander 6s ease-in-out infinite alternate;+}+@keyframes boot-drift { to { background-position: 24px 48px; } }+/* A ripple through the grid from the mark, every couple of seconds: a+ band of brighter dots running outwards and thinning as it goes. */+#boot .dots.wave {+ background-image: radial-gradient(circle at center, color-mix(in srgb, var(--boot-ink) 85%, transparent) 1.1px, transparent 1.7px);+ -webkit-mask-image: radial-gradient(circle closest-side, transparent 72%, #000 86%, transparent 100%); mask-image: radial-gradient(circle closest-side, transparent 72%, #000 86%, transparent 100%);+ -webkit-mask-position: 50% 44%; mask-position: 50% 44%; -webkit-mask-repeat: no-repeat; mask-repeat: no-repeat;+ animation: boot-drift 10s linear infinite, boot-ripple 2.4s cubic-bezier(.2,.6,.3,1) infinite;+}+@keyframes boot-ripple {+ from { -webkit-mask-size: 60px 60px; mask-size: 60px 60px; opacity: .9; }+ to { -webkit-mask-size: 1600px 1600px; mask-size: 1600px 1600px; opacity: 0; }+}+@keyframes boot-wander {+ 0% { -webkit-mask-position: 10% 20%; mask-position: 10% 20%; }+ 30% { -webkit-mask-position: 70% 10%; mask-position: 70% 10%; }+ 60% { -webkit-mask-position: 90% 75%; mask-position: 90% 75%; }+ 100% { -webkit-mask-position: 25% 90%; mask-position: 25% 90%; }+}+#boot .mid { position: relative; display: flex; flex-direction: column; align-items: center; margin-top: -4vh; padding: 0 28px; max-width: 420px; text-align: center; animation: boot-rise .9s cubic-bezier(.2,.8,.2,1) both; }+@keyframes boot-rise { from { opacity: 0; transform: translateY(8px); filter: blur(4px); } }+/* The ring goes round the mark: the start's only motion near the middle. */+#boot .orb { position: relative; width: 96px; height: 96px; display: flex; align-items: center; justify-content: center; }+#boot .mark { width: 64px; height: 64px; filter: drop-shadow(0 10px 22px rgba(0,0,0,.45)); }+:root[data-theme=light] #boot .mark { filter: drop-shadow(0 3px 6px rgba(0,0,0,.18)); }+#boot .name { margin-top: 10px; font-size: 21px; font-weight: 600; letter-spacing: .6px; }+/* A hairline ring turning, one arc of it bright. */+#boot .ring { position: absolute; inset: 0; border-radius: 50%; box-sizing: border-box; border: 2.5px solid color-mix(in srgb, var(--boot-ink) 10%, transparent); border-top-color: var(--boot-ink); animation: boot-turn 1.1s cubic-bezier(.55,.15,.45,.85) infinite; }+@keyframes boot-turn { to { transform: rotate(360deg); } }+/* The steps, as a terminal lists them: a fixed column for the mark, the+ step, and on the right what it took. Done ones go quiet, the tick in+ green with a little pop; the one under way is bright, its spinner too. */+#boot .log { margin-top: 18px; width: 188px; min-height: calc(3 * 15px + 2 * 5px); display: flex; flex-direction: column; gap: 5px; font: 400 12px ui-monospace, "SF Mono", Menlo, monospace; text-align: left; }+#boot .ln { display: grid; height: 15px; grid-template-columns: 16px 1fr auto; align-items: center; column-gap: 8px; color: color-mix(in srgb, var(--boot-ink) 88%, transparent); transition: color .4s; }+#boot .ln.done { color: color-mix(in srgb, var(--boot-ink) 45%, transparent); }+#boot .ln.bad { color: #ff6b6b; }+#boot .st { display: inline-flex; justify-content: center; }+#boot .tick { color: #3fd07a; animation: boot-pop .35s cubic-bezier(.2,1.6,.4,1) both; text-shadow: 0 0 8px rgba(63, 208, 122, .45); }+:root[data-theme=light] #boot .tick { color: #1a9f52; text-shadow: none; }+@keyframes boot-pop { from { transform: scale(.2); opacity: 0; } }+#boot .spin { width: 9px; height: 9px; border-radius: 50%; box-sizing: border-box; border: 1.5px solid color-mix(in srgb, var(--boot-ink) 22%, transparent); border-top-color: var(--boot-ink); animation: boot-turn .7s linear infinite; }+#boot .cross { color: #ff6b6b; }+#boot .t { font-size: 11px; opacity: .7; font-variant-numeric: tabular-nums; }+#boot .why { margin-top: 22px; font-size: 13px; line-height: 1.55; opacity: .75; overflow-wrap: anywhere; }+#boot .again { margin-top: 20px; height: 32px; padding: 0 18px; border-radius: 999px; border: 1px solid color-mix(in srgb, var(--boot-ink) 40%, transparent); background: transparent; color: inherit; font: 500 12px var(--ui); letter-spacing: 1px; }+#boot .again:active { background: color-mix(in srgb, var(--boot-ink) 10%, transparent); }+@media (prefers-reduced-motion: reduce) { #boot .dots, #boot .mid { animation: none; } #boot .ring { animation-duration: 2.4s; } }+/* A reader who has asked the system for less motion gets none of it: thepage still opens and closes exactly the same things. */@media (prefers-reduced-motion: reduce) {diff --git a/thinkterm-web/ui/src/touch.ts b/thinkterm-web/ui/src/touch.tsindex 44403fa6..815b77be 100644--- a/thinkterm-web/ui/src/touch.ts+++ b/thinkterm-web/ui/src/touch.ts@@ -14,6 +14,7 @@// the press began. At the anchor the selection is empty, which is the one// case its Up throws the selection away instead of copying it.+import { handle } from './client';import { openMenu } from './menu.svelte';import { focusTerminal, mobile, openSide } from './mobile.svelte';import { cellHeight, paneAt } from './pane';@@ -36,8 +37,10 @@ const PINCH_STEP = 48;type Finger = { x: number; y: number };-/** What the gesture turned out to be; `press` until it is decided. */-type Mode = 'press' | 'scroll' | 'menu';+/** What the gesture turned out to be; `press` until it is decided.+ `divider` is a finger that landed on a split's divider: the wasm drags+ it from there, with the pointer's own moves and release. */+type Mode = 'press' | 'scroll' | 'menu' | 'divider';export function installTouch(canvas: HTMLCanvasElement): () => void {const fingers = new Map<number, Finger>();@@ -199,6 +202,15 @@ export function installTouch(canvas: HTMLCanvasElement): () => void {// A finger on the glass stops whatever a fling was still scrolling.stopFling();fingers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });+ if (first === null && handle.client?.touch_divider(ev.clientX, ev.clientY)) {+ // Every move from here is the canvas's, even over a pane's bar.+ first = ev.pointerId;+ mode = 'divider';+ canvas.setPointerCapture(ev.pointerId);+ ev.stopImmediatePropagation();+ ev.preventDefault();+ return;+ }if (first === null) {first = ev.pointerId;startX = ev.clientX;@@ -239,6 +251,8 @@ export function installTouch(canvas: HTMLCanvasElement): () => void {if (!ev.isTrusted || ev.pointerType !== 'touch') return;if (!fingers.has(ev.pointerId)) return;fingers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });+ // The divider's drag is the wasm's: its move goes through.+ if (mode === 'divider') return;if (mode === 'menu') {ev.stopImmediatePropagation();return;@@ -278,6 +292,15 @@ export function installTouch(canvas: HTMLCanvasElement): () => void {const up = (ev: PointerEvent) => {if (!ev.isTrusted || ev.pointerType !== 'touch') return;if (!fingers.delete(ev.pointerId)) return;+ if (mode === 'divider') {+ // The release ends the wasm's drag; it goes through as it is.+ if (ev.pointerId === first) {+ first = null;+ mode = 'press';+ fingers.clear();+ }+ return;+ }// The wasm never saw this finger go down, so it must not see it come// up either; what it gets is the tap below, or nothing.ev.stopImmediatePropagation();diff --git a/thinkterm-web/ui/tests/machines.test.mjs b/thinkterm-web/ui/tests/machines.test.mjsnew file mode 100644index 00000000..cf028f41--- /dev/null+++ b/thinkterm-web/ui/tests/machines.test.mjs@@ -0,0 +1,198 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import vm from 'node:vm';+import { flushSync } from 'svelte';+import { compileModule } from 'svelte/compiler';+import * as runes from 'svelte/internal/client';+import ts from 'typescript';++// Exercise the actual state module with delayed sockets and clients. No+// DOM or mux server is needed to reproduce a superseded connection.+const path = new URL('../src/machines.svelte.ts', import.meta.url);+const plain = ts.transpileModule(readFileSync(path, 'utf8'), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },+}).outputText;+const compiled = compileModule(plain, { filename: 'machines.svelte.js', generate: 'client' }).js.code;++function deferred() {+ let resolve, reject;+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+}++function client() {+ return {+ freed: false,+ up: true,+ set_shown() {},+ close() {},+ free() { this.freed = true; },+ connected() { return this.up; },+ };+}++async function setup(start) {+ const clients = new Map();+ const handle = { client: null };+ const changes = [];+ const sockets = [];+ class Socket {+ constructor() { sockets.push(this); }+ close() { this.closed = true; }+ send() {}+ }+ const context = vm.createContext({+ window: { thinkterm: handle },+ localStorage: { getItem: () => null, setItem() {} },+ location: { protocol: 'https:', host: 'example' },+ WebSocket: Socket,+ setTimeout,+ });+ const dependencies = {+ 'svelte/internal/client': {+ ...runes,+ // Svelte only proxies objects from its own realm, not the VM's.+ proxy: (value) => runes.proxy(structuredClone(value)),+ },+ svelte: { flushSync },+ './client': { clients, handle },+ './client.svelte': {+ activate(next) { handle.client = next; },+ attach(_client, changed) { changes.push(changed); },+ refreshViews() {},+ s: (key) => key,+ },+ './mobile.svelte': { focusTerminal() {}, openSide() {} },+ };+ const module = new vm.SourceTextModule(compiled, { context });+ await module.link((name) => {+ const exports = dependencies[name];+ assert.ok(exports, `unexpected import ${name}`);+ return new vm.SyntheticModule(Object.keys(exports), function () {+ for (const [key, value] of Object.entries(exports)) this.setExport(key, value);+ }, { context });+ });+ await module.evaluate();+ const api = module.namespace;+ handle.client = client();+ api.configure({ start, prepare() {}, token: '' }, handle.client);+ return { api, clients, handle, changes, sockets };+}++test('switching machines moves the mounted panel subscription to the active client', async (t) => {+ const next = client();+ const { api, clients, handle } = await setup(async () => next);+ await api.connect('server-a', false);+ const calls = [];+ for (const [key, client] of clients) {+ client.set_right_panel_shown = (shown) => {+ assert.equal(client.freed, false);+ calls.push([key, shown]);+ };+ }+ // App's keyed block remounts the panel; its effect captures the handle.+ const destroy = runes.effect_root(() => runes.render_effect(() => {+ void api.machines.active;+ runes.effect(() => {+ const client = handle.client;+ client.set_right_panel_shown(true);+ return () => client.set_right_panel_shown(false);+ });+ }));+ t.after(destroy);+ flushSync();+ assert.deepEqual(calls, [[api.HERE, true]]);++ calls.length = 0;+ api.showMachine('server-a');+ assert.equal(handle.client, next);+ assert.deepEqual(calls, [[api.HERE, false], ['server-a', true]]);++ calls.length = 0;+ api.close('server-a');+ assert.equal(handle.client, clients.get(api.HERE));+ assert.deepEqual(calls, [['server-a', false], [api.HERE, true]]);+ assert.equal(next.freed, true);+});++test('an old start failure cannot fail the replacement connection', async () => {+ const pending = [];+ const { api, clients } = await setup(() => {+ const call = deferred();+ pending.push(call);+ return call.promise;+ });+ const first = api.connect('server-a', false);+ api.close('server-a');+ const second = api.connect('server-a', false);+ pending[0].reject(new Error('old connection closed'));+ await first;+ assert.equal(api.machines.open[0].state, 'connecting');+ const next = client();+ pending[1].resolve(next);+ await second;+ assert.equal(api.machines.open[0].state, 'ready');+ assert.equal(clients.get('server-a'), next);+});++test('close settles an opener even if the socket never emits close', async () => {+ const { api, sockets } = await setup(async (_canvas, _field, open) => {+ await open();+ return client();+ });+ const opening = api.connect('server-a', false);+ const oldMessage = sockets[0].onmessage;+ api.close('server-a');+ await opening;+ assert.equal(sockets[0].closed, true);+ assert.equal(api.machines.open.length, 0);++ const replacement = api.connect('server-a', false);+ oldMessage({ data: JSON.stringify({ op: 'failed', reason: 'declined', message: 'old failure' }) });+ assert.equal(api.machines.open[0].failure, null);+ sockets[1].onmessage({ data: JSON.stringify({ op: 'ready' }) });+ await replacement;+ assert.equal(api.machines.open[0].state, 'ready');+});++test('a retained opener cannot reconnect a closed generation', async () => {+ const pending = [];+ const { api, sockets } = await setup((_canvas, _field, open) => {+ const call = { ...deferred(), open };+ pending.push(call);+ return call.promise;+ });+ const first = api.connect('server-a', false);+ api.close('server-a');+ const second = api.connect('server-a', false);+ await assert.rejects(pending[0].open(), /closed/);+ assert.equal(sockets.length, 0);+ pending[0].reject(new Error('closed'));+ pending[1].resolve(client());+ await Promise.all([first, second]);+ assert.equal(api.machines.open[0].state, 'ready');+});++test('a retired view callback cannot update the new client', async () => {+ const { api, clients, changes } = await setup(async () => client());+ await api.connect('server-a', false);+ api.close('server-a');+ await api.connect('server-a', false);+ clients.get('server-a').up = false;+ changes[0]();+ assert.equal(api.machines.open[0].state, 'ready');+ changes[1]();+ assert.equal(api.machines.open[0].state, 'reconnecting');+});++test('asking to see a reconnecting machine shows it now, and leaves no flag behind', async () => {+ const { api, clients, handle, changes } = await setup(async () => client());+ await api.connect('server-a', false);+ clients.get('server-a').up = false;+ changes[0]();+ assert.equal(api.machines.open[0].state, 'reconnecting');+ await api.connect('server-a', true);+ assert.equal(handle.client, clients.get('server-a'));+ assert.equal(api.machines.open[0].showWhenReady, false);+});