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
Add a terminal-UI mux client and make the view follow the device in use
RoversXfcb9b9bc2e9c
diff --git a/Cargo.lock b/Cargo.lockindex f3903bff..7f6f8304 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -357,6 +357,15 @@ dependencies = ["openssl",]+[[package]]+name = "atomic"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340"+dependencies = [+ "bytemuck",+]+[[package]]name = "atomic-waker"version = "1.1.2"@@ -443,7 +452,7 @@ dependencies = ["config","luahelper","starship-battery",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -456,15 +465,30 @@ checksum = "6c335a9de639ba6a3e4107fe7763c9dcd4eb9422575f1191c2b8f2009f03fe4a"name = "bintree"version = "0.1.0"+[[package]]+name = "bit-set"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"+dependencies = [+ "bit-vec 0.6.3",+]+[[package]]name = "bit-set"version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"dependencies = [- "bit-vec",+ "bit-vec 0.8.0",]+[[package]]+name = "bit-vec"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"+[[package]]name = "bit-vec"version = "0.8.0"@@ -485,9 +509,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"[[package]]name = "bitflags"-version = "2.10.0"+version = "2.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"dependencies = ["serde_core",]@@ -602,7 +626,7 @@ version = "0.18.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","cairo-sys-rs","libc","once_cell",@@ -635,6 +659,15 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"+[[package]]+name = "castaway"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"+dependencies = [+ "rustversion",+]+[[package]]name = "cc"version = "1.2.67"@@ -831,7 +864,7 @@ dependencies = ["rangeset","serde","smol",- "termwiz",+ "termwiz 0.24.0","thiserror 1.0.69","varbincode","wezterm-term",@@ -866,8 +899,8 @@ dependencies = ["serde","serde_json","serde_yaml",- "wezterm-color-types",- "wezterm-dynamic",+ "wezterm-color-types 0.3.0",+ "wezterm-dynamic 0.2.1","wezterm-term",]@@ -902,6 +935,20 @@ dependencies = ["csscolorparser",]+[[package]]+name = "compact_str"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"+dependencies = [+ "castaway",+ "cfg-if",+ "itoa",+ "rustversion",+ "ryu",+ "static_assertions",+]+[[package]]name = "concurrent-queue"version = "2.5.0"@@ -937,18 +984,27 @@ dependencies = ["shlex 1.3.0","smol","tempfile",- "termwiz",+ "termwiz 0.24.0","toml 0.8.23","umask",- "wezterm-bidi",+ "wezterm-bidi 0.2.3","wezterm-config-derive",- "wezterm-dynamic",- "wezterm-input-types",+ "wezterm-dynamic 0.2.1",+ "wezterm-input-types 0.1.0","wezterm-ssh","wezterm-term","winapi",]+[[package]]+name = "convert_case"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"+dependencies = [+ "unicode-segmentation",+]+[[package]]name = "core-foundation"version = "0.9.4"@@ -994,7 +1050,7 @@ version = "0.24.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","core-foundation 0.10.0","core-graphics-types 0.2.0","foreign-types 0.5.0",@@ -1018,7 +1074,7 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","core-foundation 0.10.0","libc",]@@ -1154,6 +1210,33 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+[[package]]+name = "crossterm"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"+dependencies = [+ "bitflags 2.13.1",+ "crossterm_winapi",+ "derive_more",+ "document-features",+ "mio 1.1.0",+ "parking_lot",+ "rustix 1.1.2",+ "signal-hook",+ "signal-hook-mio",+ "winapi",+]++[[package]]+name = "crossterm_winapi"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"+dependencies = [+ "winapi",+]+[[package]]name = "crunchy"version = "0.2.4"@@ -1192,8 +1275,18 @@ version = "0.20.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"dependencies = [- "darling_core",- "darling_macro",+ "darling_core 0.20.11",+ "darling_macro 0.20.11",+]++[[package]]+name = "darling"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"+dependencies = [+ "darling_core 0.23.0",+ "darling_macro 0.23.0",][[package]]@@ -1210,13 +1303,37 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "darling_core"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.110",+]+[[package]]name = "darling_macro"version = "0.20.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"dependencies = [- "darling_core",+ "darling_core 0.20.11",+ "quote",+ "syn 2.0.110",+]++[[package]]+name = "darling_macro"+version = "0.23.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"+dependencies = [+ "darling_core 0.23.0","quote","syn 2.0.110",]@@ -1247,14 +1364,36 @@ checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4"[[package]]name = "deranged"-version = "0.5.5"+version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"dependencies = ["powerfmt","serde_core",]+[[package]]+name = "derive_more"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"+dependencies = [+ "convert_case",+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.110",+]+[[package]]name = "dhat"version = "0.3.3"@@ -1320,7 +1459,7 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "89a09f22a6c6069a18470eb92d2298acf25463f14256d24778e1230d789a2aec"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","objc2",]@@ -1491,7 +1630,7 @@ dependencies = ["share-data","spawn-funcs","ssh-funcs",- "termwiz",+ "termwiz 0.24.0","termwiz-funcs","time-funcs","url-funcs",@@ -1651,13 +1790,23 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+[[package]]+name = "fancy-regex"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b95f7c0680e4142284cf8b22c14a476e87d61b004a3a0861872b32ef7ead40a2"+dependencies = [+ "bit-set 0.5.3",+ "regex",+]+[[package]]name = "fancy-regex"version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298"dependencies = [- "bit-set",+ "bit-set 0.8.0","regex-automata","regex-syntax",]@@ -1706,6 +1855,17 @@ dependencies = ["winapi",]+[[package]]+name = "filedescriptor"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"+dependencies = [+ "libc",+ "thiserror 1.0.69",+ "winapi",+]+[[package]]name = "filenamegen"version = "0.2.7"@@ -1752,6 +1912,12 @@ name = "finl_unicode"version = "1.3.0"source = "git+https://github.com/wez/finl_unicode.git?branch=no_std#a1892f26245529f2ef3877a9ebd610c96cec07a6"+[[package]]+name = "finl_unicode"+version = "1.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9844ddc3a6e533d62bba727eb6c28b5d360921d5175e9ff0f1e621a5c590a4d5"+[[package]]name = "fixed"version = "1.29.0"@@ -2128,7 +2294,7 @@ version = "0.20.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2deb07a133b1520dc1a5690e9bd08950108873d7ed5de38dcc74d3b5ebffa110"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","libc","libgit2-sys","log",@@ -2186,7 +2352,7 @@ version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0bf760ebf69878d9fd8f110c89703d90ce35095324d1f1edcb595c63945ee757"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","ignore","walkdir",]@@ -2233,7 +2399,7 @@ version = "0.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fbcd2dba93594b227a1f57ee09b8b9da8892c34d55aa332e034a228d0fe6a171"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","gpu-alloc-types",]@@ -2243,7 +2409,7 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "98ff03b468aa837d70984d55f5d3f846f6ec31fe34bbb97c4f85219caeee1ca4"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1",][[package]]@@ -2264,7 +2430,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","gpu-descriptor-types","hashbrown 0.15.5",]@@ -2275,7 +2441,7 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1",][[package]]@@ -2805,6 +2971,15 @@ dependencies = ["hashbrown 0.16.0",]+[[package]]+name = "indoc"+version = "2.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"+dependencies = [+ "rustversion",+]+[[package]]name = "inotify"version = "0.9.6"@@ -2825,6 +3000,19 @@ dependencies = ["libc",]+[[package]]+name = "instability"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971"+dependencies = [+ "darling 0.23.0",+ "indoc",+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "interpolate_name"version = "0.2.4"@@ -2926,6 +3114,15 @@ dependencies = ["either",]+[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]+[[package]]name = "itoa"version = "1.0.15"@@ -2999,6 +3196,17 @@ dependencies = ["terminal_size",]+[[package]]+name = "kasuari"+version = "0.4.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fe90c1150662e858c7d5f945089b7517b0a80d8bf7ba4b1b5ffc984e7230a5b"+dependencies = [+ "hashbrown 0.16.0",+ "portable-atomic",+ "thiserror 2.0.17",+]+[[package]]name = "khronos-egl"version = "6.0.0"@@ -3164,7 +3372,7 @@ version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","libc","redox_syscall",]@@ -3231,6 +3439,15 @@ dependencies = ["vcpkg",]+[[package]]+name = "line-clipping"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f50e8f47623268b5407192d26876c4d7f89d686ca130fdc53bced4814cd29f8"+dependencies = [+ "bitflags 2.13.1",+]+[[package]]name = "line_drawing"version = "0.8.1"@@ -3329,7 +3546,7 @@ dependencies = ["bstr","log","mlua",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -3342,6 +3559,16 @@ dependencies = ["which",]+[[package]]+name = "mac_address"+version = "1.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303"+dependencies = [+ "nix",+ "winapi",+]+[[package]]name = "mach2"version = "0.4.3"@@ -3421,7 +3648,7 @@ version = "0.31.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f569fb946490b5743ad69813cb19629130ce9374034abe31614a36402d18f99e"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","block","core-graphics-types 0.1.3","foreign-types 0.5.0",@@ -3496,6 +3723,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873"dependencies = ["libc",+ "log","wasi","windows-sys 0.61.2",]@@ -3553,9 +3781,9 @@ dependencies = ["config","crossbeam","downcast-rs",- "fancy-regex",- "filedescriptor",- "finl_unicode",+ "fancy-regex 0.14.0",+ "filedescriptor 0.8.3",+ "finl_unicode 1.3.0","hostname","k9","lazy_static",@@ -3578,12 +3806,12 @@ dependencies = ["shell-words","smol","terminfo",- "termwiz",+ "termwiz 0.24.0","termwiz-funcs","textwrap","thiserror 1.0.69","url",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","wezterm-ssh","wezterm-term","winapi",@@ -3602,10 +3830,10 @@ dependencies = ["parking_lot","portable-pty","smol",- "termwiz",+ "termwiz 0.24.0","termwiz-funcs","url-funcs",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","wezterm-term",]@@ -3616,8 +3844,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2b977c445f26e49757f9aca3631c3b8b836942cb278d69a92e7b80d3b24da632"dependencies = ["arrayvec",- "bit-set",- "bitflags 2.10.0",+ "bit-set 0.8.0",+ "bitflags 2.13.1","cfg_aliases","codespan-reporting","half",@@ -3629,7 +3857,7 @@ dependencies = ["once_cell","rustc-hash 1.1.0","spirv",- "strum",+ "strum 0.26.3","thiserror 2.0.17","unicode-ident",]@@ -3690,7 +3918,7 @@ version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","cfg-if","cfg_aliases","libc",@@ -3868,6 +4096,15 @@ dependencies = ["libm",]+[[package]]+name = "num_threads"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"+dependencies = [+ "libc",+]+[[package]]name = "objc"version = "0.2.7"@@ -3892,7 +4129,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","dispatch2","objc2",]@@ -3903,7 +4140,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","block2","dispatch2","libc",@@ -3935,7 +4172,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","block2","libc","objc2",@@ -3948,7 +4185,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","objc2","objc2-core-foundation",]@@ -3959,7 +4196,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","objc2","objc2-foundation",]@@ -3970,7 +4207,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","block2","objc2","objc2-core-location",@@ -4010,7 +4247,7 @@ version = "0.10.75"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","cfg-if","foreign-types 0.3.2","libc",@@ -4358,7 +4595,7 @@ dependencies = ["log","luahelper","tempfile",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -4380,7 +4617,7 @@ version = "0.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "97baced388464909d42d89643fe4361939af9b7ce7a31ee32a168f832a70f2a0"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","crc32fast","fdeflate","flate2",@@ -4423,7 +4660,7 @@ dependencies = ["anyhow","bitflags 1.3.2","downcast-rs",- "filedescriptor",+ "filedescriptor 0.8.3","futures","lazy_static","libc",@@ -4534,7 +4771,7 @@ dependencies = ["log","luahelper","ntapi",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","winapi",]@@ -4547,7 +4784,7 @@ dependencies = ["libc","luahelper","procinfo",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -4588,7 +4825,7 @@ version = "0.13.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","memchr","unicase",]@@ -4740,6 +4977,80 @@ dependencies = ["num",]+[[package]]+name = "ratatui"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1ce67fb8ba4446454d1c8dbaeda0557ff5e94d39d5e5ed7f10a65eb4c8266bc"+dependencies = [+ "instability",+ "ratatui-core",+ "ratatui-crossterm",+ "ratatui-termwiz",+ "ratatui-widgets",+]++[[package]]+name = "ratatui-core"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ef8dea09a92caaf73bff7adb70b76162e5937524058a7e5bff37869cbbec293"+dependencies = [+ "bitflags 2.13.1",+ "compact_str",+ "hashbrown 0.16.0",+ "indoc",+ "itertools 0.14.0",+ "kasuari",+ "lru",+ "strum 0.27.2",+ "thiserror 2.0.17",+ "unicode-segmentation",+ "unicode-truncate",+ "unicode-width",+]++[[package]]+name = "ratatui-crossterm"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "577c9b9f652b4c121fb25c6a391dd06406d3b092ba68827e6d2f09550edc54b3"+dependencies = [+ "cfg-if",+ "crossterm",+ "instability",+ "ratatui-core",+]++[[package]]+name = "ratatui-termwiz"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f76fe0bd0ed4295f0321b1676732e2454024c15a35d01904ddb315afd3d545c"+dependencies = [+ "ratatui-core",+ "termwiz 0.23.3",+]++[[package]]+name = "ratatui-widgets"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7dbfa023cd4e604c2553483820c5fe8aa9d71a42eea5aa77c6e7f35756612db"+dependencies = [+ "bitflags 2.13.1",+ "hashbrown 0.16.0",+ "indoc",+ "instability",+ "itertools 0.14.0",+ "line-clipping",+ "ratatui-core",+ "strum 0.27.2",+ "time",+ "unicode-segmentation",+ "unicode-width",+]+[[package]]name = "ratelim"version = "0.1.0"@@ -4842,7 +5153,7 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1",][[package]]@@ -5033,7 +5344,7 @@ version = "0.32.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","fallible-iterator","fallible-streaming-iterator","hashlink",@@ -5088,7 +5399,7 @@ version = "0.38.44"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","errno","libc","linux-raw-sys 0.4.15",@@ -5101,7 +5412,7 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","errno","libc","linux-raw-sys 0.11.0",@@ -5189,7 +5500,7 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","core-foundation 0.9.4","core-foundation-sys","libc",@@ -5238,7 +5549,7 @@ dependencies = ["serde_json","serde_yaml","toml 0.8.23",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -5339,7 +5650,7 @@ version = "2.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f"dependencies = [- "darling",+ "darling 0.20.11","proc-macro2","quote","syn 2.0.110",@@ -5400,7 +5711,7 @@ dependencies = ["lazy_static","luahelper","ordered-float 4.6.0",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -5441,6 +5752,17 @@ dependencies = ["signal-hook-registry",]+[[package]]+name = "signal-hook-mio"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"+dependencies = [+ "libc",+ "mio 1.1.0",+ "signal-hook",+]+[[package]]name = "signal-hook-registry"version = "1.4.6"@@ -5519,7 +5841,7 @@ version = "0.19.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","cursor-icon","libc","log",@@ -5592,7 +5914,7 @@ dependencies = ["log","luahelper","smol",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","wezterm-open-url","winapi",]@@ -5612,7 +5934,7 @@ version = "0.3.0+sdk-1.3.268.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1",][[package]]@@ -5643,7 +5965,7 @@ version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f84d13b3b8a0d4e91a2629911e951db1bb8671512f5c09d7d4ba34500ba68c8"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","libc","libssh2-sys","parking_lot",@@ -5699,7 +6021,7 @@ name = "strip-ansi-escapes"version = "0.1.0"dependencies = ["clap",- "termwiz",+ "termwiz 0.24.0",][[package]]@@ -5714,7 +6036,16 @@ version = "0.26.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"dependencies = [- "strum_macros",+ "strum_macros 0.26.4",+]++[[package]]+name = "strum"+version = "0.27.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"+dependencies = [+ "strum_macros 0.27.2",][[package]]@@ -5730,6 +6061,18 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "strum_macros"+version = "0.27.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "subtle"version = "2.6.1"@@ -5796,7 +6139,7 @@ dependencies = ["tempfile","tokio","toml 0.8.23",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -5834,7 +6177,7 @@ version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","core-foundation 0.9.4","system-configuration-sys",]@@ -5866,7 +6209,7 @@ dependencies = [name = "tabout"version = "0.3.0"dependencies = [- "termwiz",+ "termwiz 0.24.0",][[package]]@@ -5945,18 +6288,60 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"+[[package]]+name = "termwiz"+version = "0.23.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4676b37242ccbd1aabf56edb093a4827dc49086c0ffd764a5705899e0f35f8f7"+dependencies = [+ "anyhow",+ "base64 0.22.1",+ "bitflags 2.13.1",+ "fancy-regex 0.11.0",+ "filedescriptor 0.8.3 (registry+https://github.com/rust-lang/crates.io-index)",+ "finl_unicode 1.4.0",+ "fixedbitset",+ "hex",+ "lazy_static",+ "libc",+ "log",+ "memmem",+ "nix",+ "num-derive",+ "num-traits",+ "ordered-float 4.6.0",+ "pest",+ "pest_derive",+ "phf",+ "sha2",+ "signal-hook",+ "siphasher 1.0.1",+ "terminfo",+ "termios",+ "thiserror 1.0.69",+ "ucd-trie",+ "unicode-segmentation",+ "vtparse 0.6.2",+ "wezterm-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",+ "wezterm-blob-leases 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",+ "wezterm-color-types 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",+ "wezterm-dynamic 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",+ "wezterm-input-types 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",+ "winapi",+]+[[package]]name = "termwiz"version = "0.24.0"dependencies = ["anyhow",- "bitflags 2.10.0",+ "bitflags 2.13.1","cassowary","criterion","env_logger 0.11.8",- "fancy-regex",- "filedescriptor",- "finl_unicode",+ "fancy-regex 0.14.0",+ "filedescriptor 0.8.3",+ "finl_unicode 1.3.0","fixedbitset","fnv","image",@@ -5980,15 +6365,15 @@ dependencies = ["thiserror 1.0.69","ucd-trie","unicode-segmentation",- "vtparse",- "wezterm-bidi",- "wezterm-blob-leases",+ "vtparse 0.7.0",+ "wezterm-bidi 0.2.3",+ "wezterm-blob-leases 0.1.1","wezterm-cell","wezterm-char-props",- "wezterm-color-types",- "wezterm-dynamic",+ "wezterm-color-types 0.3.0",+ "wezterm-dynamic 0.2.1","wezterm-escape-parser",- "wezterm-input-types",+ "wezterm-input-types 0.1.0","wezterm-surface","winapi",]@@ -5999,13 +6384,13 @@ version = "0.1.0"dependencies = ["anyhow","config",- "finl_unicode",+ "finl_unicode 1.3.0","lazy_static","luahelper","terminfo",- "termwiz",- "wezterm-dynamic",- "wezterm-input-types",+ "termwiz 0.24.0",+ "wezterm-dynamic 0.2.1",+ "wezterm-input-types 0.1.0",][[package]]@@ -6019,6 +6404,20 @@ dependencies = ["unicode-width",]+[[package]]+name = "thinkterm-core"+version = "0.1.0"+dependencies = [+ "anyhow",+ "base64 0.22.1",+ "config",+ "dirs-next",+ "openssl",+ "serde",+ "serde_json",+ "tempfile",+]+[[package]]name = "thinkterm-syntax"version = "0.1.0"@@ -6047,6 +6446,32 @@ dependencies = ["tree-sitter-yaml",]+[[package]]+name = "thinkterm-tui"+version = "0.1.0"+dependencies = [+ "anyhow",+ "async-channel",+ "base64 0.22.1",+ "clipboard-win",+ "codec",+ "config",+ "filedescriptor 0.8.3",+ "log",+ "mux",+ "promise",+ "ratatui",+ "serde",+ "serde_json",+ "smol",+ "termwiz 0.24.0",+ "thinkterm-core",+ "toml 0.8.23",+ "uuid",+ "wezterm-client",+ "wezterm-term",+]+[[package]]name = "thiserror"version = "1.0.69"@@ -6115,7 +6540,9 @@ checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d"dependencies = ["deranged","itoa",+ "libc","num-conv",+ "num_threads","powerfmt","serde","time-core",@@ -6140,7 +6567,7 @@ dependencies = ["promise","smol","spa",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -6375,7 +6802,7 @@ version = "0.6.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","bytes","futures-util","http",@@ -6763,6 +7190,17 @@ version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"+[[package]]+name = "unicode-truncate"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"+dependencies = [+ "itertools 0.14.0",+ "unicode-segmentation",+ "unicode-width",+]+[[package]]name = "unicode-width"version = "0.2.2"@@ -6812,7 +7250,7 @@ dependencies = ["luahelper","percent-encoding","url",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",][[package]]@@ -6861,6 +7299,7 @@ version = "1.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"dependencies = [+ "atomic","getrandom 0.3.4","js-sys","rand 0.9.2",@@ -6928,6 +7367,15 @@ dependencies = ["libc",]+[[package]]+name = "vtparse"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d9b2acfb050df409c972a37d3b8e08cdea3bddb0c09db9d53137e504cfabed0"+dependencies = [+ "utf8parse",+]+[[package]]name = "vtparse"version = "0.7.0"@@ -7056,7 +7504,7 @@ version = "0.31.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","rustix 1.1.2","wayland-backend","wayland-scanner",@@ -7068,7 +7516,7 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","cursor-icon","wayland-backend",]@@ -7100,7 +7548,7 @@ version = "0.32.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","wayland-backend","wayland-client","wayland-scanner",@@ -7112,7 +7560,7 @@ version = "0.3.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a07a14257c077ab3279987c4f8bb987851bf57081b93710381daea94f2c2c032"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","wayland-backend","wayland-client","wayland-protocols",@@ -7125,7 +7573,7 @@ version = "0.3.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "efd94963ed43cf9938a090ca4f7da58eb55325ec8200c3848963e98dc25b78ec"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","wayland-backend","wayland-client","wayland-protocols",@@ -7184,7 +7632,7 @@ dependencies = ["config","embed-resource","env-bootstrap",- "filedescriptor",+ "filedescriptor 0.8.3","hostname","humantime","image",@@ -7200,9 +7648,10 @@ dependencies = ["tabout","tempfile","termios",- "termwiz",+ "termwiz 0.24.0","termwiz-funcs","textwrap",+ "thinkterm-tui","umask","url","wezterm-client",@@ -7218,7 +7667,17 @@ dependencies = ["env_logger 0.11.8","k9","log",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",+]++[[package]]+name = "wezterm-bidi"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c0a6e355560527dd2d1cf7890652f4f09bb3433b6aadade4c9b5ed76de5f3ec"+dependencies = [+ "log",+ "wezterm-dynamic 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",][[package]]@@ -7233,21 +7692,34 @@ dependencies = ["uuid",]+[[package]]+name = "wezterm-blob-leases"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "692daff6d93d94e29e4114544ef6d5c942a7ed998b37abdc19b17136ea428eb7"+dependencies = [+ "getrandom 0.3.4",+ "mac_address",+ "sha2",+ "thiserror 1.0.69",+ "uuid",+]+[[package]]name = "wezterm-cell"version = "0.1.0"dependencies = [- "finl_unicode",+ "finl_unicode 1.3.0","image","log","ordered-float 4.6.0","serde","sha2","thiserror 1.0.69",- "wezterm-blob-leases",+ "wezterm-blob-leases 0.1.1","wezterm-char-props",- "wezterm-color-types",- "wezterm-dynamic",+ "wezterm-color-types 0.3.0",+ "wezterm-dynamic 0.2.1","wezterm-escape-parser",]@@ -7271,7 +7743,7 @@ dependencies = ["async_ossl","codec","config",- "filedescriptor",+ "filedescriptor 0.8.3","futures","lazy_static","libc",@@ -7286,12 +7758,12 @@ dependencies = ["rangeset","ratelim","smol",- "termwiz",+ "termwiz 0.24.0","textwrap","thiserror 1.0.69","umask","url",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","wezterm-ssh","wezterm-term","wezterm-uds",@@ -7306,7 +7778,19 @@ dependencies = ["deltae","num-traits","serde",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",+]++[[package]]+name = "wezterm-color-types"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7de81ef35c9010270d63772bebef2f2d6d1f2d20a983d27505ac850b8c4b4296"+dependencies = [+ "csscolorparser",+ "deltae",+ "lazy_static",+ "wezterm-dynamic 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",][[package]]@@ -7327,12 +7811,36 @@ dependencies = ["ordered-float 4.6.0","strsim","thiserror 2.0.17",- "wezterm-dynamic-derive",+ "wezterm-dynamic-derive 0.1.1",+]++[[package]]+name = "wezterm-dynamic"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac"+dependencies = [+ "log",+ "ordered-float 4.6.0",+ "strsim",+ "thiserror 1.0.69",+ "wezterm-dynamic-derive 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",+]++[[package]]+name = "wezterm-dynamic-derive"+version = "0.1.1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 1.0.109",][[package]]name = "wezterm-dynamic-derive"version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46c0cf2d539c645b448eaffec9ec494b8b19bd5077d9e58cb1ae7efece8d575b"dependencies = ["proc-macro2","quote",@@ -7344,7 +7852,7 @@ name = "wezterm-escape-parser"version = "0.1.0"dependencies = ["base64 0.22.1",- "bitflags 2.10.0",+ "bitflags 2.13.1","criterion","env_logger 0.11.8","hex",@@ -7360,11 +7868,11 @@ dependencies = ["serde","sha2","thiserror 2.0.17",- "vtparse",- "wezterm-blob-leases",- "wezterm-color-types",- "wezterm-dynamic",- "wezterm-input-types",+ "vtparse 0.7.0",+ "wezterm-blob-leases 0.1.1",+ "wezterm-color-types 0.3.0",+ "wezterm-dynamic 0.2.1",+ "wezterm-input-types 0.1.0","winapi",]@@ -7383,7 +7891,7 @@ dependencies = ["enum-display-derive","env_logger 0.11.8","euclid",- "finl_unicode",+ "finl_unicode 1.3.0","fontconfig","freetype","harfbuzz",@@ -7397,12 +7905,12 @@ dependencies = ["objc","ordered-float 4.6.0","rangeset",- "termwiz",+ "termwiz 0.24.0","thiserror 1.0.69","walkdir",- "wezterm-bidi",- "wezterm-color-types",- "wezterm-input-types",+ "wezterm-bidi 0.2.3",+ "wezterm-color-types 0.3.0",+ "wezterm-input-types 0.1.0","wezterm-term","wezterm-toast-notification","winapi",@@ -7432,8 +7940,8 @@ dependencies = ["env_logger 0.11.8","euclid","fastrand",- "filedescriptor",- "finl_unicode",+ "filedescriptor 0.8.3",+ "finl_unicode 1.3.0","fluent-bundle","fluent-langneg","frecency",@@ -7476,9 +7984,10 @@ dependencies = ["tabout","tempfile","terminfo",- "termwiz",+ "termwiz 0.24.0","termwiz-funcs","textwrap",+ "thinkterm-core","thinkterm-syntax","thiserror 1.0.69","tiny-skia",@@ -7493,10 +8002,10 @@ dependencies = ["url-funcs","uuid","walkdir",- "wezterm-bidi",- "wezterm-blob-leases",+ "wezterm-bidi 0.2.3",+ "wezterm-blob-leases 0.1.1","wezterm-client",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","wezterm-font","wezterm-gui-subcommands","wezterm-mux-server-impl",@@ -7526,7 +8035,20 @@ dependencies = ["bitflags 1.3.2","euclid","serde",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1",+]++[[package]]+name = "wezterm-input-types"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7012add459f951456ec9d6c7e6fc340b1ce15d6fc9629f8c42853412c029e57e"+dependencies = [+ "bitflags 1.3.2",+ "euclid",+ "lazy_static",+ "serde",+ "wezterm-dynamic 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",][[package]]@@ -7548,7 +8070,7 @@ dependencies = ["portable-pty","promise","umask",- "wezterm-blob-leases",+ "wezterm-blob-leases 0.1.1","wezterm-gui-subcommands","wezterm-mux-server-impl","wezterm-term",@@ -7578,8 +8100,9 @@ dependencies = ["serde_json","smol","tempfile",- "termwiz",+ "termwiz 0.24.0","url",+ "uuid","wezterm-client","wezterm-term","wezterm-uds",@@ -7610,7 +8133,7 @@ dependencies = ["clap","dirs-next","env_logger 0.11.8",- "filedescriptor",+ "filedescriptor 0.8.3","filenamegen","gethostname","hex",@@ -7628,7 +8151,7 @@ dependencies = ["smol","socket2 0.5.10","ssh2",- "termwiz",+ "termwiz 0.24.0","thiserror 1.0.69","wezterm-uds","whoami",@@ -7638,23 +8161,23 @@ dependencies = [name = "wezterm-surface"version = "0.1.0"dependencies = [- "bitflags 2.10.0",- "fancy-regex",- "finl_unicode",+ "bitflags 2.13.1",+ "fancy-regex 0.14.0",+ "finl_unicode 1.3.0","fixedbitset","k9","ordered-float 4.6.0","serde","siphasher 1.0.1","unicode-segmentation",- "wezterm-bidi",- "wezterm-blob-leases",+ "wezterm-bidi 0.2.3",+ "wezterm-blob-leases 0.1.1","wezterm-cell","wezterm-char-props",- "wezterm-color-types",- "wezterm-dynamic",+ "wezterm-color-types 0.3.0",+ "wezterm-dynamic 0.2.1","wezterm-escape-parser",- "wezterm-input-types",+ "wezterm-input-types 0.1.0",][[package]]@@ -7666,7 +8189,7 @@ dependencies = ["csscolorparser","downcast-rs","env_logger 0.11.8",- "finl_unicode",+ "finl_unicode 1.3.0","hex","humansize","image",@@ -7679,12 +8202,12 @@ dependencies = ["ordered-float 4.6.0","serde","terminfo",- "termwiz",+ "termwiz 0.24.0","unicode-normalization","url",- "wezterm-bidi",+ "wezterm-bidi 0.2.3","wezterm-cell",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","wezterm-escape-parser","wezterm-surface",]@@ -7731,7 +8254,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec8fb398f119472be4d80bc3647339f56eb63b2a331f6a3d16e25d8144197dd9"dependencies = ["arrayvec",- "bitflags 2.10.0",+ "bitflags 2.13.1","cfg_aliases","document-features","hashbrown 0.15.5",@@ -7759,9 +8282,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f7b882196f8368511d613c6aeec80655160db6646aebddf8328879a88d54e500"dependencies = ["arrayvec",- "bit-set",- "bit-vec",- "bitflags 2.10.0",+ "bit-set 0.8.0",+ "bit-vec 0.8.0",+ "bitflags 2.13.1","cfg_aliases","document-features","hashbrown 0.15.5",@@ -7819,8 +8342,8 @@ dependencies = ["android_system_properties","arrayvec","ash",- "bit-set",- "bitflags 2.10.0",+ "bit-set 0.8.0",+ "bitflags 2.13.1","block","bytemuck","cfg-if",@@ -7863,7 +8386,7 @@ version = "25.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2aa49460c2a8ee8edba3fca54325540d904dd85b2e086ada762767e17d06e8bc"dependencies = [- "bitflags 2.10.0",+ "bitflags 2.13.1","bytemuck","js-sys","log",@@ -7946,7 +8469,7 @@ dependencies = ["dirs-next","downcast-rs","euclid",- "filedescriptor",+ "filedescriptor 0.8.3","foreign-types 0.5.0","futures-lite","futures-util",@@ -7980,10 +8503,10 @@ dependencies = ["wayland-egl","wayland-protocols","wayland-protocols-plasma",- "wezterm-bidi",- "wezterm-color-types",+ "wezterm-bidi 0.2.3",+ "wezterm-color-types 0.3.0","wezterm-font",- "wezterm-input-types",+ "wezterm-input-types 0.1.0","winapi","windows 0.33.0","winreg",@@ -8002,7 +8525,7 @@ dependencies = ["anyhow","config","luahelper",- "wezterm-dynamic",+ "wezterm-dynamic 0.2.1","window",]diff --git a/Cargo.toml b/Cargo.tomlindex 2d8d766f..05722993 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -5,6 +5,8 @@ members = ["strip-ansi-escapes","sync-color-schemes","thinkterm-syntax",+ "thinkterm-core",+ "thinkterm-tui","deps/cairo","wezterm","wezterm-blob-leases",@@ -70,6 +72,7 @@ codec = { path = "codec" }color-funcs = { path = "lua-api-crates/color-funcs" }colorgrad = "0.6"config = { path = "config" }+thinkterm-core = { path = "thinkterm-core" }core-foundation = "=0.10.0"core-graphics = "=0.24.0"core-text = "=21.0.0"@@ -180,6 +183,7 @@ proc-macro2 = "1.0"procinfo = { path = "procinfo" }procinfo-funcs = { path = "lua-api-crates/procinfo-funcs" }promise = { path = "promise" }+ratatui = { version = "=0.30.0", default-features = false, features = ["std", "underline-color"] }quote = "1.0.2"rangeset = { path = "rangeset" }ratelim= { path = "ratelim" }diff --git a/README.md b/README.mdindex 9405f038..3addbbdb 100644--- a/README.md+++ b/README.md@@ -1,41 +1,149 @@# ThinkTerm-ThinkTerm is a macOS-focused terminal app based on WezTerm, with workspace and session management built into the main window. It is built for heavy AI workflows while maintaining high performance and low RAM usage.+A workspace-first terminal built for heavy AI workflows. Built on [WezTerm](https://github.com/wezterm/wezterm), keeping its fast, low-memory terminal core.-## Build+> *[main window screenshot]*++---++## Why ThinkTerm exists++I've used a lot of terminals. Some eat absurd amounts of memory. Some I just don't like looking at. Some are fast and good-looking but closed — you can't change anything. I never found one that satisfied me on memory, appearance, and openness at the same time.++What actually made me start building was AI agents. Once you have five or six agents running long tasks in different project directories, a normal tab bar stops meaning anything — a dozen tabs, all titled `zsh`, or all renamed by the program to the same string, each one scrolling output. To find out which is still working, which is waiting on you, and which finished twenty minutes ago, you have to click through them one by one.++The more sessions and the more output, the worse it gets. Which is exactly what an agent workflow looks like all day.++ThinkTerm organizes sessions into three layers — **Space / Project / Thread** — and gives every Thread its own work status.++More importantly, that structure doesn't belong to any one machine. Your laptop, your work dev box, a VPS — each runs its own mux server, but their workspaces **all show up in the same sidebar**. Local Spaces on top, then one group per server with its own connection state. Switching between them feels no different from switching a local tab.++Sessions are held by the server, so you can close your laptop, connect from another device, and find your work exactly as you left it. Several devices connected at once see the same structure. **In practice, your machines fuse into one.**++And since every agent lives in a pane the mux can address, they also have a channel to talk to each other.++---++## Core concepts++| Layer | What it is |+|---|---|+| **Space** | A working context. It can be local, bound to a remote mux server, or bound to an Obsidian-compatible Vault for notes |+| **Project** | A directory |+| **Thread** | A session with its own split layout; can be pinned or marked unread |++Threads carry one of four states, shown live in the sidebar and filterable: **running / needs attention / done / idle**. When a Thread you aren't watching finishes — or starts waiting on you — a short sound plays.++---++## Remote that feels local++There's a large gap between "it connects to a remote host" and "it feels like it's running here." Most of the engineering in ThinkTerm went into closing it:++- **Typing doesn't wait for the round trip** — predictive local echo puts keystrokes on screen immediately, without waiting for the server to confirm+- **Splits aren't a local-only luxury** — split trees, the second-level tab bar, drag-to-split, and dragging dividers to resize all work in remote sessions, and behave the same as local+- **Sizes don't jitter** — the resize races in remote layouts have been eliminated one by one; dragging a divider no longer causes snap-back, squeeze, or resync storms+- **The scroll wheel is accurate** — in mouse-mode programs like vim and less, the original notch count is preserved, so scrolling isn't too fast or too slow+- **Client state stays yours** — focus and selection are locally authoritative and won't be scrambled by server echo; each client holds its own palette, so changing the theme on one device doesn't change it on another+- **It comes back on its own** — after a network drop it reconnects and restores the session. "Disconnect (server keeps running)" and "delete on the server" are strictly separate actions++The result: a remote Space feels no different from a local one. You usually forget you're connected to another machine.++---++## The same workspace, in a plain terminal```bash-make build BUILD_OPTS=--release-TAG_NAME=v0.1.0 bash ci/deploy.sh+thinkterm tui [DOMAIN ...]```-This creates:+The TUI is a subcommand of the `thinkterm` binary, not a second program — it costs nothing when it isn't running, and exiting detaches from the server **without ending any session**.++It isn't a read-only mirror of the GUI. It's a peer client of the same authoritative server: Space/Project/Thread data is accepted only from server snapshots, and every change waits for the server to acknowledge it before the display updates, so having the GUI and TUI open at once never leaves them disagreeing. It can do what the GUI can — new tabs, splits, resizing, closing panes, reordering the sidebar, copy mode — with full mouse support.-```text-ThinkTerm-macos-v0.1.0/ThinkTerm.app-ThinkTerm-macos-v0.1.0.zip+The use case is straightforward: SSH into a machine, or just skip the GUI, and your workspace is still right there. See [thinkterm-tui/README.md](thinkterm-tui/README.md) for keys and configuration.++---++## Agents can talk to each other++Because the mux can address any pane across windows, Threads, and connected clients, one agent can push a task into another agent's pane and read the result back:++```+Agent A ──send-text──► Agent B's terminal input+ Agent B works, prints a response+Agent A ◄──get-text─── reads the result```-Upload the `.zip` file to GitHub Releases. The `.app` bundle is inside the zip.+This uses two CLI primitives that already exist — `thinkterm cli send-text` and `get-text` — and **requires no changes to the agents themselves**. Codex, Claude Code, a shell script, any interactive terminal program can take part.-## macOS Security Note+It has already produced a real collaboration: Claude Code, running in one Thread, noticed that Codex in another Thread had reached a wrong conclusion (Codex's process-list command ran inside an isolated PID namespace and found no mux server). Claude sent a correction into Codex's pane; Codex re-investigated, corrected itself, and printed a response; Claude read it back and reported to the user.-If macOS blocks the app, run this in Terminal:+Today this works by injecting terminal input. A more structured task protocol is being designed — see [Agent Collaboration](docs/thinkterm/agent-collaboration.md).-```bash-sudo xattr -r -d com.apple.quarantine /Applications/ThinkTerm.app+---++## Features++**Remote files** — Browse remote directories over SFTP, with uploads, downloads, recursive transfers, conflict handling, and retry on failure. Files can be dropped straight onto a remote terminal to upload. Idle connections close after a configurable timeout.++**SSH host book** — Your own host list, alongside a read-only view of `~/.ssh/config`. Each host can connect over plain SSH, **Mosh**, or **ThinkTerm Connect (persistent mux)**. Saved passwords are encrypted at rest with AES-256-GCM, with the key stored separately (mode 0600) — that protects against sync, backups, and someone glancing at the file; anyone holding both the key and the ciphertext can still decrypt, which is the known trade-off of a key-on-disk scheme versus the system keychain.++**Content sidebar** — Three panels: *Files* (tree, syntax-highlighted preview, fuzzy search, drag and drop, Open With), *Notes* (a built-in Markdown editor bound to an Obsidian-compatible Vault, with tables, code highlighting, spell check, remote images, and autosave), and *Snippets* (a command snippet library).++**The terminal itself** — WezTerm's GPU rendering, ligatures, color emoji, true color, hyperlinks, copy mode, inline images, and shell integration.++**Interface** — A native settings window, per-area font sizes, and a theme that follows the system or is pinned light or dark. Available in **English, 简体中文, 日本語, and Français**, switching instantly.++---++## Command line++```+thinkterm start Start the GUI (alias -e)+thinkterm tui [DOMAIN ...] Open the ThinkTerm interface in the current terminal+thinkterm connect <name> Connect to a ThinkTerm multiplexer+thinkterm ssh / serial SSH session / serial port+thinkterm cli <subcommand> Interact with the mux server+thinkterm imgcat <file> Print an image to the terminal```-Why: I can't afford Apple's developer certificate ($99/year), so macOS may block the unsigned app. This command removes the quarantine flag and lets it run. Only use this command on apps you trust.+Run `thinkterm --help` for the full list.++---++## Configuration and data++ThinkTerm uses a WezTerm-compatible Lua config on its own paths, and **never reads or writes your existing WezTerm config**. It takes the first of `$THINKTERM_CONFIG_FILE`, `~/.config/thinkterm/thinkterm.lua`, `~/.config/thinkterm/wezterm.lua`, `~/.thinkterm.lua`. The options themselves match WezTerm — see the [WezTerm config reference](https://wezterm.org/config/files.html).++Settings → Compatibility can load an existing WezTerm config and import chosen fields one by one. That's a one-time copy; the two never share live state.++Workspace data lives in `~/Library/Application Support/ThinkTerm/` (`~/.local/share/ThinkTerm/` on Linux): the Space/Project/Thread structure, the SSH host book (passwords as ciphertext), snippets, and the encryption key `secret.key`. A Notes Vault is a directory you choose; its contents are ordinary Markdown files, and ThinkTerm only records the binding.++---++## Roadmap++**Mobile clients** (design stage, not yet implemented) — iOS and Android as pure mux clients: sessions are always held by the desktop or server, so the phone app being killed by the OS never ends a session. A shared Rust core bridged to native UI through UniFFI, terminal rendering via wgpu, QR pairing with per-device mTLS, and private keys held in Secure Enclave / Keystore. Not planned: a local shell on the phone, a mobile mux daemon, or promises of a permanent background connection.++Groundwork has been landing: the mux protocol now supports moving panes between stacks, per-client palette state, and a **session tree owned by the server**. `thinkterm tui` is the first implementation of this thin-client architecture.++**Structured agent collaboration** — see above.++---++## Privacy++ThinkTerm collects no usage data. Its only outbound request is an update check: once every 24 hours it asks the GitHub Releases API whether a newer version exists, and you can turn that off with `check_for_updates = false`. Scrollback lives in memory only.++---++## Credits and license++ThinkTerm is built on [WezTerm](https://github.com/wezterm/wezterm), written in Rust by [@wez](https://github.com/wez/). Terminal emulation, font rendering, GPU drawing, the multiplexer protocol, and SSH transport all come from that project. Thank you.-## Notes+ThinkTerm is released under **GPL-3.0** — see [LICENSE.md](LICENSE.md). Code originating from WezTerm remains under its original MIT license, and those copyright notices are preserved.-- The package script uses the binaries from `target/release/`.-- The macOS app template lives in `assets/macos/ThinkTerm.app`.-- Change `TAG_NAME` for each release version.-- The `thinkterm` CLI ships inside the app bundle. To use it from a shell,- symlink it onto your PATH:+Icons from [Lucide](https://github.com/lucide-icons/lucide), [Simple Icons](https://github.com/simple-icons/simple-icons), and material-icon-theme.- ```bash- sudo ln -s /Applications/ThinkTerm.app/Contents/MacOS/thinkterm /usr/local/bin/thinkterm- ```+Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md).diff --git a/assets/sounds/done.wav b/assets/sounds/done.wavnew file mode 100644index 00000000..420b3675Binary files /dev/null and b/assets/sounds/done.wav differdiff --git a/assets/sounds/needs-input.wav b/assets/sounds/needs-input.wavnew file mode 100644index 00000000..a1a8b178Binary files /dev/null and b/assets/sounds/needs-input.wav differdiff --git a/assets/sounds/synth.py b/assets/sounds/synth.pynew file mode 100644index 00000000..ffbaec18--- /dev/null+++ b/assets/sounds/synth.py@@ -0,0 +1,99 @@+#!/usr/bin/env python3+"""Generate ThinkTerm's notification sounds.++These are synthesised rather than sourced so their provenance is unambiguous:+nothing here is licensed from anyone. Run this script to regenerate the WAVs+after changing a pitch, an envelope, or a timbre.++ python3 assets/sounds/synth.py++Standard library only, by design — nobody should need a toolchain to retune a+notification. Output is 44100 Hz / 16-bit / mono, peaking at -3 dBFS.++Three things decide whether a prompt feels gentle or sharp, and they are+independent: how high the partials reach, how fast the onset is, and how much+energy survives above a few kHz. Meaning, separately, comes from the interval —+rising and consonant reads as finished, a repeat reads as a question.+"""+import math+import os+import struct+import wave++SR = 44100+OUT_DIR = os.path.dirname(os.path.abspath(__file__))++# (frequency ratio, amplitude, decay multiplier). Upper partials die first,+# which is what makes a struck object sound struck rather than blown.+WOOD = [(1.0, 1.0, 1.0), (3.9, 0.13, 3.5)]+BELL = [(1.0, 1.0, 1.0), (2.0, 0.20, 2.6), (3.0, 0.06, 4.5)]++C5, E5, G5 = 523.25, 659.25, 784.0+++def strike(buf, start, freq, decay, timbre, gain, attack):+ """Mix one struck note into `buf`, `start` seconds in."""+ origin = int(start * SR)+ for i in range(int(min(decay * 5.0, 2.0) * SR)):+ if origin + i >= len(buf):+ break+ t = i / SR+ # Raised-cosine onset. An instant one clicks, and even a few+ # milliseconds too fast reads as a tick rather than a strike.+ envelope = 0.5 - 0.5 * math.cos(math.pi * min(t / attack, 1.0))+ value = 0.0+ for ratio, amp, decay_mul in timbre:+ value += amp * math.exp(-t / (decay / decay_mul)) * math.sin(+ 2.0 * math.pi * freq * ratio * t+ )+ buf[origin + i] += value * envelope * gain+++def lowpass(buf, cutoff):+ """One-pole rolloff, to round off whatever edge the partials leave."""+ alpha = 1.0 - math.exp(-2.0 * math.pi * cutoff / SR)+ carry = 0.0+ for i, sample in enumerate(buf):+ carry += alpha * (sample - carry)+ buf[i] = carry+++def render(name, notes, timbre, decay, length, attack, cutoff):+ buf = [0.0] * int(length * SR)+ for start, freq, gain in notes:+ strike(buf, start, freq, decay, timbre, gain, attack)+ lowpass(buf, cutoff)++ # The file must not end on a non-zero sample or it clicks on the way out.+ fade = int(0.03 * SR)+ for i in range(fade):+ buf[len(buf) - fade + i] *= 1.0 - i / fade++ peak = max(abs(sample) for sample in buf) or 1.0+ scale = 0.708 / peak # -3 dBFS: a prompt must not outshout the work+ frames = b"".join(+ struct.pack("<h", int(max(-1.0, min(1.0, sample * scale)) * 32767))+ for sample in buf+ )++ path = os.path.join(OUT_DIR, name)+ with wave.open(path, "wb") as out:+ out.setnchannels(1)+ out.setsampwidth(2)+ out.setframerate(SR)+ out.writeframes(frames)+ return path, len(buf) / SR+++SOUNDS = [+ # Finished: a rising fifth resolves, so it reads as landing somewhere.+ ("done.wav", [(0.0, C5, 1.0), (0.075, G5, 0.92)], WOOD, 0.28, 0.70, 0.012, 3800),+ # Needs input: the same note twice asks rather than answers, and sits low+ # enough not to startle.+ ("needs-input.wav", [(0.0, E5, 1.0), (0.15, E5, 0.88)], BELL, 0.30, 0.85, 0.018, 3200),+]++if __name__ == "__main__":+ for args in SOUNDS:+ path, seconds = render(*args)+ print(f"{os.path.basename(path):16} {os.path.getsize(path) / 1024:5.0f} KB {seconds:.2f}s")diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex 67327def..aef4d4ee 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -452,7 +452,14 @@ macro_rules! pdu {/// 49: Palette advisories are client-only, application palette state is/// explicit, and SetFocusedPane carries the focusing client's palette./// 50: The server owns the ThinkTerm sidebar tree (Space/Project/Thread).-pub const CODEC_VERSION: usize = 51;+/// 51: Server-side tree revisions and authoritative compound mutations.+/// 52: ThinkTerm session snapshots, runtime server identity and per-tab+/// frontend viewport ownership.+/// 53: Explicit, server-authoritative frontend viewport claims.+/// 54: Server-authoritative ThinkTerm Thread landing and materialization.+/// 55: Panes report alternate screen state so renderers can route the wheel.+/// 56: Pane entries carry that state too, so a renderer knows it on arrival.+pub const CODEC_VERSION: usize = 57;// Defines the Pdu enum.// Each struct has an explicit identifying number.@@ -520,12 +527,38 @@ pdu! {GetThinkTermTree: 67,MutateThinkTermTree: 68,ThinkTermTreeState: 69,+ GetThinkTermSessionState: 70,+ ThinkTermSessionState: 71,+ SetClientViewport: 72,+ ClientViewportState: 73,+ ClaimClientViewport: 74,+ EnsureThinkTermThread: 75,+ EnsureThinkTermThreadResponse: 76,+ SetClientView: 77,}impl Pdu {/// Returns true if this type of Pdu represents action taken/// directly by a user, rather than background traffic on/// a live connection+ /// A person doing something *to a terminal*, as opposed to a renderer+ /// managing its own geometry.+ ///+ /// This is what decides who owns a tab's viewport, so the line matters: a+ /// renderer tells the server its pane sizes on the first frame after it+ /// attaches, and counting that as interaction meant merely opening a second+ /// client took the grid away from the one being used. Resizing, zooming,+ /// spawning and stack bookkeeping are all things a frontend does to itself.+ pub fn is_terminal_interaction(&self) -> bool {+ matches!(+ self,+ Self::WriteToPane(_)+ | Self::SendKeyDown(_)+ | Self::SendMouseEvent(_)+ | Self::SendPaste(_)+ )+ }+pub fn is_user_input(&self) -> bool {match self {Self::WriteToPane(_)@@ -535,6 +568,9 @@ impl Pdu {| Self::Resize(_)| Self::SetClipboard(_)| Self::SetPaneZoomed(_)+ | Self::ClaimClientViewport(_)+ | Self::SetClientView(_)+ | Self::EnsureThinkTermThread(_)| Self::SpawnV2(_)| Self::SpawnPaneInStack(_)| Self::ActivatePaneInStack(_)@@ -638,6 +674,9 @@ pub struct GetCodecVersion {}pub struct GetCodecVersionResponse {pub codec_vers: usize,pub version_string: String,+ /// Unique to this running mux process. It deliberately does not survive a+ /// restart: the current server cannot preserve live PTYs across one.+ pub server_id: String,pub executable_path: PathBuf,pub config_file_path: Option<PathBuf>,}@@ -879,6 +918,186 @@ pub struct ThinkTermTreeState {pub tree: ThinkTermTree,}+/// Read-only view built by one authoritative mux server from its tree and its+/// live mux topology. It intentionally excludes credentials and+/// device-private presentation data.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ThinkTermSessionState {+ /// Identity of the running server that produced this snapshot.+ pub server_id: String,+ /// Revision of the authoritative Space/Project/Thread tree.+ pub tree_revision: u64,+ /// Monotonic within one server process. Consumers establish a new+ /// comparison baseline when `server_id` changes.+ pub generation: u64,+ pub spaces: Vec<ThinkTermSessionSpace>,+ pub projects: Vec<ThinkTermSessionProject>,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ThinkTermSessionSpace {+ pub id: String,+ pub name: String,+ pub is_default: bool,+ /// The mux client domain that owns this Space. `None` means local to the+ /// running ThinkTerm frontend.+ pub domain: Option<String>,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ThinkTermSessionProject {+ pub id: String,+ pub space_id: String,+ pub name: String,+ /// A path on the machine that owns this project.+ pub path: String,+ pub threads: Vec<ThinkTermSessionThread>,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ThinkTermSessionThread {+ pub id: String,+ pub project_id: String,+ pub name: String,+ pub planned_workspace_name: Option<String>,+ pub materialized_workspace_name: Option<String>,+ pub is_pinned: bool,+ pub is_unread: bool,+ pub work_status: ThinkTermSessionWorkStatus,+ /// Exact live mux objects owned by this thread. IDs are in the producing+ /// server's namespace; a client domain translates them into local mirror+ /// IDs before rendering.+ pub tabs: Vec<ThinkTermSessionTab>,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ThinkTermSessionTab {+ pub window_id: WindowId,+ pub tab_id: TabId,+ pub pane_ids: Vec<PaneId>,+ pub title: String,+ pub is_active: bool,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Copy, Default)]+pub enum ThinkTermSessionWorkStatus {+ #[default]+ Idle,+ Running,+ NeedsAttention,+ FinishedUnseen,+}++/// Ask a mux server for its authoritative ThinkTerm session view.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug)]+pub struct GetThinkTermSessionState {}++/// Select an existing authoritative Thread, or create the canonical+/// Default/Home/main landing when the server has no usable Thread, and make+/// sure that the selected Thread has a live terminal. The server validates the+/// preferred ID against its current tree and owns both fallback selection and+/// materialization.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct EnsureThinkTermThread {+ pub preferred_thread_id: Option<TtThreadId>,+ pub size: TerminalSize,+}++/// The Thread and workspace chosen by the server. A client resyncs mux+/// topology after this response before attempting to render the live tab.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct EnsureThinkTermThreadResponse {+ pub thread_id: TtThreadId,+ pub workspace: String,+ pub spawned: bool,+}++/// A complete renderer viewport. Native GUI clients include their per-pane+/// targets so that font scaling and pane chrome are restored when ownership+/// changes; cell-grid clients have a single canonical grid.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub enum ClientViewport {+ CellGrid {+ size: TerminalSize,+ },+ Native {+ size: TerminalSize,+ panes: Vec<ClientPaneViewport>,+ },+}++impl ClientViewport {+ pub fn size(&self) -> TerminalSize {+ match self {+ Self::CellGrid { size } | Self::Native { size, .. } => *size,+ }+ }+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct ClientPaneViewport {+ pub pane_id: PaneId,+ pub size: TerminalSize,+}++/// Advertise one renderer's desired viewport for a remote tab. Advertising+/// does not steal ownership; the first renderer seeds an owner, and later+/// ownership changes only on real user interaction.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct SetClientViewport {+ pub tab_id: TabId,+ pub viewport: ClientViewport,+}++/// Claim a tab's viewport after a real renderer interaction. The server uses+/// the viewport previously advertised by this registered client; this request+/// carries no geometry or owner identity for the server to trust.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct ClaimClientViewport {+ pub tab_id: TabId,+}++/// Authoritative viewport state returned by `SetClientViewport` and pushed+/// whenever the owner or canonical server grid changes.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct ClientViewportState {+ pub tab_id: TabId,+ pub owner: Option<ClientId>,+ pub canonical_size: TerminalSize,+ /// What the owner is looking at, when the owner is a renderer that says.+ /// `None` means nobody offered one, and a follower keeps its own view.+ pub view: Option<ClientView>,+ pub generation: u64,+}++/// What the renderer holding a tab's viewport is currently looking at.+///+/// Sharing the size makes two attached devices the same shape; it does not make+/// them the same view. Without this a phone and a desktop on one tab sit at+/// different points in the same scrollback, which reads as two sessions that+/// merely share a name.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Default)]+pub struct ClientView {+ /// Lines above the bottom of each pane's scrollback. A pane that is absent+ /// is following its output.+ pub scroll: Vec<ClientPaneScroll>,+}++#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct ClientPaneScroll {+ pub pane_id: PaneId,+ pub lines_from_bottom: u32,+}++/// Offer what this renderer is looking at, for the other renderers on the same+/// tab to follow. Ignored unless this client owns the tab's viewport — a+/// renderer nobody is using does not get to move everyone else.+#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone)]+pub struct SetClientView {+ pub tab_id: TabId,+ pub view: ClientView,+}+#[derive(Deserialize, Serialize, PartialEq, Debug)]pub struct TabAddedToWindow {pub tab_id: TabId,@@ -1000,6 +1219,10 @@ pub struct LivenessResponse {pub struct GetPaneRenderChangesResponse {pub pane_id: PaneId,pub mouse_grabbed: bool,+ /// Whether the pane is showing the alternate screen. A renderer needs this+ /// to know that a wheel notch has no scrollback to travel through and+ /// belongs to the full-screen program instead.+ pub alt_screen: bool,pub cursor_position: StableCursorPosition,pub dimensions: RenderableDimensions,pub dirty_lines: Vec<Range<StableRowIndex>>,@@ -1307,7 +1530,7 @@ mod test {project_id: "p1".into(),space_id: "s1".into(),name: "thinkterm".into(),- path: "/home/x/github/ThinkTerm".into(),+ path: "/srv/projects/example".into(),},TreeOp::CreateThread {thread_id: "t1".into(),@@ -1361,6 +1584,120 @@ mod test {);}+ #[test]+ fn thinkterm_session_viewport_and_landing_protocol_round_trip_at_version_56() {+ assert_eq!(CODEC_VERSION, 57);+ let size = TerminalSize {+ rows: 40,+ cols: 132,+ pixel_width: 1056,+ pixel_height: 640,+ dpi: 96,+ };+ let viewport = SetClientViewport {+ tab_id: 17,+ viewport: ClientViewport::CellGrid { size },+ };+ let mut encoded = Vec::new();+ Pdu::SetClientViewport(viewport.clone())+ .encode(&mut encoded, 0x52)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x52,+ pdu: Pdu::SetClientViewport(viewport),+ }+ );++ let claim = ClaimClientViewport { tab_id: 17 };+ let mut encoded = Vec::new();+ Pdu::ClaimClientViewport(claim.clone())+ .encode(&mut encoded, 0x53)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x53,+ pdu: Pdu::ClaimClientViewport(claim),+ }+ );++ let session = ThinkTermSessionState {+ server_id: "server-runtime-id".into(),+ tree_revision: 9,+ generation: 11,+ spaces: vec![ThinkTermSessionSpace {+ id: "space".into(),+ name: "Space".into(),+ ..Default::default()+ }],+ projects: vec![ThinkTermSessionProject {+ id: "project".into(),+ space_id: "space".into(),+ name: "Project".into(),+ threads: vec![ThinkTermSessionThread {+ id: "thread".into(),+ project_id: "project".into(),+ name: "main".into(),+ tabs: vec![ThinkTermSessionTab {+ window_id: 3,+ tab_id: 17,+ pane_ids: vec![21, 22],+ title: "shell".into(),+ is_active: true,+ }],+ ..Default::default()+ }],+ ..Default::default()+ }],+ };+ encoded.clear();+ Pdu::ThinkTermSessionState(session.clone())+ .encode(&mut encoded, 0x53)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x53,+ pdu: Pdu::ThinkTermSessionState(session),+ }+ );++ let request = EnsureThinkTermThread {+ preferred_thread_id: Some("thread".into()),+ size,+ };+ encoded.clear();+ Pdu::EnsureThinkTermThread(request.clone())+ .encode(&mut encoded, 0x54)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x54,+ pdu: Pdu::EnsureThinkTermThread(request),+ }+ );++ let response = EnsureThinkTermThreadResponse {+ thread_id: "thread".into(),+ workspace: "thinkterm:project:thread".into(),+ spawned: true,+ };+ encoded.clear();+ Pdu::EnsureThinkTermThreadResponse(response.clone())+ .encode(&mut encoded, 0x55)+ .unwrap();+ assert_eq!(+ Pdu::decode(encoded.as_slice()).unwrap(),+ DecodedPdu {+ serial: 0x55,+ pdu: Pdu::EnsureThinkTermThreadResponse(response),+ }+ );+ }+#[test]fn application_palette_state_round_trip() {for palette in [None, Some(ColorPalette::default())] {diff --git a/mux/src/domain.rs b/mux/src/domain.rsindex 077c05b0..84d59307 100644--- a/mux/src/domain.rs+++ b/mux/src/domain.rs@@ -498,6 +498,10 @@ impl LocalDomain {cmd.env("WEZTERM_UNIX_SOCKET", sock);}cmd.env("WEZTERM_PANE", pane_id.to_string());+ cmd.env(+ "THINKTERM_MUX_SERVER_ID",+ Mux::get().runtime_server_id().to_string(),+ );if let Some(agent) = Mux::get().agent.as_ref() {cmd.env("SSH_AUTH_SOCK", agent.path());}diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex 205ae4bf..c4bceb5b 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -25,7 +25,7 @@ use std::os::raw::c_int;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Weak};use std::thread;-use std::time::{Duration, Instant};+use std::time::{Duration, Instant, SystemTime};use termwiz::escape::csi::{DecPrivateMode, DecPrivateModeCode, Device, Mode};use termwiz::escape::{Action, CSI};use thiserror::*;@@ -102,10 +102,45 @@ pub enum MuxNotification {/// every connection re-sends it. Raised only on the server side — a GUI/// mux never owns a tree of its own.ThinkTermTreeChanged,+ /// The authoritative server tree or live mux topology changed; thin+ /// frontends should refresh their read-only session snapshot.+ ThinkTermSessionChanged,+ /// The renderer allowed to drive one tab's shared PTY geometry changed,+ /// or that owner published a new canonical viewport.+ FrontendLeaseChanged(FrontendViewportState),}static SUB_ID: AtomicUsize = AtomicUsize::new(0);static PALETTE_SESSION_ID: AtomicUsize = AtomicUsize::new(1);+static CLIENT_REGISTRATION_ID: AtomicUsize = AtomicUsize::new(1);+static SERVER_ID_SEQUENCE: AtomicUsize = AtomicUsize::new(1);++fn new_runtime_server_id() -> String {+ let epoch_nanos = SystemTime::now()+ .duration_since(SystemTime::UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos();+ let host = hostname::get()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_else(|_| "localhost".to_string());+ format!(+ "{host}:{}:{epoch_nanos}:{}",+ std::process::id(),+ SERVER_ID_SEQUENCE.fetch_add(1, Ordering::Relaxed)+ )+}++/// Identifies one live transport registration for a `ClientId`. A reconnect+/// intentionally reuses `ClientId`, so disconnect cleanup and queued viewport+/// work also carry this generation and cannot tear down the replacement.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct ClientRegistrationId(usize);++impl ClientRegistrationId {+ fn new() -> Self {+ Self(CLIENT_REGISTRATION_ID.fetch_add(1, Ordering::Relaxed))+ }+}/// A single mux-server transport connection. `ClientId` identifies the GUI/// process and can be reused when that process reconnects, so it is not@@ -119,6 +154,80 @@ pub struct PaletteSelectionChange {pub palette: Option<ColorPalette>,}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct FrontendPaneViewport {+ pub pane_id: PaneId,+ pub size: wezterm_term::TerminalSize,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum FrontendViewport {+ CellGrid {+ size: wezterm_term::TerminalSize,+ },+ Native {+ size: wezterm_term::TerminalSize,+ panes: Vec<FrontendPaneViewport>,+ },+}++impl FrontendViewport {+ pub fn size(&self) -> wezterm_term::TerminalSize {+ match self {+ Self::CellGrid { size } | Self::Native { size, .. } => *size,+ }+ }+}++/// What the renderer holding a tab's viewport is currently looking at.+///+/// Size alone makes two attached devices the same shape; it does not make them+/// the same view. Without this a phone and a desktop on one tab sit at+/// different points in the same scrollback, which reads as two sessions that+/// happen to share a name.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct FrontendView {+ /// Lines above the bottom of each pane's scrollback. A pane that is absent+ /// is following its output.+ pub scroll: Vec<(PaneId, u32)>,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct FrontendViewportState {+ pub tab_id: TabId,+ pub owner: Option<ClientId>,+ pub canonical_size: wezterm_term::TerminalSize,+ /// What the owner is looking at, when the owner is a renderer that says.+ /// `None` means nobody has offered one — followers keep their own view+ /// rather than being pulled somewhere arbitrary.+ pub view: Option<FrontendView>,+ pub generation: u64,+}++#[derive(Default)]+struct TabFrontendLease {+ owner: Option<ClientId>,+ viewports: HashMap<ClientId, FrontendViewport>,+ /// Written by the owner alone, and dropped the moment the lease moves, so+ /// it can never describe a renderer that is no longer driving.+ view: Option<FrontendView>,+ generation: u64,+}++struct FrontendLeaseState {+ tabs: HashMap<TabId, TabFrontendLease>,+ next_generation: u64,+}++impl Default for FrontendLeaseState {+ fn default() -> Self {+ Self {+ tabs: HashMap::new(),+ next_generation: 1,+ }+ }+}+/// Server-side palette advice is scoped to the client that supplied it./// Merely attaching records advice; focus or real input activates it for OSC/// queries. Application palette overrides are tracked by the terminal and are@@ -219,6 +328,7 @@ impl PaletteAdvisoryState {}pub struct Mux {+ runtime_server_id: String,tabs: RwLock<HashMap<TabId, Arc<Tab>>>,panes: RwLock<HashMap<PaneId, Arc<dyn Pane>>>,windows: RwLock<HashMap<WindowId, Window>>,@@ -228,6 +338,8 @@ pub struct Mux {subscribers: RwLock<HashMap<usize, Box<dyn Fn(MuxNotification) -> bool + Send + Sync>>>,banner: RwLock<Option<String>>,clients: RwLock<HashMap<ClientId, ClientInfo>>,+ client_registrations: RwLock<HashMap<ClientId, ClientRegistrationId>>,+ frontend_lease: Mutex<FrontendLeaseState>,palette_advisories: Mutex<PaletteAdvisoryState>,identity: RwLock<Option<Arc<ClientId>>>,num_panes_by_workspace: RwLock<HashMap<String, usize>>,@@ -560,6 +672,7 @@ impl Mux {};Self {+ runtime_server_id: new_runtime_server_id(),tabs: RwLock::new(HashMap::new()),panes: RwLock::new(HashMap::new()),windows: RwLock::new(HashMap::new()),@@ -569,6 +682,8 @@ impl Mux {subscribers: RwLock::new(HashMap::new()),banner: RwLock::new(None),clients: RwLock::new(HashMap::new()),+ client_registrations: RwLock::new(HashMap::new()),+ frontend_lease: Mutex::new(FrontendLeaseState::default()),palette_advisories: Mutex::new(PaletteAdvisoryState::default()),identity: RwLock::new(None),num_panes_by_workspace: RwLock::new(HashMap::new()),@@ -577,6 +692,13 @@ impl Mux {}}+ /// Identity of this running mux process. This is intentionally ephemeral:+ /// today a mux restart cannot preserve any pane whose environment refers+ /// to the old value.+ pub fn runtime_server_id(&self) -> &str {+ &self.runtime_server_id+ }+fn get_default_workspace(&self) -> String {let config = configuration();config@@ -616,9 +738,334 @@ impl Mux {}}+ /// Transport-scoped input accounting. Returns false for work from a+ /// connection that has already been superseded by a reconnect.+ pub fn registered_client_had_input(+ &self,+ client_id: &ClientId,+ registration: ClientRegistrationId,+ ) -> bool {+ let registrations = self.client_registrations.read();+ if registrations.get(client_id) != Some(®istration) {+ return false;+ }+ self.client_had_input(client_id);+ true+ }++ fn validate_frontend_viewport(+ &self,+ tab_id: TabId,+ viewport: &FrontendViewport,+ ) -> anyhow::Result<()> {+ let tab = self+ .get_tab(tab_id)+ .ok_or_else(|| anyhow!("no such tab {tab_id}"))?;+ if viewport.size().rows == 0 || viewport.size().cols == 0 {+ anyhow::bail!("viewport for tab {tab_id} has zero rows or columns");+ }+ if let FrontendViewport::Native { panes, .. } = viewport {+ for pane in panes {+ if !tab.contains_pane(pane.pane_id) {+ anyhow::bail!(+ "pane {} is not contained by viewport tab {tab_id}",+ pane.pane_id+ );+ }+ if pane.size.rows == 0 || pane.size.cols == 0 {+ anyhow::bail!("viewport for pane {} is empty", pane.pane_id);+ }+ }+ }+ Ok(())+ }++ fn viewport_state(&self, tab_id: TabId) -> Option<FrontendViewportState> {+ let tab = self.get_tab(tab_id)?;+ let lease = self.frontend_lease.lock();+ let state = lease.tabs.get(&tab_id)?;+ Some(FrontendViewportState {+ tab_id,+ owner: state.owner.clone(),+ canonical_size: tab.get_size(),+ view: state.view.clone(),+ generation: state.generation,+ })+ }++ /// Record what the owner of a tab's viewport is looking at.+ ///+ /// Only the owner may write it, for the same reason only the owner sets the+ /// size: a renderer that is not being used does not get to move everyone+ /// else. Returns whether anything changed, so a caller can avoid publishing+ /// a scroll that already matches.+ pub fn set_client_view(&self, client_id: &ClientId, tab_id: TabId, view: FrontendView) -> bool {+ let changed = {+ let mut lease = self.frontend_lease.lock();+ let Some(state) = lease.tabs.get_mut(&tab_id) else {+ return false;+ };+ if state.owner.as_ref() != Some(client_id) {+ return false;+ }+ if state.view.as_ref() == Some(&view) {+ false+ } else {+ state.view = Some(view);+ true+ }+ };+ if changed {+ self.publish_frontend_viewport_state(tab_id);+ }+ changed+ }++ /// Record one renderer's desired viewport for one tab. A passive resize+ /// never steals ownership. The first renderer establishes an owner; an+ /// existing owner applies its changed viewport immediately.+ pub fn set_client_viewport(+ &self,+ client_id: &ClientId,+ tab_id: TabId,+ viewport: FrontendViewport,+ ) -> anyhow::Result<FrontendViewportState> {+ self.validate_frontend_viewport(tab_id, &viewport)?;+ let (should_apply, should_publish) = {+ let mut lease = self.frontend_lease.lock();+ let state = lease.tabs.entry(tab_id).or_default();+ let viewport_changed = state.viewports.get(client_id) != Some(&viewport);+ if viewport_changed {+ state.viewports.insert(client_id.clone(), viewport.clone());+ }+ let owner_changed = state.owner.is_none();+ if owner_changed {+ state.owner = Some(client_id.clone());+ }+ let should_apply =+ state.owner.as_ref() == Some(client_id) && (owner_changed || viewport_changed);+ (should_apply, should_apply)+ };+ if should_apply {+ self.apply_frontend_viewport(tab_id, &viewport)?;+ }+ if should_publish {+ self.publish_frontend_viewport_state(tab_id);+ }+ self.viewport_state(tab_id)+ .ok_or_else(|| anyhow!("viewport state for tab {tab_id} disappeared"))+ }++ /// Transport-scoped viewport update. Old handlers can still have work in+ /// the mux queue after a reconnect; reject it instead of applying stale+ /// geometry to the replacement connection.+ pub fn set_registered_client_viewport(+ &self,+ client_id: &ClientId,+ registration: ClientRegistrationId,+ tab_id: TabId,+ viewport: FrontendViewport,+ ) -> anyhow::Result<Option<FrontendViewportState>> {+ let registrations = self.client_registrations.read();+ if registrations.get(client_id) != Some(®istration) {+ return Ok(None);+ }+ drop(registrations);+ self.set_client_viewport(client_id, tab_id, viewport)+ .map(Some)+ }++ pub fn client_owns_frontend_lease(&self, client_id: &ClientId, tab_id: TabId) -> bool {+ self.frontend_lease+ .lock()+ .tabs+ .get(&tab_id)+ .and_then(|state| state.owner.as_ref())+ == Some(client_id)+ }++ pub fn current_identity_owns_frontend_lease(&self, tab_id: TabId) -> bool {+ match self.active_identity() {+ Some(identity) => self.client_owns_frontend_lease(&identity, tab_id),+ None => self+ .frontend_lease+ .lock()+ .tabs+ .get(&tab_id)+ .and_then(|state| state.owner.as_ref())+ .is_none(),+ }+ }++ /// Claim the viewport for a real user interaction. Clients without a+ /// viewport (for example `thinkterm cli send-text`) update idle accounting+ /// but cannot become geometry owners.+ pub fn registered_client_had_tab_input(+ &self,+ client_id: &ClientId,+ registration: ClientRegistrationId,+ tab_id: TabId,+ ) -> bool {+ let registrations = self.client_registrations.read();+ if registrations.get(client_id) != Some(®istration) {+ return false;+ }+ drop(registrations);+ self.client_had_input(client_id);++ if let Err(err) = self.claim_frontend_viewport(client_id, tab_id) {+ log::error!("failed to apply claimed viewport for tab {tab_id}: {err:#}");+ }+ true+ }++ /// Explicit renderer claim used by UI-only interactions such as pane+ /// resize. The transport must still be current and must already have+ /// advertised a viewport; geometry is taken only from that server-held+ /// advertisement.+ pub fn claim_registered_client_viewport(+ &self,+ client_id: &ClientId,+ registration: ClientRegistrationId,+ tab_id: TabId,+ ) -> anyhow::Result<Option<FrontendViewportState>> {+ let registrations = self.client_registrations.read();+ if registrations.get(client_id) != Some(®istration) {+ return Ok(None);+ }+ drop(registrations);+ self.client_had_input(client_id);+ self.claim_frontend_viewport(client_id, tab_id)?+ .ok_or_else(|| anyhow!("client has not advertised a viewport for tab {tab_id}"))+ .map(Some)+ }++ fn claim_frontend_viewport(+ &self,+ client_id: &ClientId,+ tab_id: TabId,+ ) -> anyhow::Result<Option<FrontendViewportState>> {+ let (viewport, already_owned) = {+ let lease = self.frontend_lease.lock();+ let Some(state) = lease.tabs.get(&tab_id) else {+ return Ok(None);+ };+ let Some(viewport) = state.viewports.get(client_id).cloned() else {+ return Ok(None);+ };+ (viewport, state.owner.as_ref() == Some(client_id))+ };+ if already_owned {+ return Ok(self.viewport_state(tab_id));+ }++ self.apply_frontend_viewport(tab_id, &viewport)?;+ {+ let mut lease = self.frontend_lease.lock();+ let Some(state) = lease.tabs.get_mut(&tab_id) else {+ return Ok(None);+ };+ if !state.viewports.contains_key(client_id) {+ return Ok(None);+ }+ state.owner = Some(client_id.clone());+ // The view belonged to whoever was driving. Carrying it across a+ // handover would leave the new owner's followers pinned to a+ // scrollback position nobody chose; the new owner publishes its own+ // on its next frame.+ state.view = None;+ }+ self.publish_frontend_viewport_state(tab_id);+ Ok(self.viewport_state(tab_id))+ }++ /// `None` means the transport generation is stale. `Some(false)` means a+ /// live non-owner submitted a legacy pane resize and it must be a no-op.+ pub fn registered_client_may_resize_tab(+ &self,+ client_id: &ClientId,+ registration: ClientRegistrationId,+ tab_id: TabId,+ ) -> Option<bool> {+ if self.client_registrations.read().get(client_id) != Some(®istration) {+ return None;+ }+ let lease = self.frontend_lease.lock();+ Some(match lease.tabs.get(&tab_id) {+ None => true,+ Some(state) => state.owner.as_ref() == Some(client_id),+ })+ }++ fn publish_frontend_viewport_state(&self, tab_id: TabId) {+ let (generation, owner, view) = {+ let mut lease = self.frontend_lease.lock();+ let generation = lease.next_generation;+ lease.next_generation = lease.next_generation.saturating_add(1);+ let Some(state) = lease.tabs.get_mut(&tab_id) else {+ return;+ };+ state.generation = generation;+ (generation, state.owner.clone(), state.view.clone())+ };+ let Some(tab) = self.get_tab(tab_id) else {+ return;+ };+ self.notify(MuxNotification::FrontendLeaseChanged(+ FrontendViewportState {+ tab_id,+ owner,+ canonical_size: tab.get_size(),+ view,+ generation,+ },+ ));+ }++ fn apply_frontend_viewport(+ &self,+ tab_id: TabId,+ viewport: &FrontendViewport,+ ) -> anyhow::Result<()> {+ let tab = self+ .get_tab(tab_id)+ .ok_or_else(|| anyhow!("no such tab {tab_id}"))?;+ let size = viewport.size();+ tab.resize(size);++ if let FrontendViewport::Native { panes, .. } = viewport {+ for pane_viewport in panes {+ let pane = self+ .get_pane(pane_viewport.pane_id)+ .ok_or_else(|| anyhow!("no such pane {}", pane_viewport.pane_id))?;+ if !tab.contains_pane(pane_viewport.pane_id) {+ anyhow::bail!("pane {} is not in tab {tab_id}", pane_viewport.pane_id);+ }+ pane.resize(pane_viewport.size)?;+ }+ if !panes.is_empty() {+ tab.rebuild_splits_sizes_from_contained_panes();+ }+ return Ok(());+ }++ for positioned in tab.iter_panes() {+ let target = pane_size_for_cell_grid(size, positioned.width, positioned.height);+ positioned.pane.resize(target)?;+ }+ Ok(())+ }+pub fn record_input_for_current_identity(&self) {- if let Some(ident) = self.identity.read().as_ref() {- self.client_had_input(ident);+ let Some(ident) = self.active_identity() else {+ return;+ };+ self.client_had_input(&ident);+ let Some((_domain, _window, tab_id, _pane)) = self.resolve_focused_pane(&ident) else {+ return;+ };+ if let Err(err) = self.claim_frontend_viewport(&ident, tab_id) {+ log::error!("failed to claim local frontend viewport for tab {tab_id}: {err:#}");}}@@ -690,10 +1137,20 @@ impl Mux {Ok(())}- pub fn register_client(&self, client_id: Arc<ClientId>) {- self.clients- .write()- .insert((*client_id).clone(), ClientInfo::new(client_id));+ pub fn register_client(&self, client_id: Arc<ClientId>) -> ClientRegistrationId {+ let registration = ClientRegistrationId::new();+ let key = (*client_id).clone();+ {+ // Registration generation and client metadata are one logical+ // replacement. Keep the generation lock until both are visible so+ // a stale Drop cannot remove the newly reconnected client between+ // the two writes.+ let mut registrations = self.client_registrations.write();+ let mut clients = self.clients.write();+ clients.insert(key.clone(), ClientInfo::new(client_id));+ registrations.insert(key.clone(), registration);+ }+ registration}pub fn iter_clients(&self) -> Vec<ClientInfo> {@@ -813,8 +1270,48 @@ impl Mux {/// Remove a client from the ordinary mux client list./// Palette ownership is connection-scoped and is cleaned independently.- pub fn unregister_client(&self, client_id: &ClientId) {- self.clients.write().remove(client_id);+ pub fn unregister_client(&self, client_id: &ClientId, registration: ClientRegistrationId) {+ {+ let mut registrations = self.client_registrations.write();+ if registrations.get(client_id) != Some(®istration) {+ return;+ }+ self.clients.write().remove(client_id);+ registrations.remove(client_id);+ }+ let clients = self.clients.read();+ let affected = {+ let mut lease = self.frontend_lease.lock();+ let mut affected = Vec::new();+ for (tab_id, state) in &mut lease.tabs {+ state.viewports.remove(client_id);+ if state.owner.as_ref() != Some(client_id) {+ continue;+ }+ let replacement = clients+ .values()+ .filter(|info| state.viewports.contains_key(info.client_id.as_ref()))+ .max_by_key(|info| info.last_input)+ .map(|info| (*info.client_id).clone());+ state.owner = replacement.clone();+ state.view = None;+ let viewport = replacement+ .as_ref()+ .and_then(|replacement| state.viewports.get(replacement).cloned());+ affected.push((*tab_id, viewport));+ }+ affected+ };+ drop(clients);++ for (tab_id, viewport) in affected {+ if let Some(viewport) = viewport {+ if let Err(err) = self.apply_frontend_viewport(tab_id, &viewport) {+ log::error!("failed to apply fallback viewport for tab {tab_id}: {err:#}");+ }+ }+ self.publish_frontend_viewport_state(tab_id);+ }}/// Register one transport connection for palette advice. The returned@@ -1006,6 +1503,7 @@ impl Mux {log::debug!("remove_tab_internal tab {}", tab_id);let tab = self.tabs.write().remove(&tab_id)?;+ self.frontend_lease.lock().tabs.remove(&tab_id);if let Some(mut windows) = self.windows.try_write() {for w in windows.values_mut() {@@ -1850,6 +2348,24 @@ impl Mux {}}+fn pane_size_for_cell_grid(size: TerminalSize, cols: usize, rows: usize) -> TerminalSize {+ let cols = cols.max(1);+ let rows = rows.max(1);+ let cell_width = (size.pixel_width != 0)+ .then(|| size.pixel_width / size.cols.max(1))+ .map(|width| width.max(1));+ let cell_height = (size.pixel_height != 0)+ .then(|| size.pixel_height / size.rows.max(1))+ .map(|height| height.max(1));+ TerminalSize {+ rows,+ cols,+ pixel_width: cell_width.map_or(0, |width| cols.saturating_mul(width)),+ pixel_height: cell_height.map_or(0, |height| rows.saturating_mul(height)),+ dpi: size.dpi,+ }+}+pub struct IdentityHolder {prior: Option<Arc<ClientId>>,}@@ -2009,6 +2525,252 @@ mod tests {assert_eq!(state.activate(session, 4), None);}+ #[test]+ fn stale_client_disconnect_cannot_remove_reconnected_frontend_lease() {+ let mux = Mux::new(None);+ let client = Arc::new(client_id(21));+ let old_registration = mux.register_client(Arc::clone(&client));+ let new_registration = mux.register_client(Arc::clone(&client));++ assert!(!mux.registered_client_had_input(&client, old_registration));+ assert!(mux.registered_client_had_input(&client, new_registration));+ mux.unregister_client(&client, old_registration);++ assert_eq!(mux.iter_clients().len(), 1);+ mux.unregister_client(&client, new_registration);+ assert!(mux.iter_clients().is_empty());+ }++ #[test]+ fn frontend_ownership_is_scoped_per_tab() {+ let mux = Mux::new(None);+ let first = Arc::new(client_id(31));+ let second = Arc::new(client_id(32));+ let mut lease = mux.frontend_lease.lock();+ lease.tabs.entry(10).or_default().owner = Some((*first).clone());+ lease.tabs.entry(11).or_default().owner = Some((*second).clone());+ drop(lease);++ assert!(mux.client_owns_frontend_lease(&first, 10));+ assert!(!mux.client_owns_frontend_lease(&first, 11));+ assert!(mux.client_owns_frontend_lease(&second, 11));+ }++ #[test]+ fn non_rendering_cli_input_does_not_steal_a_tab_viewport() {+ let mux = Mux::new(None);+ let tui = Arc::new(client_id(62));+ let cli = Arc::new(client_id(63));+ mux.register_client(Arc::clone(&tui));+ let cli_registration = mux.register_client(Arc::clone(&cli));+ mux.frontend_lease.lock().tabs.entry(30).or_default().owner = Some((*tui).clone());++ assert!(mux.registered_client_had_tab_input(&cli, cli_registration, 30));+ assert!(mux.client_owns_frontend_lease(&tui, 30));+ }++ /// A view outliving its author would pin every follower to a scrollback+ /// position that the renderer now driving never chose.+ #[test]+ fn only_the_owner_publishes_a_view_and_a_handover_drops_it() {+ fn grid() -> FrontendViewport {+ FrontendViewport::CellGrid {+ size: TerminalSize::default(),+ }+ }+ let mux = Mux::new(None);+ let tab = Arc::new(Tab::new(&TerminalSize::default()));+ mux.add_tab_no_panes(&tab);+ let tab_40 = tab.tab_id();+ let first = Arc::new(client_id(80));+ let second = Arc::new(client_id(81));+ {+ let mut lease = mux.frontend_lease.lock();+ let state = lease.tabs.entry(tab_40).or_default();+ state.owner = Some((*first).clone());+ state.viewports.insert((*first).clone(), grid());+ state.viewports.insert((*second).clone(), grid());+ }++ assert!(mux.set_client_view(+ &first,+ tab_40,+ FrontendView {+ scroll: vec![(7, 120)]+ }+ ));+ assert!(+ !mux.set_client_view(+ &first,+ tab_40,+ FrontendView {+ scroll: vec![(7, 120)]+ }+ ),+ "saying the same thing twice is not a change worth publishing"+ );+ assert!(+ !mux.set_client_view(+ &second,+ tab_40,+ FrontendView {+ scroll: vec![(7, 999)]+ }+ ),+ "a renderer nobody is using does not get to move everyone else"+ );+ assert_eq!(+ mux.frontend_lease.lock().tabs[&tab_40].view,+ Some(FrontendView {+ scroll: vec![(7, 120)]+ })+ );++ let _ = mux.claim_frontend_viewport(&second, tab_40);+ assert_eq!(+ mux.frontend_lease.lock().tabs[&tab_40].view,+ None,+ "the new owner publishes its own on its next frame"+ );+ }++ #[test]+ fn different_sized_renderers_converge_on_one_owner_without_oscillation() {+ fn size(cols: usize, rows: usize) -> TerminalSize {+ TerminalSize {+ cols,+ rows,+ pixel_width: cols * 8,+ pixel_height: rows * 16,+ dpi: 96,+ }+ }++ let mux = Mux::new(None);+ let initial = size(132, 40);+ let tab = Arc::new(Tab::new(&initial));+ mux.add_tab_no_panes(&tab);+ let tab_id = tab.tab_id();++ let large = Arc::new(client_id(70));+ let small = Arc::new(client_id(71));+ let large_registration = mux.register_client(Arc::clone(&large));+ let small_registration = mux.register_client(Arc::clone(&small));++ mux.set_registered_client_viewport(+ &large,+ large_registration,+ tab_id,+ FrontendViewport::CellGrid { size: initial },+ )+ .unwrap()+ .unwrap();+ mux.set_registered_client_viewport(+ &small,+ small_registration,+ tab_id,+ FrontendViewport::CellGrid { size: size(80, 24) },+ )+ .unwrap()+ .unwrap();++ assert_eq!(tab.get_size(), initial);+ assert_eq!(+ mux.registered_client_may_resize_tab(&large, large_registration, tab_id),+ Some(true)+ );+ assert_eq!(+ mux.registered_client_may_resize_tab(&small, small_registration, tab_id),+ Some(false)+ );++ assert!(mux.registered_client_had_tab_input(&small, small_registration, tab_id));+ assert_eq!(tab.get_size(), size(80, 24));+ assert!(mux.client_owns_frontend_lease(&small, tab_id));+ assert_eq!(+ mux.registered_client_may_resize_tab(&large, large_registration, tab_id),+ Some(false)+ );+ }++ #[test]+ fn explicit_viewport_claim_uses_the_server_stored_advertisement() {+ let mux = Mux::new(None);+ let initial = TerminalSize {+ cols: 120,+ rows: 36,+ pixel_width: 960,+ pixel_height: 576,+ dpi: 96,+ };+ let tab = Arc::new(Tab::new(&initial));+ mux.add_tab_no_panes(&tab);+ let tab_id = tab.tab_id();+ let first = Arc::new(client_id(80));+ let second = Arc::new(client_id(81));+ let first_registration = mux.register_client(Arc::clone(&first));+ let second_registration = mux.register_client(Arc::clone(&second));++ mux.set_registered_client_viewport(+ &first,+ first_registration,+ tab_id,+ FrontendViewport::CellGrid { size: initial },+ )+ .unwrap();+ let smaller = TerminalSize {+ cols: 72,+ rows: 20,+ pixel_width: 576,+ pixel_height: 320,+ dpi: 96,+ };+ mux.set_registered_client_viewport(+ &second,+ second_registration,+ tab_id,+ FrontendViewport::CellGrid { size: smaller },+ )+ .unwrap();++ let state = mux+ .claim_registered_client_viewport(&second, second_registration, tab_id)+ .unwrap()+ .unwrap();+ assert_eq!(state.owner.as_ref(), Some(second.as_ref()));+ assert_eq!(state.canonical_size, smaller);+ assert_eq!(tab.get_size(), smaller);+ }++ #[test]+ fn unknown_cell_grid_pixels_stay_unknown_for_each_pane() {+ let target = pane_size_for_cell_grid(+ TerminalSize {+ cols: 120,+ rows: 40,+ pixel_width: 0,+ pixel_height: 0,+ dpi: 96,+ },+ 60,+ 20,+ );+ assert_eq!((target.pixel_width, target.pixel_height), (0, 0));++ let known = pane_size_for_cell_grid(+ TerminalSize {+ cols: 120,+ rows: 40,+ pixel_width: 960,+ pixel_height: 640,+ dpi: 96,+ },+ 60,+ 20,+ );+ assert_eq!((known.pixel_width, known.pixel_height), (480, 320));+ }+#[test]fn late_palette_updates_from_a_disconnected_client_are_rejected() {let mut state = PaletteAdvisoryState::default();diff --git a/mux/src/tab.rs b/mux/src/tab.rsindex e2ef625b..e815889a 100644--- a/mux/src/tab.rs+++ b/mux/src/tab.rs@@ -430,6 +430,7 @@ fn pane_tree(title: pane.get_title(),is_active_pane: is_pane(pane, &active),is_zoomed_pane: is_pane(pane, &zoomed),+ alt_screen: pane.is_alt_screen_active(),size: TerminalSize {cols: dims.cols,rows: dims.viewport_rows,@@ -3468,6 +3469,10 @@ pub struct PaneEntry {pub working_dir: Option<SerdeUrl>,pub is_active_pane: bool,pub is_zoomed_pane: bool,+ /// Whether the pane is showing the alternate screen. Carried here as well+ /// as in render changes so that a renderer knows it the moment it learns+ /// the pane exists, rather than only once something in it next changes.+ pub alt_screen: bool,pub workspace: String,pub cursor_pos: StableCursorPosition,pub physical_top: StableRowIndex,@@ -4299,6 +4304,7 @@ mod test {working_dir: None,is_active_pane,is_zoomed_pane: false,+ alt_screen: false,workspace: "default".to_string(),cursor_pos: StableCursorPosition::default(),physical_top: 0,diff --git a/thinkterm-core/Cargo.toml b/thinkterm-core/Cargo.tomlnew file mode 100644index 00000000..051d68c3--- /dev/null+++ b/thinkterm-core/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "thinkterm-core"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+anyhow.workspace = true+base64.workspace = true+config.workspace = true+dirs-next.workspace = true+openssl.workspace = true+serde = { workspace = true, features = ["derive"] }+serde_json.workspace = true++[dev-dependencies]+tempfile.workspace = truediff --git a/thinkterm-core/src/lib.rs b/thinkterm-core/src/lib.rsnew file mode 100644index 00000000..323cade4--- /dev/null+++ b/thinkterm-core/src/lib.rs@@ -0,0 +1,27 @@+//! Frontend-neutral ThinkTerm data and connection helpers.+//!+//! Both the desktop GUI and `thinkterm tui` consume this crate. It contains+//! no window-system or terminal-rendering code and never owns mux state.++pub mod secret;+pub mod ssh_hosts;++/// The native GUI data directory. Keep the historical capitalisation: the+/// existing host catalog and encryption key live under `ThinkTerm`, while+/// config's protocol/runtime data uses a separate lowercase directory.+pub fn frontend_data_dir() -> std::path::PathBuf {+ dirs_next::data_dir()+ .unwrap_or_else(|| config::HOME_DIR.join(".local/share"))+ .join("ThinkTerm")+}++#[cfg(test)]+mod tests {+ #[test]+ fn frontend_store_keeps_legacy_gui_capitalisation() {+ assert_eq!(+ super::frontend_data_dir().file_name(),+ Some(std::ffi::OsStr::new("ThinkTerm"))+ );+ }+}diff --git a/thinkterm-core/src/secret.rs b/thinkterm-core/src/secret.rsnew file mode 100644index 00000000..208deb4d--- /dev/null+++ b/thinkterm-core/src/secret.rs@@ -0,0 +1,115 @@+//! At-rest encryption for secrets stored by ThinkTerm.++use anyhow::{Context, Result};+use base64::engine::general_purpose::STANDARD;+use base64::Engine;+use openssl::symm::{decrypt_aead, encrypt_aead, Cipher};+use std::fs;+use std::io::Write;+use std::path::Path;++const MARKER: &str = "enc:v1:";+const IV_LEN: usize = 12;+const TAG_LEN: usize = 16;++fn key_path() -> std::path::PathBuf {+ crate::frontend_data_dir().join("secret.key")+}++fn load_or_create_key() -> Result<[u8; 32]> {+ load_or_create_key_at(&key_path())+}++fn load_or_create_key_at(path: &Path) -> Result<[u8; 32]> {+ if let Ok(bytes) = fs::read(path) {+ if bytes.len() == 32 {+ let mut key = [0u8; 32];+ key.copy_from_slice(&bytes);+ return Ok(key);+ }+ }+ let mut key = [0u8; 32];+ openssl::rand::rand_bytes(&mut key).context("generate secret key")?;+ if let Some(parent) = path.parent() {+ fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;+ }+ write_key_file(path, &key)?;+ Ok(key)+}++#[cfg(unix)]+fn write_key_file(path: &Path, key: &[u8]) -> Result<()> {+ use std::os::unix::fs::OpenOptionsExt;+ let mut file = fs::OpenOptions::new()+ .write(true)+ .create(true)+ .truncate(true)+ .mode(0o600)+ .open(path)+ .with_context(|| format!("create {}", path.display()))?;+ file.write_all(key)+ .with_context(|| format!("write {}", path.display()))+}++#[cfg(not(unix))]+fn write_key_file(path: &Path, key: &[u8]) -> Result<()> {+ fs::write(path, key).with_context(|| format!("write {}", path.display()))+}++pub fn is_encrypted(value: &str) -> bool {+ value.starts_with(MARKER)+}++pub fn encrypt(plaintext: &str) -> Result<String> {+ let key = load_or_create_key()?;+ let mut iv = [0u8; IV_LEN];+ openssl::rand::rand_bytes(&mut iv).context("generate nonce")?;+ let mut tag = [0u8; TAG_LEN];+ let ciphertext = encrypt_aead(+ Cipher::aes_256_gcm(),+ &key,+ Some(&iv),+ &[],+ plaintext.as_bytes(),+ &mut tag,+ )+ .context("aes-256-gcm encrypt")?;+ let mut blob = Vec::with_capacity(IV_LEN + TAG_LEN + ciphertext.len());+ blob.extend_from_slice(&iv);+ blob.extend_from_slice(&tag);+ blob.extend_from_slice(&ciphertext);+ Ok(format!("{MARKER}{}", STANDARD.encode(&blob)))+}++pub fn decrypt(stored: &str) -> Option<String> {+ let blob = STANDARD.decode(stored.strip_prefix(MARKER)?).ok()?;+ if blob.len() < IV_LEN + TAG_LEN {+ return None;+ }+ let key = load_or_create_key().ok()?;+ let (iv, rest) = blob.split_at(IV_LEN);+ let (tag, ciphertext) = rest.split_at(TAG_LEN);+ let plaintext =+ decrypt_aead(Cipher::aes_256_gcm(), &key, Some(iv), &[], ciphertext, tag).ok()?;+ String::from_utf8(plaintext).ok()+}++pub fn reveal(stored: &str) -> String {+ if is_encrypted(stored) {+ decrypt(stored).unwrap_or_default()+ } else {+ stored.to_string()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn encrypted_marker_is_distinct_from_plaintext() {+ assert!(!is_encrypted("plain"));+ assert!(is_encrypted("enc:v1:anything"));+ assert_eq!(reveal("plain"), "plain");+ }+}diff --git a/thinkterm-core/src/ssh_hosts.rs b/thinkterm-core/src/ssh_hosts.rsnew file mode 100644index 00000000..b02a6157--- /dev/null+++ b/thinkterm-core/src/ssh_hosts.rs@@ -0,0 +1,331 @@+//! Shared SSH host catalog and mux-domain translation.++use anyhow::{Context, Result};+use config::{SshDomain, SshMultiplexing};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::fs;+use std::path::Path;++pub type SshHostId = String;+pub const DEFAULT_MOSH_SERVER_COMMAND: &str = "mosh-server new -s -l LANG=en_US.UTF-8";++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct SshHostSpec {+ pub label: String,+ pub host: String,+ #[serde(default)]+ pub port: Option<u16>,+ #[serde(default)]+ pub username: Option<String>,+ #[serde(default)]+ pub identity_file: Option<String>,+ #[serde(default)]+ pub password: Option<String>,+ #[serde(default)]+ pub ssh_options: HashMap<String, String>,+ #[serde(default)]+ pub multiplexing: bool,+ #[serde(default)]+ pub default_workspace: Option<String>,+ #[serde(default = "default_true")]+ pub detect_os: bool,+ #[serde(default)]+ pub detected_distro: Option<String>,+ #[serde(default)]+ pub use_mosh: bool,+ #[serde(default = "default_mosh_server_command")]+ pub mosh_server_command: String,+}++pub fn default_true() -> bool {+ true+}++pub fn default_mosh_server_command() -> String {+ DEFAULT_MOSH_SERVER_COMMAND.to_string()+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SshHostSource {+ ThinkTerm,+ System,+}++#[derive(Debug, Clone)]+pub struct SshHostEntry {+ pub id: SshHostId,+ pub source: SshHostSource,+ pub spec: SshHostSpec,+}++#[derive(Debug, Clone, Deserialize)]+struct SshHostRecord {+ id: SshHostId,+ spec: SshHostSpec,+}++#[derive(Debug, Clone, Default, Deserialize)]+struct SshHostStore {+ #[allow(dead_code)]+ #[serde(default)]+ version: u32,+ #[serde(default)]+ hosts: Vec<SshHostRecord>,+}++pub fn saved_hosts_path() -> std::path::PathBuf {+ crate::frontend_data_dir().join("ssh_hosts.json")+}++pub fn list_saved_hosts() -> Result<Vec<SshHostEntry>> {+ list_saved_hosts_from_path(&saved_hosts_path())+}++pub fn list_saved_hosts_from_path(path: &Path) -> Result<Vec<SshHostEntry>> {+ if !path.exists() {+ return Ok(vec![]);+ }+ let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;+ let store: SshHostStore =+ serde_json::from_reader(file).with_context(|| format!("parse {}", path.display()))?;+ Ok(store+ .hosts+ .into_iter()+ .map(|record| SshHostEntry {+ id: record.id,+ source: SshHostSource::ThinkTerm,+ spec: record.spec,+ })+ .collect())+}++pub fn list_system_hosts() -> Result<Vec<SshHostEntry>> {+ list_system_hosts_from_path(&config::HOME_DIR.join(".ssh").join("config"))+}++pub fn list_system_hosts_from_path(path: &Path) -> Result<Vec<SshHostEntry>> {+ if !path.exists() {+ return Ok(vec![]);+ }+ let content = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;+ Ok(parse_system_ssh_config(&content))+}++pub fn list_all_hosts() -> Result<Vec<SshHostEntry>> {+ let mut entries = list_saved_hosts()?;+ entries.extend(list_system_hosts()?);+ entries.sort_by(|a, b| {+ a.spec+ .label+ .to_ascii_lowercase()+ .cmp(&b.spec.label.to_ascii_lowercase())+ });+ entries.dedup_by(|a, b| a.id == b.id);+ Ok(entries)+}++#[derive(Default)]+struct SystemHostBlock {+ aliases: Vec<String>,+ user: Option<String>,+ port: Option<u16>,+ identity_file: Option<String>,+}++pub fn parse_system_ssh_config(content: &str) -> Vec<SshHostEntry> {+ fn flush(block: &mut Option<SystemHostBlock>, out: &mut Vec<SshHostEntry>) {+ let Some(block) = block.take() else { return };+ for alias in block.aliases {+ if alias.starts_with('!') || alias.contains('*') || alias.contains('?') {+ continue;+ }+ out.push(SshHostEntry {+ id: system_host_id(&alias),+ source: SshHostSource::System,+ spec: SshHostSpec {+ label: alias.clone(),+ host: alias,+ port: block.port,+ username: block.user.clone(),+ identity_file: block.identity_file.clone(),+ password: None,+ ssh_options: HashMap::new(),+ multiplexing: false,+ default_workspace: None,+ detect_os: true,+ detected_distro: None,+ use_mosh: false,+ mosh_server_command: default_mosh_server_command(),+ },+ });+ }+ }++ let mut entries = Vec::new();+ let mut current: Option<SystemHostBlock> = None;+ for raw in content.lines() {+ let line = raw.split_once('#').map_or(raw, |(head, _)| head).trim();+ if line.is_empty() {+ continue;+ }+ let mut parts = line.split_whitespace();+ let Some(key) = parts.next() else { continue };+ match key.to_ascii_lowercase().as_str() {+ "host" => {+ flush(&mut current, &mut entries);+ current = Some(SystemHostBlock {+ aliases: parts.map(str::to_string).collect(),+ ..Default::default()+ });+ }+ "user" => {+ if let Some(block) = current.as_mut() {+ block.user = parts.next().map(str::to_string);+ }+ }+ "port" => {+ if let Some(block) = current.as_mut() {+ block.port = parts.next().and_then(|value| value.parse().ok());+ }+ }+ "identityfile" => {+ if let Some(block) = current.as_mut() {+ block.identity_file = parts.next().map(expand_home);+ }+ }+ _ => {}+ }+ }+ flush(&mut current, &mut entries);+ entries.sort_by(|a, b| {+ a.spec+ .label+ .to_ascii_lowercase()+ .cmp(&b.spec.label.to_ascii_lowercase())+ });+ entries.dedup_by(|a, b| a.id == b.id);+ entries+}++fn expand_home(value: &str) -> String {+ if value == "~" {+ config::HOME_DIR.to_string_lossy().into_owned()+ } else if let Some(rest) = value.strip_prefix("~/") {+ config::HOME_DIR.join(rest).to_string_lossy().into_owned()+ } else {+ value.to_string()+ }+}++fn fnv1a(input: &str) -> u64 {+ let mut hash = 0xcbf29ce484222325u64;+ for byte in input.bytes() {+ hash ^= byte as u64;+ hash = hash.wrapping_mul(0x100000001b3);+ }+ hash+}++fn system_host_id(alias: &str) -> SshHostId {+ format!("system-ssh-{:x}", fnv1a(&format!("system:{alias}")))+}++pub fn endpoint(spec: &SshHostSpec) -> String {+ let host = match spec.port {+ Some(port) if port != 22 => format!("{}:{port}", spec.host),+ _ => spec.host.clone(),+ };+ match &spec.username {+ Some(user) if !user.is_empty() => format!("{user}@{host}"),+ _ => host,+ }+}++pub fn ssh_domain_name(spec: &SshHostSpec) -> String {+ format!("ssh:{}", endpoint(spec))+}++pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {+ let mut ssh_option = spec+ .ssh_options+ .iter()+ .map(|(key, value)| (key.to_lowercase(), value.clone()))+ .collect::<HashMap<_, _>>();+ if let Some(identity) = &spec.identity_file {+ if !identity.trim().is_empty() {+ ssh_option.insert("identityfile".into(), identity.clone());+ }+ }+ ssh_option+ .entry("connecttimeout".into())+ .or_insert_with(|| "10".into());+ SshDomain {+ name: ssh_domain_name(spec),+ remote_address: match spec.port {+ Some(port) => format!("{}:{port}", spec.host),+ None => spec.host.clone(),+ },+ username: spec.username.clone(),+ multiplexing: if spec.multiplexing {+ SshMultiplexing::WezTerm+ } else {+ SshMultiplexing::None+ },+ ssh_option,+ local_echo_threshold_ms: config::default_local_echo_threshold_ms(),+ timeout: config::default_read_timeout(),+ ..Default::default()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_only_concrete_system_hosts() {+ let entries = parse_system_ssh_config(+ "Host prod *.internal\n User deploy\n Port 2202\n IdentityFile ~/.ssh/prod\n",+ );+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].spec.host, "prod");+ assert_eq!(entries[0].spec.username.as_deref(), Some("deploy"));+ assert_eq!(entries[0].spec.port, Some(2202));+ }++ #[test]+ fn saved_catalog_schema_is_frontend_neutral() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("ssh_hosts.json");+ std::fs::write(+ &path,+ r#"{"version":1,"hosts":[{"id":"h","spec":{"label":"AM2","host":"host","multiplexing":true}}]}"#,+ )+ .unwrap();+ let hosts = list_saved_hosts_from_path(&path).unwrap();+ assert_eq!(hosts[0].spec.label, "AM2");+ assert!(hosts[0].spec.multiplexing);+ }++ #[test]+ fn explicit_default_port_keeps_the_legacy_domain_name() {+ let spec = SshHostSpec {+ label: "server".into(),+ host: "example.test".into(),+ port: Some(22),+ username: Some("root".into()),+ identity_file: None,+ password: None,+ ssh_options: HashMap::new(),+ multiplexing: true,+ default_workspace: None,+ detect_os: true,+ detected_distro: None,+ use_mosh: false,+ mosh_server_command: default_mosh_server_command(),+ };+ assert_eq!(ssh_domain_name(&spec), "ssh:[email protected]");+ assert_eq!(build_ssh_domain(&spec).remote_address, "example.test:22");+ }+}diff --git a/thinkterm-tui/Cargo.toml b/thinkterm-tui/Cargo.tomlnew file mode 100644index 00000000..e150b0cd--- /dev/null+++ b/thinkterm-tui/Cargo.toml@@ -0,0 +1,29 @@+[package]+name = "thinkterm-tui"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+anyhow.workspace = true+async-channel.workspace = true+base64.workspace = true+codec.workspace = true+config.workspace = true+filedescriptor.workspace = true+log.workspace = true+mux.workspace = true+promise.workspace = true+ratatui.workspace = true+serde.workspace = true+serde_json.workspace = true+smol.workspace = true+termwiz.workspace = true+thinkterm-core.workspace = true+toml.workspace = true+uuid = { workspace = true, features = ["v4"] }+wezterm-client.workspace = true+wezterm-term.workspace = true++[target.'cfg(windows)'.dependencies]+clipboard-win.workspace = truediff --git a/thinkterm-tui/src/action.rs b/thinkterm-tui/src/action.rsnew file mode 100644index 00000000..a8f2e74a--- /dev/null+++ b/thinkterm-tui/src/action.rs@@ -0,0 +1,121 @@+use crate::model::{ThreadKey, TreeNodeKey};+use config::keyassignment::PaneDirection;+use mux::pane::PaneId;+use mux::tab::TabId;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SplitAxis {+ Right,+ Down,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum DestructiveAction {+ ClosePane {+ pane_id: PaneId,+ },+ CloseTab {+ tab_id: TabId,+ },+ DeleteThread {+ key: ThreadKey,+ end_sessions: bool,+ },+ RemoveProject {+ domain_name: String,+ project_id: String,+ end_sessions: bool,+ },+ DeleteSpace {+ domain_name: String,+ space_id: String,+ end_sessions: bool,+ },+}++/// Input handlers are deliberately side-effect free: keyboard and mouse both+/// produce an Action, and only the runtime dispatcher may touch mux/server+/// state.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Action {+ None,+ Detach,+ ToggleSidebar,+ ToggleHelp,+ OpenNavigator,+ OpenConnections,+ OpenSettings,+ AdjustSetting {+ index: usize,+ delta: isize,+ },+ CloseOverlay,+ SelectThread(ThreadKey),+ SelectRelativeThread(isize),+ SelectTab(TabId),+ SelectRelativeTab(isize),+ SelectNextAttention,+ FocusPane(PaneDirection),+ FocusPaneId(PaneId),+ CyclePane(isize),+ NewTab,+ RenameTab,+ /// Another terminal behind this pane, sharing its rectangle, reached by the+ /// pane's own level-2 tabs. Not a split: the geometry does not change.+ NewPaneInStack(PaneId),+ SplitPane(SplitAxis),+ ToggleZoom,+ EnterResize,+ ResizePane(PaneDirection, isize),+ ResizeSplit {+ split_index: usize,+ delta: isize,+ },+ EnterCopyMode,+ LeaveCopyMode,+ ScrollPane {+ pane_id: PaneId,+ lines: isize,+ },+ ScrollToBottom {+ pane_id: PaneId,+ },+ CopySelection,+ PasteClipboard,+ BeginSearch {+ backwards: bool,+ },+ SearchNext {+ backwards: bool,+ },+ SubmitPrompt,+ CancelPrompt,+ NewSpace {+ domain_name: String,+ },+ NewProject {+ domain_name: String,+ space_id: String,+ },+ NewThread {+ domain_name: String,+ project_id: String,+ },+ RenameNode(TreeNodeKey),+ ToggleThreadPinned(ThreadKey),+ MoveThread {+ key: ThreadKey,+ before: Option<String>,+ },+ MoveProject {+ domain_name: String,+ space_id: String,+ project_id: String,+ before: Option<String>,+ },+ Confirm(DestructiveAction),+ AcceptConfirmation,+ ConnectDomain(String),+ DisconnectDomain(String),+ RetryDomain(String),+}diff --git a/thinkterm-tui/src/backend.rs b/thinkterm-tui/src/backend.rsnew file mode 100644index 00000000..50ac9f21--- /dev/null+++ b/thinkterm-tui/src/backend.rs@@ -0,0 +1,305 @@+use ratatui::backend::{Backend, ClearType, WindowSize};+use ratatui::buffer::Cell;+use ratatui::layout::{Position, Size};+use ratatui::style::{Color, Modifier};+use std::io;+use std::time::Duration;+use termwiz::cell::{unicode_column_width, AttributeChange, Blink, Intensity, Underline};+use termwiz::color::{AnsiColor, ColorAttribute, SrgbaTuple};+use termwiz::input::InputEvent;+use termwiz::surface::{Change, CursorVisibility, Position as TermwizPosition};+use termwiz::terminal::buffered::BufferedTerminal;+use termwiz::terminal::{ScreenSize, Terminal, TerminalWaker};++/// Everything about a cell that decides how it is painted, so two neighbours+/// can be compared in one go rather than nine.+#[derive(Clone, Copy, PartialEq, Eq)]+struct Pen {+ fg: Color,+ bg: Color,+ modifier: Modifier,+}++impl Pen {+ fn of(cell: &Cell) -> Self {+ Self {+ fg: cell.fg,+ bg: cell.bg,+ modifier: cell.modifier,+ }+ }+}++/// Ratatui output over ThinkTerm's existing Termwiz version. Keeping this+/// adapter local avoids a second terminal/input type system: mux panes already+/// consume Termwiz keys, mouse events and paste data directly.+pub struct TermwizBackend<T: Terminal> {+ terminal: BufferedTerminal<T>,+}++impl<T: Terminal> TermwizBackend<T> {+ pub fn new(mut terminal: T) -> anyhow::Result<Self> {+ terminal.set_raw_mode()?;+ terminal.enter_alternate_screen()?;+ Ok(Self {+ terminal: BufferedTerminal::new(terminal)?,+ })+ }++ pub fn poll_input(&mut self, wait: Option<Duration>) -> anyhow::Result<Option<InputEvent>> {+ Ok(self.terminal.terminal().poll_input(wait)?)+ }++ pub fn check_for_resize(&mut self) -> anyhow::Result<bool> {+ Ok(self.terminal.check_for_resize()?)+ }++ pub fn screen_size(&mut self) -> anyhow::Result<ScreenSize> {+ Ok(self.terminal.terminal().get_screen_size()?)+ }++ pub fn waker(&mut self) -> TerminalWaker {+ self.terminal.terminal().waker()+ }+}++impl<T: Terminal> Backend for TermwizBackend<T> {+ type Error = io::Error;++ fn draw<'a, I>(&mut self, content: I) -> io::Result<()>+ where+ I: Iterator<Item = (u16, u16, &'a Cell)>,+ {+ // Ratatui hands over the cells that changed, in reading order, and the+ // common case is a run of neighbours that share a style. Restating the+ // cursor and all nine attributes for each of them costs far more bytes+ // than the text does — on a phone reached over ssh, that is the+ // difference between a repaint that keeps up with a finger and one that+ // does not. Emit each only where it actually differs.+ let mut pen: Option<Pen> = None;+ let mut cursor: Option<(u16, u16)> = None;+ for (x, y, cell) in content {+ if cursor != Some((x, y)) {+ self.terminal.add_change(Change::CursorPosition {+ x: TermwizPosition::Absolute(x as usize),+ y: TermwizPosition::Absolute(y as usize),+ });+ }+ let next = Pen::of(cell);+ let changed = pen != Some(next);+ pen = Some(next);+ cursor = Some((+ x.saturating_add(+ unicode_column_width(cell.symbol(), None)+ .max(1)+ .min(u16::MAX as usize) as u16,+ ),+ y,+ ));+ if !changed {+ self.terminal+ .add_change(Change::Text(cell.symbol().to_string()));+ continue;+ }+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Foreground(+ to_termwiz_color(cell.fg),+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Background(+ to_termwiz_color(cell.bg),+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Intensity(+ if cell.modifier.contains(Modifier::BOLD) {+ Intensity::Bold+ } else if cell.modifier.contains(Modifier::DIM) {+ Intensity::Half+ } else {+ Intensity::Normal+ },+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Italic(+ cell.modifier.contains(Modifier::ITALIC),+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Underline(+ if cell.modifier.contains(Modifier::UNDERLINED) {+ Underline::Single+ } else {+ Underline::None+ },+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Reverse(+ cell.modifier.contains(Modifier::REVERSED),+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Invisible(+ cell.modifier.contains(Modifier::HIDDEN),+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::StrikeThrough(+ cell.modifier.contains(Modifier::CROSSED_OUT),+ )));+ self.terminal+ .add_change(Change::Attribute(AttributeChange::Blink(+ if cell.modifier.contains(Modifier::RAPID_BLINK) {+ Blink::Rapid+ } else if cell.modifier.contains(Modifier::SLOW_BLINK) {+ Blink::Slow+ } else {+ Blink::None+ },+ )));+ self.terminal+ .add_change(Change::Text(cell.symbol().to_string()));+ }+ Ok(())+ }++ fn hide_cursor(&mut self) -> io::Result<()> {+ self.terminal+ .add_change(Change::CursorVisibility(CursorVisibility::Hidden));+ Ok(())+ }++ fn show_cursor(&mut self) -> io::Result<()> {+ self.terminal+ .add_change(Change::CursorVisibility(CursorVisibility::Visible));+ Ok(())+ }++ fn get_cursor_position(&mut self) -> io::Result<Position> {+ let (x, y) = self.terminal.cursor_position();+ Ok(Position::new(saturating_u16(x), saturating_u16(y)))+ }++ fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> io::Result<()> {+ let position = position.into();+ self.terminal.add_change(Change::CursorPosition {+ x: TermwizPosition::Absolute(position.x as usize),+ y: TermwizPosition::Absolute(position.y as usize),+ });+ Ok(())+ }++ fn clear(&mut self) -> io::Result<()> {+ self.terminal+ .add_change(Change::ClearScreen(ColorAttribute::Default));+ Ok(())+ }++ fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {+ if clear_type == ClearType::All {+ self.clear()+ } else {+ Err(io::Error::other(format!(+ "Termwiz does not support clearing {clear_type:?}"+ )))+ }+ }++ fn size(&self) -> io::Result<Size> {+ let (cols, rows) = self.terminal.dimensions();+ Ok(Size::new(saturating_u16(cols), saturating_u16(rows)))+ }++ fn window_size(&mut self) -> io::Result<WindowSize> {+ let size = self+ .terminal+ .terminal()+ .get_screen_size()+ .map_err(io::Error::other)?;+ Ok(WindowSize {+ columns_rows: Size::new(saturating_u16(size.cols), saturating_u16(size.rows)),+ pixels: Size::new(saturating_u16(size.xpixel), saturating_u16(size.ypixel)),+ })+ }++ fn flush(&mut self) -> io::Result<()> {+ self.terminal.flush().map_err(io::Error::other)+ }+}++fn saturating_u16(value: usize) -> u16 {+ value.min(u16::MAX as usize) as u16+}++fn to_termwiz_color(color: Color) -> ColorAttribute {+ match color {+ Color::Reset => ColorAttribute::Default,+ Color::Black => AnsiColor::Black.into(),+ Color::DarkGray => AnsiColor::Grey.into(),+ Color::Gray => AnsiColor::Silver.into(),+ Color::Red => AnsiColor::Maroon.into(),+ Color::LightRed => AnsiColor::Red.into(),+ Color::Green => AnsiColor::Green.into(),+ Color::LightGreen => AnsiColor::Lime.into(),+ Color::Yellow => AnsiColor::Olive.into(),+ Color::LightYellow => AnsiColor::Yellow.into(),+ Color::Blue => AnsiColor::Navy.into(),+ Color::LightBlue => AnsiColor::Blue.into(),+ Color::Magenta => AnsiColor::Purple.into(),+ Color::LightMagenta => AnsiColor::Fuchsia.into(),+ Color::Cyan => AnsiColor::Teal.into(),+ Color::LightCyan => AnsiColor::Aqua.into(),+ Color::White => AnsiColor::White.into(),+ Color::Indexed(index) => ColorAttribute::PaletteIndex(index),+ Color::Rgb(red, green, blue) => ColorAttribute::TrueColorWithPaletteFallback(+ SrgbaTuple::from((red, green, blue)),+ nearest_xterm_256(red, green, blue),+ ),+ }+}++/// Keep RGB colors meaningful when the host advertises only `xterm-256color`.+/// A default fallback collapses every RGB color to the same terminal color.+fn nearest_xterm_256(red: u8, green: u8, blue: u8) -> u8 {+ const CUBE: [u8; 6] = [0, 95, 135, 175, 215, 255];++ fn distance(a: (u8, u8, u8), b: (u8, u8, u8)) -> u32 {+ let red = i32::from(a.0) - i32::from(b.0);+ let green = i32::from(a.1) - i32::from(b.1);+ let blue = i32::from(a.2) - i32::from(b.2);+ (red * red + green * green + blue * blue) as u32+ }++ fn nearest_level(value: u8) -> usize {+ CUBE.iter()+ .enumerate()+ .min_by_key(|(_, level)| (i16::from(value) - i16::from(**level)).abs())+ .map_or(0, |(index, _)| index)+ }++ let red_level = nearest_level(red);+ let green_level = nearest_level(green);+ let blue_level = nearest_level(blue);+ let cube_rgb = (CUBE[red_level], CUBE[green_level], CUBE[blue_level]);+ let cube_index = 16 + 36 * red_level + 6 * green_level + blue_level;++ let average = (u16::from(red) + u16::from(green) + u16::from(blue)) / 3;+ let gray_level = ((i32::from(average) - 8 + 5) / 10).clamp(0, 23) as usize;+ let gray = 8 + 10 * gray_level as u8;+ if distance((red, green, blue), (gray, gray, gray)) < distance((red, green, blue), cube_rgb) {+ (232 + gray_level) as u8+ } else {+ cube_index as u8+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rgb_colors_have_a_256_color_fallback() {+ assert_eq!(nearest_xterm_256(255, 0, 0), 196);+ assert_eq!(nearest_xterm_256(128, 128, 128), 244);+ assert!(matches!(+ to_termwiz_color(Color::Rgb(137, 180, 250)),+ ColorAttribute::TrueColorWithPaletteFallback(_, _)+ ));+ }+}diff --git a/thinkterm-tui/src/clipboard.rs b/thinkterm-tui/src/clipboard.rsnew file mode 100644index 00000000..daae28d0--- /dev/null+++ b/thinkterm-tui/src/clipboard.rs@@ -0,0 +1,205 @@+use anyhow::{bail, Context, Result};+use base64::engine::general_purpose::STANDARD;+use base64::Engine;+use std::io::{Read, Write};+use std::process::{Command, Stdio};++const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;+const _: () = assert!(MAX_CLIPBOARD_BYTES >= 1024 * 1024);+const _: () = assert!(MAX_CLIPBOARD_BYTES <= 16 * 1024 * 1024);++pub trait ClipboardProvider: Send + Sync {+ fn write_text(&self, text: &str) -> Result<()>;+ fn read_text(&self) -> Result<String>;+}++#[derive(Default)]+pub struct SystemClipboard;++impl ClipboardProvider for SystemClipboard {+ fn write_text(&self, text: &str) -> Result<()> {+ if text.len() > MAX_CLIPBOARD_BYTES {+ bail!("selection is too large for the clipboard");+ }+ platform_write(text.as_bytes()).or_else(|platform_error| {+ write_osc52(text).with_context(|| format!("{platform_error:#}; OSC 52 fallback"))+ })+ }++ fn read_text(&self) -> Result<String> {+ let bytes = platform_read()?;+ if bytes.len() > MAX_CLIPBOARD_BYTES {+ bail!("clipboard text exceeds 8 MiB");+ }+ String::from_utf8(bytes).context("clipboard text is not UTF-8")+ }+}++#[cfg(target_os = "macos")]+fn platform_write(bytes: &[u8]) -> Result<()> {+ run_writer("pbcopy", &[], bytes)+}++#[cfg(target_os = "macos")]+fn platform_read() -> Result<Vec<u8>> {+ run_reader("pbpaste", &[])+}++#[cfg(all(unix, not(target_os = "macos")))]+fn platform_write(bytes: &[u8]) -> Result<()> {+ let mut failures = Vec::new();+ for (program, args) in linux_write_commands() {+ match run_writer(program, args, bytes) {+ Ok(()) => return Ok(()),+ Err(err) => failures.push(format!("{program}: {err}")),+ }+ }+ bail!("no clipboard writer succeeded ({})", failures.join("; "))+}++#[cfg(all(unix, not(target_os = "macos")))]+fn platform_read() -> Result<Vec<u8>> {+ let mut failures = Vec::new();+ for (program, args) in linux_read_commands() {+ match run_reader(program, args) {+ Ok(bytes) => return Ok(bytes),+ Err(err) => failures.push(format!("{program}: {err}")),+ }+ }+ bail!("no clipboard reader succeeded ({})", failures.join("; "))+}++#[cfg(all(unix, not(target_os = "macos")))]+fn linux_write_commands() -> Vec<(&'static str, &'static [&'static str])> {+ let mut commands = Vec::new();+ if std::env::var_os("WAYLAND_DISPLAY").is_some() {+ commands.push(("wl-copy", &[][..]));+ }+ commands.push(("xclip", &["-selection", "clipboard", "-in"]));+ commands.push(("xsel", &["--clipboard", "--input"]));+ commands+}++#[cfg(all(unix, not(target_os = "macos")))]+fn linux_read_commands() -> Vec<(&'static str, &'static [&'static str])> {+ let mut commands = Vec::new();+ if std::env::var_os("WAYLAND_DISPLAY").is_some() {+ commands.push(("wl-paste", &["--no-newline", "--type", "text"] as &[_]));+ commands.push(("wl-paste", &["--no-newline"]));+ }+ commands.push(("xclip", &["-selection", "clipboard", "-out"]));+ commands.push(("xsel", &["--clipboard", "--output"]));+ commands+}++#[cfg(windows)]+fn platform_write(bytes: &[u8]) -> Result<()> {+ let text = String::from_utf8(bytes.to_vec()).context("clipboard text is not UTF-8")?;+ clipboard_win::set_clipboard_string(&text).context("write Windows clipboard")+}++#[cfg(windows)]+fn platform_read() -> Result<Vec<u8>> {+ let text = clipboard_win::get_clipboard_string().context("read Windows clipboard")?;+ Ok(text.into_bytes())+}++#[cfg(not(any(unix, windows)))]+fn platform_write(_bytes: &[u8]) -> Result<()> {+ bail!("system clipboard is unavailable on this platform")+}++#[cfg(not(any(unix, windows)))]+fn platform_read() -> Result<Vec<u8>> {+ bail!("system clipboard is unavailable on this platform")+}++fn run_writer(program: &str, args: &[&str], bytes: &[u8]) -> Result<()> {+ let mut child = Command::new(program)+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .with_context(|| format!("start {program}"))?;+ child+ .stdin+ .take()+ .context("clipboard process has no stdin")?+ .write_all(bytes)+ .with_context(|| format!("write to {program}"))?;+ let status = child+ .wait()+ .with_context(|| format!("wait for {program}"))?;+ if !status.success() {+ bail!("exited with {status}");+ }+ Ok(())+}++fn run_reader(program: &str, args: &[&str]) -> Result<Vec<u8>> {+ let mut child = Command::new(program)+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .with_context(|| format!("start {program}"))?;+ let mut stdout = child+ .stdout+ .take()+ .context("clipboard process has no stdout")?;+ let mut bytes = Vec::new();+ stdout+ .by_ref()+ .take((MAX_CLIPBOARD_BYTES + 1) as u64)+ .read_to_end(&mut bytes)+ .with_context(|| format!("read from {program}"))?;+ if bytes.len() > MAX_CLIPBOARD_BYTES {+ // `take` deliberately stops consuming output at the limit. Close the+ // pipe and terminate the producer before waiting, otherwise a command+ // with more output can remain blocked forever on its full stdout pipe.+ drop(stdout);+ let _ = child.kill();+ let _ = child.wait();+ bail!("clipboard text exceeds 8 MiB");+ }+ drop(stdout);+ let status = child+ .wait()+ .with_context(|| format!("wait for {program}"))?;+ if !status.success() {+ bail!("exited with {status}");+ }+ Ok(bytes)+}++fn write_osc52(text: &str) -> Result<()> {+ let encoded = STANDARD.encode(text.as_bytes());+ let mut stdout = std::io::stdout().lock();+ stdout+ .write_all(format!("\x1b]52;c;{encoded}\x07").as_bytes())+ .context("write OSC 52")?;+ stdout.flush().context("flush OSC 52")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[cfg(all(unix, not(target_os = "macos")))]+ #[test]+ fn linux_always_has_x11_fallbacks() {+ let writers = linux_write_commands();+ assert!(writers.iter().any(|(program, _)| *program == "xclip"));+ assert!(writers.iter().any(|(program, _)| *program == "xsel"));+ }++ #[cfg(unix)]+ #[test]+ fn oversized_reader_terminates_the_producer_instead_of_waiting_on_its_pipe() {+ let error = run_reader("sh", &["-c", "head -c 9000000 /dev/zero"])+ .expect_err("oversized clipboard output must be rejected");+ assert!(error.to_string().contains("exceeds 8 MiB"));+ }+}diff --git a/thinkterm-tui/src/lib.rs b/thinkterm-tui/src/lib.rsnew file mode 100644index 00000000..965c0121--- /dev/null+++ b/thinkterm-tui/src/lib.rs@@ -0,0 +1,4999 @@+mod action;+mod backend;+mod clipboard;+mod model;+mod render;+mod settings;+mod state;+mod view;++use action::{Action, DestructiveAction, SplitAxis};+use anyhow::{Context, Result};+use async_channel::{Receiver, Sender};+use backend::TermwizBackend;+use clipboard::{ClipboardProvider, SystemClipboard};+use codec::{ClientViewport, ThinkTermSessionState};+use config::keyassignment::{PaneDirection, SpawnTabDomain};+use config::{ConfigHandle, SshMultiplexing};+use model::{AppModel, ThreadKey, TreeNodeKey};+use mux::client::ClientId;+use mux::connui::ConnectionUI;+use mux::domain::{Domain, DomainState, SplitSource};+use mux::pane::{Pane, PaneId, Pattern};+use mux::tab::{SplitDirection, SplitRequest, SplitSize, Tab, TabId};+use mux::{Mux, MuxNotification};+use ratatui::backend::Backend;+use ratatui::Terminal;+use settings::{TuiConfig, TuiPersistentState};+use state::{+ AppMode, ConfirmationState, ConnectionItem, ConnectionStatus, ContextMenuState, CopyState,+ MenuEntry, PendingOperation, PromptAction, PromptState, SearchState, SelectionPoint,+ TextSelection, UiState, ViewClass,+};+use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};+use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, OnceLock};+use std::time::{Duration, Instant};+use termwiz::caps::{Capabilities, ProbeHints};+use termwiz::input::{+ InputEvent, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseEvent as TermwizMouseEvent,+};+use termwiz::terminal::{new_terminal, ScreenSize, TerminalWaker};+use uuid::Uuid;+use view::{HitTarget, PaneTool, TabBarControl, TreeAction, ViewLayout};+use wezterm_client::client::Client;+use wezterm_client::domain::{ClientDomain, ClientDomainConfig};+use wezterm_client::pane::ClientPane;+use wezterm_term::input::{MouseButton, MouseEvent, MouseEventKind};+use wezterm_term::TerminalSize;++static EVENT_SENDER: OnceLock<Sender<AppEvent>> = OnceLock::new();+static TERMINAL_WAKER: OnceLock<TerminalWaker> = OnceLock::new();+const INPUT_PROGRESS_WINDOW: Duration = Duration::from_millis(50);+const INPUT_PROGRESS_POLL_INTERVAL: Duration = Duration::from_millis(2);+/// How still the terminal has to be before its size is worth telling the server+/// about. Long enough to swallow a pinch-zoom's intermediate steps, short+/// enough that a deliberate resize still feels immediate.+const RESIZE_SETTLE: Duration = Duration::from_millis(150);+/// How often to ask the panes for new content when nothing has asked to draw.+///+/// A remote pane only asks the server from inside `get_changed_since`, and+/// `RenderableInner::poll` doubles its own interval every time it runs — up to+/// half a minute — resetting only when a response lands. Until now the only+/// caller was `paint_pane`, so a renderer that draws strictly on demand stopped+/// asking, and the screen sat still until something was tapped.+///+/// This asks on a timer instead, and deliberately does *not* draw: content that+/// actually arrives notifies the mux, which marks the frame dirty by the normal+/// route. Drawing on the timer as well was measured at 88% of a core and+/// 3.4 KB/s to the tty on a screen with nothing happening — a cost paid over+/// SSH from a phone, which is the whole audience.+const PANE_POLL_INTERVAL: Duration = Duration::from_millis(150);++/// How long to keep drawing after a resize so the grid the server owes us has a+/// chance to arrive. Comfortably longer than the settle plus a couple of round+/// trips, and bounded so an idle terminal goes back to costing nothing.+const RESIZE_REDRAW_WINDOW: Duration = Duration::from_millis(1500);+/// Pace of those extra draws. Fast enough to look immediate, slow enough that+/// the prefetch throttle refills between attempts.+const RESIZE_REDRAW_INTERVAL: Duration = Duration::from_millis(60);++#[derive(Debug, Clone)]+pub struct TuiOptions {+ /// Configured mux client-domain names. If empty, the standard Local mux+ /// resolver is used and other servers remain available in Connections.+ pub domains: Vec<String>,+ /// Window class used by the standard GUI-socket discovery resolver.+ pub class_name: String,+ /// Independent TUI presentation settings. ThinkTerm's Lua config remains+ /// the shared source for connections, shells and terminal behavior.+ pub tui_config_path: Option<PathBuf>,+}++impl Default for TuiOptions {+ fn default() -> Self {+ Self {+ domains: Vec::new(),+ class_name: "com.roversx.thinkterm".to_string(),+ tui_config_path: None,+ }+ }+}++enum AppEvent {+ Mux(MuxNotification),+ Session {+ domain_name: String,+ connection_generation: u64,+ state: ThinkTermSessionState,+ },+ TreeChanged(String),+ Connected {+ domain_name: String,+ connection_generation: u64,+ },+}++/// Whether a wake has been delivered that the loop has not yet acted on.+static WAKE_PENDING: AtomicBool = AtomicBool::new(false);++/// Tell the render loop that something is waiting for it.+///+/// A wake carries no information beyond "look again", so repeating it before+/// the loop has looked buys nothing and costs a write plus a full trip through+/// `poll_input`. Attaching to a busy mux says it more than a thousand times a+/// second — every fetched line is a notification — and the loop spends that+/// second answering the doorbell instead of drawing. Collapsing the repeats+/// leaves exactly one pending wake, which is all the loop can use anyway.+fn wake_terminal() {+ if WAKE_PENDING.swap(true, Ordering::AcqRel) {+ return;+ }+ if let Some(waker) = TERMINAL_WAKER.get() {+ let _ = waker.wake();+ }+}++fn send_event(event: AppEvent) {+ if let Some(sender) = EVENT_SENDER.get() {+ let _ = sender.try_send(event);+ }+ wake_terminal();+}++fn receive_session_state(+ domain_name: &str,+ connection_generation: u64,+ state: ThinkTermSessionState,+) {+ send_event(AppEvent::Session {+ domain_name: domain_name.to_string(),+ connection_generation,+ state,+ });+}++fn receive_tree(domain_name: &str, _tree: codec::ThinkTermTree) {+ send_event(AppEvent::TreeChanged(domain_name.to_string()));+}++fn receive_connection(domain_name: &str, connection_generation: u64) {+ send_event(AppEvent::Connected {+ domain_name: domain_name.to_string(),+ connection_generation,+ });+}++/// Run the terminal UI inside the already initialized `thinkterm` process.+/// This function deliberately does not initialize config, install a second+/// executor or shut down the mux; those lifetimes belong to the host binary.+/// Sends this process's stderr to a file for as long as the TUI owns the screen.+///+/// The logger writes every line to stderr *and* to its own file, and here stderr+/// is the screen being drawn on — so a reconnect, a dropped domain, or any+/// warning paints itself over the interface, which is what every screenshot of+/// this program has had scribbled across it. Nothing is lost by redirecting:+/// the same lines are already going to the log file. Restoring on the way out+/// matters just as much, because an error returned from here is printed by the+/// caller, and that has to land on the stderr the reader can actually see.+#[cfg(unix)]+struct StderrToLogFile(Option<filedescriptor::FileDescriptor>);++#[cfg(unix)]+impl StderrToLogFile {+ fn install() -> Self {+ use filedescriptor::FileDescriptor;+ use std::os::fd::{AsRawFd, IntoRawFd};+ let path =+ config::RUNTIME_DIR.join(format!("thinkterm-tui-stderr-{}.txt", std::process::id()));+ let Ok(file) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&path)+ else {+ return Self(None);+ };+ let stderr = std::io::stderr();+ let Ok(saved) = FileDescriptor::dup(&stderr.as_raw_fd()) else {+ return Self(None);+ };+ // `dup2` hands back an owning handle to the descriptor it just wrote+ // to. Dropping that handle would close the process's stderr outright —+ // which looks like success, because nothing can be written over the+ // screen any more, and is not, because nothing can be written anywhere.+ // Releasing it leaves descriptor 2 open and pointing at the file.+ match unsafe { FileDescriptor::dup2(&file.as_raw_fd(), stderr.as_raw_fd()) } {+ Ok(installed) => {+ let _ = installed.into_raw_fd();+ Self(Some(saved))+ }+ Err(_) => Self(None),+ }+ }+}++#[cfg(unix)]+impl Drop for StderrToLogFile {+ fn drop(&mut self) {+ use filedescriptor::FileDescriptor;+ use std::os::fd::{AsRawFd, IntoRawFd};+ if let Some(saved) = self.0.take() {+ if let Ok(restored) =+ unsafe { FileDescriptor::dup2(&saved.as_raw_fd(), std::io::stderr().as_raw_fd()) }+ {+ let _ = restored.into_raw_fd();+ }+ }+ }+}++#[cfg(not(unix))]+struct StderrToLogFile;++#[cfg(not(unix))]+impl StderrToLogFile {+ fn install() -> Self {+ Self+ }+}++pub fn run(config: ConfigHandle, options: TuiOptions) -> Result<()> {+ let _stderr = StderrToLogFile::install();+ let executor = promise::spawn::SimpleExecutor::new();+ let (result_tx, result_rx) = std::sync::mpsc::sync_channel(1);+ promise::spawn::spawn(async move {+ let _ = result_tx.send(run_async(config, options).await);+ })+ .detach();+ loop {+ match result_rx.try_recv() {+ Ok(result) => return result,+ Err(std::sync::mpsc::TryRecvError::Empty) => executor.tick()?,+ Err(std::sync::mpsc::TryRecvError::Disconnected) => {+ anyhow::bail!("TUI executor stopped without a result")+ }+ }+ }+}++async fn fetch_current_session(domain: &ClientDomain) -> Result<(u64, ThinkTermSessionState)> {+ if domain.state() != DomainState::Attached {+ anyhow::bail!("domain is not attached");+ }+ let before = domain+ .connection_generation()+ .filter(|generation| *generation != 0)+ .context("domain has no live connection generation")?;+ let snapshot = domain.fetch_thinkterm_session_state().await?;+ let after = domain.connection_generation();+ if domain.state() != DomainState::Attached || after != Some(before) {+ anyhow::bail!("connection changed while fetching the session snapshot");+ }+ Ok((before, snapshot))+}++async fn run_async(config: ConfigHandle, options: TuiOptions) -> Result<()> {+ let tui_config_path = settings::config_path(options.tui_config_path.clone());+ let tui_config = settings::load_config(&tui_config_path)?;+ settings::set_active_theme(tui_config.theme);+ let tui_state_path = settings::state_path();+ let persisted = settings::load_state(&tui_state_path).unwrap_or_else(|err| {+ log::warn!("failed to load TUI state: {err:#}");+ TuiPersistentState::default()+ });+ let catalog = all_client_domain_configs(&config, &options.class_name)?;+ let available = catalog.domains;+ if available.is_empty() {+ anyhow::bail!("no mux client domains or multiplexed ThinkTerm SSH hosts are configured");+ }+ let configs = select_domain_configs(&available, &options.domains, &catalog.local_domain_name)?;+ let has_initial_configs = !configs.is_empty();+ let domain_configs = available+ .iter()+ .cloned()+ .map(|domain| (domain.name().to_string(), domain))+ .collect::<BTreeMap<_, _>>();+ let connection_items = connection_catalog(&available, &catalog.local_domain_name);+ let mux = Arc::new(Mux::new(None));+ Mux::set_mux(&mux);+ let client_id = Arc::new(ClientId::new());+ mux.register_client(Arc::clone(&client_id));+ mux.replace_identity(Some(client_id));++ let (sender, receiver) = async_channel::unbounded();+ EVENT_SENDER+ .set(sender.clone())+ .map_err(|_| anyhow::anyhow!("the TUI event channel was already initialized"))?;+ wezterm_client::domain::set_thinkterm_session_sink(receive_session_state);+ wezterm_client::domain::set_thinkterm_tree_sink(receive_tree);+ wezterm_client::domain::set_thinkterm_connect_sink(receive_connection);+ wezterm_client::domain::set_thinkterm_frontend_wake_sink(wake_terminal);+ mux.subscribe(move |notification| {+ let _ = sender.try_send(AppEvent::Mux(notification));+ wake_terminal();+ true+ });++ let mut domains = BTreeMap::new();+ for domain_config in configs {+ let name = domain_config.name().to_string();+ let domain = Arc::new(ClientDomain::new(domain_config));+ let mux_domain: Arc<dyn Domain> = domain.clone();+ mux.add_domain(&mux_domain);+ domains.insert(name, domain);+ }+ if let Some(domain) = domains.values().next() {+ let mux_domain: Arc<dyn Domain> = domain.clone();+ mux.set_default_domain(&mux_domain);+ }++ let mut model = AppModel::default();+ let mut attach_failures = Vec::new();+ let domain_names: Vec<_> = domains.keys().cloned().collect();+ for name in domain_names {+ let domain = Arc::clone(&domains[&name]);+ match domain+ .attach_with_ui(None, ConnectionUI::new_headless())+ .await+ .with_context(|| format!("attaching to mux domain {name}"))+ {+ Ok(()) => {+ if let Err(err) = guard_against_same_server_nesting(&domain) {+ domain.perform_detach();+ attach_failures.push(format!("{name}: {err:#}"));+ continue;+ }+ match fetch_current_session(&domain).await {+ Ok((_generation, snapshot)) => {+ model.apply_snapshot(name.clone(), snapshot);+ }+ Err(err) => {+ domain.perform_detach();+ attach_failures.push(format!("{name}: session snapshot: {err:#}"));+ }+ }+ }+ Err(err) => attach_failures.push(format!("{name}: {err:#}")),+ }+ }+ domains.retain(|_, domain| domain.state() == DomainState::Attached);+ restore_persisted_selection(&mut model, &persisted);++ let initial_status = if !has_initial_configs {+ "Choose a mux server to connect".to_string()+ } else if attach_failures.is_empty() {+ String::new()+ } else {+ format!("Some servers failed: {}", attach_failures.join("; "))+ };+ let result = run_terminal(+ domain_configs,+ connection_items,+ domains.clone(),+ receiver,+ model,+ initial_status,+ tui_config,+ tui_config_path,+ tui_state_path,+ )+ .await;+ for domain in domains.values() {+ domain.perform_detach();+ }+ result+}++struct DomainCatalog {+ domains: Vec<ClientDomainConfig>,+ local_domain_name: String,+}++fn all_client_domain_configs(config: &ConfigHandle, class_name: &str) -> Result<DomainCatalog> {+ // Keep the default local entry on exactly the same resolver as `thinkterm+ // cli`: an explicit environment socket wins, then a published GUI socket,+ // and only then the configured daemon socket. The resolver's synthetic+ // domains have an empty name because the ordinary CLI does not need one;+ // the TUI does, so preserve the configured default name (normally `unix`).+ let mut local = Client::resolve_default_unix_domain(false, class_name)?;+ let local_domain_name = config+ .unix_domains+ .first()+ .map(|domain| domain.name.clone())+ .filter(|name| !name.is_empty())+ .unwrap_or_else(|| "unix".to_string());+ local.name = local_domain_name.clone();++ let mut domains = vec![ClientDomainConfig::Unix(local)];+ domains.extend(+ config+ .unix_domains+ .iter()+ .skip(1)+ .cloned()+ .map(ClientDomainConfig::Unix),+ );+ domains.extend(+ config+ .ssh_domains()+ .into_iter()+ .filter(|domain| domain.multiplexing == SshMultiplexing::WezTerm)+ .map(ClientDomainConfig::Ssh),+ );+ domains.extend(+ config+ .tls_clients+ .iter()+ .cloned()+ .map(ClientDomainConfig::Tls),+ );+ match thinkterm_core::ssh_hosts::list_all_hosts() {+ Ok(entries) => {+ let mut existing = domains+ .iter()+ .map(|domain| domain.name().to_string())+ .collect::<HashSet<_>>();+ for entry in entries {+ if !entry.spec.multiplexing || entry.spec.use_mosh {+ continue;+ }+ let mut ssh = thinkterm_core::ssh_hosts::build_ssh_domain(&entry.spec);+ ssh.name = entry.spec.label.clone();+ ssh.multiplexing = SshMultiplexing::WezTerm;+ ssh.stored_password = entry+ .spec+ .password+ .as_deref()+ .map(thinkterm_core::secret::reveal)+ .filter(|password| !password.is_empty());+ if existing.insert(ssh.name.clone()) {+ domains.push(ClientDomainConfig::Ssh(ssh));+ }+ }+ }+ Err(err) => log::warn!("failed to read saved ThinkTerm SSH hosts: {err:#}"),+ }+ Ok(DomainCatalog {+ domains,+ local_domain_name,+ })+}++fn select_domain_configs(+ available: &[ClientDomainConfig],+ requested: &[String],+ local_domain_name: &str,+) -> Result<Vec<ClientDomainConfig>> {+ let names = || {+ available+ .iter()+ .map(|domain| domain.name())+ .collect::<Vec<_>>()+ .join(", ")+ };+ if !requested.is_empty() {+ let mut selected = Vec::new();+ let mut seen = HashSet::new();+ for name in requested {+ if !seen.insert(name) {+ continue;+ }+ let domain = available+ .iter()+ .find(|domain| domain.name() == name)+ .cloned()+ .with_context(|| {+ format!(+ "no mux client domain named {name:?}; available: {}",+ names()+ )+ })?;+ selected.push(domain);+ }+ return Ok(selected);+ }++ // `thinkterm tui` is a standalone local frontend by default. Remote+ // servers are explicit (`thinkterm tui DOMAIN`) or selected later from+ // Connections; silently following GUI auto-connect settings makes startup+ // surprising and can land on a remote host with no local terminal.+ if let Some(local) = available+ .iter()+ .find(|domain| domain.name() == local_domain_name)+ {+ return Ok(vec![local.clone()]);+ }+ if available.len() == 1 {+ return Ok(available.to_vec());+ }+ if available.is_empty() {+ anyhow::bail!("no mux client domains are configured")+ }+ // An interactive frontend can resolve ambiguity itself; start on the+ // connection chooser rather than rejecting `thinkterm tui`.+ Ok(vec![])+}++fn connection_catalog(+ available: &[ClientDomainConfig],+ local_domain_name: &str,+) -> Vec<ConnectionItem> {+ let mut items = available+ .iter()+ .map(|domain| ConnectionItem {+ name: domain.name().to_string(),+ label: if matches!(domain, ClientDomainConfig::Unix(_))+ && domain.name() == local_domain_name+ {+ "Local".to_string()+ } else {+ domain.name().to_string()+ },+ detail: if matches!(domain, ClientDomainConfig::Unix(_))+ && domain.name() == local_domain_name+ {+ "Current ThinkTerm GUI or local mux".to_string()+ } else {+ domain.label()+ },+ status: ConnectionStatus::Disconnected,+ connectable: true,+ })+ .collect::<Vec<_>>();+ if let Ok(hosts) = thinkterm_core::ssh_hosts::list_all_hosts() {+ let known = items+ .iter()+ .map(|item| item.name.clone())+ .collect::<HashSet<_>>();+ for host in hosts {+ if host.spec.multiplexing && !host.spec.use_mosh {+ continue;+ }+ if known.contains(&host.spec.label) {+ continue;+ }+ items.push(ConnectionItem {+ name: host.id,+ label: host.spec.label,+ detail: if host.spec.use_mosh {+ "Mosh sessions are not mux servers; edit in GUI".into()+ } else {+ "Enable ThinkTerm Connect in SSH Hosts".into()+ },+ status: ConnectionStatus::Unsupported,+ connectable: false,+ });+ }+ }+ items.sort_by(|a, b| {+ a.label+ .to_ascii_lowercase()+ .cmp(&b.label.to_ascii_lowercase())+ });+ items+}++fn guard_against_same_server_nesting(domain: &ClientDomain) -> Result<()> {+ let origin = std::env::var("THINKTERM_MUX_SERVER_ID").ok();+ let target = domain+ .remote_server_id()+ .context("the target server did not report its runtime identity")?;+ check_nesting(+ origin.as_deref(),+ std::env::var_os("WEZTERM_PANE").is_some(),+ &target,+ )+}++fn check_nesting(origin: Option<&str>, inside_thinkterm_pane: bool, target: &str) -> Result<()> {+ if origin == Some(target) {+ anyhow::bail!("refusing to run ThinkTerm TUI inside a pane owned by the same mux server");+ }+ if inside_thinkterm_pane && origin.is_none() {+ anyhow::bail!(+ "refusing nested TUI: this pane predates server identity support, so a different target cannot be proven"+ );+ }+ Ok(())+}++struct TuiState {+ model: AppModel,+ domain_configs: BTreeMap<String, ClientDomainConfig>,+ domains: BTreeMap<String, Arc<ClientDomain>>,+ ui: UiState,+ dirty: bool,+ layout: ViewLayout,+ last_mouse_buttons: MouseButtons,+ /// Each tab's last advertised grid, and — through the key alone — whether+ /// this renderer has advertised one at all. Forgetting a size re-sends it+ /// on the next frame; the key has to outlive that, because taking control+ /// of a tab requires the server to already hold a viewport for us.+ /// Also carries whether this renderer owned the viewport when it last said+ /// so: a handover changes what the server does with the same numbers, so it+ /// has to count as something new to say.+ last_viewports: HashMap<(String, TabId), Option<(TerminalSize, bool)>>,+ /// A deliberate frontend layout change (such as hiding the sidebar)+ /// should make this renderer's newly advertised grid authoritative.+ claim_viewport_after_layout: bool,+ /// When the panes were last asked for new content, so the loop keeps asking+ /// even while nothing local has changed.+ last_pane_poll: Instant,+ /// The view last offered to the server, and when, so a flick of the wheel+ /// does not become a round trip per notch.+ shared_view: Option<codec::ClientView>,+ shared_view_at: Option<Instant>,+ /// A view change arrived inside the coalescing window and still has to go+ /// out once that window closes.+ share_view_pending: bool,+ /// The view last adopted from the owner, so following it is idempotent and+ /// does not fight this renderer's own scrolling every frame.+ followed_view: Option<codec::ClientView>,+ /// When the terminal last changed size, plus the time it has to stay still+ /// before that size is worth forwarding. `None` once it has been forwarded.+ resize_settles_at: Option<Instant>,+ /// Deadline until which to keep drawing regardless of whether anything+ /// asked for it, so a pane whose refetch was throttled away still recovers.+ redraw_until: Option<Instant>,+ /// Current transport generation accepted for each domain. Session pushes+ /// from any other generation are stale even when the restarted server has+ /// the same runtime id and a numerically newer snapshot generation.+ connection_generations: HashMap<String, u64>,+ refresh_sessions: HashSet<String>,+ actions: VecDeque<Action>,+ clipboard: Arc<dyn ClipboardProvider>,+ drag: Option<DragState>,+ /// Pane that owns an in-progress mouse sequence passed through to an+ /// application. Releases must go to the same pane even outside its rect.+ forwarded_mouse_pane: Option<PaneId>,+ settings: TuiConfig,+ settings_path: PathBuf,+ state_path: PathBuf,+}++#[derive(Clone, Debug)]+enum DragState {+ Selection {+ pane_id: usize,+ },+ TreeNode {+ key: TreeNodeKey,+ },+ SidebarResize,+ Scrollbar {+ pane_id: PaneId,+ },+ SplitResize {+ split_index: usize,+ last_x: u16,+ last_y: u16,+ },+}++impl TuiState {+ fn new(+ domain_configs: BTreeMap<String, ClientDomainConfig>,+ connections: Vec<ConnectionItem>,+ domains: BTreeMap<String, Arc<ClientDomain>>,+ model: AppModel,+ status: String,+ settings: TuiConfig,+ settings_path: PathBuf,+ state_path: PathBuf,+ ) -> Self {+ let no_attached_domain = domains.is_empty();+ let connection_generations = domains+ .iter()+ .filter_map(|(name, domain)| {+ domain+ .connection_generation()+ .filter(|generation| *generation != 0)+ .map(|generation| (name.clone(), generation))+ })+ .collect();+ let mut state = Self {+ model,+ domain_configs,+ domains,+ ui: {+ let mut ui = UiState::new(status);+ ui.sidebar_visible = settings.sidebar_visible;+ ui.sidebar_width = settings.sidebar_width;+ ui.narrow_width = settings.narrow_width;+ ui.touch_targets = settings.touch_targets;+ ui.pane_scrollbars = settings.pane_scrollbars;+ ui.pane_borders = settings.pane_borders;+ ui.pane_nav_bar = settings.pane_nav_bar;+ ui.connections = connections;+ if no_attached_domain {+ ui.mode = AppMode::Connections;+ }+ ui+ },+ dirty: true,+ layout: ViewLayout::default(),+ last_mouse_buttons: MouseButtons::NONE,+ last_viewports: HashMap::new(),+ claim_viewport_after_layout: false,+ last_pane_poll: Instant::now(),+ shared_view: None,+ shared_view_at: None,+ share_view_pending: false,+ followed_view: None,+ resize_settles_at: None,+ redraw_until: None,+ connection_generations,+ refresh_sessions: HashSet::new(),+ actions: VecDeque::new(),+ clipboard: Arc::new(SystemClipboard),+ drag: None,+ forwarded_mouse_pane: None,+ settings,+ settings_path,+ state_path,+ };+ sync_connection_statuses(&mut state);+ state+ }++ fn active_tab(&self) -> Option<(String, Arc<ClientDomain>, Arc<Tab>, TabId)> {+ let remote_tab_id = self.model.selected_tab()?.tab_id;+ let row = self.model.selected_row()?;+ let domain_name = row.key.domain_name.clone();+ let domain = Arc::clone(self.domains.get(&domain_name)?);+ let local_id = domain.remote_to_local_tab_id(remote_tab_id)?;+ let tab = Mux::get().get_tab(local_id)?;+ Some((domain_name, domain, tab, remote_tab_id))+ }++ fn active_pane(&self) -> Option<Arc<dyn Pane>> {+ self.active_tab()?.2.get_active_pane()+ }++ fn clear_selected_viewport_cache(&mut self) {+ let Some(domain_name) = self+ .model+ .selected_row()+ .map(|row| row.key.domain_name.clone())+ else {+ return;+ };+ for ((domain, _), size) in self.last_viewports.iter_mut() {+ if domain == &domain_name {+ *size = None;+ }+ }+ }++ /// False only when the server has told us another renderer holds the lease.+ fn owns_active_viewport(&self) -> bool {+ let Some((_, domain, tab, _)) = self.active_tab() else {+ return true;+ };+ domain.owns_remote_viewport(tab.tab_id()) != Some(false)+ }++ fn viewport_status(&self) -> Option<String> {+ let (_, domain, tab, _) = self.active_tab()?;+ let state = domain.remote_viewport_state(tab.tab_id())?;+ if domain.owns_remote_viewport(tab.tab_id()) == Some(false) {+ Some(format!(+ "VIEW {}×{} · input to take control",+ state.canonical_size.cols, state.canonical_size.rows+ ))+ } else {+ None+ }+ }++ fn queue(&mut self, action: Action) {+ if action != Action::None {+ self.actions.push_back(action);+ }+ }++ fn pane(&self, pane_id: usize) -> Option<Arc<dyn Pane>> {+ Mux::get().get_pane(pane_id)+ }+}++fn sync_connection_statuses(state: &mut TuiState) {+ for item in &mut state.ui.connections {+ if !item.connectable {+ item.status = ConnectionStatus::Unsupported;+ continue;+ }+ item.status = match state.domains.get(&item.name) {+ Some(domain)+ if domain.state() == DomainState::Attached && domain.is_reconnect_suspended() =>+ {+ ConnectionStatus::Reconnecting+ }+ Some(domain) if domain.state() == DomainState::Attached => ConnectionStatus::Attached,+ Some(domain) if domain.is_attaching() => ConnectionStatus::Connecting,+ Some(domain) if domain.is_reconnect_suspended() => ConnectionStatus::Failed,+ Some(_) => ConnectionStatus::Disconnected,+ None => ConnectionStatus::Disconnected,+ };+ }+ state.ui.connection_index = state+ .ui+ .connection_index+ .min(state.ui.connections.len().saturating_sub(1));+}++async fn run_terminal(+ domain_configs: BTreeMap<String, ClientDomainConfig>,+ connections: Vec<ConnectionItem>,+ domains: BTreeMap<String, Arc<ClientDomain>>,+ receiver: Receiver<AppEvent>,+ model: AppModel,+ initial_status: String,+ settings: TuiConfig,+ settings_path: PathBuf,+ state_path: PathBuf,+) -> Result<()> {+ let caps = tui_terminal_capabilities(ProbeHints::new_from_env())?;+ let backend = TermwizBackend::new(new_terminal(caps).context("opening the terminal")?)?;+ let mut terminal = Terminal::new(backend).context("initializing Ratatui")?;+ let waker = terminal.backend_mut().waker();+ TERMINAL_WAKER+ .set(waker)+ .map_err(|_| anyhow::anyhow!("the TUI terminal was already initialized"))?;+ terminal.clear()?;++ let mut state = TuiState::new(+ domain_configs,+ connections,+ domains,+ model,+ initial_status,+ settings,+ settings_path,+ state_path,+ );+ let area = terminal.size()?;+ // A screen this narrow shows the tree over the whole terminal, so honouring+ // a remembered "visible" opens straight into something covering the thing+ // you came for, every single time. The tree is one tap away on the ≡.+ state.ui.sidebar_visible = opens_with_tree(+ view::classify(area.width, state.ui.narrow_width),+ state.ui.sidebar_visible,+ );+ state.layout = view::compute_view(area.into(), &state.model, &state.ui, None);+ if !state.domains.is_empty() {+ if let Err(err) = ensure_selected_thread_live(&mut state, true, None).await {+ state.ui.pending = None;+ state.ui.status = format!("Opening terminal: {err:#}");+ }+ }+ let mut input_progress_until = None;+ while !state.ui.exit {+ // Cleared before the queue is read, never after: anything that arrives+ // from here on sets it again and rings, so no notification can slip in+ // behind a wake this iteration has already spent.+ WAKE_PENDING.store(false, Ordering::Release);+ drain_events(&receiver, &mut state);+ refresh_sessions(&mut state).await;+ if state.ui.expire_toast(std::time::Instant::now()) {+ state.dirty = true;+ }++ if terminal.backend_mut().check_for_resize()? {+ terminal.resize(terminal.backend().size()?.into())?;+ state.dirty = true;+ state.clear_selected_viewport_cache();+ // Pinching a phone terminal walks through a dozen sizes on the way+ // to the one that was meant. Handing each of them to the pane+ // reflows its contents that many times, and anything a program drew+ // for a width it held for 200ms is destroyed by the next step.+ // Redraw locally at once; tell the server only where it landed.+ state.resize_settles_at = Some(Instant::now() + RESIZE_SETTLE);+ state.redraw_until = Some(Instant::now() + RESIZE_REDRAW_WINDOW);+ }++ // A resize dirties every row at once, which can outrun the client's+ // line-prefetch throttle. A dropped prefetch delivers nothing, so no+ // notification arrives to wake this loop, and `get_lines` — the very+ // call that would retry — only runs while drawing. Left alone, a+ // renderer that draws on demand sits on the pre-resize picture until+ // the next keystroke. Drawing for a moment longer lets it retry.+ match state.redraw_until {+ Some(until) if Instant::now() < until => state.dirty = true,+ Some(_) => state.redraw_until = None,+ None => {}+ }++ if state+ .resize_settles_at+ .is_some_and(|settles_at| Instant::now() >= settles_at)+ {+ state.dirty = true;+ }++ if state.last_pane_poll.elapsed() >= PANE_POLL_INTERVAL {+ poll_panes(&state);+ state.last_pane_poll = Instant::now();+ }++ if state.share_view_pending && share_view_is_due(&state) {+ state.dirty = true;+ }++ if state.dirty {+ let active = state.active_tab();+ let local_tab = active.as_ref().map(|(_, _, tab, _)| Arc::clone(tab));+ let viewport_status = state.viewport_status();+ let mut rendered = render::RenderResult::default();+ let mut next_layout = ViewLayout::default();+ state.ui.begin_frame();+ terminal.draw(|frame| {+ next_layout =+ view::compute_view(frame.area(), &state.model, &state.ui, local_tab.as_ref());+ rendered = render::render(+ frame,+ &state.model,+ &state.ui,+ local_tab.as_ref(),+ &next_layout,+ viewport_status.as_deref(),+ &state.settings,+ );+ })?;+ state.layout = next_layout;+ // Cleared before the trip to the server, never after — the same+ // rule the wake flag follows, and for the same reason. Adopting the+ // owner's scroll position happens in there, and clearing afterwards+ // would wipe the request to draw it, leaving a follower holding the+ // right position and showing the old one.+ state.dirty = false;+ report_viewport_if_changed(&mut state, rendered.selected_tab, terminal.backend_mut())+ .await;+ }++ let now = Instant::now();+ let mut wait = input_progress_wait(state.ui.toast_timeout(now), input_progress_until, now);+ // Nothing external will wake the loop to ask again, so the next ask has+ // to be one of the things the input poll waits on.+ let until_poll =+ PANE_POLL_INTERVAL.saturating_sub(now.saturating_duration_since(state.last_pane_poll));+ wait = Some(wait.map_or(until_poll, |wait| wait.min(until_poll)));+ if state.share_view_pending {+ let until_share = state.shared_view_at.map_or(Duration::ZERO, |at| {+ SHARE_VIEW_INTERVAL.saturating_sub(now.saturating_duration_since(at))+ });+ wait = Some(wait.map_or(until_share, |wait| wait.min(until_share)));+ }+ // Nothing else will wake this loop once the terminal stops changing, so+ // the settle deadline has to be one of the things it waits on.+ if let Some(remaining) = state+ .resize_settles_at+ .and_then(|settles_at| settles_at.checked_duration_since(now))+ {+ wait = Some(wait.map_or(remaining, |wait| wait.min(remaining)));+ }+ if let Some(remaining) = state+ .redraw_until+ .and_then(|until| until.checked_duration_since(now))+ {+ let tick = remaining.min(RESIZE_REDRAW_INTERVAL);+ wait = Some(wait.map_or(tick, |wait| wait.min(tick)));+ }+ if let Some(first) = terminal.backend_mut().poll_input(wait)? {+ // Termwiz may decode a single tty read into many key events. Drain+ // that ready queue before drawing so fast typing costs one frame+ // per batch instead of one full Ratatui frame per character.+ let mut next = Some(first);+ let mut had_user_input = false;+ for _ in 0..256 {+ let Some(event) = next.take() else {+ break;+ };+ had_user_input |= is_user_input(&event);+ handle_input(event, &mut state);+ dispatch_actions(&mut state).await;+ if state.ui.exit {+ break;+ }+ next = terminal.backend_mut().poll_input(Some(Duration::ZERO))?;+ }+ if had_user_input {+ // Pane input is dispatched through futures scheduled on the+ // same SimpleExecutor as this loop. Entering an indefinite+ // tty poll immediately after the final key can otherwise+ // starve that send (and its echo) until an unrelated wakeup.+ // Keep the executor moving briefly after real user input,+ // then return to an idle, zero-CPU indefinite poll.+ input_progress_until = Some(Instant::now() + INPUT_PROGRESS_WINDOW);+ }+ }+ smol::future::yield_now().await;+ }+ terminal.clear()?;+ persist_ui_state(&state).ok();+ Ok(())+}++fn is_user_input(event: &InputEvent) -> bool {+ matches!(+ event,+ InputEvent::Key(_)+ | InputEvent::Mouse(_)+ | InputEvent::PixelMouse(_)+ | InputEvent::Paste(_)+ )+}++/// Whether to open with the tree showing.+///+/// A screen narrow enough to draw the tree over the whole terminal opens on the+/// terminal, whatever was remembered: the tree there is a way to get somewhere,+/// and starting inside it means starting on top of the thing you came for. It+/// is one tap away on the ≡.+fn opens_with_tree(class: ViewClass, remembered: bool) -> bool {+ class != ViewClass::Narrow && remembered+}++/// Whether showing or hiding the tree at this width is worth remembering.+///+/// Only where it is a panel beside the terminal. As an overlay it is view+/// state, and writing it to the config makes a phone and a desktop sharing one+/// file fight over a single boolean — whoever toggled last decides how the+/// other one opens.+fn tree_visibility_is_a_preference(class: ViewClass) -> bool {+ class != ViewClass::Narrow+}++fn input_progress_wait(+ ordinary_wait: Option<Duration>,+ progress_until: Option<Instant>,+ now: Instant,+) -> Option<Duration> {+ let Some(remaining) = progress_until+ .and_then(|until| until.checked_duration_since(now))+ .filter(|remaining| !remaining.is_zero())+ else {+ return ordinary_wait;+ };+ let progress_wait = remaining.min(INPUT_PROGRESS_POLL_INTERVAL);+ Some(ordinary_wait.map_or(progress_wait, |wait| wait.min(progress_wait)))+}++fn tui_terminal_capabilities(hints: ProbeHints) -> Result<Capabilities> {+ // Theme selection is an explicit TUI setting and can change while the+ // process is running. Let the selected theme decide whether to use color;+ // retaining NO_COLOR as a renderer-level capability override would make+ // every named theme silently monochrome. The two Monochrome themes remain+ // the in-app way to request color-free output.+ Capabilities::new_with_hints(hints.color_level(None)).context("reading terminal capabilities")+}++fn restore_persisted_selection(model: &mut AppModel, state: &TuiPersistentState) {+ let selected = state.last_domain.as_deref().and_then(|domain_name| {+ let thread_id = state.selected_threads.get(domain_name)?;+ model+ .rows()+ .iter()+ .find(|row| row.key.domain_name == domain_name && row.thread.id == *thread_id)+ .map(|row| row.key.clone())+ });+ if let Some(key) = selected {+ model.select_thread(&key);+ let tab_key = format!("{}/{}", key.domain_name, key.thread_id);+ if let Some(tab_id) = state.selected_tabs.get(&tab_key) {+ model.select_tab(*tab_id);+ }+ }+}++fn persist_ui_state(state: &TuiState) -> Result<()> {+ let mut saved = TuiPersistentState::default();+ if let Some(row) = state.model.selected_row() {+ saved.last_domain = Some(row.key.domain_name.clone());+ saved+ .selected_threads+ .insert(row.key.domain_name.clone(), row.thread.id.clone());+ if let Some(tab) = state.model.selected_tab() {+ saved.selected_tabs.insert(+ format!("{}/{}", row.key.domain_name, row.thread.id),+ tab.tab_id,+ );+ }+ }+ settings::save_state(&state.state_path, &saved)+}++fn drain_events(receiver: &Receiver<AppEvent>, state: &mut TuiState) {+ let mut connection_changed = false;+ while let Ok(event) = receiver.try_recv() {+ match event {+ AppEvent::Session {+ domain_name,+ connection_generation,+ state: snapshot,+ } => {+ let current = state.domains.get(&domain_name).is_some_and(|domain| {+ session_generation_is_current(+ domain.state() == DomainState::Attached,+ domain.connection_generation(),+ state.connection_generations.get(&domain_name).copied(),+ connection_generation,+ )+ });+ if current && state.model.apply_snapshot(domain_name.clone(), snapshot) {+ state+ .last_viewports+ .retain(|(domain, _), _| domain != &domain_name);+ state.dirty = true;+ }+ }+ AppEvent::TreeChanged(domain_name) => {+ state.refresh_sessions.insert(domain_name);+ }+ AppEvent::Connected {+ domain_name,+ connection_generation,+ } => {+ let current = state.domains.get(&domain_name).is_some_and(|domain| {+ domain.state() == DomainState::Attached+ && domain.connection_generation() == Some(connection_generation)+ });+ if current {+ connection_changed = true;+ state+ .connection_generations+ .insert(domain_name.clone(), connection_generation);+ state.model.begin_connection_generation(&domain_name);+ state.refresh_sessions.insert(domain_name.clone());+ state+ .last_viewports+ .retain(|(domain, _), _| domain != &domain_name);+ state.dirty = true;+ }+ }+ AppEvent::Mux(notification) => {+ if notification_refreshes_session(¬ification) {+ state.refresh_sessions.extend(state.domains.keys().cloned());+ }++ if matches!(notification, MuxNotification::Empty) {+ state.ui.status = "No live panes".to_string();+ }+ state.dirty = true;+ }+ }+ }+ if connection_changed {+ sync_connection_statuses(state);+ }+}++fn session_generation_is_current(+ attached: bool,+ live_generation: Option<u64>,+ accepted_generation: Option<u64>,+ event_generation: u64,+) -> bool {+ attached+ && live_generation == Some(event_generation)+ && accepted_generation == Some(event_generation)+}++fn notification_refreshes_session(notification: &MuxNotification) -> bool {+ matches!(+ notification,+ MuxNotification::PaneAdded(_)+ | MuxNotification::PaneRemoved(_)+ | MuxNotification::WindowCreated(_)+ | MuxNotification::WindowRemoved(_)+ | MuxNotification::WindowWorkspaceChanged(_)+ | MuxNotification::TabAddedToWindow { .. }+ | MuxNotification::TabTitleChanged { .. }+ | MuxNotification::ThinkTermSessionChanged+ )+}++async fn refresh_sessions(state: &mut TuiState) {+ let pending: Vec<_> = state.refresh_sessions.drain().collect();+ for name in pending {+ let Some(domain) = state.domains.get(&name).cloned() else {+ continue;+ };+ if domain.state() != DomainState::Attached {+ state.ui.status = format!("{name}: reconnecting");+ state.dirty = true;+ continue;+ }+ match fetch_current_session(&domain).await {+ Ok((generation, snapshot))+ if state.connection_generations.get(&name) == Some(&generation) =>+ {+ state.model.apply_snapshot(name, snapshot);+ state.ui.status.clear();+ state.dirty = true;+ }+ Ok(_) => {}+ Err(err) => {+ state.ui.status = format!("{name}: session refresh: {err}");+ state.dirty = true;+ }+ }+ }+}++async fn report_viewport_if_changed<T: termwiz::terminal::Terminal>(+ state: &mut TuiState,+ remote_tab_id: Option<TabId>,+ backend: &mut TermwizBackend<T>,+) {+ if let Some(settles_at) = state.resize_settles_at {+ if Instant::now() < settles_at {+ // Still mid-gesture. The local redraw already happened; only the+ // trip to the server waits for the size to mean something.+ return;+ }+ state.resize_settles_at = None;+ }+ let Some(remote_tab_id) = remote_tab_id else {+ return;+ };+ let Some(row) = state.model.selected_row() else {+ return;+ };+ let domain_name = row.key.domain_name.clone();+ let Some(domain) = state.domains.get(&domain_name).cloned() else {+ return;+ };+ let Some(local_tab_id) = domain.remote_to_local_tab_id(remote_tab_id) else {+ return;+ };+ let content = state.layout.content;+ if content.width == 0 || content.height == 0 {+ return;+ }+ let screen = match backend.screen_size() {+ Ok(screen) => screen,+ Err(err) => {+ state.ui.status = format!("Viewport: {err}");+ return;+ }+ };+ let size = terminal_size(content.width as usize, content.height as usize, screen);+ // Reported as one grid for the whole tab, never per pane. The server owns+ // how a tab divides into panes and answers with a tab-level size that this+ // renderer then adopts; describing the panes as well means both sides are+ // deciding the same split from different inputs, and dragging a divider+ // leaves every pty a step behind the layout it was drawn for.+ // Ownership is part of what was said, not just the numbers. A device that+ // takes the viewport by typing changes what the server will do with the+ // very same grid, and the tab this renderer lays out from is still the+ // shape the *other* device left it. Keying the cache on both means the+ // next frame notices and says it again — and stops as soon as the two+ // agree, which reacting to the server's own publication did not: that+ // published back at us and cost a thousand frames a second.+ let owns = domain.owns_remote_viewport(local_tab_id) != Some(false);+ let cache_key = (domain_name, remote_tab_id);+ if state.last_viewports.get(&cache_key) != Some(&Some((size, owns))) {+ match domain+ .set_client_viewport(local_tab_id, ClientViewport::CellGrid { size })+ .await+ {+ Ok(viewport) => {+ let owns = domain.owns_remote_viewport(local_tab_id) != Some(false);+ state.last_viewports.insert(cache_key, Some((size, owns)));+ adopt_local_tab_size(+ local_tab_id,+ local_tab_size(&domain, local_tab_id, size, viewport.canonical_size),+ );+ }+ Err(err) => {+ state.ui.status = format!("Viewport: {err}");+ state.dirty = true;+ return;+ }+ }+ }+ push_pane_sizes(state, &domain, local_tab_id, screen);+ share_view_if_changed(state, &domain, local_tab_id).await;++ if state.claim_viewport_after_layout {+ state.claim_viewport_after_layout = false;+ match domain.claim_client_viewport(local_tab_id).await {+ Ok(viewport) => {+ // Deliberately no pane push here. `state.layout` still+ // describes the tab at the size the *other* renderer left it,+ // and pushing those rectangles immediately after adopting a new+ // tab size hands the server the old geometry back — the claim+ // undoing itself. Resizing the tab dirties the frame, and the+ // next one pushes rectangles that match.+ adopt_local_tab_size(+ local_tab_id,+ local_tab_size(&domain, local_tab_id, size, viewport.canonical_size),+ );+ }+ Err(err) => {+ state.ui.status = format!("Viewport control: {err}");+ state.dirty = true;+ }+ }+ }+}++/// Ask every pane on screen whether anything changed.+///+/// The answer is discarded: what matters is the side effect, which is that a+/// remote pane forwards the question to the server. Anything that comes back+/// arrives as a mux notification and marks the frame dirty on its own, so this+/// never draws and an idle screen stays idle.+fn poll_panes(state: &TuiState) {+ for pane in &state.layout.panes {+ if let Some(handle) = Mux::get().get_pane(pane.pane_id) {+ let _ = handle.get_changed_since(0..0, handle.get_current_seqno());+ }+ }+}++/// How often at most to tell the server what this renderer is looking at.+///+/// A wheel notch changes the scroll position, and a flick on a phone is a+/// stream of them; one round trip per notch would spend the link on saying the+/// same thing repeatedly. The follower is a person watching another screen, so+/// a tenth of a second is well below what anyone can see.+const SHARE_VIEW_INTERVAL: Duration = Duration::from_millis(100);++/// Whether the coalescing window has closed on a deferred view change.+fn share_view_is_due(state: &TuiState) -> bool {+ state+ .shared_view_at+ .map_or(true, |at| at.elapsed() >= SHARE_VIEW_INTERVAL)+}++/// Offer what this renderer is looking at, so the other renderers on this tab+/// can show the same thing.+///+/// Sharing the size makes two attached devices the same shape; it does not make+/// them the same view, and a phone and a desktop sitting at different points in+/// one scrollback read as two sessions that merely share a name.+///+/// Only what the *owner* sees is worth offering — a renderer nobody is using+/// does not get to move everyone else — and the server enforces that too, so+/// this can be wrong about ownership without any harm beyond a wasted message.+async fn share_view_if_changed(+ state: &mut TuiState,+ domain: &Arc<ClientDomain>,+ local_tab_id: TabId,+) {+ if domain.owns_remote_viewport(local_tab_id) == Some(false) {+ follow_shared_view(state, domain, local_tab_id);+ return;+ }+ let mut scroll = Vec::new();+ for pane in &state.layout.panes {+ let offset = state.ui.scroll_offset(pane.pane_id);+ if offset == 0 {+ // Following its output, which is the default a follower already has.+ continue;+ }+ let Some(handle) = Mux::get().get_pane(pane.pane_id) else {+ continue;+ };+ let Some(client_pane) = handle.downcast_ref::<ClientPane>() else {+ continue;+ };+ scroll.push(codec::ClientPaneScroll {+ pane_id: client_pane.remote_pane_id,+ lines_from_bottom: offset.min(u32::MAX as usize) as u32,+ });+ }+ scroll.sort_by_key(|entry| entry.pane_id);+ let view = codec::ClientView { scroll };+ if state.shared_view.as_ref() == Some(&view) {+ state.share_view_pending = false;+ return;+ }+ if state+ .shared_view_at+ .is_some_and(|at| at.elapsed() < SHARE_VIEW_INTERVAL)+ {+ // Deferred, not dropped. Skipping outright leaves the follower one+ // notch behind for good, because the last notch of a flick is exactly+ // the one that lands inside the window and nothing draws afterwards to+ // try again.+ state.share_view_pending = true;+ return;+ }+ state.shared_view_at = Some(Instant::now());+ state.share_view_pending = false;+ match domain.set_client_view(local_tab_id, view.clone()).await {+ Ok(()) => state.shared_view = Some(view),+ Err(err) => {+ log::trace!("sharing the view of tab {local_tab_id}: {err:#}");+ state.share_view_pending = true;+ }+ }+}++/// Show what the renderer being used is showing.+///+/// The other half of `share_view_if_changed`, and deliberately one-way: a+/// follower never writes back, so two attached devices cannot argue about where+/// the scrollback should sit. When nobody has offered a view — because the+/// owner is a renderer that does not publish one — this leaves the follower+/// exactly where it was rather than pulling it somewhere arbitrary.+fn follow_shared_view(state: &mut TuiState, domain: &Arc<ClientDomain>, local_tab_id: TabId) {+ let Some(remote) = domain.remote_viewport_state(local_tab_id) else {+ return;+ };+ let Some(view) = remote.view else {+ return;+ };+ if state.followed_view.as_ref() == Some(&view) {+ return;+ }+ for pane in &state.layout.panes {+ let Some(handle) = Mux::get().get_pane(pane.pane_id) else {+ continue;+ };+ let Some(client_pane) = handle.downcast_ref::<ClientPane>() else {+ continue;+ };+ let offset = view+ .scroll+ .iter()+ .find(|entry| entry.pane_id == client_pane.remote_pane_id)+ .map_or(0, |entry| entry.lines_from_bottom as usize);+ // Clamped against this renderer's own scrollback: the two ends agree on+ // how far back the owner is, not on how much history each has fetched.+ let dims = handle.get_dimensions();+ let offset = offset.min(dims.scrollback_rows.saturating_sub(dims.viewport_rows));+ state.ui.set_scroll_offset(pane.pane_id, offset);+ }+ state.followed_view = Some(view);+ state.dirty = true;+}++/// Tell each remote pane the size this layout actually gave its grid.+///+/// `PaneStack::resize` skips remote mirrors on purpose: only the frontend knows+/// how much of a pane's rectangle went to chrome, so sizing them is its job —+/// and it must report the grid it actually drew, not the rectangle it was+/// given, or every row spent on a pane's own nav bar goes unaccounted for.+///+/// Two guards, both copied from the GUI's `sync_active_mux_tab_pane_sizes`:+/// a renderer that does not own the viewport does not get to set sizes, and a+/// pane that already has the size it is about to be told is left alone. The+/// second is what makes this safe to run on every layout — without it, each+/// call would resize panes the server then answers with a fresh pane tree,+/// which is another layout, which resizes again.+fn push_pane_sizes(+ state: &TuiState,+ domain: &Arc<ClientDomain>,+ local_tab_id: TabId,+ screen: ScreenSize,+) {+ // `Some(true)`, not "anything but no": until the server has answered, this+ // renderer does not know whether it owns the grid, and guessing yes means+ // its very first frame resizes panes that another device is using.+ if domain.owns_remote_viewport(local_tab_id) != Some(true) {+ return;+ }+ for pane in &state.layout.panes {+ let Some(handle) = Mux::get().get_pane(pane.pane_id) else {+ continue;+ };+ let size = terminal_size(pane.rect.width as usize, pane.rect.height as usize, screen);+ let dims = handle.get_dimensions();+ if dims.cols == size.cols && dims.viewport_rows == size.rows {+ continue;+ }+ if let Err(err) = handle.resize(size) {+ log::trace!("pane {} declined {size:?}: {err:#}", pane.pane_id);+ }+ }+}++/// Which size this renderer's own copy of the tab should be laid out at.+///+/// `canonical_size` is the *server's* tab size, and the server derives it back+/// from the pane sizes it was told (`rebuild_splits_sizes_from_contained_panes`).+/// Once a pane's rectangle loses a row to its own nav bar, that shrunken row+/// count is what comes home in the echo — adopting it costs another row on the+/// next layout, and another after that. The GUI never adopts it either: the+/// only use of `canonical_size` on that side is the `VIEW 73×28` title, and+/// `ClientDomain`'s own resync refuses the wire size for the same reason+/// ("would shrink the tab by the chrome height on every resync").+///+/// So the owner lays out at the size it just reported and the server just+/// applied. A renderer that does *not* own the viewport has nothing of its own+/// to lay out at and still needs to draw the grid the panes really have, so it+/// keeps taking the server's answer.+fn choose_local_tab_size(+ owns: Option<bool>,+ reported: TerminalSize,+ canonical: TerminalSize,+) -> TerminalSize {+ match owns {+ Some(false) => canonical,+ _ => reported,+ }+}++fn local_tab_size(+ domain: &Arc<ClientDomain>,+ local_tab_id: TabId,+ reported: TerminalSize,+ canonical: TerminalSize,+) -> TerminalSize {+ choose_local_tab_size(+ domain.owns_remote_viewport(local_tab_id),+ reported,+ canonical,+ )+}++/// Pane rectangles are laid out from the tab's pane geometry, not from the+/// screen, so a tab left at a stale size leaves every pane drawn at whatever it+/// last measured — full-width output arrives and is then clipped to the width+/// the terminal had before it was resized.+fn adopt_local_tab_size(local_tab_id: TabId, size: TerminalSize) {+ if size.rows == 0 || size.cols == 0 {+ return;+ }+ if let Some(tab) = Mux::get().get_tab(local_tab_id) {+ tab.resize(size);+ }+}++async fn dispatch_actions(state: &mut TuiState) {+ while let Some(action) = state.actions.pop_front() {+ if let Err(err) = dispatch_action(state, action).await {+ state.ui.pending = None;+ state.ui.status = format!("{err:#}");+ }+ if let Err(err) = persist_ui_state(state) {+ state.ui.status = format!("Saving TUI state: {err:#}");+ }+ state.dirty = true;+ }+}++async fn claim_active_viewport(state: &mut TuiState) -> Result<Arc<Tab>> {+ let (domain_name, domain, tab, remote_tab_id) =+ state.active_tab().context("no live tab selected")?;+ let local_tab_id = tab.tab_id();+ if !state+ .last_viewports+ .contains_key(&(domain_name, remote_tab_id))+ {+ anyhow::bail!("viewport is not ready; retry after the terminal redraws");+ }+ domain.claim_client_viewport(local_tab_id).await?;+ if domain.owns_remote_viewport(local_tab_id) != Some(true) {+ anyhow::bail!("the server did not grant viewport ownership");+ }+ Ok(tab)+}++async fn dispatch_action(state: &mut TuiState, action: Action) -> Result<()> {+ match action {+ Action::None => {}+ Action::Detach => state.ui.exit = true,+ Action::ToggleSidebar => {+ state.ui.sidebar_visible = !state.ui.sidebar_visible;+ // On a narrow screen the tree is not a panel beside the terminal,+ // it is an overlay on top of it — a way to get somewhere, not a+ // thing you leave open. Remembering it as a preference means a+ // phone and a desktop sharing one config fight over a single+ // boolean, and whoever opened it last decides that the other one+ // opens covered.+ if tree_visibility_is_a_preference(state.layout.class) {+ state.settings.sidebar_visible = state.ui.sidebar_visible;+ save_tui_settings(state)?;+ }+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ Action::ToggleHelp => {+ state.ui.mode = if state.ui.mode == AppMode::Help {+ AppMode::Terminal+ } else {+ AppMode::Help+ };+ }+ Action::OpenNavigator => {+ state.ui.sidebar_visible = true;+ state.ui.mode = AppMode::Navigate;+ }+ Action::OpenConnections => {+ sync_connection_statuses(state);+ state.ui.mode = AppMode::Connections;+ }+ Action::OpenSettings => {+ state.ui.mode = AppMode::Settings;+ state.ui.settings_index = 0;+ }+ Action::AdjustSetting { index, delta } => {+ adjust_setting(state, index, delta)?;+ }+ Action::CloseOverlay | Action::CancelPrompt => state.ui.close_overlay(),+ Action::SelectThread(key) => select_thread(state, &key).await?,+ Action::SelectRelativeThread(delta) => {+ if state.model.select_relative_thread(delta) {+ let key = state.model.selected_key().cloned();+ state.clear_selected_viewport_cache();+ if let Some(key) = key {+ select_thread(state, &key).await?;+ }+ }+ }+ Action::SelectTab(tab_id) => {+ if state.model.select_tab(tab_id) {+ state.clear_selected_viewport_cache();+ }+ }+ Action::SelectRelativeTab(delta) => {+ if state.model.select_relative_tab(delta) {+ state.clear_selected_viewport_cache();+ }+ }+ Action::SelectNextAttention => {+ if let Some(key) = state.model.next_attention(state.model.selected_key()) {+ select_thread(state, &key).await?;+ }+ }+ Action::FocusPane(direction) => {+ if let Some((_, _, tab, _)) = state.active_tab() {+ tab.activate_pane_direction(direction);+ }+ }+ Action::FocusPaneId(pane_id) => {+ if let (Some((_, _, tab, _)), Some(pane)) = (state.active_tab(), state.pane(pane_id)) {+ tab.set_active_pane(&pane);+ }+ }+ Action::CyclePane(delta) => cycle_pane(state, delta),+ Action::NewTab => spawn_tab_for_selected_thread(state).await?,+ Action::RenameTab => begin_rename_tab(state),+ Action::NewPaneInStack(pane_id) => new_pane_in_stack(state, pane_id).await?,+ Action::SplitPane(axis) => split_active_pane(state, axis).await?,+ Action::ToggleZoom => {+ if let Some((_, _, tab, _)) = state.active_tab() {+ tab.toggle_zoom();+ }+ }+ Action::EnterResize => state.ui.mode = AppMode::Resize,+ Action::ResizePane(direction, amount) => {+ let tab = claim_active_viewport(state).await?;+ tab.adjust_pane_size(direction, amount.unsigned_abs().max(1));+ state.clear_selected_viewport_cache();+ }+ Action::ResizeSplit { split_index, delta } => {+ let tab = claim_active_viewport(state).await?;+ tab.resize_split_by(split_index, delta);+ state.clear_selected_viewport_cache();+ }+ Action::EnterCopyMode => enter_copy_mode(state),+ Action::LeaveCopyMode => {+ state.ui.copy = None;+ state.ui.mode = AppMode::Terminal;+ }+ Action::ScrollPane { pane_id, lines } => scroll_pane(state, pane_id, lines),+ Action::ScrollToBottom { pane_id } => state.ui.set_scroll_offset(pane_id, 0),+ Action::CopySelection => copy_selection(state)?,+ Action::PasteClipboard => paste_clipboard(state)?,+ Action::BeginSearch { backwards } => begin_search(state, backwards),+ Action::SearchNext { backwards } => select_search_match(state, backwards),+ Action::SubmitPrompt => submit_prompt(state).await?,+ Action::NewSpace { domain_name } => begin_prompt(+ state,+ "New Space",+ "",+ PromptAction::CreateSpace { domain_name },+ ),+ Action::NewProject {+ domain_name,+ space_id,+ } => begin_prompt(+ state,+ "New Project",+ "",+ PromptAction::CreateProject {+ domain_name,+ space_id,+ },+ ),+ Action::NewThread {+ domain_name,+ project_id,+ } => begin_prompt(+ state,+ "New Thread",+ "",+ PromptAction::CreateThread {+ domain_name,+ project_id,+ },+ ),+ Action::RenameNode(key) => begin_rename_node(state, key),+ Action::ToggleThreadPinned(key) => toggle_thread_pinned(state, key).await?,+ Action::MoveThread { key, before } => move_thread(state, key, before).await?,+ Action::MoveProject {+ domain_name,+ space_id,+ project_id,+ before,+ } => {+ mutate_authoritative(+ state,+ &domain_name,+ "Moving project",+ vec![codec::TreeOp::MoveProjectBefore {+ space_id,+ project_id,+ before,+ }],+ )+ .await?;+ }+ Action::Confirm(action) => begin_confirmation(state, action),+ Action::AcceptConfirmation => accept_confirmation(state).await?,+ Action::ConnectDomain(name) | Action::RetryDomain(name) => {+ retry_domain(state, &name).await?+ }+ Action::DisconnectDomain(name) => {+ if let Some(domain) = state.domains.get(&name) {+ domain.perform_detach();+ }+ state.model.remove_domain(&name);+ state.connection_generations.remove(&name);+ state.refresh_sessions.remove(&name);+ state+ .last_viewports+ .retain(|(domain, _), _| domain != &name);+ state.ui.mode = AppMode::Terminal;+ state.ui.status = format!("{name}: disconnected; remote sessions are still running");+ sync_connection_statuses(state);+ }+ }+ Ok(())+}++/// Every row of the settings overlay, in order, as `(section, label)`.+///+/// Drawing, moving the cursor and changing a value all index this one list.+/// They used to agree only by hand-counted index, which is why three settings+/// added since could be changed by nobody: the cursor stopped at four.+pub const SETTINGS: [(&str, &str); 9] = [+ ("Appearance", "Theme"),+ ("Appearance", "Sidebar"),+ ("Appearance", "Pane nav bar"),+ ("Appearance", "Pane borders"),+ ("Appearance", "Pane scrollbars"),+ ("Input", "Application mouse"),+ ("Input", "Copy on select"),+ ("Input", "Touch targets"),+ ("Terminal", "Scroll lines"),+];++/// What the row at `index` currently reads, and whether it is a plain on/off.+pub fn setting_value(settings: &TuiConfig, sidebar_visible: bool, index: usize) -> (String, bool) {+ match index {+ 0 => (settings.theme.label().to_string(), false),+ 1 => (String::new(), sidebar_visible),+ 2 => (String::new(), settings.pane_nav_bar),+ 3 => (String::new(), settings.pane_borders),+ 4 => (String::new(), settings.pane_scrollbars),+ 5 => (String::new(), settings.mouse),+ 6 => (String::new(), settings.copy_on_select),+ // Undecided is a real state here: it means "follow the layout", which+ // is neither on nor off and has to say so.+ 7 => match settings.touch_targets {+ None => ("Auto".to_string(), false),+ Some(value) => (String::new(), value),+ },+ 8 => (settings.scroll_lines.to_string(), false),+ _ => (String::new(), false),+ }+}++fn adjust_setting(state: &mut TuiState, index: usize, delta: isize) -> Result<()> {+ match index {+ 0 => {+ state.settings.theme = state.settings.theme.next(delta.signum());+ settings::set_active_theme(state.settings.theme);+ }+ 1 => {+ state.ui.sidebar_visible = !state.ui.sidebar_visible;+ state.settings.sidebar_visible = state.ui.sidebar_visible;+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ 2 => {+ state.settings.pane_nav_bar = !state.settings.pane_nav_bar;+ state.ui.pane_nav_bar = state.settings.pane_nav_bar;+ // All three of these hand columns and rows between the chrome and+ // the grid, so the server has to be told the pane changed size.+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ 3 => {+ state.settings.pane_borders = !state.settings.pane_borders;+ state.ui.pane_borders = state.settings.pane_borders;+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ 4 => {+ state.settings.pane_scrollbars = !state.settings.pane_scrollbars;+ state.ui.pane_scrollbars = state.settings.pane_scrollbars;+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ 5 => state.settings.mouse = !state.settings.mouse,+ 6 => state.settings.copy_on_select = !state.settings.copy_on_select,+ // Cycles through the third state rather than skipping it: following the+ // layout is the default and has to be reachable again.+ 7 => {+ state.settings.touch_targets = match state.settings.touch_targets {+ None => Some(true),+ Some(true) => Some(false),+ Some(false) => None,+ };+ state.ui.touch_targets = state.settings.touch_targets;+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ 8 => {+ state.settings.scroll_lines =+ (state.settings.scroll_lines as isize + delta).clamp(1, 20) as usize;+ }+ _ => return Ok(()),+ }+ save_tui_settings(state)+}++fn save_tui_settings(state: &TuiState) -> Result<()> {+ settings::save_config(&state.settings_path, &state.settings)+}++async fn select_thread(state: &mut TuiState, key: &ThreadKey) -> Result<()> {+ if state.model.select_thread(key) {+ state.clear_selected_viewport_cache();+ }+ // On a screen too narrow to show both, the tree is covering the terminal+ // the reader just asked for. Picking a thread is the whole point of opening+ // it, so getting out of the way is the answer they meant.+ if state.layout.class == ViewClass::Narrow && state.ui.sidebar_visible {+ state.ui.sidebar_visible = false;+ state.clear_selected_viewport_cache();+ state.claim_viewport_after_layout = true;+ }+ mark_thread_seen(state, key).await?;+ ensure_selected_thread_live(state, false, None).await+}++async fn ensure_selected_thread_live(+ state: &mut TuiState,+ force: bool,+ domain_override: Option<&str>,+) -> Result<()> {+ let selected = state+ .model+ .selected_row()+ .filter(|row| domain_override.is_none_or(|domain| row.key.domain_name == domain))+ .cloned();+ if !force+ && selected+ .as_ref()+ .is_some_and(|row| !row.thread.tabs.is_empty())+ {+ return Ok(());+ }+ let domain_name = domain_override+ .map(str::to_string)+ .or_else(|| selected.as_ref().map(|row| row.key.domain_name.clone()))+ .or_else(|| state.domains.keys().next().cloned())+ .context("no attached mux server")?;+ let preferred_thread_id = selected.as_ref().map(|row| row.thread.id.clone());+ let domain = state+ .domains+ .get(&domain_name)+ .cloned()+ .with_context(|| format!("{domain_name}: not attached"))?;+ let generation = domain+ .connection_generation()+ .context("connection has no generation")?;++ state.ui.pending = Some(PendingOperation {+ label: "Opening terminal".into(),+ domain_name: domain_name.clone(),+ });+ state.ui.status = format!("Opening terminal on {domain_name}…");+ let response = domain+ .ensure_thinkterm_thread(preferred_thread_id, spawn_size(state))+ .await+ .with_context(|| format!("materializing a Thread on {domain_name}"))?;+ if domain.state() != DomainState::Attached+ || domain.connection_generation() != Some(generation)+ || state.connection_generations.get(&domain_name) != Some(&generation)+ {+ anyhow::bail!("{domain_name}: connection changed while opening the terminal");+ }+ let (snapshot_generation, snapshot) = fetch_current_session(&domain).await?;+ if snapshot_generation != generation {+ anyhow::bail!("{domain_name}: stale terminal snapshot");+ }+ state.model.apply_snapshot(domain_name.clone(), snapshot);+ let key = state+ .model+ .rows()+ .iter()+ .find(|row| row.key.domain_name == domain_name && row.thread.id == response.thread_id)+ .map(|row| row.key.clone())+ .context("the server landing Thread is missing from its session snapshot")?;+ state.model.select_thread(&key);+ state.clear_selected_viewport_cache();+ state.ui.pending = None;+ state.ui.status.clear();+ Ok(())+}++async fn mark_thread_seen(state: &mut TuiState, key: &ThreadKey) -> Result<()> {+ let Some(row) = state.model.row(key) else {+ return Ok(());+ };+ if !row.thread.is_unread {+ return Ok(());+ }+ let thread_id = row.thread.id.clone();+ let domain_name = row.key.domain_name.clone();+ mutate_authoritative(+ state,+ &domain_name,+ "Marking Thread read",+ vec![codec::TreeOp::SetThreadUnread {+ thread_id,+ unread: false,+ }],+ )+ .await?;+ Ok(())+}++fn cycle_pane(state: &mut TuiState, delta: isize) {+ let Some((_, _, tab, _)) = state.active_tab() else {+ return;+ };+ let panes = tab.iter_panes();+ if panes.is_empty() {+ return;+ }+ let active = tab.get_active_pane().map(|pane| pane.pane_id());+ let current = active+ .and_then(|id| panes.iter().position(|pane| pane.pane.pane_id() == id))+ .unwrap_or(0);+ let next = (current as isize + delta).rem_euclid(panes.len() as isize) as usize;+ tab.set_active_pane(&panes[next].pane);+}++fn enter_copy_mode(state: &mut TuiState) {+ let Some(pane) = state.active_pane() else {+ state.ui.status = "No live pane selected".into();+ return;+ };+ let cursor = pane.get_cursor_position();+ let selection = state+ .ui+ .selection+ .clone()+ .filter(|selection| selection.pane_id == pane.pane_id());+ state.ui.copy = Some(CopyState {+ pane_id: pane.pane_id(),+ cursor: SelectionPoint {+ row: cursor.y,+ col: cursor.x,+ },+ selection,+ search: SearchState::default(),+ });+ state.ui.mode = AppMode::Copy;+}++fn scroll_pane(state: &mut TuiState, pane_id: usize, lines: isize) {+ let Some(pane) = state.pane(pane_id) else {+ return;+ };+ let dims = pane.get_dimensions();+ let current = state.ui.scroll_offset(pane_id);+ let next = if lines >= 0 {+ current.saturating_add(lines as usize)+ } else {+ current.saturating_sub(lines.unsigned_abs())+ }+ .min(dims.scrollback_rows.saturating_sub(dims.viewport_rows));+ state.ui.set_scroll_offset(pane_id, next);+}++fn copy_selection(state: &mut TuiState) -> Result<()> {+ let selection = state+ .ui+ .copy+ .as_ref()+ .and_then(|copy| copy.selection.as_ref())+ .or(state.ui.selection.as_ref())+ .cloned()+ .context("nothing is selected")?;+ let pane = state+ .pane(selection.pane_id)+ .context("the selected pane no longer exists")?;+ let text = selection_text(&pane, &selection);+ state.clipboard.write_text(&text)?;+ // Terminal-mode selections have served their purpose once copied.+ // Retaining one makes a later Ctrl-C look like another copy request+ // instead of interrupting the foreground process. Copy mode owns its+ // separate selection and can keep it for continued navigation.+ state.ui.selection = None;+ if let Some(copy) = state.ui.copy.as_mut() {+ copy.selection = Some(selection);+ }+ state+ .ui+ .set_toast(format!("Copied {} characters", text.chars().count()));+ Ok(())+}++fn selection_text(pane: &Arc<dyn Pane>, selection: &TextSelection) -> String {+ let (start, end) = selection.ordered();+ let (actual_top, lines) = pane.get_lines(start.row..end.row.saturating_add(1));+ let mut result = String::new();+ for (offset, line) in lines.iter().enumerate() {+ let row = actual_top + offset as wezterm_term::StableRowIndex;+ if row < start.row || row > end.row {+ continue;+ }+ let first = if row == start.row { start.col } else { 0 };+ let last = if row == end.row {+ end.col.saturating_add(1)+ } else {+ line.len()+ }+ .min(line.len());+ if first < last {+ let text = line.columns_as_str(first..last);+ let wrapped = line+ .get_cell(last.saturating_sub(1))+ .is_some_and(|cell| cell.attrs().wrapped());+ if wrapped {+ result.push_str(&text);+ } else {+ result.push_str(text.trim_end());+ if row < end.row {+ result.push('\n');+ }+ }+ } else if row < end.row {+ result.push('\n');+ }+ }+ result+}++fn paste_clipboard(state: &mut TuiState) -> Result<()> {+ let text = state.clipboard.read_text()?;+ let pane = state.active_pane().context("no live pane selected")?;+ pane.send_paste(&text)?;+ state.ui.set_scroll_offset(pane.pane_id(), 0);+ Ok(())+}++fn begin_search(state: &mut TuiState, backwards: bool) {+ let value = state+ .ui+ .copy+ .as_ref()+ .map(|copy| copy.search.query.clone())+ .unwrap_or_default();+ begin_prompt(+ state,+ if backwards {+ "Search backward"+ } else {+ "Search"+ },+ &value,+ PromptAction::Search { backwards },+ );+ state.ui.mode = AppMode::Search;+}++fn select_search_match(state: &mut TuiState, backwards: bool) {+ let Some(copy) = state.ui.copy.as_mut() else {+ return;+ };+ if copy.search.matches.is_empty() {+ return;+ }+ let len = copy.search.matches.len();+ let current = copy+ .search+ .current+ .unwrap_or(if backwards { 0 } else { len - 1 });+ let next = if backwards {+ (current + len - 1) % len+ } else {+ (current + 1) % len+ };+ copy.search.current = Some(next);+ let found = copy.search.matches[next];+ copy.cursor = SelectionPoint {+ row: found.start_y,+ col: found.start_x,+ };+ let pane_id = copy.pane_id;+ let _ = copy;+ if let Some(pane) = state.pane(pane_id) {+ let dims = pane.get_dimensions();+ let offset = dims.physical_top.saturating_sub(found.start_y).max(0) as usize;+ state.ui.set_scroll_offset(pane_id, offset);+ }+}++fn begin_prompt(state: &mut TuiState, title: &str, value: &str, action: PromptAction) {+ state.ui.prompt = Some(PromptState {+ title: title.into(),+ value: value.into(),+ action,+ });+ state.ui.context_menu = None;+ state.ui.mode = AppMode::Prompt;+}++fn begin_rename_node(state: &mut TuiState, key: TreeNodeKey) {+ let value = match &key {+ TreeNodeKey::Domain(name) => name.clone(),+ TreeNodeKey::Space {+ domain_name,+ space_id,+ } => state+ .model+ .domain(domain_name)+ .and_then(|snapshot| snapshot.spaces.iter().find(|space| space.id == *space_id))+ .map(|space| space.name.clone())+ .unwrap_or_default(),+ TreeNodeKey::Project {+ domain_name,+ project_id,+ } => state+ .model+ .domain(domain_name)+ .and_then(|snapshot| {+ snapshot+ .projects+ .iter()+ .find(|project| project.id == *project_id)+ })+ .map(|project| project.name.clone())+ .unwrap_or_default(),+ TreeNodeKey::Thread(key) => state+ .model+ .row(key)+ .map(|row| row.thread.name.clone())+ .unwrap_or_default(),+ };+ begin_prompt(state, "Rename", &value, PromptAction::RenameNode(key));+}++fn begin_rename_tab(state: &mut TuiState) {+ let value = state+ .active_tab()+ .map(|(_, _, tab, _)| tab.get_title())+ .unwrap_or_default();+ begin_prompt(state, "Rename Tab", &value, PromptAction::RenameTab);+}++async fn submit_prompt(state: &mut TuiState) -> Result<()> {+ let Some(prompt) = state.ui.prompt.take() else {+ state.ui.mode = AppMode::Terminal;+ return Ok(());+ };+ let value = prompt.value.trim().to_string();+ if value.is_empty() {+ state.ui.mode = AppMode::Terminal;+ return Ok(());+ }+ state.ui.mode = AppMode::Terminal;++ match prompt.action {+ PromptAction::RenameTab => {+ let (_, _, tab, _) = state.active_tab().context("no live tab selected")?;+ tab.set_title(&value);+ }+ PromptAction::RenameNode(key) => rename_node(state, key, value).await?,+ PromptAction::CreateSpace { domain_name } => {+ create_space(state, domain_name, value).await?+ }+ PromptAction::CreateProject {+ domain_name,+ space_id,+ } => create_project(state, domain_name, space_id, value).await?,+ PromptAction::CreateThread {+ domain_name,+ project_id,+ } => create_thread(state, domain_name, project_id, value).await?,+ PromptAction::Search { backwards } => run_search(state, value, backwards).await?,+ }+ Ok(())+}++async fn rename_node(state: &mut TuiState, key: TreeNodeKey, name: String) -> Result<()> {+ let (domain_name, op) = match key {+ TreeNodeKey::Domain(_) => {+ anyhow::bail!("connection names are edited in ThinkTerm Settings")+ }+ TreeNodeKey::Space {+ domain_name,+ space_id,+ } => (domain_name, codec::TreeOp::RenameSpace { space_id, name }),+ TreeNodeKey::Project {+ domain_name,+ project_id,+ } => (+ domain_name,+ codec::TreeOp::RenameProject { project_id, name },+ ),+ TreeNodeKey::Thread(key) => (+ key.domain_name,+ codec::TreeOp::RenameThread {+ thread_id: key.thread_id,+ name,+ last_active_at: now_timestamp(),+ },+ ),+ };+ mutate_authoritative(state, &domain_name, "Renaming", vec![op]).await?;+ Ok(())+}++async fn create_space(state: &mut TuiState, domain_name: String, name: String) -> Result<()> {+ let space_id = new_id("space");+ let project_id = new_id("project");+ let thread_id = new_id("thread");+ let workspace = workspace_name(&project_id, &thread_id);+ mutate_authoritative(+ state,+ &domain_name,+ "Creating Space",+ vec![+ codec::TreeOp::CreateSpace {+ space_id: space_id.clone(),+ name,+ },+ codec::TreeOp::CreateProject {+ project_id: project_id.clone(),+ space_id,+ name: "Home".into(),+ path: "~".into(),+ },+ codec::TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id,+ name: "main".into(),+ workspace: Some(workspace),+ created_at: now_timestamp(),+ },+ ],+ )+ .await?;+ select_new_thread(state, &domain_name, &thread_id)?;+ ensure_selected_thread_live(state, true, None).await+}++async fn create_project(+ state: &mut TuiState,+ domain_name: String,+ space_id: String,+ name: String,+) -> Result<()> {+ let project_id = new_id("project");+ let thread_id = new_id("thread");+ let workspace = workspace_name(&project_id, &thread_id);+ mutate_authoritative(+ state,+ &domain_name,+ "Creating Project",+ vec![+ codec::TreeOp::CreateProject {+ project_id: project_id.clone(),+ space_id,+ name,+ path: "~".into(),+ },+ codec::TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id,+ name: "main".into(),+ workspace: Some(workspace),+ created_at: now_timestamp(),+ },+ ],+ )+ .await?;+ select_new_thread(state, &domain_name, &thread_id)?;+ ensure_selected_thread_live(state, true, None).await+}++async fn create_thread(+ state: &mut TuiState,+ domain_name: String,+ project_id: String,+ name: String,+) -> Result<()> {+ let thread_id = new_id("thread");+ let workspace = workspace_name(&project_id, &thread_id);+ mutate_authoritative(+ state,+ &domain_name,+ "Creating Thread",+ vec![codec::TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id,+ name,+ workspace: Some(workspace),+ created_at: now_timestamp(),+ }],+ )+ .await?;+ select_new_thread(state, &domain_name, &thread_id)?;+ ensure_selected_thread_live(state, true, None).await+}++fn select_new_thread(state: &mut TuiState, domain_name: &str, thread_id: &str) -> Result<()> {+ let key = state+ .model+ .rows()+ .iter()+ .find(|row| row.key.domain_name == domain_name && row.thread.id == thread_id)+ .map(|row| row.key.clone())+ .context("the server did not accept the new Thread")?;+ state.model.select_thread(&key);+ state.clear_selected_viewport_cache();+ Ok(())+}++async fn toggle_thread_pinned(state: &mut TuiState, key: ThreadKey) -> Result<()> {+ let row = state+ .model+ .row(&key)+ .context("the Thread no longer exists")?;+ let pinned = !row.thread.is_pinned;+ let domain_name = key.domain_name.clone();+ mutate_authoritative(+ state,+ &domain_name,+ if pinned {+ "Pinning Thread"+ } else {+ "Unpinning Thread"+ },+ vec![codec::TreeOp::SetThreadPinned {+ thread_id: key.thread_id,+ pinned,+ last_active_at: now_timestamp(),+ }],+ )+ .await?;+ Ok(())+}++async fn move_thread(state: &mut TuiState, key: ThreadKey, before: Option<String>) -> Result<()> {+ let project_id = state+ .model+ .row(&key)+ .context("the Thread no longer exists")?+ .project+ .id+ .clone();+ let domain_name = key.domain_name.clone();+ mutate_authoritative(+ state,+ &domain_name,+ "Moving Thread",+ vec![codec::TreeOp::MoveThreadBefore {+ project_id,+ thread_id: key.thread_id,+ before,+ }],+ )+ .await?;+ Ok(())+}++async fn run_search(state: &mut TuiState, query: String, backwards: bool) -> Result<()> {+ let pane_id = state+ .ui+ .copy+ .as_ref()+ .map(|copy| copy.pane_id)+ .or_else(|| state.active_pane().map(|pane| pane.pane_id()))+ .context("no live pane selected")?;+ let pane = state.pane(pane_id).context("the pane no longer exists")?;+ let dims = pane.get_dimensions();+ let end = dims.physical_top + dims.viewport_rows as wezterm_term::StableRowIndex;+ let matches = pane+ .search(+ Pattern::CaseInSensitiveString(query.clone()),+ dims.scrollback_top..end,+ None,+ )+ .await?;+ if state.ui.copy.is_none() {+ let cursor = pane.get_cursor_position();+ state.ui.copy = Some(CopyState {+ pane_id,+ cursor: SelectionPoint {+ row: cursor.y,+ col: cursor.x,+ },+ selection: None,+ search: SearchState::default(),+ });+ }+ let copy = state.ui.copy.as_mut().unwrap();+ copy.search = SearchState {+ query,+ current: if matches.is_empty() {+ None+ } else if backwards {+ Some(matches.len() - 1)+ } else {+ Some(0)+ },+ matches,+ };+ state.ui.mode = AppMode::Copy;+ if let Some(index) = copy.search.current {+ let found = copy.search.matches[index];+ copy.cursor = SelectionPoint {+ row: found.start_y,+ col: found.start_x,+ };+ let offset = dims.physical_top.saturating_sub(found.start_y).max(0) as usize;+ state.ui.set_scroll_offset(pane_id, offset);+ } else {+ state.ui.status = "No matches".into();+ }+ Ok(())+}++async fn mutate_authoritative(+ state: &mut TuiState,+ domain_name: &str,+ label: &str,+ ops: Vec<codec::TreeOp>,+) -> Result<ThinkTermSessionState> {+ let domain = state+ .domains+ .get(domain_name)+ .cloned()+ .with_context(|| format!("unknown mux connection {domain_name:?}"))?;+ if domain.state() != DomainState::Attached {+ anyhow::bail!("{domain_name}: offline; no client-side change was queued");+ }+ state.ui.pending = Some(PendingOperation {+ label: label.into(),+ domain_name: domain_name.into(),+ });+ state.ui.status = format!("{label} on server…");++ if let Err(err) = domain.mutate_thinkterm_tree(ops).await {+ if let Ok((generation, snapshot)) = fetch_current_session(&domain).await {+ if state.connection_generations.get(domain_name) == Some(&generation) {+ state.model.apply_snapshot(domain_name, snapshot);+ }+ }+ state.ui.pending = None;+ return Err(err).with_context(|| format!("{label} on {domain_name}"));+ }+ let (generation, snapshot) = fetch_current_session(&domain)+ .await+ .with_context(|| format!("refreshing {domain_name} after {label}"))?;+ if state.connection_generations.get(domain_name) != Some(&generation) {+ anyhow::bail!("{domain_name}: connection changed after {label}");+ }+ state.model.apply_snapshot(domain_name, snapshot.clone());+ state.ui.pending = None;+ state.ui.status.clear();+ Ok(snapshot)+}++async fn spawn_tab_for_selected_thread(state: &mut TuiState) -> Result<()> {+ let row = state+ .model+ .selected_row()+ .cloned()+ .context("no Thread selected")?;+ let domain = state+ .domains+ .get(&row.key.domain_name)+ .cloned()+ .context("the selected server is unavailable")?;+ if domain.state() != DomainState::Attached {+ anyhow::bail!("{}: offline", row.key.domain_name);+ }+ let workspace = row+ .thread+ .materialized_workspace_name+ .clone()+ .or(row.thread.planned_workspace_name.clone())+ .unwrap_or_else(|| workspace_name(&row.project.id, &row.thread.id));+ let existing_window = state+ .model+ .selected_tab()+ .and_then(|tab| domain.remote_to_local_window_id(tab.window_id));+ let mux = Mux::get();+ let tagged_window = existing_window.is_none().then(|| {+ mux.new_empty_window_for_domain(Some(workspace.clone()), None, Some(domain.domain_id()))+ });+ let window_id = existing_window.or_else(|| tagged_window.as_ref().map(|builder| **builder));+ let current_pane = state.active_pane().map(|pane| pane.pane_id());+ let size = spawn_size(state);+ let spawned = mux+ .spawn_tab_or_window(+ window_id,+ SpawnTabDomain::DomainName(row.key.domain_name.clone()),+ None,+ (!row.project.path.trim().is_empty()).then(|| row.project.path.clone()),+ size,+ current_pane,+ workspace.clone(),+ None,+ )+ .await;+ drop(tagged_window);+ let (tab, _, _) = spawned?;+ let remote_tab_id = domain+ .local_to_remote_tab_id(tab.tab_id())+ .context("the server did not map the new tab")?;+ mutate_authoritative(+ state,+ &row.key.domain_name,+ "Binding tab to Thread",+ vec![+ codec::TreeOp::SetThreadWorkspaceName {+ thread_id: row.thread.id.clone(),+ planned: None,+ materialized: Some(workspace),+ },+ codec::TreeOp::TouchThread {+ thread_id: row.thread.id,+ at: now_timestamp(),+ },+ ],+ )+ .await?;+ state.model.select_tab(remote_tab_id);+ Ok(())+}++fn spawn_size(state: &TuiState) -> TerminalSize {+ if let Some(pane) = state.active_pane() {+ let dims = pane.get_dimensions();+ return TerminalSize {+ rows: dims.viewport_rows.max(2),+ cols: dims.cols.max(2),+ pixel_width: dims.pixel_width,+ pixel_height: dims.pixel_height,+ dpi: dims.dpi,+ };+ }+ TerminalSize {+ rows: state.layout.content.height.max(2) as usize,+ cols: state.layout.content.width.max(2) as usize,+ pixel_width: 0,+ pixel_height: 0,+ dpi: 96,+ }+}++/// Add a terminal to a pane's own stack: same rectangle, one more level-2 tab.+///+/// The size is taken from the pane already sitting there rather than recomputed+/// from the layout, because that pane's grid is what the new one inherits —+/// including the row its nav bar already took.+async fn new_pane_in_stack(state: &mut TuiState, pane_id: PaneId) -> Result<()> {+ let row = state+ .model+ .selected_row()+ .cloned()+ .context("no Thread selected")?;+ let dims = state+ .pane(pane_id)+ .context("no such pane")?+ .get_dimensions();+ let size = TerminalSize {+ rows: dims.viewport_rows,+ cols: dims.cols,+ pixel_width: dims.pixel_width,+ pixel_height: dims.pixel_height,+ dpi: dims.dpi,+ };+ Mux::get()+ .spawn_pane_in_stack(+ pane_id,+ SpawnTabDomain::DomainName(row.key.domain_name.clone()),+ None,+ (!row.project.path.trim().is_empty()).then(|| row.project.path.clone()),+ size,+ )+ .await?;+ state.clear_selected_viewport_cache();+ Ok(())+}++async fn split_active_pane(state: &mut TuiState, axis: SplitAxis) -> Result<()> {+ let row = state+ .model+ .selected_row()+ .cloned()+ .context("no Thread selected")?;+ let pane = state.active_pane().context("no live pane selected")?;+ let request = SplitRequest {+ direction: match axis {+ SplitAxis::Right => SplitDirection::Horizontal,+ SplitAxis::Down => SplitDirection::Vertical,+ },+ target_is_second: true,+ top_level: false,+ size: SplitSize::Percent(50),+ };+ Mux::get()+ .split_pane(+ pane.pane_id(),+ request,+ SplitSource::Spawn {+ command: None,+ command_dir: (!row.project.path.trim().is_empty())+ .then(|| row.project.path.clone()),+ },+ SpawnTabDomain::DomainName(row.key.domain_name.clone()),+ )+ .await?;+ state.clear_selected_viewport_cache();+ let domain = state.domains[&row.key.domain_name].clone();+ let (generation, snapshot) = fetch_current_session(&domain).await?;+ if state.connection_generations.get(&row.key.domain_name) == Some(&generation) {+ state.model.apply_snapshot(&row.key.domain_name, snapshot);+ }+ Ok(())+}++fn begin_confirmation(state: &mut TuiState, action: DestructiveAction) {+ let (title, detail) = match &action {+ DestructiveAction::ClosePane { .. } => (+ "Close pane",+ "This ends the remote pane on the mux server for every client.".to_string(),+ ),+ DestructiveAction::CloseTab { tab_id } => {+ let count = remote_panes_for_tab(state, *tab_id).len();+ (+ "Close tab",+ format!("End {count} remote pane(s) on the mux server for every client?"),+ )+ }+ DestructiveAction::DeleteThread { key, end_sessions } => {+ let count = remote_panes_for_thread(state, key).len();+ (+ "Delete Thread",+ if *end_sessions {+ format!("Delete this server-owned Thread and end {count} remote pane(s) for every client?")+ } else {+ "Delete this server-owned Thread on every client? Its sessions will keep running.".into()+ },+ )+ }+ DestructiveAction::RemoveProject {+ domain_name,+ project_id,+ end_sessions,+ } => {+ let count = remote_panes_for_project(state, domain_name, project_id).len();+ (+ "Remove Project",+ if *end_sessions {+ format!(+ "Remove this Project from the server tree and end {count} remote pane(s)?"+ )+ } else {+ "Remove this Project from the server tree on every client?".into()+ },+ )+ }+ DestructiveAction::DeleteSpace {+ domain_name,+ space_id,+ end_sessions,+ } => {+ let count = remote_panes_for_space(state, domain_name, space_id).len();+ (+ "Delete Space",+ if *end_sessions {+ format!("Delete this Space on the authoritative server and end {count} remote pane(s)?")+ } else {+ "Delete this Space from the authoritative server on every client? Remote sessions keep running.".into()+ },+ )+ }+ };+ state.ui.context_menu = None;+ state.ui.confirmation = Some(ConfirmationState {+ title: title.into(),+ detail,+ action,+ });+ state.ui.mode = AppMode::Confirm;+}++async fn accept_confirmation(state: &mut TuiState) -> Result<()> {+ let Some(confirm) = state.ui.confirmation.take() else {+ state.ui.mode = AppMode::Terminal;+ return Ok(());+ };+ state.ui.mode = AppMode::Terminal;+ execute_destructive(state, confirm.action).await+}++async fn execute_destructive(state: &mut TuiState, action: DestructiveAction) -> Result<()> {+ match action {+ DestructiveAction::ClosePane { pane_id } => {+ end_local_remote_panes(state, &[pane_id]).await?+ }+ DestructiveAction::CloseTab { tab_id } => {+ let panes = remote_panes_for_tab(state, tab_id);+ end_local_remote_panes(state, &panes).await?;+ }+ DestructiveAction::DeleteThread { key, end_sessions } => {+ let panes = remote_panes_for_thread(state, &key);+ mutate_authoritative(+ state,+ &key.domain_name,+ "Deleting Thread",+ vec![codec::TreeOp::DeleteThread {+ thread_id: key.thread_id,+ }],+ )+ .await?;+ if end_sessions {+ end_local_remote_panes(state, &panes).await?;+ }+ }+ DestructiveAction::RemoveProject {+ domain_name,+ project_id,+ end_sessions,+ } => {+ let panes = remote_panes_for_project(state, &domain_name, &project_id);+ mutate_authoritative(+ state,+ &domain_name,+ "Removing Project",+ vec![codec::TreeOp::RemoveProject { project_id }],+ )+ .await?;+ if end_sessions {+ end_local_remote_panes(state, &panes).await?;+ }+ }+ DestructiveAction::DeleteSpace {+ domain_name,+ space_id,+ end_sessions,+ } => {+ let panes = remote_panes_for_space(state, &domain_name, &space_id);+ mutate_authoritative(+ state,+ &domain_name,+ "Deleting Space",+ vec![codec::TreeOp::DeleteSpace { space_id }],+ )+ .await?;+ if end_sessions {+ end_local_remote_panes(state, &panes).await?;+ }+ }+ }+ Ok(())+}++fn remote_panes_for_tab(state: &TuiState, tab_id: TabId) -> Vec<usize> {+ let Some(row) = state.model.selected_row() else {+ return vec![];+ };+ let ids = row+ .thread+ .tabs+ .iter()+ .find(|tab| tab.tab_id == tab_id)+ .into_iter()+ .flat_map(|tab| tab.pane_ids.iter().copied());+ map_remote_panes(state.domains.get(&row.key.domain_name), ids)+}++fn remote_panes_for_thread(state: &TuiState, key: &ThreadKey) -> Vec<usize> {+ let Some(row) = state.model.row(key) else {+ return vec![];+ };+ map_remote_panes(+ state.domains.get(&key.domain_name),+ row.thread+ .tabs+ .iter()+ .flat_map(|tab| tab.pane_ids.iter().copied()),+ )+}++fn remote_panes_for_project(state: &TuiState, domain_name: &str, project_id: &str) -> Vec<usize> {+ let ids = state+ .model+ .rows()+ .iter()+ .filter(|row| row.key.domain_name == domain_name && row.project.id == project_id)+ .flat_map(|row| &row.thread.tabs)+ .flat_map(|tab| tab.pane_ids.iter().copied());+ map_remote_panes(state.domains.get(domain_name), ids)+}++fn remote_panes_for_space(state: &TuiState, domain_name: &str, space_id: &str) -> Vec<usize> {+ let ids = state+ .model+ .rows()+ .iter()+ .filter(|row| row.key.domain_name == domain_name && row.space.id == space_id)+ .flat_map(|row| &row.thread.tabs)+ .flat_map(|tab| tab.pane_ids.iter().copied());+ map_remote_panes(state.domains.get(domain_name), ids)+}++fn map_remote_panes(+ domain: Option<&Arc<ClientDomain>>,+ remote_ids: impl IntoIterator<Item = usize>,+) -> Vec<usize> {+ let Some(domain) = domain else {+ return vec![];+ };+ let mut result = remote_ids+ .into_iter()+ .filter_map(|remote| domain.remote_to_local_pane_id(remote))+ .collect::<Vec<_>>();+ result.sort_unstable();+ result.dedup();+ result+}++async fn end_local_remote_panes(state: &mut TuiState, pane_ids: &[usize]) -> Result<()> {+ let mut errors = Vec::new();+ for pane_id in pane_ids {+ let Some(pane) = state.pane(*pane_id) else {+ continue;+ };+ if let Some(remote) = pane.downcast_ref::<ClientPane>() {+ if let Err(err) = remote.kill_remote_and_wait().await {+ errors.push(format!("pane {pane_id}: {err:#}"));+ }+ } else {+ pane.kill();+ }+ }+ if !errors.is_empty() {+ anyhow::bail!(+ "some remote panes could not be ended: {}",+ errors.join("; ")+ );+ }+ let domain_names = state.domains.keys().cloned().collect::<Vec<_>>();+ for name in domain_names {+ if let Some(domain) = state.domains.get(&name).cloned() {+ if domain.state() == DomainState::Attached {+ if let Ok((generation, snapshot)) = fetch_current_session(&domain).await {+ if state.connection_generations.get(&name) == Some(&generation) {+ state.model.apply_snapshot(name, snapshot);+ }+ }+ }+ }+ }+ Ok(())+}++async fn retry_domain(state: &mut TuiState, name: &str) -> Result<()> {+ let domain = if let Some(domain) = state.domains.get(name).cloned() {+ domain+ } else {+ let config = state+ .domain_configs+ .get(name)+ .cloned()+ .with_context(|| format!("unknown mux connection {name:?}"))?;+ let domain = Arc::new(ClientDomain::new(config));+ let mux_domain: Arc<dyn Domain> = domain.clone();+ Mux::get().add_domain(&mux_domain);+ if state+ .domains+ .values()+ .all(|domain| domain.state() != DomainState::Attached)+ {+ Mux::get().set_default_domain(&mux_domain);+ }+ state.domains.insert(name.to_string(), Arc::clone(&domain));+ domain+ };+ if domain.state() != DomainState::Attached {+ if let Some(item) = state+ .ui+ .connections+ .iter_mut()+ .find(|item| item.name == name)+ {+ item.status = ConnectionStatus::Connecting;+ }+ state.model.begin_connection_generation(name);+ if let Err(err) = domain+ .attach_with_ui(None, ConnectionUI::new_headless())+ .await+ {+ if let Some(item) = state+ .ui+ .connections+ .iter_mut()+ .find(|item| item.name == name)+ {+ item.status = ConnectionStatus::Failed;+ item.detail = format!("{err:#}");+ }+ return Err(err).with_context(|| format!("connecting to {name}"));+ }+ if let Err(err) = guard_against_same_server_nesting(&domain) {+ domain.perform_detach();+ state.connection_generations.remove(name);+ sync_connection_statuses(state);+ return Err(err);+ }+ }+ let (generation, snapshot) = fetch_current_session(&domain).await?;+ state+ .connection_generations+ .insert(name.to_string(), generation);+ state.model.begin_connection_generation(name);+ state.model.apply_snapshot(name, snapshot);+ if let Some(key) = state+ .model+ .rows()+ .iter()+ .filter(|row| row.key.domain_name == name)+ .find(|row| !row.thread.tabs.is_empty())+ .or_else(|| {+ state+ .model+ .rows()+ .iter()+ .find(|row| row.key.domain_name == name)+ })+ .map(|row| row.key.clone())+ {+ state.model.select_thread(&key);+ }+ sync_connection_statuses(state);+ state.ui.mode = AppMode::Terminal;+ ensure_selected_thread_live(state, true, Some(name)).await?;+ Ok(())+}++fn new_id(prefix: &str) -> String {+ format!("{prefix}-{}", Uuid::new_v4())+}++fn now_millis() -> u128 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis()+}++fn now_timestamp() -> i64 {+ (now_millis() / 1000).min(i64::MAX as u128) as i64+}++fn workspace_name(project_id: &str, thread_id: &str) -> String {+ format!("thinkterm:{project_id}:{thread_id}")+}++fn terminal_size(cols: usize, rows: usize, screen: ScreenSize) -> TerminalSize {+ #[cfg(unix)]+ let (pixel_width, pixel_height) = (+ scale_total_pixels(screen.xpixel, screen.cols, cols),+ scale_total_pixels(screen.ypixel, screen.rows, rows),+ );+ #[cfg(not(unix))]+ let (pixel_width, pixel_height) = (+ screen.xpixel.saturating_mul(cols),+ screen.ypixel.saturating_mul(rows),+ );+ TerminalSize {+ rows,+ cols,+ pixel_width,+ pixel_height,+ dpi: 96,+ }+}++#[cfg(unix)]+fn scale_total_pixels(total_pixels: usize, source_cells: usize, target_cells: usize) -> usize {+ if total_pixels == 0 || source_cells == 0 {+ 0+ } else {+ (total_pixels / source_cells).saturating_mul(target_cells)+ }+}++/// Append one decoded input event to `THINKTERM_LOG_INPUT`, if it is set.+///+/// A touchscreen terminal decides for itself what a swipe means, and the two+/// plausible answers — a wheel notch, or a button press that drags — reach this+/// program as entirely different events that it must treat differently. Which+/// one arrives is not something the code can be read to discover, so this+/// writes down what actually came in. Off unless the variable names a file, and+/// deliberately unbuffered: a session that has to be killed still leaves its+/// evidence on disk.+fn log_input_event(event: &InputEvent) {+ let Some(path) = std::env::var_os("THINKTERM_LOG_INPUT") else {+ return;+ };+ use std::io::Write;+ let Ok(mut file) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)+ else {+ return;+ };+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0.0, |since| since.as_secs_f64());+ // Formatted whole and written once: `writeln!` straight to the file splits+ // into several `write` calls, and the input threads then interleave inside+ // each other's lines. One append-mode write per line keeps them separable.+ let _ = file.write_all(format!("{stamp:.3} {event:?}\n").as_bytes());+}++fn handle_input(event: InputEvent, state: &mut TuiState) {+ log_input_event(&event);+ match event {+ InputEvent::Key(event) => handle_key(event, state),+ InputEvent::Mouse(event) => handle_mouse(event, state),+ InputEvent::PixelMouse(_) => {}+ InputEvent::Resized { .. } => {+ state.dirty = true;+ state.clear_selected_viewport_cache();+ }+ InputEvent::Paste(text) => {+ match state.ui.mode {+ AppMode::Prompt | AppMode::Search => {+ if let Some(prompt) = state.ui.prompt.as_mut() {+ prompt.value.push_str(&text);+ }+ }+ AppMode::Terminal => {+ if let Some(pane) = state.active_pane() {+ if let Err(err) = pane.send_paste(&text) {+ state.ui.status = format!("Paste: {err}");+ }+ }+ }+ _ => state.ui.status = "Paste is unavailable while an overlay is open".into(),+ }+ state.dirty = true;+ }+ InputEvent::Wake => {}+ }+}++fn handle_key(event: KeyEvent, state: &mut TuiState) {+ let modifiers = event.modifiers.remove_positional_mods();+ let key = event.key.normalize_shift_to_upper_case(modifiers);+ let is_prefix = key == KeyCode::Char('b') && modifiers.contains(Modifiers::CTRL);++ match state.ui.mode {+ AppMode::Prompt | AppMode::Search => {+ handle_prompt_key(key, state);+ return;+ }+ AppMode::Confirm => {+ match key {+ KeyCode::Enter | KeyCode::Char('y' | 'Y') => {+ state.queue(Action::AcceptConfirmation)+ }+ KeyCode::Escape | KeyCode::Char('n' | 'N') => state.queue(Action::CancelPrompt),+ _ => {}+ }+ state.dirty = true;+ return;+ }+ AppMode::ContextMenu => {+ handle_context_menu_key(key, state);+ return;+ }+ AppMode::Help => {+ if matches!(key, KeyCode::Escape | KeyCode::Char('?')) {+ state.queue(Action::ToggleHelp);+ }+ return;+ }+ AppMode::Navigate => {+ handle_navigate_key(key, state);+ return;+ }+ AppMode::Resize => {+ handle_resize_key(key, state);+ return;+ }+ AppMode::Copy => {+ handle_copy_key(key, state);+ return;+ }+ AppMode::Connections => {+ match key {+ KeyCode::Escape => state.queue(Action::CloseOverlay),+ KeyCode::Char('q') => state.queue(Action::Detach),+ KeyCode::UpArrow | KeyCode::Char('k') => {+ state.ui.connection_index = state.ui.connection_index.saturating_sub(1);+ }+ KeyCode::DownArrow | KeyCode::Char('j') => {+ state.ui.connection_index = (state.ui.connection_index + 1)+ .min(state.ui.connections.len().saturating_sub(1));+ }+ KeyCode::Enter | KeyCode::Char('r') => {+ if let Some(item) = state+ .ui+ .connections+ .get(state.ui.connection_index)+ .filter(|item| item.connectable)+ {+ state.queue(Action::ConnectDomain(item.name.clone()));+ }+ }+ KeyCode::Char('d') => {+ if let Some(item) = state+ .ui+ .connections+ .get(state.ui.connection_index)+ .filter(|item| item.status == ConnectionStatus::Attached)+ {+ state.queue(Action::DisconnectDomain(item.name.clone()));+ }+ }+ _ => {}+ }+ state.dirty = true;+ return;+ }+ AppMode::Settings => {+ match key {+ KeyCode::Escape => state.queue(Action::CloseOverlay),+ KeyCode::UpArrow | KeyCode::Char('k') => {+ state.ui.settings_index = state.ui.settings_index.saturating_sub(1);+ }+ KeyCode::DownArrow | KeyCode::Char('j') => {+ state.ui.settings_index = (state.ui.settings_index + 1).min(SETTINGS.len() - 1);+ }+ KeyCode::LeftArrow | KeyCode::Char('h') => {+ state.queue(Action::AdjustSetting {+ index: state.ui.settings_index,+ delta: -1,+ });+ }+ KeyCode::RightArrow | KeyCode::Char('l') | KeyCode::Enter | KeyCode::Char(' ') => {+ state.queue(Action::AdjustSetting {+ index: state.ui.settings_index,+ delta: 1,+ });+ }+ _ => {}+ }+ state.dirty = true;+ return;+ }+ AppMode::Prefix => {+ handle_prefix_key(key, modifiers, state);+ return;+ }+ AppMode::Terminal => {}+ }++ if is_prefix {+ state.ui.mode = AppMode::Prefix;+ state.ui.status.clear();+ state.dirty = true;+ return;+ }++ if should_copy_retained_selection(+ key,+ modifiers,+ state.settings.copy_on_select,+ state.ui.selection.as_ref(),+ ) {+ state.queue(Action::CopySelection);+ return;+ }+ send_key_to_pane(key, modifiers, state);+}++fn should_copy_retained_selection(+ key: KeyCode,+ modifiers: Modifiers,+ copy_on_select: bool,+ selection: Option<&TextSelection>,+) -> bool {+ !copy_on_select+ && matches!(key, KeyCode::Char('c' | 'C'))+ && (modifiers.contains(Modifiers::CTRL) || modifiers.contains(Modifiers::SUPER))+ && selection.is_some_and(|selection| selection.finalized)+}++fn handle_prefix_key(key: KeyCode, modifiers: Modifiers, state: &mut TuiState) {+ state.ui.mode = AppMode::Terminal;+ let action = match key {+ KeyCode::Char('b') if modifiers.contains(Modifiers::CTRL) => {+ send_key_to_pane(KeyCode::Char('b'), Modifiers::CTRL, state);+ Action::None+ }+ KeyCode::Char('d' | 'q') => Action::Detach,+ KeyCode::Char('b' | 's') => Action::ToggleSidebar,+ KeyCode::Char('?') => Action::ToggleHelp,+ KeyCode::Char('g' | 'w') => Action::OpenNavigator,+ KeyCode::Char('C') => Action::OpenConnections,+ KeyCode::Char(',') => Action::OpenSettings,+ KeyCode::Char('c') => Action::NewTab,+ KeyCode::Char('n') => Action::SelectRelativeTab(1),+ KeyCode::Char('p') => Action::SelectRelativeTab(-1),+ KeyCode::Char('o') => Action::SelectNextAttention,+ KeyCode::Tab => Action::CyclePane(1),+ KeyCode::UpArrow => Action::SelectRelativeThread(-1),+ KeyCode::DownArrow => Action::SelectRelativeThread(1),+ KeyCode::Char('h') | KeyCode::LeftArrow => Action::FocusPane(PaneDirection::Left),+ KeyCode::Char('j') => Action::FocusPane(PaneDirection::Down),+ KeyCode::Char('k') => Action::FocusPane(PaneDirection::Up),+ KeyCode::Char('l') | KeyCode::RightArrow => Action::FocusPane(PaneDirection::Right),+ KeyCode::Char('v') => Action::SplitPane(SplitAxis::Right),+ KeyCode::Char('-') | KeyCode::Subtract => Action::SplitPane(SplitAxis::Down),+ KeyCode::Char('x') => state+ .active_pane()+ .map(|pane| {+ Action::Confirm(DestructiveAction::ClosePane {+ pane_id: pane.pane_id(),+ })+ })+ .unwrap_or(Action::None),+ KeyCode::Char('X') => state+ .model+ .selected_tab()+ .map(|tab| Action::Confirm(DestructiveAction::CloseTab { tab_id: tab.tab_id }))+ .unwrap_or(Action::None),+ KeyCode::Char('z') => Action::ToggleZoom,+ KeyCode::Char('r') => Action::EnterResize,+ KeyCode::Char('[') => Action::EnterCopyMode,+ KeyCode::Char(c @ '1'..='9') => {+ let index = c as usize - '1' as usize;+ state+ .model+ .tabs_for_selected_thread()+ .get(index)+ .map(|tab| Action::SelectTab(tab.tab_id))+ .unwrap_or(Action::None)+ }+ _ => {+ state.ui.status = "Unknown prefix command · Ctrl-b ? for help".into();+ Action::None+ }+ };+ state.queue(action);+ state.dirty = true;+}++fn handle_navigate_key(key: KeyCode, state: &mut TuiState) {+ let action = match key {+ KeyCode::Escape | KeyCode::Enter => Action::CloseOverlay,+ KeyCode::UpArrow | KeyCode::Char('k') => Action::SelectRelativeThread(-1),+ KeyCode::DownArrow | KeyCode::Char('j') => Action::SelectRelativeThread(1),+ KeyCode::LeftArrow | KeyCode::Char('h') => Action::FocusPane(PaneDirection::Left),+ KeyCode::RightArrow | KeyCode::Char('l') => Action::FocusPane(PaneDirection::Right),+ KeyCode::Char('n') => Action::SelectRelativeTab(1),+ KeyCode::Char('p') => Action::SelectRelativeTab(-1),+ KeyCode::Char('?') => Action::ToggleHelp,+ _ => Action::None,+ };+ state.queue(action);+ state.dirty = true;+}++fn handle_resize_key(key: KeyCode, state: &mut TuiState) {+ let action = match key {+ KeyCode::Escape | KeyCode::Enter => Action::CloseOverlay,+ KeyCode::LeftArrow | KeyCode::Char('h') => Action::ResizePane(PaneDirection::Left, 1),+ KeyCode::DownArrow | KeyCode::Char('j') => Action::ResizePane(PaneDirection::Down, 1),+ KeyCode::UpArrow | KeyCode::Char('k') => Action::ResizePane(PaneDirection::Up, 1),+ KeyCode::RightArrow | KeyCode::Char('l') => Action::ResizePane(PaneDirection::Right, 1),+ _ => Action::None,+ };+ state.queue(action);+ state.dirty = true;+}++fn handle_copy_key(key: KeyCode, state: &mut TuiState) {+ if state.ui.copy.is_none() {+ state.ui.mode = AppMode::Terminal;+ return;+ }+ let mut moved = false;+ let mut action = Action::None;+ {+ let copy = state.ui.copy.as_mut().unwrap();+ match key {+ KeyCode::Escape => action = Action::LeaveCopyMode,+ KeyCode::LeftArrow | KeyCode::Char('h') => {+ copy.cursor.col = copy.cursor.col.saturating_sub(1);+ moved = true;+ }+ KeyCode::RightArrow | KeyCode::Char('l') => {+ copy.cursor.col = copy.cursor.col.saturating_add(1);+ moved = true;+ }+ KeyCode::UpArrow | KeyCode::Char('k') => {+ copy.cursor.row = copy.cursor.row.saturating_sub(1);+ moved = true;+ }+ KeyCode::DownArrow | KeyCode::Char('j') => {+ copy.cursor.row = copy.cursor.row.saturating_add(1);+ moved = true;+ }+ KeyCode::PageUp => {+ action = Action::ScrollPane {+ pane_id: copy.pane_id,+ lines: 10,+ }+ }+ KeyCode::PageDown => {+ action = Action::ScrollPane {+ pane_id: copy.pane_id,+ lines: -10,+ }+ }+ KeyCode::End => {+ action = Action::ScrollToBottom {+ pane_id: copy.pane_id,+ }+ }+ KeyCode::Char(' ') => {+ if let Some(selection) = copy.selection.as_mut() {+ selection.head = copy.cursor;+ selection.finalized = true;+ } else {+ copy.selection = Some(TextSelection {+ pane_id: copy.pane_id,+ anchor: copy.cursor,+ head: copy.cursor,+ finalized: false,+ });+ }+ }+ KeyCode::Char('y' | 'Y') | KeyCode::Enter => action = Action::CopySelection,+ KeyCode::Char('/') => action = Action::BeginSearch { backwards: false },+ KeyCode::Char('?') => action = Action::BeginSearch { backwards: true },+ KeyCode::Char('n') => action = Action::SearchNext { backwards: false },+ KeyCode::Char('N') => action = Action::SearchNext { backwards: true },+ _ => {}+ }+ }+ if moved {+ keep_copy_cursor_visible(state);+ if let Some(copy) = state.ui.copy.as_mut() {+ if let Some(selection) = copy+ .selection+ .as_mut()+ .filter(|selection| !selection.finalized)+ {+ selection.head = copy.cursor;+ }+ }+ }+ state.queue(action);+ state.dirty = true;+}++fn keep_copy_cursor_visible(state: &mut TuiState) {+ let Some(copy) = state.ui.copy.as_ref() else {+ return;+ };+ let pane_id = copy.pane_id;+ let cursor = copy.cursor;+ let Some(pane) = state.pane(pane_id) else {+ return;+ };+ let dims = pane.get_dimensions();+ let visible_rows = state+ .layout+ .panes+ .iter()+ .find(|pane| pane.pane_id == pane_id)+ .map(|pane| pane.rect.height as usize)+ .unwrap_or(dims.viewport_rows)+ .max(1);+ let max_row =+ dims.physical_top + dims.viewport_rows.saturating_sub(1) as wezterm_term::StableRowIndex;+ let max_offset = dims.scrollback_rows.saturating_sub(dims.viewport_rows);+ let (cursor, offset) = adjusted_copy_view(+ cursor,+ dims.cols,+ dims.scrollback_top,+ max_row,+ dims.physical_top,+ visible_rows,+ state.ui.scroll_offset(pane_id),+ max_offset,+ );+ if let Some(copy) = state.ui.copy.as_mut() {+ copy.cursor = cursor;+ }+ state.ui.set_scroll_offset(pane_id, offset);+}++#[allow(clippy::too_many_arguments)]+fn adjusted_copy_view(+ mut cursor: SelectionPoint,+ cols: usize,+ earliest_row: wezterm_term::StableRowIndex,+ latest_row: wezterm_term::StableRowIndex,+ physical_top: wezterm_term::StableRowIndex,+ visible_rows: usize,+ current_offset: usize,+ max_offset: usize,+) -> (SelectionPoint, usize) {+ cursor.row = cursor.row.clamp(earliest_row, latest_row);+ cursor.col = cursor.col.min(cols.saturating_sub(1));++ let visible_rows = visible_rows.max(1) as wezterm_term::StableRowIndex;+ let current_offset = current_offset.min(max_offset);+ let visible_top = physical_top+ .saturating_sub(current_offset as wezterm_term::StableRowIndex)+ .max(earliest_row);+ let desired_top = if cursor.row < visible_top {+ cursor.row+ } else if cursor.row >= visible_top + visible_rows {+ cursor.row - visible_rows + 1+ } else {+ visible_top+ };+ let offset = physical_top.saturating_sub(desired_top).max(0) as usize;+ let offset = offset.min(max_offset);+ let final_top = physical_top+ .saturating_sub(offset as wezterm_term::StableRowIndex)+ .max(earliest_row);+ let final_bottom = (final_top + visible_rows - 1).min(latest_row);+ cursor.row = cursor.row.clamp(final_top, final_bottom);+ (cursor, offset)+}++fn handle_prompt_key(key: KeyCode, state: &mut TuiState) {+ let action = match key {+ KeyCode::Escape => Action::CancelPrompt,+ KeyCode::Enter => Action::SubmitPrompt,+ KeyCode::Backspace => {+ if let Some(prompt) = state.ui.prompt.as_mut() {+ prompt.value.pop();+ }+ Action::None+ }+ KeyCode::Char(ch) if !ch.is_control() => {+ if let Some(prompt) = state.ui.prompt.as_mut() {+ prompt.value.push(ch);+ }+ Action::None+ }+ _ => Action::None,+ };+ state.queue(action);+ state.dirty = true;+}++fn handle_context_menu_key(key: KeyCode, state: &mut TuiState) {+ if state.ui.context_menu.is_none() {+ state.ui.mode = AppMode::Terminal;+ return;+ }+ let mut action = Action::None;+ let mut close = false;+ {+ let menu = state.ui.context_menu.as_mut().unwrap();+ match key {+ KeyCode::Escape => action = Action::CloseOverlay,+ KeyCode::UpArrow | KeyCode::Char('k') => {+ menu.selected = menu.selected.saturating_sub(1);+ }+ KeyCode::DownArrow | KeyCode::Char('j') => {+ menu.selected = (menu.selected + 1).min(menu.entries.len().saturating_sub(1));+ }+ KeyCode::Enter => {+ if let Some(entry) = menu+ .entries+ .get(menu.selected)+ .filter(|entry| entry.enabled)+ {+ action = entry.action.clone();+ }+ close = true;+ }+ _ => {}+ }+ }+ if close {+ state.ui.context_menu = None;+ state.ui.mode = AppMode::Terminal;+ }+ state.queue(action);+ state.dirty = true;+}++fn menu_entry(label: impl Into<String>, action: Action) -> MenuEntry {+ MenuEntry {+ label: label.into(),+ action,+ destructive: false,+ enabled: true,+ }+}++fn destructive_menu_entry(label: impl Into<String>, action: Action) -> MenuEntry {+ MenuEntry {+ label: label.into(),+ action,+ destructive: true,+ enabled: true,+ }+}++fn open_context_menu(state: &mut TuiState, x: u16, y: u16, target: Option<HitTarget>) {+ use crate::model::TreeNodeKey;++ let entries = match target {+ Some(HitTarget::Tree(TreeNodeKey::Domain(domain_name))) => vec![+ menu_entry(+ "New Space",+ Action::NewSpace {+ domain_name: domain_name.clone(),+ },+ ),+ menu_entry("Retry connection", Action::RetryDomain(domain_name.clone())),+ menu_entry("Disconnect", Action::DisconnectDomain(domain_name)),+ ],+ Some(HitTarget::Tree(TreeNodeKey::Space {+ domain_name,+ space_id,+ })) => vec![+ menu_entry(+ "New Project",+ Action::NewProject {+ domain_name: domain_name.clone(),+ space_id: space_id.clone(),+ },+ ),+ menu_entry(+ "Rename Space",+ Action::RenameNode(TreeNodeKey::Space {+ domain_name: domain_name.clone(),+ space_id: space_id.clone(),+ }),+ ),+ destructive_menu_entry(+ "Delete from server",+ Action::Confirm(DestructiveAction::DeleteSpace {+ domain_name: domain_name.clone(),+ space_id: space_id.clone(),+ end_sessions: false,+ }),+ ),+ destructive_menu_entry(+ "End sessions and delete",+ Action::Confirm(DestructiveAction::DeleteSpace {+ domain_name,+ space_id,+ end_sessions: true,+ }),+ ),+ ],+ Some(HitTarget::Tree(TreeNodeKey::Project {+ domain_name,+ project_id,+ })) => vec![+ menu_entry(+ "New Thread",+ Action::NewThread {+ domain_name: domain_name.clone(),+ project_id: project_id.clone(),+ },+ ),+ menu_entry(+ "Rename Project",+ Action::RenameNode(TreeNodeKey::Project {+ domain_name: domain_name.clone(),+ project_id: project_id.clone(),+ }),+ ),+ destructive_menu_entry(+ "End sessions and remove",+ Action::Confirm(DestructiveAction::RemoveProject {+ domain_name,+ project_id,+ end_sessions: true,+ }),+ ),+ ],+ Some(HitTarget::Tree(TreeNodeKey::Thread(key))) => {+ let pinned = state+ .model+ .row(&key)+ .is_some_and(|row| row.thread.is_pinned);+ vec![+ menu_entry("Open", Action::SelectThread(key.clone())),+ menu_entry(+ "New Thread",+ Action::NewThread {+ domain_name: key.domain_name.clone(),+ project_id: state+ .model+ .row(&key)+ .map(|row| row.project.id.clone())+ .unwrap_or_default(),+ },+ ),+ menu_entry(+ "Rename Thread",+ Action::RenameNode(TreeNodeKey::Thread(key.clone())),+ ),+ menu_entry(+ if pinned { "Unpin" } else { "Pin" },+ Action::ToggleThreadPinned(key.clone()),+ ),+ destructive_menu_entry(+ "End session and delete",+ Action::Confirm(DestructiveAction::DeleteThread {+ key,+ end_sessions: true,+ }),+ ),+ ]+ }+ Some(HitTarget::Tab(tab_id)) => vec![+ menu_entry("Open", Action::SelectTab(tab_id)),+ menu_entry("New Tab", Action::NewTab),+ menu_entry("Rename Tab", Action::RenameTab),+ destructive_menu_entry(+ "Close Tab",+ Action::Confirm(DestructiveAction::CloseTab { tab_id }),+ ),+ ],+ Some(HitTarget::Pane(pane_id)) => {+ if let (Some((_, _, tab, _)), Some(pane)) = (state.active_tab(), state.pane(pane_id)) {+ tab.set_active_pane(&pane);+ }+ let mut copy = menu_entry("Copy", Action::CopySelection);+ copy.enabled = state+ .ui+ .selection+ .as_ref()+ .is_some_and(|selection| selection.pane_id == pane_id && selection.finalized);+ vec![+ copy,+ menu_entry("Paste", Action::PasteClipboard),+ menu_entry("Split Right", Action::SplitPane(SplitAxis::Right)),+ menu_entry("Split Down", Action::SplitPane(SplitAxis::Down)),+ menu_entry("Zoom", Action::ToggleZoom),+ destructive_menu_entry(+ "Close Pane",+ Action::Confirm(DestructiveAction::ClosePane { pane_id }),+ ),+ ]+ }+ _ => Vec::new(),+ };++ if entries.is_empty() {+ state.ui.context_menu = None;+ state.ui.mode = AppMode::Terminal;+ return;+ }+ state.ui.context_menu = Some(ContextMenuState {+ anchor: (x, y),+ selected: 0,+ entries,+ });+ state.ui.mode = AppMode::ContextMenu;+}++fn open_main_menu(state: &mut TuiState, x: u16, y: u16) {+ state.ui.context_menu = Some(ContextMenuState {+ anchor: (x, y),+ selected: 0,+ entries: vec![+ menu_entry("New Tab", Action::NewTab),+ menu_entry("Split Right", Action::SplitPane(SplitAxis::Right)),+ menu_entry("Split Down", Action::SplitPane(SplitAxis::Down)),+ menu_entry("Copy Mode", Action::EnterCopyMode),+ menu_entry("Paste", Action::PasteClipboard),+ menu_entry("Connections", Action::OpenConnections),+ menu_entry("TUI Settings", Action::OpenSettings),+ menu_entry("Toggle Sidebar", Action::ToggleSidebar),+ menu_entry("Help", Action::ToggleHelp),+ menu_entry("Detach", Action::Detach),+ ],+ });+ state.ui.mode = AppMode::ContextMenu;+}++fn activate_context_menu_entry(state: &mut TuiState, index: usize) {+ let action = state+ .ui+ .context_menu+ .as_ref()+ .and_then(|menu| menu.entries.get(index))+ .filter(|entry| entry.enabled)+ .map(|entry| entry.action.clone());+ state.ui.context_menu = None;+ state.ui.mode = AppMode::Terminal;+ if let Some(action) = action {+ state.queue(action);+ }+}++fn send_key_to_pane(key: KeyCode, modifiers: Modifiers, state: &mut TuiState) {+ if let Some(pane) = state.active_pane() {+ if let Err(err) = pane.key_down(key, modifiers) {+ state.ui.status = format!("Input: {err}");+ } else {+ state.ui.status.clear();+ state.ui.set_scroll_offset(pane.pane_id(), 0);+ }+ } else {+ state.ui.status = "No live pane selected".to_string();+ }+ state.dirty = true;+}++/// Where one wheel notch over a pane belongs.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum WheelRouting {+ /// The program asked for mouse events, so it gets the notch itself.+ Pane,+ /// Travel through the pane's scrollback.+ Scrollback,+ /// Translate the notch into the arrow keys a full-screen program is+ /// already listening for.+ ArrowKeys,+}++/// The alternate screen keeps no scrollback to travel through, so a notch spent+/// there would otherwise do nothing whatsoever. Spending it on arrow keys is+/// what makes `less` and `git log` readable from a touchscreen, which has no+/// keyboard to offer instead. Shift, and an existing scroll position, both mean+/// the reader deliberately left the live screen, so they keep the scrollback.+fn wheel_routing(+ pane_wants_mouse: bool,+ alt_screen: bool,+ shifted: bool,+ scroll_offset: usize,+) -> WheelRouting {+ if shifted || scroll_offset != 0 {+ WheelRouting::Scrollback+ } else if pane_wants_mouse {+ WheelRouting::Pane+ } else if alt_screen {+ WheelRouting::ArrowKeys+ } else {+ WheelRouting::Scrollback+ }+}++fn handle_mouse(event: TermwizMouseEvent, state: &mut TuiState) {+ let (x, y) = mouse_cell_coordinates(&event);+ let prior = state.last_mouse_buttons.clone();+ let current = event.mouse_buttons.clone();+ let left_pressed = current.contains(MouseButtons::LEFT) && !prior.contains(MouseButtons::LEFT);+ let left_released = !current.contains(MouseButtons::LEFT) && prior.contains(MouseButtons::LEFT);+ let right_pressed =+ current.contains(MouseButtons::RIGHT) && !prior.contains(MouseButtons::RIGHT);+ let middle_pressed =+ current.contains(MouseButtons::MIDDLE) && !prior.contains(MouseButtons::MIDDLE);+ let shifted = event.modifiers.contains(Modifiers::SHIFT);+ let wheel =+ current.contains(MouseButtons::VERT_WHEEL) || current.contains(MouseButtons::HORZ_WHEEL);++ // Before any of the branches below, every one of which returns early.+ //+ // Touching a renderer is the plainest statement that it is the one being+ // looked at, and the server only hands the viewport over on input it can+ // see — a click or a scroll on a pane that has not asked for mouse+ // reporting never leaves this process. Hanging this off the left-click+ // branch alone was not enough: the wheel is handled and returned several+ // branches earlier, so scrolling, which is most of what a phone does, never+ // took the viewport at all. Motion is excluded on purpose; a pointer+ // crossing the window is not a statement about anything.+ if (left_pressed || right_pressed || middle_pressed || wheel) && !state.owns_active_viewport() {+ state.claim_viewport_after_layout = true;+ }++ if modal_mouse_input(state, x, y, left_pressed) {+ state.last_mouse_buttons = current;+ state.dirty = true;+ return;+ }++ if let Some(pane_id) = state.forwarded_mouse_pane {+ forward_mouse_to_pane(event, x, y, Some(pane_id), state);+ if first_button(¤t).is_none() {+ state.forwarded_mouse_pane = None;+ }+ state.last_mouse_buttons = current;+ state.dirty = true;+ return;+ }++ if (right_pressed && shifted) || middle_pressed {+ if let Some(pane_id) = state.layout.pane_at(x, y).map(|pane| pane.pane_id) {+ state.forwarded_mouse_pane = Some(pane_id);+ forward_mouse_to_pane(event, x, y, Some(pane_id), state);+ }+ state.last_mouse_buttons = current;+ state.dirty = true;+ return;+ }++ if wheel {+ if state+ .layout+ .sidebar_body+ .is_some_and(|body| body.contains((x, y).into()))+ {+ let amount = state.settings.scroll_lines.max(1);+ if current.contains(MouseButtons::WHEEL_POSITIVE) {+ state.ui.sidebar_scroll = state.ui.sidebar_scroll.saturating_sub(amount);+ } else {+ state.ui.sidebar_scroll = state.ui.sidebar_scroll.saturating_add(amount);+ }+ state.last_mouse_buttons = current;+ state.dirty = true;+ return;+ }+ if let Some(pane_view) = state.layout.pane_at(x, y) {+ let pane_id = pane_view.pane_id;+ if let Some(pane) = state.pane(pane_id) {+ let routing = wheel_routing(+ state.settings.mouse && pane.is_mouse_grabbed(),+ pane.is_alt_screen_active(),+ shifted,+ state.ui.scroll_offset(pane_id),+ );+ let vertical = current.contains(MouseButtons::VERT_WHEEL);+ let up = current.contains(MouseButtons::WHEEL_POSITIVE);+ match routing {+ WheelRouting::Pane => {+ forward_mouse_to_pane(event.clone(), x, y, Some(pane_id), state);+ }+ WheelRouting::ArrowKeys if vertical => {+ let key = if up {+ KeyCode::UpArrow+ } else {+ KeyCode::DownArrow+ };+ for _ in 0..state.settings.scroll_lines.max(1) {+ if pane.key_down(key, Modifiers::NONE).is_err() {+ break;+ }+ }+ }+ WheelRouting::Scrollback if vertical => {+ let lines = state.settings.scroll_lines as isize;+ state.queue(Action::ScrollPane {+ pane_id,+ lines: if up { lines } else { -lines },+ });+ }+ _ => {}+ }+ }+ }+ state.last_mouse_buttons = current;+ state.dirty = true;+ return;+ }++ if right_pressed && !shifted {+ let target = state.layout.hit(x, y).cloned();+ open_context_menu(state, x, y, target);+ state.last_mouse_buttons = current;+ state.dirty = true;+ return;+ }++ if left_pressed {+ let target = state.layout.hit(x, y).cloned();+ match target {+ Some(HitTarget::SidebarToggle) => state.queue(Action::ToggleSidebar),+ Some(HitTarget::TabControl(control)) => match control {+ TabBarControl::Menu => open_main_menu(state, x, y),+ TabBarControl::NewTab => state.queue(Action::NewTab),+ },+ // Closing a tab takes the same confirmation the menu entry does.+ Some(HitTarget::CloseTab(tab_id)) => {+ state.queue(Action::Confirm(DestructiveAction::CloseTab { tab_id }))+ }+ Some(HitTarget::Detach) => state.queue(Action::Detach),+ Some(HitTarget::Attention) => state.queue(Action::SelectNextAttention),+ Some(HitTarget::OpenSettings) => state.queue(Action::OpenSettings),+ Some(HitTarget::NewThread) => {+ if let Some(row) = state.model.selected_row() {+ state.queue(Action::NewThread {+ domain_name: row.key.domain_name.clone(),+ project_id: row.project.id.clone(),+ });+ }+ }+ // The heading has no space of its own, so the new project joins the+ // one the selected thread is already in — which is the space the+ // tree is showing you.+ Some(HitTarget::NewProject) => {+ if let Some(row) = state.model.selected_row() {+ state.queue(Action::NewProject {+ domain_name: row.key.domain_name.clone(),+ space_id: row.space.id.clone(),+ });+ }+ }+ Some(HitTarget::TreeAction(key, action)) => tree_action(state, x, y, key, action),+ Some(HitTarget::PaneNavTab(pane_id)) => activate_pane_in_stack(state, pane_id),+ // Closing a pane takes the same confirmation the menu entry does.+ Some(HitTarget::PaneNavClose(pane_id)) => {+ state.queue(Action::Confirm(DestructiveAction::ClosePane { pane_id }))+ }+ Some(HitTarget::PaneTool(pane_id, tool)) => pane_tool(state, pane_id, tool),+ Some(HitTarget::Scrollbar(pane_id)) => {+ scroll_to_scrollbar_position(state, pane_id, y);+ state.drag = Some(DragState::Scrollbar { pane_id });+ }+ Some(HitTarget::TreeToggle(key)) => state.ui.toggle_collapsed(key),+ Some(HitTarget::Tree(crate::model::TreeNodeKey::Thread(key))) => {+ state.queue(Action::SelectThread(key.clone()));+ state.drag = Some(DragState::TreeNode {+ key: TreeNodeKey::Thread(key),+ });+ }+ Some(HitTarget::Tree(key)) => {+ state.drag = Some(DragState::TreeNode { key });+ }+ Some(HitTarget::Tab(tab_id)) => state.queue(Action::SelectTab(tab_id)),+ Some(HitTarget::Pane(pane_id)) => {+ if let Some(pane) = state.pane(pane_id) {+ if state.settings.mouse && pane.is_mouse_grabbed() && !shifted {+ state.forwarded_mouse_pane = Some(pane_id);+ forward_mouse_to_pane(event.clone(), x, y, Some(pane_id), state);+ } else if let Some(point) = pane_point(state, pane_id, x, y) {+ state.queue(Action::FocusPaneId(pane_id));+ state.ui.selection = Some(TextSelection {+ pane_id,+ anchor: point,+ head: point,+ finalized: false,+ });+ state.drag = Some(DragState::Selection { pane_id });+ }+ }+ }+ Some(HitTarget::SidebarResize) => state.drag = Some(DragState::SidebarResize),+ Some(HitTarget::Split(split_index)) => {+ state.drag = Some(DragState::SplitResize {+ split_index,+ last_x: x,+ last_y: y,+ });+ }+ Some(HitTarget::ContextMenu(index)) => activate_context_menu_entry(state, index),+ Some(HitTarget::Connection(index)) => {+ state.ui.connection_index = index;+ if let Some(item) = state+ .ui+ .connections+ .get(index)+ .filter(|item| item.connectable)+ {+ state.queue(Action::ConnectDomain(item.name.clone()));+ }+ }+ Some(HitTarget::DialogConfirm) => state.queue(Action::AcceptConfirmation),+ Some(HitTarget::DialogCancel) => state.queue(Action::CancelPrompt),+ Some(HitTarget::Setting(_)) => {}+ None => {}+ }+ } else if current.contains(MouseButtons::LEFT) {+ match state.drag.clone() {+ Some(DragState::Selection { pane_id }) => {+ if let Some(point) = pane_point(state, pane_id, x, y) {+ if let Some(selection) = state.ui.selection.as_mut() {+ selection.head = point;+ }+ }+ }+ Some(DragState::Scrollbar { pane_id }) => {+ scroll_to_scrollbar_position(state, pane_id, y);+ }+ Some(DragState::SidebarResize) => {+ state.ui.sidebar_width = x.saturating_sub(state.layout.screen.x).clamp(18, 36);+ state.clear_selected_viewport_cache();+ // Dragging the divider is as deliberate as toggling the sidebar+ // away, so it earns the same authority over the grid; without+ // this the terminal keeps whichever width another client chose.+ state.claim_viewport_after_layout = true;+ }+ Some(DragState::TreeNode { .. }) => {}+ Some(DragState::SplitResize {+ split_index,+ last_x,+ last_y,+ }) => {+ if state.active_tab().is_some() {+ if let Some(split) = state+ .layout+ .splits+ .iter()+ .find(|split| split.index == split_index)+ {+ let delta = match split.direction {+ SplitDirection::Horizontal => x as isize - last_x as isize,+ SplitDirection::Vertical => y as isize - last_y as isize,+ };+ if delta != 0 {+ state.queue(Action::ResizeSplit { split_index, delta });+ }+ }+ }+ state.drag = Some(DragState::SplitResize {+ split_index,+ last_x: x,+ last_y: y,+ });+ }+ None => {+ if state.layout.content.contains((x, y).into()) {+ forward_mouse_to_pane(event.clone(), x, y, None, state);+ }+ }+ }+ }++ if left_released {+ if matches!(state.drag, Some(DragState::Selection { .. })) {+ let copy = finish_pointer_selection(&mut state.ui.selection);+ if copy && state.settings.copy_on_select {+ state.queue(Action::CopySelection);+ }+ } else if let Some(DragState::TreeNode { key }) = state.drag.clone() {+ if let Some(HitTarget::Tree(target)) = state.layout.hit(x, y).cloned() {+ if let Some(action) = tree_reorder_action(state, key, target) {+ state.queue(action);+ }+ }+ } else if matches!(state.drag, Some(DragState::SidebarResize)) {+ state.settings.sidebar_width = state.ui.sidebar_width;+ if let Err(err) = save_tui_settings(state) {+ state.ui.status = format!("Saving TUI settings: {err:#}");+ }+ } else if state.layout.content.contains((x, y).into()) {+ forward_mouse_to_pane(event.clone(), x, y, None, state);+ }+ state.drag = None;+ }+ state.last_mouse_buttons = current;+ state.dirty = true;+}++/// How far along one row a pointer must travel before it is selecting rather+/// than pointing. A mouse lands on the cell it was aimed at; a fingertip covers+/// several and reports whichever the touchscreen picked, so a tap that meant+/// "focus this pane" arrives as a one- or two-cell drag. With copy-on-select+/// enabled that tap would take the clipboard with it.+const SELECTION_DRAG_THRESHOLD: usize = 3;++/// A click focuses a pane; only deliberate movement creates a text selection.+///+/// Any movement across rows counts, however small — reaching a different line+/// is unambiguous. Within one row the pointer has to cover+/// [`SELECTION_DRAG_THRESHOLD`] cells, which is more than a fingertip's slop+/// and less than any selection worth making.+fn finish_pointer_selection(selection: &mut Option<TextSelection>) -> bool {+ let Some(current) = selection.as_mut() else {+ return false;+ };+ let same_row = current.anchor.row == current.head.row;+ let travelled = current.anchor.col.abs_diff(current.head.col);+ if same_row && travelled < SELECTION_DRAG_THRESHOLD {+ *selection = None;+ return false;+ }+ current.finalized = true;+ true+}++/// Put the pane where the scrollbar was grabbed.+///+/// The bar maps the whole scrollback onto its own height, so the row a finger+/// lands on names a position directly — the same gesture works as a jump and,+/// held, as a drag.+fn scroll_to_scrollbar_position(state: &mut TuiState, pane_id: PaneId, y: u16) {+ let Some(bar) = state+ .layout+ .panes+ .iter()+ .find(|pane| pane.pane_id == pane_id)+ .and_then(|pane| pane.scrollbar)+ else {+ return;+ };+ let Some(pane) = state.pane(pane_id) else {+ return;+ };+ let dims = pane.get_dimensions();+ let scrollable = dims.scrollback_rows.saturating_sub(dims.viewport_rows);+ if scrollable == 0 || bar.height == 0 {+ return;+ }+ // The top of the bar is the oldest line, so distance from the bottom is how+ // far back the view has been pulled.+ let from_bottom = bar+ .bottom()+ .saturating_sub(1)+ .saturating_sub(y.min(bar.bottom() - 1));+ let offset = (from_bottom as usize * scrollable) / bar.height.max(1) as usize;+ state.ui.set_scroll_offset(pane_id, offset.min(scrollable));+ state.dirty = true;+}++/// Run the command a tree row's own button stands for.+///+/// Every arm here forwards to an `Action` that the row's context menu already+/// offered; the button is a second doorway to it, not a second implementation.+/// `Menu` opens that very menu, so anything not worth its own button stays one+/// tap away.+/// Show a pane that is stacked behind the one currently drawn in its place.+///+/// The server keeps its own idea of which pane in a stack is showing, and the+/// next resync would flip a purely local change back to it — so the change has+/// to be sent as well. The GUI mirrors it for the same reason.+fn activate_pane_in_stack(state: &mut TuiState, pane_id: PaneId) {+ let mux = Mux::get();+ if let Err(err) = mux.activate_pane_in_stack(pane_id) {+ state.ui.status = format!("Show pane: {err:#}");+ return;+ }+ if let Some(pane) = mux.get_pane(pane_id) {+ if let Some(client_pane) = pane.downcast_ref::<ClientPane>() {+ client_pane.activate_in_stack_on_server();+ }+ }+ state.queue(Action::FocusPaneId(pane_id));+}++/// Every pane tool acts on "the" pane, so the pane whose button was pressed has+/// to become that pane first. Two actions rather than one, drained in order.+fn pane_tool(state: &mut TuiState, pane_id: PaneId, tool: PaneTool) {+ state.queue(Action::FocusPaneId(pane_id));+ state.queue(match tool {+ PaneTool::Zoom { .. } => Action::ToggleZoom,+ PaneTool::SplitRight => Action::SplitPane(SplitAxis::Right),+ PaneTool::SplitDown => Action::SplitPane(SplitAxis::Down),+ PaneTool::NewTab => Action::NewPaneInStack(pane_id),+ });+}++fn tree_action(state: &mut TuiState, x: u16, y: u16, key: TreeNodeKey, action: TreeAction) {+ match (action, key) {+ (TreeAction::Menu, key) => open_context_menu(state, x, y, Some(HitTarget::Tree(key))),+ (+ TreeAction::Add,+ TreeNodeKey::Space {+ domain_name,+ space_id,+ },+ ) => state.queue(Action::NewProject {+ domain_name,+ space_id,+ }),+ (+ TreeAction::Add,+ TreeNodeKey::Project {+ domain_name,+ project_id,+ },+ ) => state.queue(Action::NewThread {+ domain_name,+ project_id,+ }),+ _ => {}+ }+}++/// Modal overlays own the entire screen, not just their visible buttons. This+/// prevents clicks and scrolling outside a dialog from reaching hidden panes.+fn modal_mouse_input(state: &mut TuiState, x: u16, y: u16, left_pressed: bool) -> bool {+ match state.ui.mode {+ AppMode::ContextMenu => {+ if left_pressed {+ match state.layout.hit(x, y).cloned() {+ Some(HitTarget::ContextMenu(index)) => {+ activate_context_menu_entry(state, index)+ }+ _ => state.queue(Action::CloseOverlay),+ }+ }+ true+ }+ AppMode::Confirm => {+ if left_pressed {+ match state.layout.hit(x, y) {+ Some(HitTarget::DialogConfirm) => state.queue(Action::AcceptConfirmation),+ Some(HitTarget::DialogCancel) => state.queue(Action::CancelPrompt),+ _ => {}+ }+ }+ true+ }+ AppMode::Connections => {+ if left_pressed {+ if let Some(HitTarget::Connection(index)) = state.layout.hit(x, y).cloned() {+ state.ui.connection_index = index;+ if let Some(item) = state+ .ui+ .connections+ .get(index)+ .filter(|item| item.connectable)+ {+ state.queue(Action::ConnectDomain(item.name.clone()));+ }+ }+ }+ true+ }+ AppMode::Settings => {+ if left_pressed {+ match state.layout.hit(x, y).cloned() {+ Some(HitTarget::Setting(index)) => {+ state.ui.settings_index = index;+ state.queue(Action::AdjustSetting { index, delta: 1 });+ }+ _ => state.queue(Action::CloseOverlay),+ }+ }+ true+ }+ AppMode::Help => {+ if left_pressed {+ state.queue(Action::ToggleHelp);+ }+ true+ }+ AppMode::Prompt | AppMode::Search => true,+ _ => false,+ }+}++fn tree_reorder_action(+ state: &TuiState,+ source: TreeNodeKey,+ target: TreeNodeKey,+) -> Option<Action> {+ match (source, target) {+ (TreeNodeKey::Thread(source), TreeNodeKey::Thread(target)) => {+ let source_row = state.model.row(&source)?;+ let target_row = state.model.row(&target)?;+ (source.domain_name == target.domain_name+ && source_row.project.id == target_row.project.id+ && source != target)+ .then_some(Action::MoveThread {+ key: source,+ before: Some(target.thread_id),+ })+ }+ (+ TreeNodeKey::Project {+ domain_name: source_domain,+ project_id: source_project,+ },+ TreeNodeKey::Project {+ domain_name: target_domain,+ project_id: target_project,+ },+ ) => {+ let snapshot = state.model.domain(&source_domain)?;+ let source = snapshot+ .projects+ .iter()+ .find(|item| item.id == source_project)?;+ let target = snapshot+ .projects+ .iter()+ .find(|item| item.id == target_project)?;+ (source_domain == target_domain+ && source.space_id == target.space_id+ && source_project != target_project)+ .then(|| Action::MoveProject {+ domain_name: source_domain,+ space_id: source.space_id.clone(),+ project_id: source_project,+ before: Some(target_project),+ })+ }+ _ => None,+ }+}++/// Unix terminals report SGR mouse cells using the protocol's one-based+/// coordinates. Ratatui rectangles and mux pane positions are zero-based.+/// The Windows console backend already supplies zero-based coordinates.+fn mouse_cell_coordinates(event: &TermwizMouseEvent) -> (u16, u16) {+ #[cfg(unix)]+ {+ (event.x.saturating_sub(1), event.y.saturating_sub(1))+ }+ #[cfg(not(unix))]+ {+ (event.x, event.y)+ }+}++fn forward_mouse_to_pane(+ event: TermwizMouseEvent,+ screen_x: u16,+ screen_y: u16,+ pane_hint: Option<PaneId>,+ state: &mut TuiState,+) {+ let Some((_, _, tab, _)) = state.active_tab() else {+ return;+ };+ let pane_view = pane_hint+ .and_then(|pane_id| {+ state+ .layout+ .panes+ .iter()+ .find(|pane| pane.pane_id == pane_id)+ })+ .or_else(|| state.layout.pane_at(screen_x, screen_y))+ .cloned();+ let Some(pane_view) = pane_view else {+ return;+ };+ let Some(pane) = state.pane(pane_view.pane_id) else {+ return;+ };++ let prior = &state.last_mouse_buttons;+ let current = &event.mouse_buttons;+ let (kind, button) = mouse_transition(prior, current);++ if kind == MouseEventKind::Press {+ tab.set_active_pane(&pane);+ }+ let mouse = MouseEvent {+ kind,+ x: screen_x+ .saturating_sub(pane_view.rect.x)+ .min(pane_view.rect.width.saturating_sub(1)) as usize,+ y: screen_y+ .saturating_sub(pane_view.rect.y)+ .min(pane_view.rect.height.saturating_sub(1)) as i64,+ x_pixel_offset: 0,+ y_pixel_offset: 0,+ button,+ modifiers: event.modifiers.remove_positional_mods(),+ };+ if let Err(err) = pane.mouse_event(mouse) {+ state.ui.status = format!("Mouse: {err}");+ }+}++fn pane_point(+ state: &TuiState,+ pane_id: usize,+ screen_x: u16,+ screen_y: u16,+) -> Option<SelectionPoint> {+ let view = state+ .layout+ .panes+ .iter()+ .find(|pane| pane.pane_id == pane_id)?;+ let pane = state.pane(pane_id)?;+ let dims = pane.get_dimensions();+ let offset = state.ui.scroll_offset(pane_id).min(dims.scrollback_rows);+ let top = dims+ .physical_top+ .saturating_sub(offset as wezterm_term::StableRowIndex)+ .max(dims.scrollback_top);+ Some(SelectionPoint {+ row: top + screen_y.saturating_sub(view.rect.y) as wezterm_term::StableRowIndex,+ col: screen_x.saturating_sub(view.rect.x) as usize,+ })+}++fn first_button(buttons: &MouseButtons) -> Option<MouseButton> {+ if buttons.contains(MouseButtons::LEFT) {+ Some(MouseButton::Left)+ } else if buttons.contains(MouseButtons::MIDDLE) {+ Some(MouseButton::Middle)+ } else if buttons.contains(MouseButtons::RIGHT) {+ Some(MouseButton::Right)+ } else {+ None+ }+}++fn mouse_transition(prior: &MouseButtons, current: &MouseButtons) -> (MouseEventKind, MouseButton) {+ if current.contains(MouseButtons::VERT_WHEEL) {+ if current.contains(MouseButtons::WHEEL_POSITIVE) {+ (MouseEventKind::Press, MouseButton::WheelUp(1))+ } else {+ (MouseEventKind::Press, MouseButton::WheelDown(1))+ }+ } else if current.contains(MouseButtons::HORZ_WHEEL) {+ if current.contains(MouseButtons::WHEEL_POSITIVE) {+ (MouseEventKind::Press, MouseButton::WheelRight(1))+ } else {+ (MouseEventKind::Press, MouseButton::WheelLeft(1))+ }+ } else if let Some(button) = first_button(current) {+ let kind = if first_button(prior) == Some(button) {+ MouseEventKind::Move+ } else {+ MouseEventKind::Press+ };+ (kind, button)+ } else if let Some(button) = first_button(prior) {+ (MouseEventKind::Release, button)+ } else {+ (MouseEventKind::Move, MouseButton::None)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn model_for_reorder() -> AppModel {+ let mut model = AppModel::default();+ model.apply_snapshot(+ "server",+ ThinkTermSessionState {+ server_id: "runtime".into(),+ generation: 1,+ spaces: vec![codec::ThinkTermSessionSpace {+ id: "space".into(),+ name: "Space".into(),+ ..Default::default()+ }],+ projects: vec![codec::ThinkTermSessionProject {+ id: "project".into(),+ space_id: "space".into(),+ name: "Project".into(),+ threads: ["one", "two"]+ .into_iter()+ .map(|id| codec::ThinkTermSessionThread {+ id: id.into(),+ project_id: "project".into(),+ name: id.into(),+ ..Default::default()+ })+ .collect(),+ ..Default::default()+ }],+ ..Default::default()+ },+ );+ model+ }++ #[test]+ fn nesting_guard_uses_the_transport_target_as_authority() {+ assert!(check_nesting(Some("server-a"), true, "server-a").is_err());+ assert!(check_nesting(Some("server-a"), true, "server-b").is_ok());+ assert!(check_nesting(None, false, "server-b").is_ok());+ assert!(check_nesting(None, true, "server-b").is_err());+ }++ #[test]+ fn terminal_pixels_scale_with_the_cell_grid() {+ let size = terminal_size(+ 80,+ 24,+ ScreenSize {+ cols: 100,+ rows: 40,+ #[cfg(unix)]+ xpixel: 800,+ #[cfg(unix)]+ ypixel: 640,+ #[cfg(not(unix))]+ xpixel: 8,+ #[cfg(not(unix))]+ ypixel: 16,+ },+ );+ assert_eq!((size.pixel_width, size.pixel_height), (640, 384));+ }++ #[test]+ fn terminal_pixels_remain_unknown_when_the_terminal_does_not_report_them() {+ let size = terminal_size(+ 80,+ 24,+ ScreenSize {+ cols: 100,+ rows: 40,+ xpixel: 0,+ ypixel: 0,+ },+ );+ assert_eq!((size.pixel_width, size.pixel_height), (0, 0));+ }++ #[test]+ fn terminal_mouse_coordinates_match_ratatui_cells() {+ let event = TermwizMouseEvent {+ x: 23,+ y: 9,+ mouse_buttons: MouseButtons::LEFT,+ modifiers: Modifiers::NONE,+ };+ #[cfg(unix)]+ assert_eq!(mouse_cell_coordinates(&event), (22, 8));+ #[cfg(not(unix))]+ assert_eq!(mouse_cell_coordinates(&event), (23, 9));+ }++ #[test]+ fn tree_drag_uses_stable_thread_ids_not_visual_indices() {+ let model = model_for_reorder();+ let state = TuiState::new(+ BTreeMap::new(),+ vec![],+ BTreeMap::new(),+ model,+ String::new(),+ TuiConfig::default(),+ PathBuf::from("/tmp/test-tui.toml"),+ PathBuf::from("/tmp/test-tui.json"),+ );+ let one = TreeNodeKey::Thread(state.model.rows()[0].key.clone());+ let two = TreeNodeKey::Thread(state.model.rows()[1].key.clone());+ let action = tree_reorder_action(&state, two, one).unwrap();+ let Action::MoveThread { key, before } = action else {+ panic!("thread drag did not produce a server move action")+ };+ assert_eq!(key.thread_id, "two");+ assert_eq!(before.as_deref(), Some("one"));+ }++ #[test]+ fn the_viewport_owner_lays_out_at_the_size_it_reported() {+ let reported = TerminalSize {+ rows: 30,+ cols: 100,+ ..TerminalSize::default()+ };+ // What the server derives back from pane sizes that already lost a row+ // to each pane's nav bar. Adopting it is what used to cost another row+ // per layout.+ let echo = TerminalSize {+ rows: 29,+ cols: 100,+ ..TerminalSize::default()+ };+ assert_eq!(+ choose_local_tab_size(Some(true), reported, echo),+ reported,+ "an owner must not adopt the shrunken echo"+ );+ assert_eq!(+ choose_local_tab_size(None, reported, echo),+ reported,+ "an unknown lease is treated as ours, as it is before the first answer"+ );+ assert_eq!(+ choose_local_tab_size(Some(false), reported, echo),+ echo,+ "a viewer has no geometry of its own and draws what the panes have"+ );+ }++ /// The loop that used to eat a row per layout, run five times.+ ///+ /// Lay out at the tab size, spend a row on each pane's own bar, tell the+ /// server the smaller grid, let the server derive its tab size back from+ /// those panes, and lay out again. Every step is real; the only question is+ /// which size the next layout starts from.+ #[test]+ fn a_pane_bar_costs_its_row_once_rather_than_once_per_layout() {+ fn rows(rows: usize) -> TerminalSize {+ TerminalSize {+ rows,+ cols: 100,+ ..TerminalSize::default()+ }+ }++ let reported = rows(30);+ let mut laid_out = reported;+ let mut grid = 0;+ for _ in 0..5 {+ grid = laid_out.rows - 1;+ laid_out = choose_local_tab_size(Some(true), reported, rows(grid));+ }+ assert_eq!(laid_out.rows, 30, "the tab is still the size we asked for");+ assert_eq!(grid, 29, "and the bar has cost exactly one row, once");++ // A viewer has no size of its own, so it does follow the panes down —+ // and settles, because it never spends the row it was not asked to.+ let mut viewing = reported;+ for _ in 0..5 {+ viewing = choose_local_tab_size(Some(false), reported, rows(29));+ }+ assert_eq!(viewing.rows, 29);+ }++ /// A phone and a desktop on the same machine share one `tui.toml`, so a+ /// remembered "sidebar visible" is a single boolean the two of them fight+ /// over — and on the phone "visible" means covering the terminal entirely.+ #[test]+ fn a_narrow_screen_neither_opens_covered_nor_rewrites_the_shared_preference() {+ assert!(+ !opens_with_tree(ViewClass::Narrow, true),+ "opens on its terminal"+ );+ assert!(!opens_with_tree(ViewClass::Narrow, false));+ assert!(+ opens_with_tree(ViewClass::Compact, true),+ "a panel is remembered"+ );+ assert!(opens_with_tree(ViewClass::Desktop, true));+ assert!(!opens_with_tree(ViewClass::Desktop, false));++ assert!(!tree_visibility_is_a_preference(ViewClass::Narrow));+ assert!(tree_visibility_is_a_preference(ViewClass::Compact));+ assert!(tree_visibility_is_a_preference(ViewClass::Desktop));+ }++ #[test]+ fn generated_tree_ids_are_process_independent_uuids() {+ let ids = (0..1_000).map(|_| new_id("thread")).collect::<HashSet<_>>();+ assert_eq!(ids.len(), 1_000);+ assert!(ids.iter().all(|id| id.starts_with("thread-")));+ }++ #[test]+ fn tab_title_changes_request_a_fresh_server_snapshot() {+ assert!(notification_refreshes_session(+ &MuxNotification::TabTitleChanged {+ tab_id: 7,+ title: "editor".into(),+ }+ ));+ assert!(!notification_refreshes_session(+ &MuxNotification::FrontendLeaseChanged(mux::FrontendViewportState {+ tab_id: 7,+ owner: None,+ canonical_size: TerminalSize::default(),+ view: None,+ generation: 1,+ })+ ));+ }++ #[test]+ fn snapshots_from_superseded_or_detached_connections_are_rejected() {+ assert!(session_generation_is_current(true, Some(9), Some(9), 9));+ assert!(!session_generation_is_current(true, Some(10), Some(10), 9));+ assert!(!session_generation_is_current(true, Some(10), Some(9), 10));+ assert!(!session_generation_is_current(false, Some(9), Some(9), 9));+ }++ #[test]+ fn copy_cursor_scrolls_at_both_viewport_edges_and_stays_in_bounds() {+ let (above, above_offset) = adjusted_copy_view(+ SelectionPoint { row: 8, col: 200 },+ 80,+ 0,+ 119,+ 100,+ 20,+ 80,+ 100,+ );+ assert_eq!(above, SelectionPoint { row: 8, col: 79 });+ assert_eq!(above_offset, 92);++ let (below, below_offset) = adjusted_copy_view(+ SelectionPoint { row: 115, col: 1 },+ 80,+ 0,+ 119,+ 100,+ 10,+ 20,+ 100,+ );+ assert_eq!(below.row, 109);+ assert_eq!(below_offset, 0);+ }++ #[test]+ fn modal_mouse_clicks_never_fall_through_to_the_tree() {+ let model = model_for_reorder();+ let mut state = TuiState::new(+ BTreeMap::new(),+ vec![],+ BTreeMap::new(),+ model,+ String::new(),+ TuiConfig::default(),+ PathBuf::from("/tmp/test-tui.toml"),+ PathBuf::from("/tmp/test-tui.json"),+ );+ state.ui.mode = AppMode::Help;+ state.layout.hits.push(view::HitRegion {+ rect: ratatui::layout::Rect::new(0, 0, 10, 10),+ target: HitTarget::Tree(TreeNodeKey::Thread(state.model.rows()[0].key.clone())),+ });++ assert!(modal_mouse_input(&mut state, 1, 1, true));+ assert_eq!(state.actions.pop_front(), Some(Action::ToggleHelp));+ assert!(state.actions.is_empty());+ }++ /// Taking control of a tab reads a present key as proof that the server+ /// already holds this renderer's viewport. Forgetting a size is how the+ /// next frame is told to re-send it, and a burst of resize actions all runs+ /// before that frame — so the key has to outlive the forgetting, or every+ /// step of a drag after the first one is refused for lack of a viewport.+ #[test]+ fn forgetting_a_viewport_size_keeps_the_evidence_that_one_was_sent() {+ let model = model_for_reorder();+ let mut state = TuiState::new(+ BTreeMap::new(),+ vec![],+ BTreeMap::new(),+ model,+ String::new(),+ TuiConfig::default(),+ PathBuf::from("/tmp/test-tui.toml"),+ PathBuf::from("/tmp/test-tui.json"),+ );+ let domain_name = state+ .model+ .selected_row()+ .expect("a selected row")+ .key+ .domain_name+ .clone();+ let key = (domain_name, 7);+ state.last_viewports.insert(+ key.clone(),+ Some((+ TerminalSize {+ rows: 24,+ cols: 80,+ ..Default::default()+ },+ true,+ )),+ );++ state.clear_selected_viewport_cache();++ assert_eq!(state.last_viewports.get(&key), Some(&None));+ }++ /// A fingertip covers several cells and the touchscreen picks one, so a tap+ /// meant to focus a pane arrives as a short drag. With copy-on-select on,+ /// that used to hand the clipboard one stray character on every tap.+ #[test]+ fn a_tap_that_slips_a_cell_or_two_is_not_a_selection() {+ fn finish(+ anchor: (wezterm_term::StableRowIndex, usize),+ head: (wezterm_term::StableRowIndex, usize),+ ) -> bool {+ let mut selection = Some(TextSelection {+ pane_id: 1,+ anchor: SelectionPoint {+ row: anchor.0,+ col: anchor.1,+ },+ head: SelectionPoint {+ row: head.0,+ col: head.1,+ },+ finalized: false,+ });+ finish_pointer_selection(&mut selection)+ }++ assert!(!finish((5, 10), (5, 10)), "a still tap");+ assert!(!finish((5, 10), (5, 11)), "one cell of slip");+ assert!(!finish((5, 10), (5, 8)), "slip backwards counts the same");+ assert!(finish((5, 10), (5, 13)), "a deliberate drag along the row");+ // Reaching another line is unambiguous however short the move.+ assert!(finish((5, 10), (6, 10)), "one row down");+ assert!(finish((5, 10), (4, 11)), "one row up");+ }++ /// A touchscreen has no keyboard, so the wheel is the only way through a+ /// full-screen program — and it must not be spent on a scrollback that the+ /// alternate screen does not keep.+ #[test]+ fn a_wheel_notch_on_the_alternate_screen_reaches_a_program_that_never_asked_for_the_mouse() {+ assert_eq!(+ wheel_routing(false, true, false, 0),+ WheelRouting::ArrowKeys+ );+ // One that did ask for the mouse still receives the notch itself.+ assert_eq!(wheel_routing(true, true, false, 0), WheelRouting::Pane);+ // Shift is the deliberate way back to the scrollback, as is having+ // already scrolled away from the live screen.+ assert_eq!(+ wheel_routing(false, true, true, 0),+ WheelRouting::Scrollback+ );+ assert_eq!(+ wheel_routing(true, true, false, 3),+ WheelRouting::Scrollback+ );+ // The primary screen keeps the scrollback it actually has.+ assert_eq!(+ wheel_routing(false, false, false, 0),+ WheelRouting::Scrollback+ );+ }++ #[test]+ fn paste_is_blocked_by_non_prompt_overlays() {+ let mut state = TuiState::new(+ BTreeMap::new(),+ vec![],+ BTreeMap::new(),+ AppModel::default(),+ String::new(),+ TuiConfig::default(),+ PathBuf::from("/tmp/test-tui.toml"),+ PathBuf::from("/tmp/test-tui.json"),+ );+ state.ui.mode = AppMode::Confirm;+ handle_input(InputEvent::Paste("dangerous command\n".into()), &mut state);+ assert!(state.ui.status.contains("unavailable"));+ }++ #[test]+ fn passed_through_mouse_sequences_include_release_and_horizontal_wheel() {+ assert_eq!(+ mouse_transition(&MouseButtons::NONE, &MouseButtons::RIGHT),+ (MouseEventKind::Press, MouseButton::Right)+ );+ assert_eq!(+ mouse_transition(&MouseButtons::RIGHT, &MouseButtons::RIGHT),+ (MouseEventKind::Move, MouseButton::Right)+ );+ assert_eq!(+ mouse_transition(&MouseButtons::RIGHT, &MouseButtons::NONE),+ (MouseEventKind::Release, MouseButton::Right)+ );+ assert_eq!(+ mouse_transition(+ &MouseButtons::NONE,+ &(MouseButtons::HORZ_WHEEL | MouseButtons::WHEEL_POSITIVE),+ ),+ (MouseEventKind::Press, MouseButton::WheelRight(1))+ );+ }++ #[test]+ fn plain_click_does_not_become_a_copy_selection() {+ let point = SelectionPoint { row: 4, col: 7 };+ let mut selection = Some(TextSelection {+ pane_id: 1,+ anchor: point,+ head: point,+ finalized: false,+ });+ assert!(!finish_pointer_selection(&mut selection));+ assert!(selection.is_none());+ }++ #[test]+ fn pointer_drag_becomes_a_finalized_selection() {+ let selection = TextSelection {+ pane_id: 1,+ anchor: SelectionPoint { row: 4, col: 7 },+ head: SelectionPoint { row: 4, col: 10 },+ finalized: false,+ };+ let mut selection = Some(selection);+ assert!(finish_pointer_selection(&mut selection));+ assert!(selection.is_some_and(|selection| selection.finalized));+ }++ #[test]+ fn ctrl_c_only_copies_a_retained_manual_selection() {+ let selection = TextSelection {+ pane_id: 1,+ anchor: SelectionPoint { row: 4, col: 7 },+ head: SelectionPoint { row: 4, col: 10 },+ finalized: true,+ };+ assert!(should_copy_retained_selection(+ KeyCode::Char('c'),+ Modifiers::CTRL,+ false,+ Some(&selection),+ ));+ assert!(!should_copy_retained_selection(+ KeyCode::Char('c'),+ Modifiers::CTRL,+ true,+ Some(&selection),+ ));+ assert!(!should_copy_retained_selection(+ KeyCode::Char('c'),+ Modifiers::CTRL,+ false,+ None,+ ));+ }++ #[test]+ fn explicit_tui_themes_are_not_forced_monochrome_by_no_color() {+ let caps = tui_terminal_capabilities(+ ProbeHints::default()+ .term(Some("xterm-256color".to_string()))+ .color_level(Some(termwiz::caps::ColorLevel::MonoChrome)),+ )+ .unwrap();++ assert_ne!(caps.color_level(), termwiz::caps::ColorLevel::MonoChrome);+ }++ #[test]+ fn recent_input_keeps_executor_progress_bounded_without_spinning_when_idle() {+ let now = Instant::now();+ assert_eq!(+ input_progress_wait(None, Some(now + INPUT_PROGRESS_WINDOW), now),+ Some(INPUT_PROGRESS_POLL_INTERVAL)+ );+ assert_eq!(+ input_progress_wait(+ Some(Duration::from_millis(1)),+ Some(now + INPUT_PROGRESS_WINDOW),+ now,+ ),+ Some(Duration::from_millis(1))+ );+ assert_eq!(+ input_progress_wait(Some(Duration::from_secs(2)), None, now),+ Some(Duration::from_secs(2))+ );+ assert_eq!(input_progress_wait(None, Some(now), now), None);+ }+}diff --git a/thinkterm-tui/src/model.rs b/thinkterm-tui/src/model.rsnew file mode 100644index 00000000..fb878658--- /dev/null+++ b/thinkterm-tui/src/model.rs@@ -0,0 +1,465 @@+use codec::{+ ThinkTermSessionProject, ThinkTermSessionSpace, ThinkTermSessionState, ThinkTermSessionTab,+ ThinkTermSessionThread, ThinkTermSessionWorkStatus,+};+use mux::tab::TabId;+use std::collections::{BTreeMap, HashMap};++/// A thread is only unique inside one running server. Keep both the configured+/// transport name and the server runtime id in every UI key so that a restart+/// or two servers with identical tree ids can never cross-select each other.+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct ThreadKey {+ pub domain_name: String,+ pub server_id: String,+ pub thread_id: String,+}++#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub enum TreeNodeKey {+ Domain(String),+ Space {+ domain_name: String,+ space_id: String,+ },+ Project {+ domain_name: String,+ project_id: String,+ },+ Thread(ThreadKey),+}++#[derive(Clone, Debug)]+pub struct ThreadRow {+ pub key: ThreadKey,+ pub space: ThinkTermSessionSpace,+ pub project: ThinkTermSessionProject,+ pub thread: ThinkTermSessionThread,+}++impl ThreadRow {+ pub fn status_marker(&self) -> &'static str {+ if self.thread.is_unread {+ return "!";+ }+ match self.thread.work_status {+ ThinkTermSessionWorkStatus::Idle => " ",+ ThinkTermSessionWorkStatus::Running => "*",+ ThinkTermSessionWorkStatus::NeedsAttention => "!",+ ThinkTermSessionWorkStatus::FinishedUnseen => "+",+ }+ }++ /// How much this thread wants to be looked at, lowest first.+ ///+ /// Waiting on a person outranks having finished, which outranks still+ /// working — the order in which ignoring one costs something. There is no+ /// timestamp on a thread, so anything idle is left to tree order rather+ /// than guessing at recency.+ pub fn attention_rank(&self) -> u8 {+ if self.thread.is_unread {+ return 0;+ }+ match self.thread.work_status {+ ThinkTermSessionWorkStatus::NeedsAttention => 1,+ ThinkTermSessionWorkStatus::FinishedUnseen => 2,+ ThinkTermSessionWorkStatus::Running => 3,+ ThinkTermSessionWorkStatus::Idle => 4,+ }+ }++ pub fn has_attention(&self) -> bool {+ self.thread.is_unread+ || matches!(+ self.thread.work_status,+ ThinkTermSessionWorkStatus::NeedsAttention+ | ThinkTermSessionWorkStatus::FinishedUnseen+ )+ }+}++/// Server snapshots are the shared truth. `rows` is a derived, normalized+/// index rebuilt only when a snapshot changes; rendering and hit testing never+/// clone and re-walk the complete tree.+#[derive(Default)]+pub struct AppModel {+ domains: BTreeMap<String, ThinkTermSessionState>,+ rows: Vec<ThreadRow>,+ selected_thread: Option<ThreadKey>,+ selected_tabs: HashMap<ThreadKey, TabId>,+}++impl AppModel {+ /// Generations are only comparable during one server connection.+ pub fn begin_connection_generation(&mut self, domain_name: &str) {+ if let Some(state) = self.domains.get_mut(domain_name) {+ state.generation = 0;+ }+ }++ pub fn apply_snapshot(+ &mut self,+ domain_name: impl Into<String>,+ state: ThinkTermSessionState,+ ) -> bool {+ let domain_name = domain_name.into();+ if self.domains.get(&domain_name).is_some_and(|prior| {+ prior.server_id == state.server_id && state.generation <= prior.generation+ }) {+ return false;+ }++ let server_changed = self+ .domains+ .get(&domain_name)+ .is_some_and(|prior| prior.server_id != state.server_id);+ if server_changed {+ self.selected_tabs+ .retain(|key, _| key.domain_name != domain_name);+ if self+ .selected_thread+ .as_ref()+ .is_some_and(|key| key.domain_name == domain_name)+ {+ self.selected_thread = None;+ }+ }++ self.domains.insert(domain_name, state);+ self.rebuild_index();+ self.normalize_selection();+ true+ }++ pub fn remove_domain(&mut self, domain_name: &str) -> bool {+ if self.domains.remove(domain_name).is_none() {+ return false;+ }+ self.selected_tabs+ .retain(|key, _| key.domain_name != domain_name);+ if self+ .selected_thread+ .as_ref()+ .is_some_and(|key| key.domain_name == domain_name)+ {+ self.selected_thread = None;+ }+ self.rebuild_index();+ self.normalize_selection();+ true+ }++ fn rebuild_index(&mut self) {+ self.rows.clear();+ for (domain_name, state) in &self.domains {+ let spaces: HashMap<&str, &ThinkTermSessionSpace> = state+ .spaces+ .iter()+ .map(|space| (space.id.as_str(), space))+ .collect();+ for project in &state.projects {+ let Some(space) = spaces.get(project.space_id.as_str()) else {+ continue;+ };+ for thread in &project.threads {+ self.rows.push(ThreadRow {+ key: ThreadKey {+ domain_name: domain_name.clone(),+ server_id: state.server_id.clone(),+ thread_id: thread.id.clone(),+ },+ space: (*space).clone(),+ project: project.clone(),+ thread: thread.clone(),+ });+ }+ }+ }+ }++ fn normalize_selection(&mut self) {+ let selected_still_exists = self+ .selected_thread+ .as_ref()+ .is_some_and(|selected| self.rows.iter().any(|row| &row.key == selected));+ if !selected_still_exists {+ // Tree order says where a thread lives, not whether it wants+ // attention, and opening on whichever happened to sort first meant+ // arriving at the least interesting one. Rank by what the thread is+ // doing instead; tree order only breaks ties.+ self.selected_thread = self+ .rows+ .iter()+ .filter(|row| !row.thread.tabs.is_empty())+ .min_by_key(|row| row.attention_rank())+ .or_else(|| self.rows.first())+ .map(|row| row.key.clone());+ }+ self.normalize_selected_tab();+ }++ fn normalize_selected_tab(&mut self) {+ let Some(key) = self.selected_thread.clone() else {+ return;+ };+ let Some(row) = self.rows.iter().find(|row| row.key == key) else {+ self.selected_tabs.remove(&key);+ return;+ };+ if row.thread.tabs.is_empty() {+ self.selected_tabs.remove(&key);+ return;+ }+ if self+ .selected_tabs+ .get(&key)+ .is_some_and(|id| row.thread.tabs.iter().any(|tab| tab.tab_id == *id))+ {+ return;+ }+ let tab = row+ .thread+ .tabs+ .iter()+ .find(|tab| tab.is_active)+ .unwrap_or(&row.thread.tabs[0]);+ self.selected_tabs.insert(key, tab.tab_id);+ }++ pub fn domain(&self, domain_name: &str) -> Option<&ThinkTermSessionState> {+ self.domains.get(domain_name)+ }++ pub fn domains(&self) -> impl Iterator<Item = (&str, &ThinkTermSessionState)> {+ self.domains+ .iter()+ .map(|(name, state)| (name.as_str(), state))+ }++ pub fn rows(&self) -> &[ThreadRow] {+ &self.rows+ }++ pub fn selected_key(&self) -> Option<&ThreadKey> {+ self.selected_thread.as_ref()+ }++ pub fn selected_row(&self) -> Option<&ThreadRow> {+ let selected = self.selected_thread.as_ref()?;+ self.rows.iter().find(|row| &row.key == selected)+ }++ pub fn row(&self, key: &ThreadKey) -> Option<&ThreadRow> {+ self.rows.iter().find(|row| &row.key == key)+ }++ pub fn generation(&self) -> u64 {+ self.selected_row()+ .and_then(|row| self.domains.get(&row.key.domain_name))+ .map_or(0, |state| state.generation)+ }++ pub fn tree_revision(&self) -> u64 {+ self.selected_row()+ .and_then(|row| self.domains.get(&row.key.domain_name))+ .map_or(0, |state| state.tree_revision)+ }++ pub fn select_thread(&mut self, key: &ThreadKey) -> bool {+ if self.selected_thread.as_ref() == Some(key)+ || !self.rows.iter().any(|row| &row.key == key)+ {+ return false;+ }+ self.selected_thread = Some(key.clone());+ self.normalize_selected_tab();+ true+ }++ pub fn select_relative_thread(&mut self, delta: isize) -> bool {+ if self.rows.is_empty() {+ return false;+ }+ let current = self+ .selected_thread+ .as_ref()+ .and_then(|key| self.rows.iter().position(|row| &row.key == key))+ .unwrap_or(0);+ let next = (current as isize + delta).rem_euclid(self.rows.len() as isize) as usize;+ let key = self.rows[next].key.clone();+ self.select_thread(&key)+ }++ pub fn tabs_for_selected_thread(&self) -> &[ThinkTermSessionTab] {+ self.selected_row()+ .map(|row| row.thread.tabs.as_slice())+ .unwrap_or_default()+ }++ /// Read-only by design: render code must never repair selection.+ pub fn selected_tab(&self) -> Option<&ThinkTermSessionTab> {+ let key = self.selected_thread.as_ref()?;+ let selected = self.selected_tabs.get(key)?;+ self.tabs_for_selected_thread()+ .iter()+ .find(|tab| tab.tab_id == *selected)+ }++ pub fn select_tab(&mut self, tab_id: TabId) -> bool {+ let Some(key) = self.selected_thread.clone() else {+ return false;+ };+ if !self+ .tabs_for_selected_thread()+ .iter()+ .any(|tab| tab.tab_id == tab_id)+ {+ return false;+ }+ self.selected_tabs.insert(key, tab_id) != Some(tab_id)+ }++ pub fn select_relative_tab(&mut self, delta: isize) -> bool {+ let tabs = self.tabs_for_selected_thread();+ if tabs.is_empty() {+ return false;+ }+ let current_id = self.selected_tab().map(|tab| tab.tab_id);+ let current = current_id+ .and_then(|id| tabs.iter().position(|tab| tab.tab_id == id))+ .unwrap_or(0);+ let next = (current as isize + delta).rem_euclid(tabs.len() as isize) as usize;+ let tab_id = tabs[next].tab_id;+ self.select_tab(tab_id)+ }++ pub fn attention_count(&self) -> usize {+ self.rows.iter().filter(|row| row.has_attention()).count()+ }++ pub fn next_attention(&self, after: Option<&ThreadKey>) -> Option<ThreadKey> {+ if self.rows.is_empty() {+ return None;+ }+ let start = after+ .and_then(|key| self.rows.iter().position(|row| &row.key == key))+ .map_or(0, |index| index + 1);+ (0..self.rows.len())+ .map(|offset| (start + offset) % self.rows.len())+ .find_map(|index| {+ self.rows[index]+ .has_attention()+ .then(|| self.rows[index].key.clone())+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn state(server: &str, generation: u64, thread_ids: &[&str]) -> ThinkTermSessionState {+ ThinkTermSessionState {+ server_id: server.into(),+ tree_revision: generation,+ generation,+ spaces: vec![ThinkTermSessionSpace {+ id: "space".into(),+ name: "Space".into(),+ ..Default::default()+ }],+ projects: vec![ThinkTermSessionProject {+ id: "project".into(),+ space_id: "space".into(),+ name: "Project".into(),+ threads: thread_ids+ .iter()+ .map(|id| ThinkTermSessionThread {+ id: (*id).into(),+ project_id: "project".into(),+ name: (*id).into(),+ ..Default::default()+ })+ .collect(),+ ..Default::default()+ }],+ }+ }++ /// Opening on whichever thread happened to sort first meant arriving at+ /// the least interesting one while another was waiting to be answered.+ #[test]+ fn the_thread_that_wants_attention_is_the_one_opened() {+ let mut snapshot = state("server", 1, &["quiet", "running", "done", "asking"]);+ let threads = &mut snapshot.projects[0].threads;+ // Everything has a live tab, so tree order alone would pick "quiet".+ for thread in threads.iter_mut() {+ thread.tabs = vec![ThinkTermSessionTab::default()];+ }+ threads[1].work_status = ThinkTermSessionWorkStatus::Running;+ threads[2].work_status = ThinkTermSessionWorkStatus::FinishedUnseen;+ threads[3].work_status = ThinkTermSessionWorkStatus::NeedsAttention;++ let mut model = AppModel::default();+ model.apply_snapshot("a", snapshot.clone());+ assert_eq!(model.selected_row().unwrap().thread.id, "asking");++ // With nobody waiting, finishing unseen outranks still working.+ snapshot.projects[0].threads[3].work_status = ThinkTermSessionWorkStatus::Idle;+ let mut model = AppModel::default();+ model.apply_snapshot("a", snapshot.clone());+ assert_eq!(model.selected_row().unwrap().thread.id, "done");++ // ...and with nothing to report at all, tree order decides.+ for thread in snapshot.projects[0].threads.iter_mut() {+ thread.work_status = ThinkTermSessionWorkStatus::Idle;+ }+ let mut model = AppModel::default();+ model.apply_snapshot("a", snapshot);+ assert_eq!(model.selected_row().unwrap().thread.id, "quiet");+ }++ #[test]+ fn ignores_stale_snapshots_from_the_same_server() {+ let mut model = AppModel::default();+ assert!(model.apply_snapshot("a", state("server", 2, &["a", "b"])));+ let key = model.rows()[1].key.clone();+ assert!(model.select_thread(&key));+ assert!(!model.apply_snapshot("a", state("server", 1, &["a"])));+ assert_eq!(model.selected_row().unwrap().thread.id, "b");+ }++ #[test]+ fn accepts_lower_generation_from_a_restarted_server() {+ let mut model = AppModel::default();+ model.apply_snapshot("a", state("old", 20, &["old"]));+ assert!(model.apply_snapshot("a", state("new", 1, &["new"])));+ assert_eq!(model.selected_row().unwrap().thread.id, "new");+ }++ #[test]+ fn identical_thread_ids_on_two_servers_do_not_collide() {+ let mut model = AppModel::default();+ model.apply_snapshot("a", state("one", 1, &["main"]));+ model.apply_snapshot("b", state("two", 1, &["main"]));+ assert_eq!(model.rows().len(), 2);+ assert_ne!(model.rows()[0].key, model.rows()[1].key);+ let key = model.rows()[1].key.clone();+ assert!(model.select_thread(&key));+ assert_eq!(model.selected_row().unwrap().key.domain_name, "b");+ }++ #[test]+ fn selected_tab_is_pure_after_snapshot_normalization() {+ let mut snapshot = state("server", 1, &["main"]);+ snapshot.projects[0].threads[0].tabs = vec![ThinkTermSessionTab {+ tab_id: 7,+ is_active: true,+ ..Default::default()+ }];+ let mut model = AppModel::default();+ model.apply_snapshot("a", snapshot);+ assert_eq!(model.selected_tab().map(|tab| tab.tab_id), Some(7));+ assert_eq!(model.selected_tab().map(|tab| tab.tab_id), Some(7));+ }+}diff --git a/thinkterm-tui/src/render.rs b/thinkterm-tui/src/render.rsnew file mode 100644index 00000000..4d80822a--- /dev/null+++ b/thinkterm-tui/src/render.rs@@ -0,0 +1,1167 @@+use crate::model::AppModel;+use crate::settings::TuiConfig;+use crate::state::{AppMode, ConnectionStatus, SelectionPoint, TextSelection, UiState, ViewClass};+use crate::view::{PaneNav, ViewLayout};+use mux::pane::{Pane, PaneId, SearchResult};+use mux::tab::{SplitDirection, Tab, TabId};+use ratatui::layout::{Alignment, Rect};+use ratatui::style::{Color, Modifier, Style};+use ratatui::text::{Line as TextLine, Span};+use ratatui::widgets::{Block, Borders, Clear, Paragraph};+use ratatui::Frame;+use std::sync::Arc;+use termwiz::cell::{unicode_column_width, Blink, CellAttributes, Intensity, Underline};+use termwiz::color::ColorAttribute;+use wezterm_term::color::SrgbaTuple;+use wezterm_term::StableRowIndex;++#[derive(Clone, Debug, Default)]+pub struct RenderResult {+ /// This ID is in the remote server namespace.+ pub selected_tab: Option<TabId>,+ pub active_pane: Option<PaneId>,+}++/// Rendering is intentionally read-only. Selection normalization and geometry+/// are completed before this function is called, so a draw can never change+/// what the next mouse event means.+pub fn render(+ frame: &mut Frame<'_>,+ model: &AppModel,+ ui: &UiState,+ local_tab: Option<&Arc<Tab>>,+ view: &ViewLayout,+ viewport_status: Option<&str>,+ settings: &TuiConfig,+) -> RenderResult {+ let mut result = RenderResult {+ selected_tab: model.selected_tab().map(|tab| tab.tab_id),+ ..Default::default()+ };+ frame.render_widget(Clear, view.screen);+ if view.screen.width == 0 || view.screen.height == 0 {+ return result;+ }+ if view.screen.width < 20 || view.screen.height < 4 {+ render_center(frame, view.screen, "Terminal too small", chrome_selected());+ return result;+ }++ render_sidebar(frame, view);+ render_tabs(frame, view);+ render_status(frame, model, ui, view, viewport_status);++ if let Some(tab) = local_tab {+ result.active_pane = tab.get_active_pane().map(|pane| pane.pane_id());+ render_panes(frame, tab, ui, view);+ } else {+ let message = match model.selected_row() {+ None => "Opening your local terminal…",+ Some(row) if row.thread.tabs.is_empty() => "Opening terminal…",+ Some(_) => "Waiting for the mux view",+ };+ render_center(frame, view.content, message, chrome_dim());+ }++ render_overlays(frame, ui, view, settings);+ result+}++fn render_sidebar(frame: &mut Frame<'_>, view: &ViewLayout) {+ let Some(sidebar) = view.sidebar else {+ return;+ };+ fill(frame, sidebar, " ", chrome());+ if let Some(header) = view.sidebar_header {+ let title = match view.class {+ ViewClass::Compact => " ≡ TT",+ _ => " ≡ THINKTERM",+ };+ draw_text(+ frame,+ header,+ title,+ chrome_accent_text().add_modifier(Modifier::BOLD),+ );+ }+ if let Some(rect) = view.sidebar_new_thread {+ // Text in the accent colour, not a second filled bar: the header above+ // is already solid, and two stacked blocks of colour read as one heavy+ // slab rather than as a title and a button.+ draw_text(frame, rect, " ⊕ New Thread", chrome_accent_text());+ }+ if let Some(rect) = view.sidebar_heading {+ draw_text(frame, rect, " WORKSPACES", chrome_dim());+ }+ if let Some(rect) = view.sidebar_new_project {+ draw_text(frame, rect, "+", chrome_bold());+ }+ for line in &view.tree_lines {+ let mut label = String::new();+ label.push_str(&" ".repeat(line.depth as usize));+ if line.expandable {+ label.push_str(if line.collapsed { "▸ " } else { "▾ " });+ } else {+ label.push_str(" ");+ }+ if let Some(status) = line.status {+ label.push_str(status);+ label.push(' ');+ }+ if line.pinned {+ label.push_str("★ ");+ }+ label.push_str(&line.label);+ // The selected row is lifted by a surface block and bold text, not by a+ // slab of accent: at three nesting levels a saturated bar is the+ // loudest thing on the screen, and it is only saying "here".+ let style = match (line.selected, line.status) {+ (true, _) => chrome_surface().add_modifier(Modifier::BOLD),+ (false, Some("!")) => chrome_danger().add_modifier(Modifier::BOLD),+ (false, Some("+")) => chrome_success().add_modifier(Modifier::BOLD),+ // Running had no colour of its own, so the one status that changes+ // by itself was the one the eye could not find.+ (false, Some("*")) => chrome_accent_text().add_modifier(Modifier::BOLD),+ (false, _) if line.depth < 3 => chrome_bold(),+ _ => chrome_dim(),+ };+ fill(frame, line.rect, " ", style);+ // The label is clipped to where the buttons begin, so a long name is+ // shortened rather than drawn underneath them.+ let label_width = line+ .actions+ .iter()+ .map(|(rect, _)| rect.x)+ .min()+ .unwrap_or(line.rect.right())+ .saturating_sub(line.rect.x);+ draw_text(+ frame,+ Rect::new(line.rect.x, line.rect.y, label_width, line.rect.height),+ &label,+ style,+ );+ // On the row being worked on the buttons share its weight; elsewhere+ // they stay out of the way of the names, which is what the list is for.+ let action_style = if line.selected {+ style+ } else {+ style.patch(chrome_dim())+ };+ for (rect, action) in &line.actions {+ draw_text(frame, *rect, action.glyph(), action_style);+ }+ }+ if let Some(rect) = view.sidebar_settings {+ fill(frame, rect, " ", chrome_dim());+ draw_text(frame, rect, " ⚙ Settings", chrome_dim());+ }+ if let Some(resize) = view.sidebar_resize {+ for y in resize.y..resize.bottom() {+ frame.buffer_mut()[(resize.x, y)]+ .set_symbol("│")+ .set_style(chrome_border());+ }+ }+}++fn render_tabs(frame: &mut Frame<'_>, view: &ViewLayout) {+ if view.tab_bar.is_empty() {+ return;+ }+ fill(frame, view.tab_bar, " ", chrome());+ if view.sidebar.is_none() {+ if let Some(toggle) = view.sidebar_toggle {+ draw_text(+ frame,+ toggle,+ " ≡ ",+ chrome_accent_text().add_modifier(Modifier::BOLD),+ );+ }+ }+ for (rect, control) in &view.tab_controls {+ draw_text(frame, *rect, control.glyph(), chrome_dim());+ }+ if view.tabs.is_empty() {+ draw_text(frame, view.tab_bar, " Opening terminal…", chrome_dim());+ return;+ }+ for tab in &view.tabs {+ // The active tab is the single filled block on the screen, which is+ // what makes it findable at a glance.+ let style = if tab.selected {+ chrome_selected()+ } else {+ chrome_dim()+ };+ fill(frame, tab.rect, " ", style);+ draw_text(frame, tab.rect, &tab.label, style);+ if let Some(close) = tab.close {+ draw_text(frame, close, "✕", style);+ }+ }+ let used = view+ .tabs+ .last()+ .map_or(view.tab_bar.x, |tab| tab.rect.right());+ if used < view.tab_bar.right() {+ let separator = Rect::new(used, view.tab_bar.y, 1, view.tab_bar.height);+ fill(frame, separator, "│", chrome_border());+ }+}++fn render_panes(frame: &mut Frame<'_>, tab: &Arc<Tab>, ui: &UiState, view: &ViewLayout) {+ let panes = tab.iter_panes();+ for pane_view in &view.panes {+ let Some(positioned) = panes+ .iter()+ .find(|positioned| positioned.pane.pane_id() == pane_view.pane_id)+ else {+ continue;+ };+ if let Some(border) = pane_view.border {+ let focused = tab+ .get_active_pane()+ .is_some_and(|active| active.pane_id() == pane_view.pane_id);+ let style = if focused {+ chrome_accent_text()+ } else {+ chrome_border()+ };+ frame.render_widget(+ Block::default().borders(Borders::ALL).border_style(style),+ border,+ );+ }+ if let Some(nav) = &pane_view.nav {+ let focused = tab+ .get_active_pane()+ .is_some_and(|active| active.pane_id() == pane_view.pane_id);+ paint_pane_nav(frame, nav, focused);+ }+ paint_pane(frame, &positioned.pane, pane_view.rect, ui);+ if let Some(bar) = pane_view.scrollbar {+ paint_scrollbar(frame, &positioned.pane, bar, ui);+ }+ }++ // Framed panes already show where each one ends, and a divider between two+ // frames is a third line of chrome in a row that has two. When the frames+ // were not drawn — too small, or turned off — the divider is the only thing+ // separating them.+ let framed = view.panes.iter().any(|pane| pane.border.is_some());+ for split in view.splits.iter().filter(|_| !framed) {+ let symbol = match split.direction {+ SplitDirection::Horizontal => "│",+ SplitDirection::Vertical => "─",+ };+ for y in split.rect.y..split.rect.bottom() {+ for x in split.rect.x..split.rect.right() {+ frame.buffer_mut()[(x, y)]+ .set_symbol(symbol)+ .set_style(chrome_border());+ }+ }+ }++ if let Some(active) = tab.get_active_pane() {+ if let Some(pane_view) = view+ .panes+ .iter()+ .find(|pane| pane.pane_id == active.pane_id())+ {+ let dims = active.get_dimensions();+ let offset = ui.scroll_offset(active.pane_id());+ if offset == 0 {+ let cursor = active.get_cursor_position();+ let visible_y = cursor.y - dims.physical_top;+ if visible_y >= 0+ && visible_y < pane_view.rect.height as isize+ && cursor.x < pane_view.rect.width as usize+ {+ frame.set_cursor_position((+ pane_view.rect.x + cursor.x as u16,+ pane_view.rect.y + visible_y as u16,+ ));+ }+ }+ }+ }+}++/// Draw one pane's own strip: what is stacked behind it, and what can be done+/// to it.+///+/// The focused pane's bar is the only one drawn in the accent, which is what+/// says where typing goes — a job the frame used to do alone, and only when the+/// pane was wide enough to afford one.+fn paint_pane_nav(frame: &mut Frame<'_>, nav: &PaneNav, focused: bool) {+ if nav.rect.is_empty() {+ return;+ }+ // No fill. A band of surface behind every pane turned the screen into+ // stacked grey slabs — and because every style below sets its own+ // background, the glyphs punched the plain background back through it in+ // streaks. The bar sits on the background like everything else; which pane+ // has the focus is said by the colour of its name, which is where the eye+ // already is.+ let base = chrome();+ // No fill. On a framed pane this row *is* the frame's top edge, and filling+ // it with spaces rubs the line out between the corners, leaving `┌` and `┐`+ // floating either side of a gap. Leaving it alone lets the line run behind+ // the names and buttons, which is what a titled box looks like.+ for entry in &nav.tabs {+ // Each item clears its own cells. Filling the whole row would rub out+ // the frame's top edge; filling none of it lets the line run through+ // the gaps inside a name and between the buttons.+ fill(frame, entry.rect, " ", base);+ let style = match (entry.active, focused) {+ (true, true) => chrome_accent_text().add_modifier(Modifier::BOLD),+ (true, false) => chrome_bold(),+ (false, _) => chrome_dim(),+ };+ // Clipped to where the close button starts, so a long title is+ // shortened rather than drawn underneath it.+ // One column short of the close button, so a title long enough to be+ // clipped does not end up flush against the ✕ and read as part of it.+ let label = Rect::new(+ entry.rect.x,+ entry.rect.y,+ entry.close.map_or(entry.rect.width, |close| {+ (close.x - entry.rect.x).saturating_sub(1)+ }),+ entry.rect.height,+ );+ draw_text(frame, label, &entry.label, style);+ if let Some(close) = entry.close {+ draw_text(frame, close, "✕", style);+ }+ }+ let tool_style = if focused { chrome_bold() } else { chrome_dim() };+ for (rect, tool) in &nav.tools {+ fill(frame, *rect, " ", base);+ draw_text(frame, *rect, tool.glyph(), tool_style);+ }+}++/// Draw a pane's position in its own scrollback.+///+/// The thumb is sized by how much of the scrollback is on screen and placed by+/// how far back the view has been pulled, so its length says how much there is+/// and its position says where you are. A pane with nothing to scroll gets a+/// plain track rather than a full-height thumb, which would otherwise read as+/// "there is more here" on a screen that has none.+fn paint_scrollbar(frame: &mut Frame<'_>, pane: &Arc<dyn Pane>, area: Rect, ui: &UiState) {+ if area.is_empty() {+ return;+ }+ fill(frame, area, "│", chrome_border());+ let dims = pane.get_dimensions();+ let scrollable = dims.scrollback_rows.saturating_sub(dims.viewport_rows);+ if scrollable == 0 {+ return;+ }+ let height = area.height as usize;+ let thumb = ((dims.viewport_rows * height) / dims.scrollback_rows.max(1)).clamp(1, height);+ let offset = ui.scroll_offset(pane.pane_id()).min(scrollable);+ // Offset counts backwards from the live screen, and the bar runs forwards.+ let travel = height - thumb;+ let from_top = travel - (offset * travel) / scrollable.max(1);+ fill(+ frame,+ Rect::new(+ area.x,+ area.y + from_top as u16,+ area.width,+ thumb.min(height) as u16,+ ),+ "█",+ chrome_accent_text(),+ );+}++fn paint_pane(frame: &mut Frame<'_>, pane: &Arc<dyn Pane>, area: Rect, ui: &UiState) {+ if area.is_empty() {+ return;+ }+ // Note that this does *not* ask the pane what changed. Asking is what makes+ // a remote pane ask the server, and the server's answer notifies the mux,+ // which marks the frame dirty, which draws, which would ask again: an idle+ // screen measured at half a core and 19 KB/s to the tty, spent on nothing.+ // The asking lives on a timer in the event loop (`poll_panes`) so that its+ // rate is set by the clock rather than by how fast this machine can paint.+ let dims = pane.get_dimensions();+ let height = (area.height as usize).min(dims.scrollback_rows.max(dims.viewport_rows));+ let offset = ui.scroll_offset(pane.pane_id());+ let earliest = dims.scrollback_top;+ let top = dims+ .physical_top+ .saturating_sub(offset.min(dims.scrollback_rows) as StableRowIndex)+ .max(earliest);+ let (resolved_top, lines) = pane.get_lines(top..top + height as StableRowIndex);+ // Named and indexed colors are forwarded as themselves rather than looked+ // up in the pane's palette, so the host terminal resolves them the way it+ // resolves colors for every other program running in it. Resolving here+ // instead would mean a program's `ESC[31m` could arrive as some other+ // color entirely whenever the pane's palette is not what we assumed —+ // which is exactly how red logos ended up painted in the default+ // foreground. Only true color carries an absolute value, so only true+ // color keeps one.+ let blank_style = Style::reset();+ let buffer = frame.buffer_mut();+ for y in area.y..area.bottom() {+ for x in area.x..area.right() {+ buffer[(x, y)].set_symbol(" ").set_style(blank_style);+ }+ }+ for (row, line) in lines.into_iter().take(area.height as usize).enumerate() {+ let y = area.y + row as u16;+ for cell in line.visible_cells() {+ if cell.cell_index() >= area.width as usize {+ break;+ }+ let x = area.x + cell.cell_index() as u16;+ let remaining = area.right().saturating_sub(x) as usize;+ buffer.set_stringn(x, y, cell.str(), remaining, cell_style(cell.attrs()));+ }+ }++ if let Some(selection) = ui+ .selection+ .as_ref()+ .filter(|selection| selection.pane_id == pane.pane_id())+ {+ render_selection(frame, area, resolved_top, selection, Modifier::REVERSED);+ }+ if let Some(copy) = ui+ .copy+ .as_ref()+ .filter(|copy| copy.pane_id == pane.pane_id())+ {+ if let Some(selection) = ©.selection {+ render_selection(frame, area, resolved_top, selection, Modifier::REVERSED);+ }+ render_search_matches(+ frame,+ area,+ resolved_top,+ ©.search.matches,+ copy.search.current,+ );+ if copy.cursor.row >= resolved_top+ && copy.cursor.row < resolved_top + area.height as StableRowIndex+ && copy.cursor.col < area.width as usize+ {+ let x = area.x + copy.cursor.col as u16;+ let y = area.y + (copy.cursor.row - resolved_top) as u16;+ let cell = &mut frame.buffer_mut()[(x, y)];+ cell.set_style(+ cell.style()+ .add_modifier(Modifier::REVERSED | Modifier::BOLD),+ );+ }+ }+}++fn render_selection(+ frame: &mut Frame<'_>,+ area: Rect,+ visible_top: StableRowIndex,+ selection: &TextSelection,+ modifier: Modifier,+) {+ let (start, end) = selection.ordered();+ let visible_end = visible_top + area.height as StableRowIndex;+ for row in start.row.max(visible_top)..=(end.row.min(visible_end.saturating_sub(1))) {+ let first = if row == start.row { start.col } else { 0 };+ let last = if row == end.row {+ end.col.saturating_add(1)+ } else {+ area.width as usize+ };+ for col in first.min(area.width as usize)..last.min(area.width as usize) {+ let cell =+ &mut frame.buffer_mut()[(area.x + col as u16, area.y + (row - visible_top) as u16)];+ cell.set_style(cell.style().add_modifier(modifier));+ }+ }+}++fn render_search_matches(+ frame: &mut Frame<'_>,+ area: Rect,+ visible_top: StableRowIndex,+ matches: &[SearchResult],+ current: Option<usize>,+) {+ for (index, found) in matches.iter().enumerate() {+ let selection = TextSelection {+ pane_id: 0,+ anchor: SelectionPoint {+ row: found.start_y,+ col: found.start_x,+ },+ head: SelectionPoint {+ row: found.end_y,+ col: found.end_x,+ },+ finalized: true,+ };+ render_selection(+ frame,+ area,+ visible_top,+ &selection,+ if current == Some(index) {+ Modifier::REVERSED | Modifier::BOLD+ } else {+ Modifier::UNDERLINED+ },+ );+ }+}++fn render_status(+ frame: &mut Frame<'_>,+ model: &AppModel,+ ui: &UiState,+ view: &ViewLayout,+ viewport_status: Option<&str>,+) {+ if view.status.is_empty() {+ return;+ }+ // A full-width block of accent across the bottom of the screen is the+ // heaviest thing on it, and it is spending that weight on a hint. The bar+ // keeps the background; only a mode worth noticing gets picked out.+ fill(frame, view.status, " ", chrome());+ let left = match ui.mode {+ AppMode::Prefix => " PREFIX ? help b sidebar g go c tab v/- split x close ",+ AppMode::Navigate => " NAVIGATE ↑↓ thread hjkl pane Enter open Esc back ",+ AppMode::Resize => " RESIZE hjkl/arrows resize Enter/Esc finish ",+ AppMode::Copy => " COPY hjkl move Space select / search y copy Esc back ",+ AppMode::Search => " SEARCH Enter apply Esc cancel ",+ AppMode::Connections => " CONNECTIONS ↑↓ select Enter connect Esc back ",+ AppMode::Settings => " SETTINGS ↑↓ select ←→ change Esc close ",+ AppMode::Help => " HELP Esc close ",+ _ => " Ctrl-b commands ",+ };+ let mode_style = if ui.mode == AppMode::Terminal {+ chrome_dim()+ } else {+ chrome_accent_text().add_modifier(Modifier::BOLD)+ };+ draw_text(frame, view.status, left, mode_style);++ let message = if let Some(pending) = &ui.pending {+ format!(" {} on {}… ", pending.label, pending.domain_name)+ } else if !ui.status.is_empty() {+ format!(" {} ", ui.status)+ } else if let Some(viewport) = viewport_status {+ format!(" {viewport} ")+ } else {+ format!(" r{} · #{} ", model.tree_revision(), model.generation())+ };+ let reserve_right = if model.attention_count() > 0 { 18 } else { 8 };+ let message_width = unicode_column_width(&message, None)+ .min(view.status.width.saturating_sub(reserve_right) as usize)+ as u16;+ if message_width > 0 {+ let rect = Rect::new(+ view.status+ .right()+ .saturating_sub(reserve_right + message_width),+ view.status.y,+ message_width,+ 1,+ );+ draw_text(frame, rect, &message, chrome_dim());+ }++ if model.attention_count() > 0 && view.status.width >= 18 {+ let text = format!(" ! {} ", model.attention_count());+ let rect = Rect::new(view.status.right() - 17, view.status.y, 9, 1);+ draw_text(+ frame,+ rect,+ &text,+ chrome_danger().add_modifier(Modifier::BOLD),+ );+ }+ if view.status.width >= 8 {+ let rect = Rect::new(view.status.right() - 7, view.status.y, 7, 1);+ draw_text(frame, rect, " Detach", chrome_dim());+ }+}++fn render_overlays(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, settings: &TuiConfig) {+ if ui.mode == AppMode::Help {+ render_help(frame, view.screen);+ }+ if ui.mode == AppMode::Connections {+ render_connections(frame, ui, view);+ }+ if ui.mode == AppMode::Settings {+ render_settings(frame, ui, view, settings);+ }+ if let (Some(menu), Some(rect)) = (&ui.context_menu, view.context_menu) {+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome())+ .title(" Actions ");+ let inner = block.inner(rect);+ frame.render_widget(block, rect);+ for (index, entry) in menu.entries.iter().enumerate() {+ if index as u16 >= inner.height {+ break;+ }+ let row = Rect::new(inner.x, inner.y + index as u16, inner.width, 1);+ let style = if index == menu.selected {+ chrome_selected()+ } else if !entry.enabled {+ chrome_dim()+ } else if entry.destructive {+ chrome_danger().add_modifier(Modifier::BOLD)+ } else {+ chrome()+ };+ fill(frame, row, " ", style);+ draw_text(frame, row, &format!(" {}", entry.label), style);+ }+ }++ if let (Some(prompt), Some(rect)) = (&ui.prompt, view.dialog) {+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome())+ .title(format!(" {} ", prompt.title));+ let inner = block.inner(rect);+ frame.render_widget(block, rect);+ if inner.height > 0 {+ let input = Rect::new(inner.x, inner.y + 1.min(inner.height - 1), inner.width, 1);+ fill(frame, input, " ", chrome_surface());+ draw_text(+ frame,+ input,+ &format!(" {}", prompt.value),+ chrome_surface(),+ );+ let cursor_x = input.x+ + 1+ + unicode_column_width(&prompt.value, None)+ .min(input.width.saturating_sub(2) as usize) as u16;+ frame.set_cursor_position((cursor_x.min(input.right().saturating_sub(1)), input.y));+ }+ if inner.height > 2 {+ let hint = Rect::new(inner.x, inner.bottom() - 1, inner.width, 1);+ draw_text(frame, hint, " Enter confirm · Esc cancel", chrome_dim());+ }+ }++ if let (Some(confirm), Some(rect)) = (&ui.confirmation, view.dialog) {+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome())+ .title(format!(" {} ", confirm.title));+ let inner = block.inner(rect);+ frame.render_widget(block, rect);+ let detail = Paragraph::new(confirm.detail.as_str())+ .style(chrome())+ .wrap(ratatui::widgets::Wrap { trim: true });+ let detail_rect = Rect::new(+ inner.x,+ inner.y,+ inner.width,+ inner.height.saturating_sub(2),+ );+ frame.render_widget(detail, detail_rect);+ if inner.height >= 2 {+ let button_y = inner.bottom() - 1;+ let half = inner.width / 2;+ let confirm_rect = Rect::new(inner.x, button_y, half, 1);+ let cancel_rect = Rect::new(inner.x + half, button_y, inner.width - half, 1);+ fill(frame, confirm_rect, " ", chrome_bold_selected());+ draw_text(frame, confirm_rect, " Confirm", chrome_bold_selected());+ fill(frame, cancel_rect, " ", chrome_surface());+ draw_text(frame, cancel_rect, " Cancel", chrome_surface());+ }+ }++ if let Some(toast) = &ui.toast {+ let width = (unicode_column_width(&toast.message, None) as u16 + 4)+ .min(view.screen.width)+ .max(4);+ let rect = Rect::new(+ view.screen.right().saturating_sub(width),+ view.screen.y,+ width,+ 3.min(view.screen.height),+ );+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ frame.render_widget(+ Paragraph::new(TextLine::from(vec![+ Span::styled(" + ", chrome_success().add_modifier(Modifier::BOLD)),+ Span::raw(toast.message.as_str()),+ ]))+ .style(chrome())+ .block(+ Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome()),+ ),+ rect,+ );+ }+}++fn render_settings(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout, settings: &TuiConfig) {+ let Some(rect) = view.dialog else {+ return;+ };+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome())+ .title(" TUI Settings ");+ let inner = block.inner(rect);+ frame.render_widget(block, rect);+ if inner.is_empty() {+ return;+ }+ let mut y = inner.y;+ let mut section = "";+ for (index, (row_section, label)) in crate::SETTINGS.iter().enumerate() {+ if *row_section != section {+ if y >= inner.bottom() {+ break;+ }+ section = row_section;+ draw_text(+ frame,+ Rect::new(inner.x, y, inner.width, 1),+ &format!(" {}", section.to_lowercase()),+ chrome_dim(),+ );+ y += 1;+ }+ if y >= inner.bottom() {+ break;+ }+ let (value, on) = crate::setting_value(settings, ui.sidebar_visible, index);+ let selected = index == ui.settings_index;+ let style = if selected {+ chrome_selected()+ } else {+ chrome()+ };+ let row = Rect::new(inner.x, y, inner.width, 1);+ fill(frame, row, " ", style);+ // A cursor on the left, the value on the right: the eye scans one+ // column for "where am I" and another for "what is it set to".+ draw_text(+ frame,+ row,+ &format!(" {} {}", if selected { "▸" } else { " " }, label),+ style,+ );+ let reading = if value.is_empty() {+ if on { "✓ On" } else { " Off" }.to_string()+ } else {+ value+ };+ let width = unicode_column_width(&reading, None).min(u16::MAX as usize) as u16;+ if width + 2 < row.width {+ draw_text(+ frame,+ Rect::new(row.right() - width - 1, row.y, width, 1),+ &reading,+ style,+ );+ }+ y += 1;+ }+ if inner.height >= 2 {+ let footer = Rect::new(inner.x, inner.bottom() - 1, inner.width, 1);+ fill(frame, footer, " ", chrome());+ draw_text(frame, footer, " ↑↓ move · ←→ change", chrome_dim());+ let done = " Done ";+ let width = unicode_column_width(done, None) as u16;+ if width + 2 < footer.width {+ draw_text(+ frame,+ Rect::new(footer.right() - width - 1, footer.y, width, 1),+ done,+ chrome_accent(),+ );+ }+ }+}++fn render_connections(frame: &mut Frame<'_>, ui: &UiState, view: &ViewLayout) {+ let Some(rect) = view.dialog else {+ return;+ };+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome())+ .title(" Connections ");+ let inner = block.inner(rect);+ frame.render_widget(block, rect);+ if inner.height == 0 {+ return;+ }+ draw_text(+ frame,+ Rect::new(inner.x, inner.y, inner.width, 1),+ " Enter connect/retry · d disconnect · Esc close",+ chrome_dim(),+ );+ for (index, item) in ui.connections.iter().enumerate() {+ let y = inner.y.saturating_add(1 + index as u16);+ if y >= inner.bottom() {+ break;+ }+ let marker = match item.status {+ ConnectionStatus::Attached => "●",+ ConnectionStatus::Connecting | ConnectionStatus::Reconnecting => "…",+ ConnectionStatus::Failed => "!",+ ConnectionStatus::Unsupported => "-",+ ConnectionStatus::Disconnected => "○",+ };+ let detail = if item.detail.is_empty() {+ String::new()+ } else {+ format!(" · {}", item.detail)+ };+ let text = format!(" {marker} {}{detail}", item.label);+ let style = if index == ui.connection_index {+ chrome_selected()+ } else {+ match item.status {+ ConnectionStatus::Attached => chrome_success(),+ ConnectionStatus::Connecting | ConnectionStatus::Reconnecting => chrome_warning(),+ ConnectionStatus::Failed => chrome_danger(),+ ConnectionStatus::Unsupported => chrome_dim(),+ ConnectionStatus::Disconnected => chrome(),+ }+ };+ let row = Rect::new(inner.x, y, inner.width, 1);+ fill(frame, row, " ", style);+ draw_text(frame, row, &text, style);+ }+}++fn render_help(frame: &mut Frame<'_>, screen: Rect) {+ let width = screen.width.saturating_sub(4).clamp(1, 72);+ let height = screen.height.saturating_sub(2).clamp(1, 22);+ let rect = Rect::new(+ screen.x + screen.width.saturating_sub(width) / 2,+ screen.y + screen.height.saturating_sub(height) / 2,+ width,+ height,+ );+ frame.render_widget(Clear, rect);+ fill(frame, rect, " ", chrome());+ let help = [+ "ThinkTerm TUI",+ "",+ "Mouse: click thread/tab/pane · drag select · right-click actions",+ "Shift+mouse: local selection when an app captures the mouse",+ "",+ "Ctrl-b ? help Ctrl-b q/d detach",+ "Ctrl-b b sidebar Ctrl-b g navigator",+ "Ctrl-b C connections Ctrl-b Tab next pane",+ "Ctrl-b c new tab Ctrl-b n/p next/prev tab",+ "Ctrl-b 1..9 select tab Ctrl-b hjkl focus pane",+ "Ctrl-b v/- split Ctrl-b x close pane",+ "Ctrl-b z zoom Ctrl-b r resize mode",+ "Ctrl-b [ copy mode Ctrl-b o next attention",+ "",+ "Copy mode: hjkl/arrows move · Space select · / search · y copy",+ "Esc closes the current mode or dialog.",+ ]+ .join("\n");+ frame.render_widget(+ Paragraph::new(help)+ .style(chrome())+ .alignment(Alignment::Left)+ .block(+ Block::default()+ .borders(Borders::ALL)+ .border_style(chrome_border())+ .style(chrome())+ .title(" Help "),+ ),+ rect,+ );+}++fn render_center(frame: &mut Frame<'_>, area: Rect, text: &str, style: Style) {+ if area.is_empty() {+ return;+ }+ let width = unicode_column_width(text, None).min(area.width as usize) as u16;+ let target = Rect::new(+ area.x + area.width.saturating_sub(width) / 2,+ area.y + area.height / 2,+ width,+ 1,+ );+ draw_text(frame, target, text, style);+}++fn fill(frame: &mut Frame<'_>, area: Rect, symbol: &str, style: Style) {+ let buffer = frame.buffer_mut();+ for y in area.y..area.bottom() {+ for x in area.x..area.right() {+ buffer[(x, y)].set_symbol(symbol).set_style(style);+ }+ }+}++fn draw_text(frame: &mut Frame<'_>, area: Rect, text: &str, style: Style) {+ if area.is_empty() {+ return;+ }+ frame.buffer_mut().set_stringn(+ area.x,+ area.y,+ fit_text(text, area.width as usize),+ area.width as usize,+ style,+ );+}++fn fit_text(text: &str, width: usize) -> String {+ let mut result = String::new();+ for ch in text.chars() {+ let mut candidate = result.clone();+ candidate.push(ch);+ if unicode_column_width(&candidate, None) > width {+ break;+ }+ result.push(ch);+ }+ result+}++fn chrome() -> Style {+ let palette = crate::settings::palette();+ if palette.reset_chrome {+ Style::reset()+ } else {+ Style::reset().fg(palette.foreground).bg(palette.background)+ }+}++fn chrome_dim() -> Style {+ let palette = crate::settings::palette();+ if palette.reset_chrome {+ Style::reset().add_modifier(Modifier::DIM)+ } else {+ Style::reset().fg(palette.dim).bg(palette.background)+ }+}++fn chrome_surface() -> Style {+ let palette = crate::settings::palette();+ Style::reset().fg(palette.foreground).bg(palette.surface)+}++fn chrome_border() -> Style {+ let palette = crate::settings::palette();+ Style::reset().fg(palette.border).bg(palette.background)+}++fn chrome_success() -> Style {+ let palette = crate::settings::palette();+ Style::reset().fg(palette.success).bg(palette.background)+}++fn chrome_warning() -> Style {+ let palette = crate::settings::palette();+ Style::reset().fg(palette.warning).bg(palette.background)+}++fn chrome_danger() -> Style {+ let palette = crate::settings::palette();+ Style::reset().fg(palette.danger).bg(palette.background)+}++fn chrome_bold() -> Style {+ chrome().add_modifier(Modifier::BOLD)+}++/// A filled button: the one command a sidebar leads with.+fn chrome_accent() -> Style {+ let palette = crate::settings::palette();+ if palette.reset_chrome {+ Style::reset().add_modifier(Modifier::BOLD)+ } else {+ Style::reset()+ .fg(palette.accent_foreground)+ .bg(palette.accent)+ .add_modifier(Modifier::BOLD)+ }+}++/// The accent colour as text on the ordinary background, for a status that has+/// to stand out from a row without taking the row over.+fn chrome_accent_text() -> Style {+ let palette = crate::settings::palette();+ Style::reset().fg(palette.accent).bg(palette.background)+}++fn chrome_selected() -> Style {+ let palette = crate::settings::palette();+ if palette.reset_chrome {+ Style::reset().add_modifier(Modifier::REVERSED)+ } else {+ Style::reset()+ .fg(palette.accent_foreground)+ .bg(palette.accent)+ }+}++fn chrome_bold_selected() -> Style {+ chrome_selected().add_modifier(Modifier::BOLD)+}++fn cell_style(attrs: &CellAttributes) -> Style {+ let mut modifiers = Modifier::empty();+ match attrs.intensity() {+ Intensity::Bold => modifiers.insert(Modifier::BOLD),+ Intensity::Half => modifiers.insert(Modifier::DIM),+ Intensity::Normal => {}+ }+ if attrs.underline() != Underline::None {+ modifiers.insert(Modifier::UNDERLINED);+ }+ match attrs.blink() {+ Blink::Slow => modifiers.insert(Modifier::SLOW_BLINK),+ Blink::Rapid => modifiers.insert(Modifier::RAPID_BLINK),+ Blink::None => {}+ }+ if attrs.italic() {+ modifiers.insert(Modifier::ITALIC);+ }+ if attrs.reverse() {+ modifiers.insert(Modifier::REVERSED);+ }+ if attrs.strikethrough() {+ modifiers.insert(Modifier::CROSSED_OUT);+ }+ if attrs.invisible() {+ modifiers.insert(Modifier::HIDDEN);+ }+ Style::new()+ .fg(to_ratatui_color(attrs.foreground()))+ .bg(to_ratatui_color(attrs.background()))+ .add_modifier(modifiers)+}++/// Carry a cell's color across as the same *kind* of color it arrived as.+///+/// `Default` becomes Ratatui's `Reset` so the host terminal supplies its own+/// default, an index stays an index, and only a true color — the one form that+/// already names an absolute value — is passed through as RGB.+fn to_ratatui_color(color: ColorAttribute) -> Color {+ match color {+ ColorAttribute::Default => Color::Reset,+ ColorAttribute::PaletteIndex(index) => Color::Indexed(index),+ // The palette fallback exists for terminals without true color; the+ // host decides which of the two it can honour, so hand it the exact+ // color and let it downgrade.+ ColorAttribute::TrueColorWithPaletteFallback(color, _)+ | ColorAttribute::TrueColorWithDefaultFallback(color) => to_ratatui_rgb(color),+ }+}++fn to_ratatui_rgb(color: SrgbaTuple) -> Color {+ let (red, green, blue, _) = color.as_rgba_u8();+ Color::Rgb(red, green, blue)+}++#[cfg(test)]+mod tests {+ use super::*;++ static THEME_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++ #[test]+ fn fit_text_respects_cell_width() {+ assert_eq!(fit_text("abc", 2), "ab");+ assert_eq!(fit_text("你好x", 4), "你好");+ }++ #[test]+ fn terminal_default_chrome_uses_host_colors() {+ let _guard = THEME_TEST_LOCK.lock().unwrap();+ crate::settings::set_active_theme(crate::settings::ThemeName::Terminal);+ for style in [+ chrome(),+ chrome_dim(),+ chrome_bold(),+ chrome_selected(),+ chrome_bold_selected(),+ ] {+ assert!(style.fg.is_none() || style.fg == Some(Color::Reset));+ assert!(style.bg.is_none() || style.bg == Some(Color::Reset));+ }+ }++ #[test]+ fn named_theme_chrome_uses_its_palette() {+ let _guard = THEME_TEST_LOCK.lock().unwrap();+ crate::settings::set_active_theme(crate::settings::ThemeName::Catppuccin);+ assert_eq!(chrome().fg, Some(Color::Rgb(205, 214, 244)));+ // The chrome shares the terminal's background rather than declaring one+ // of its own, so the sidebar cannot end up a different shade from the+ // panes beside it.+ assert_eq!(chrome().bg, Some(Color::Reset));+ assert_eq!(chrome_selected().bg, Some(Color::Rgb(137, 180, 250)));+ }++ /// A program's `ESC[31m` has to reach the host terminal as "red", not as+ /// whatever RGB some palette happens to map index 1 to. Resolving it here+ /// is what let a red logo arrive in the default foreground.+ #[test]+ fn terminal_cells_forward_colors_without_resolving_them() {+ use wezterm_term::color::RgbColor;++ let defaults = cell_style(&CellAttributes::default());+ assert_eq!(defaults.fg, Some(Color::Reset));+ assert_eq!(defaults.bg, Some(Color::Reset));++ let ansi = CellAttributes::default()+ .set_foreground(ColorAttribute::PaletteIndex(1))+ .clone();+ assert_eq!(cell_style(&ansi).fg, Some(Color::Indexed(1)));++ // True color is the one form that already names an absolute color, so+ // it is the one form that survives as RGB.+ let exact = CellAttributes::default()+ .set_foreground(ColorAttribute::TrueColorWithDefaultFallback(+ RgbColor::new_8bpc(77, 88, 99).into(),+ ))+ .clone();+ assert_eq!(cell_style(&exact).fg, Some(Color::Rgb(77, 88, 99)));+ }+}diff --git a/thinkterm-tui/src/settings.rs b/thinkterm-tui/src/settings.rsnew file mode 100644index 00000000..fb8c3a07--- /dev/null+++ b/thinkterm-tui/src/settings.rs@@ -0,0 +1,553 @@+use anyhow::{Context, Result};+use ratatui::style::Color;+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::{OnceLock, RwLock};++#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum ThemeName {+ #[default]+ MonochromeDark,+ MonochromeLight,+ Terminal,+ Catppuccin,+ TokyoNight,+ Dracula,+ Nord,+ Gruvbox,+ SolarizedDark,+ SolarizedLight,+}++impl ThemeName {+ pub const ALL: [Self; 10] = [+ Self::MonochromeDark,+ Self::MonochromeLight,+ Self::Terminal,+ Self::Catppuccin,+ Self::TokyoNight,+ Self::Dracula,+ Self::Nord,+ Self::Gruvbox,+ Self::SolarizedDark,+ Self::SolarizedLight,+ ];++ pub fn label(self) -> &'static str {+ match self {+ Self::MonochromeDark => "Monochrome Dark",+ Self::MonochromeLight => "Monochrome Light",+ Self::Terminal => "Terminal Default",+ Self::Catppuccin => "Catppuccin",+ Self::TokyoNight => "Tokyo Night",+ Self::Dracula => "Dracula",+ Self::Nord => "Nord",+ Self::Gruvbox => "Gruvbox",+ Self::SolarizedDark => "Solarized Dark",+ Self::SolarizedLight => "Solarized Light",+ }+ }++ pub fn next(self, delta: isize) -> Self {+ let current = Self::ALL+ .iter()+ .position(|theme| *theme == self)+ .unwrap_or(0);+ Self::ALL[(current as isize + delta).rem_euclid(Self::ALL.len() as isize) as usize]+ }+}++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(default)]+pub struct TuiConfig {+ pub theme: ThemeName,+ pub sidebar_visible: bool,+ pub sidebar_width: u16,+ pub mouse: bool,+ pub copy_on_select: bool,+ pub scroll_lines: usize,+ /// Width at or below which the tree stops sharing the screen with the+ /// terminal and becomes a full-width overlay instead. Phones and tablets+ /// vary enormously in how many columns they report, so this is the one+ /// number worth turning up by hand.+ pub narrow_width: u16,+ /// Whether to size the buttons for a fingertip rather than a pointer.+ ///+ /// How big a target has to be is a property of what is doing the pointing,+ /// not of how wide the screen is: a phone held sideways reports plenty of+ /// columns and still has no mouse. Left unset this is inferred from the+ /// layout being narrow, which is right often enough to be a default and+ /// wrong exactly when a phone is roomy — hence the override.+ pub touch_targets: Option<bool>,+ /// Draw an interactive scrollbar beside each terminal pane.+ ///+ /// Off by default: the column it takes is one the server is not told about,+ /// because a tab reports a single grid and the split arithmetic belongs to+ /// the server. Until the two agree, the bar is worth having only where the+ /// last column can be spared.+ pub pane_scrollbars: bool,+ /// Draw a frame around each pane, with the focused one picked out.+ ///+ /// On, and cheaper than it sounds: the pane's nav bar is drawn on the+ /// frame's top edge rather than under it, so the frame costs one row and+ /// two columns beyond what the bar already spends. What it buys is the+ /// thing a split screen most needs — an unambiguous edge, and somewhere for+ /// "this is the pane you are typing into" to live.+ pub pane_borders: bool,+ /// Give each pane a strip of its own carrying the panes stacked behind it+ /// and what can be done to it.+ ///+ /// On by default, and the one piece of chrome that earns its row even on a+ /// single unsplit pane: zoom, split and new-terminal live nowhere else a+ /// finger can reach them. Without it a phone can only get at them through+ /// `Ctrl-b`, which is exactly the keyboard a phone does not have.+ pub pane_nav_bar: bool,+}++impl Default for TuiConfig {+ fn default() -> Self {+ Self {+ theme: ThemeName::MonochromeDark,+ sidebar_visible: true,+ sidebar_width: 26,+ mouse: true,+ copy_on_select: true,+ scroll_lines: 3,+ narrow_width: 64,+ touch_targets: None,+ pane_scrollbars: false,+ pane_borders: true,+ pane_nav_bar: true,+ }+ }+}++impl TuiConfig {+ pub fn normalize(&mut self) {+ self.sidebar_width = self.sidebar_width.clamp(18, 36);+ self.scroll_lines = self.scroll_lines.clamp(1, 20);+ // The floor keeps a tree that is narrower than its own indentation from+ // being reachable at all; the ceiling keeps a typo from turning a+ // desktop into a phone.+ self.narrow_width = self.narrow_width.clamp(20, 200);+ }+}++#[derive(Clone, Debug, Default, Deserialize, Serialize)]+#[serde(default)]+pub struct TuiPersistentState {+ pub last_domain: Option<String>,+ pub selected_threads: BTreeMap<String, String>,+ pub selected_tabs: BTreeMap<String, usize>,+}++fn home_relative(env_name: &str, fallback: &[&str]) -> PathBuf {+ if let Some(path) = std::env::var_os(env_name) {+ return PathBuf::from(path);+ }+ let mut path = std::env::var_os("HOME")+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("."));+ for component in fallback {+ path.push(component);+ }+ path+}++pub fn config_path(override_path: Option<PathBuf>) -> PathBuf {+ override_path+ .or_else(|| std::env::var_os("THINKTERM_TUI_CONFIG").map(PathBuf::from))+ .unwrap_or_else(|| {+ home_relative("XDG_CONFIG_HOME", &[".config"]).join("thinkterm/tui.toml")+ })+}++pub fn state_path() -> PathBuf {+ home_relative("XDG_STATE_HOME", &[".local", "state"]).join("thinkterm/tui.json")+}++pub fn load_config(path: &Path) -> Result<TuiConfig> {+ if !path.exists() {+ return Ok(TuiConfig::default());+ }+ let mut config: TuiConfig = toml::from_str(+ &std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?,+ )+ .with_context(|| format!("parse {}", path.display()))?;+ config.normalize();+ Ok(config)+}++/// Write only the settings that differ from the built-in defaults.+///+/// Writing the whole struct is what made changing a default pointless: any+/// reader who had ever touched a single setting had every *other* setting+/// written out at its value of that day, pinned forever. A file that records+/// only the deliberate choices lets a default stay a default.+pub fn save_config(path: &Path, config: &TuiConfig) -> Result<()> {+ write_atomic(path, changed_settings_toml(config)?.as_bytes())+}++fn changed_settings_toml(config: &TuiConfig) -> Result<String> {+ let toml::Value::Table(mut table) =+ toml::Value::try_from(config).context("serialize TUI settings")?+ else {+ anyhow::bail!("TUI settings did not serialize to a table");+ };+ let toml::Value::Table(defaults) =+ toml::Value::try_from(TuiConfig::default()).context("serialize default TUI settings")?+ else {+ anyhow::bail!("default TUI settings did not serialize to a table");+ };+ table.retain(|key, value| defaults.get(key) != Some(value));+ toml::to_string_pretty(&toml::Value::Table(table)).context("format TUI settings")+}++pub fn load_state(path: &Path) -> Result<TuiPersistentState> {+ if !path.exists() {+ return Ok(TuiPersistentState::default());+ }+ serde_json::from_slice(+ &std::fs::read(path).with_context(|| format!("read {}", path.display()))?,+ )+ .with_context(|| format!("parse {}", path.display()))+}++pub fn save_state(path: &Path, state: &TuiPersistentState) -> Result<()> {+ write_atomic(+ path,+ &serde_json::to_vec_pretty(state).context("serialize TUI state")?,+ )+}++fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> {+ let parent = path+ .parent()+ .with_context(|| format!("{} has no parent", path.display()))?;+ std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;+ let temporary = path.with_extension("tmp");+ std::fs::write(&temporary, contents)+ .with_context(|| format!("write {}", temporary.display()))?;+ std::fs::rename(&temporary, path).with_context(|| format!("replace {}", path.display()))+}++#[derive(Clone, Copy, Debug)]+/// A theme paints its own `background` only when it cannot rely on the host's.+///+/// The dark themes leave it `Color::Reset` and share whatever background the+/// terminal already has, so the sidebar and the panes can never disagree about+/// what "the background" is — that disagreement is what made the chrome read as+/// a different shade of grey stuck beside the terminal. A terminal is dark+/// almost always, so this is almost always right.+///+/// The two light themes cannot make that bet: black text inherited onto a dark+/// terminal is black text nobody can read. They state a background and accept+/// looking like a panel, which is the lesser of the two.+///+/// Either way only `surface` lifts anything off it, and only for the one row+/// being worked on.+pub struct ThemePalette {+ pub reset_chrome: bool,+ pub foreground: Color,+ pub background: Color,+ /// The background this theme's colours were *chosen* against. Never+ /// painted — `background` is what gets painted — but it is what the+ /// readability of every other colour here is measured against, which is+ /// where the only reader of it lives.+ #[allow(dead_code)]+ pub designed_for: Color,+ pub surface: Color,+ pub dim: Color,+ pub border: Color,+ pub accent: Color,+ pub accent_foreground: Color,+ pub success: Color,+ pub warning: Color,+ pub danger: Color,+}++impl ThemePalette {+ fn for_name(name: ThemeName) -> Self {+ let rgb = Color::Rgb;+ match name {+ ThemeName::MonochromeDark => Self {+ reset_chrome: false,+ foreground: Color::White,+ background: Color::Reset,+ designed_for: Color::Rgb(0, 0, 0),+ surface: Color::DarkGray,+ dim: Color::DarkGray,+ border: Color::DarkGray,+ accent: Color::White,+ accent_foreground: Color::Black,+ success: Color::White,+ warning: Color::White,+ danger: Color::White,+ },+ ThemeName::Terminal => Self {+ reset_chrome: true,+ foreground: Color::Reset,+ background: Color::Reset,+ designed_for: Color::Rgb(0, 0, 0),+ surface: Color::Reset,+ dim: Color::DarkGray,+ border: Color::DarkGray,+ accent: Color::White,+ accent_foreground: Color::Black,+ success: Color::Green,+ warning: Color::Yellow,+ danger: Color::LightRed,+ },+ ThemeName::MonochromeLight => Self {+ reset_chrome: false,+ foreground: Color::Black,+ background: Color::White,+ designed_for: Color::Rgb(255, 255, 255),+ surface: Color::Gray,+ dim: Color::DarkGray,+ border: Color::DarkGray,+ accent: Color::Black,+ accent_foreground: Color::White,+ success: Color::Black,+ warning: Color::Black,+ danger: Color::Black,+ },+ ThemeName::Catppuccin => Self {+ reset_chrome: false,+ foreground: rgb(205, 214, 244),+ background: Color::Reset,+ designed_for: rgb(24, 24, 37),+ surface: rgb(49, 50, 68),+ dim: rgb(166, 173, 200),+ border: rgb(69, 71, 90),+ accent: rgb(137, 180, 250),+ accent_foreground: rgb(30, 30, 46),+ success: rgb(166, 227, 161),+ warning: rgb(249, 226, 175),+ danger: rgb(243, 139, 168),+ },+ ThemeName::TokyoNight => Self {+ reset_chrome: false,+ foreground: rgb(192, 202, 245),+ background: Color::Reset,+ designed_for: rgb(26, 27, 38),+ surface: rgb(36, 40, 59),+ dim: rgb(169, 177, 214),+ border: rgb(65, 72, 104),+ accent: rgb(122, 162, 247),+ accent_foreground: rgb(26, 27, 38),+ success: rgb(158, 206, 106),+ warning: rgb(224, 175, 104),+ danger: rgb(247, 118, 142),+ },+ ThemeName::Dracula => Self {+ reset_chrome: false,+ foreground: rgb(248, 248, 242),+ background: Color::Reset,+ designed_for: rgb(40, 42, 54),+ surface: rgb(68, 71, 90),+ dim: rgb(210, 210, 220),+ border: rgb(98, 114, 164),+ accent: rgb(189, 147, 249),+ accent_foreground: rgb(40, 42, 54),+ success: rgb(80, 250, 123),+ warning: rgb(241, 250, 140),+ danger: rgb(255, 85, 85),+ },+ ThemeName::Nord => Self {+ reset_chrome: false,+ foreground: rgb(236, 239, 244),+ background: Color::Reset,+ designed_for: rgb(46, 52, 64),+ surface: rgb(59, 66, 82),+ dim: rgb(216, 222, 233),+ border: rgb(76, 86, 106),+ accent: rgb(136, 192, 208),+ accent_foreground: rgb(46, 52, 64),+ success: rgb(163, 190, 140),+ warning: rgb(235, 203, 139),+ danger: rgb(191, 97, 106),+ },+ ThemeName::Gruvbox => Self {+ reset_chrome: false,+ foreground: rgb(235, 219, 178),+ background: Color::Reset,+ designed_for: rgb(40, 40, 40),+ surface: rgb(60, 56, 54),+ dim: rgb(213, 196, 161),+ border: rgb(80, 73, 69),+ accent: rgb(250, 189, 47),+ accent_foreground: rgb(40, 40, 40),+ success: rgb(184, 187, 38),+ warning: rgb(250, 189, 47),+ danger: rgb(251, 73, 52),+ },+ ThemeName::SolarizedDark => Self {+ reset_chrome: false,+ foreground: rgb(147, 161, 161),+ background: Color::Reset,+ designed_for: rgb(0, 43, 54),+ surface: rgb(7, 54, 66),+ dim: rgb(131, 148, 150),+ border: rgb(88, 110, 117),+ accent: rgb(38, 139, 210),+ accent_foreground: rgb(0, 0, 0),+ success: rgb(133, 153, 0),+ warning: rgb(181, 137, 0),+ danger: rgb(220, 50, 47),+ },+ ThemeName::SolarizedLight => Self {+ reset_chrome: false,+ foreground: rgb(88, 110, 117),+ background: rgb(253, 246, 227),+ designed_for: rgb(253, 246, 227),+ surface: rgb(238, 232, 213),+ dim: rgb(88, 110, 117),+ border: rgb(147, 161, 161),+ accent: rgb(38, 139, 210),+ accent_foreground: rgb(0, 0, 0),+ success: rgb(133, 153, 0),+ warning: rgb(181, 137, 0),+ danger: rgb(220, 50, 47),+ },+ }+ }+}++static ACTIVE_THEME: OnceLock<RwLock<ThemePalette>> = OnceLock::new();++pub fn set_active_theme(name: ThemeName) {+ let palette = ThemePalette::for_name(name);+ if let Some(active) = ACTIVE_THEME.get() {+ *active.write().unwrap() = palette;+ } else {+ let _ = ACTIVE_THEME.set(RwLock::new(palette));+ }+}++pub fn palette() -> ThemePalette {+ *ACTIVE_THEME+ .get_or_init(|| RwLock::new(ThemePalette::for_name(ThemeName::default())))+ .read()+ .unwrap()+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A default that a reader never chose must not be frozen into their file,+ /// or changing it later reaches nobody who has ever opened the settings.+ #[test]+ fn only_deliberate_choices_are_written_back() {+ assert_eq!(+ changed_settings_toml(&TuiConfig::default()).unwrap().trim(),+ "",+ "an untouched config writes nothing at all"+ );++ let mut config = TuiConfig::default();+ config.pane_borders = !TuiConfig::default().pane_borders;+ config.scroll_lines = 9;+ let written = changed_settings_toml(&config).unwrap();+ assert!(written.contains("pane_borders"));+ assert!(written.contains("scroll_lines = 9"));+ assert!(+ !written.contains("theme"),+ "a setting left alone stays absent: {written}"+ );++ // And what is written still round-trips.+ let reloaded: TuiConfig = toml::from_str(&written).unwrap();+ assert_eq!(reloaded.pane_borders, config.pane_borders);+ assert_eq!(reloaded.scroll_lines, 9);+ assert_eq!(reloaded.theme, TuiConfig::default().theme);+ }++ #[test]+ fn config_defaults_and_normalizes_bounds() {+ let mut config: TuiConfig = toml::from_str("sidebar_width = 2\nscroll_lines = 99").unwrap();+ config.normalize();+ assert_eq!(config.sidebar_width, 18);+ assert_eq!(config.scroll_lines, 20);+ assert_eq!(config.theme, ThemeName::MonochromeDark);+ }++ #[test]+ fn themes_cycle_without_falling_off_the_list() {+ assert_eq!(+ ThemeName::MonochromeDark.next(-1),+ ThemeName::SolarizedLight+ );+ assert_eq!(ThemeName::SolarizedLight.next(1), ThemeName::MonochromeDark);+ }++ #[test]+ fn monochrome_and_terminal_default_are_distinct_themes() {+ let monochrome = ThemePalette::for_name(ThemeName::MonochromeDark);+ let terminal = ThemePalette::for_name(ThemeName::Terminal);+ // Both paint on the terminal's own background; what separates them is+ // whether the theme states its foreground at all.+ assert_eq!(monochrome.background, Color::Reset);+ assert_eq!(terminal.background, Color::Reset);+ assert!(!monochrome.reset_chrome);+ assert_eq!(monochrome.foreground, Color::White);+ assert!(terminal.reset_chrome);+ assert_eq!(terminal.foreground, Color::Reset);+ }++ #[test]+ fn named_themes_keep_primary_muted_and_selected_text_readable() {+ fn rgb(color: Color) -> [u8; 3] {+ let Color::Rgb(red, green, blue) = color else {+ panic!("named theme color is not RGB: {color:?}")+ };+ [red, green, blue]+ }+ fn luminance(color: [u8; 3]) -> f64 {+ let channel = |value: u8| {+ let value = f64::from(value) / 255.0;+ if value <= 0.03928 {+ value / 12.92+ } else {+ ((value + 0.055) / 1.055).powf(2.4)+ }+ };+ 0.2126 * channel(color[0]) + 0.7152 * channel(color[1]) + 0.0722 * channel(color[2])+ }+ fn contrast(left: Color, right: Color) -> f64 {+ let left = luminance(rgb(left));+ let right = luminance(rgb(right));+ (left.max(right) + 0.05) / (left.min(right) + 0.05)+ }++ for name in [+ ThemeName::Catppuccin,+ ThemeName::TokyoNight,+ ThemeName::Dracula,+ ThemeName::Nord,+ ThemeName::Gruvbox,+ ThemeName::SolarizedDark,+ ThemeName::SolarizedLight,+ ] {+ let palette = ThemePalette::for_name(name);+ assert!(+ contrast(palette.foreground, palette.designed_for) >= 4.5,+ "{} primary text lacks contrast",+ name.label()+ );+ assert!(+ contrast(palette.dim, palette.designed_for) >= 4.5,+ "{} muted text lacks contrast",+ name.label()+ );+ assert!(+ contrast(palette.accent_foreground, palette.accent) >= 4.5,+ "{} selected text lacks contrast",+ name.label()+ );+ }+ }+}diff --git a/thinkterm-tui/src/state.rs b/thinkterm-tui/src/state.rsnew file mode 100644index 00000000..61735fe1--- /dev/null+++ b/thinkterm-tui/src/state.rs@@ -0,0 +1,279 @@+use crate::action::{Action, DestructiveAction};+use crate::model::TreeNodeKey;+use mux::pane::{PaneId, SearchResult};+use std::collections::{BTreeSet, HashMap};+use std::time::{Duration, Instant};+use wezterm_term::StableRowIndex;++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum AppMode {+ #[default]+ Terminal,+ Prefix,+ Navigate,+ Resize,+ Copy,+ Search,+ ContextMenu,+ Prompt,+ Confirm,+ Help,+ Connections,+ Settings,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum ViewClass {+ #[default]+ Desktop,+ Compact,+ Narrow,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct SelectionPoint {+ pub row: StableRowIndex,+ pub col: usize,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct TextSelection {+ pub pane_id: PaneId,+ pub anchor: SelectionPoint,+ pub head: SelectionPoint,+ pub finalized: bool,+}++impl TextSelection {+ pub fn ordered(&self) -> (SelectionPoint, SelectionPoint) {+ if (self.anchor.row, self.anchor.col) <= (self.head.row, self.head.col) {+ (self.anchor, self.head)+ } else {+ (self.head, self.anchor)+ }+ }+}++#[derive(Clone, Debug, Default)]+pub struct SearchState {+ pub query: String,+ pub matches: Vec<SearchResult>,+ pub current: Option<usize>,+}++#[derive(Clone, Debug)]+pub struct CopyState {+ pub pane_id: PaneId,+ pub cursor: SelectionPoint,+ pub selection: Option<TextSelection>,+ pub search: SearchState,+}++#[derive(Clone, Debug)]+pub struct PromptState {+ pub title: String,+ pub value: String,+ pub action: PromptAction,+}++#[derive(Clone, Debug)]+pub enum PromptAction {+ RenameNode(TreeNodeKey),+ RenameTab,+ CreateSpace {+ domain_name: String,+ },+ CreateProject {+ domain_name: String,+ space_id: String,+ },+ CreateThread {+ domain_name: String,+ project_id: String,+ },+ Search {+ backwards: bool,+ },+}++#[derive(Clone, Debug)]+pub struct ConfirmationState {+ pub title: String,+ pub detail: String,+ pub action: DestructiveAction,+}++#[derive(Clone, Debug)]+pub struct MenuEntry {+ pub label: String,+ pub action: Action,+ pub destructive: bool,+ pub enabled: bool,+}++#[derive(Clone, Debug)]+pub struct ContextMenuState {+ pub anchor: (u16, u16),+ pub selected: usize,+ pub entries: Vec<MenuEntry>,+}++#[derive(Clone, Debug)]+pub struct PendingOperation {+ pub label: String,+ pub domain_name: String,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum ConnectionStatus {+ #[default]+ Disconnected,+ Connecting,+ Attached,+ Reconnecting,+ Unsupported,+ Failed,+}++#[derive(Clone, Debug)]+pub struct ConnectionItem {+ pub name: String,+ pub label: String,+ pub detail: String,+ pub status: ConnectionStatus,+ pub connectable: bool,+}++#[derive(Clone, Debug)]+pub struct Toast {+ pub message: String,+ pub expires_at: Instant,+}++#[derive(Default)]+pub struct UiState {+ pub mode: AppMode,+ pub sidebar_visible: bool,+ pub sidebar_width: u16,+ /// Mirrors `TuiConfig::narrow_width` so layout can read it without the+ /// whole settings struct.+ pub narrow_width: u16,+ /// Mirrors `TuiConfig::touch_targets`, still undecided until layout knows+ /// how wide the screen turned out to be.+ pub touch_targets: Option<bool>,+ /// Mirrors `TuiConfig::pane_scrollbars`.+ pub pane_scrollbars: bool,+ /// Mirrors `TuiConfig::pane_borders`.+ pub pane_borders: bool,+ /// Mirrors `TuiConfig::pane_nav_bar`.+ pub pane_nav_bar: bool,+ pub sidebar_scroll: usize,+ pub tree_collapsed: BTreeSet<TreeNodeKey>,+ /// Lines above the physical screen for each pane. Zero follows output.+ pub scroll_offsets: HashMap<PaneId, usize>,+ pub selection: Option<TextSelection>,+ pub copy: Option<CopyState>,+ pub prompt: Option<PromptState>,+ pub confirmation: Option<ConfirmationState>,+ pub context_menu: Option<ContextMenuState>,+ pub pending: Option<PendingOperation>,+ pub connections: Vec<ConnectionItem>,+ pub connection_index: usize,+ pub settings_index: usize,+ pub status: String,+ pub toast: Option<Toast>,+ pub exit: bool,+ pub frame_number: u64,+}++impl UiState {+ pub fn new(status: String) -> Self {+ Self {+ sidebar_visible: true,+ sidebar_width: 26,+ narrow_width: 64,+ touch_targets: None,+ pane_scrollbars: false,+ pane_borders: true,+ pane_nav_bar: true,+ status,+ ..Default::default()+ }+ }++ pub fn begin_frame(&mut self) {+ self.frame_number = self.frame_number.wrapping_add(1);+ }++ pub fn set_toast(&mut self, message: impl Into<String>) {+ self.toast = Some(Toast {+ message: message.into(),+ expires_at: Instant::now() + Duration::from_secs(3),+ });+ }++ pub fn expire_toast(&mut self, now: Instant) -> bool {+ if self+ .toast+ .as_ref()+ .is_some_and(|toast| toast.expires_at <= now)+ {+ self.toast = None;+ true+ } else {+ false+ }+ }++ pub fn toast_timeout(&self, now: Instant) -> Option<Duration> {+ self.toast+ .as_ref()+ .map(|toast| toast.expires_at.saturating_duration_since(now))+ }++ pub fn scroll_offset(&self, pane_id: PaneId) -> usize {+ self.scroll_offsets.get(&pane_id).copied().unwrap_or(0)+ }++ pub fn set_scroll_offset(&mut self, pane_id: PaneId, offset: usize) {+ if offset == 0 {+ self.scroll_offsets.remove(&pane_id);+ } else {+ self.scroll_offsets.insert(pane_id, offset);+ }+ }++ pub fn close_overlay(&mut self) {+ self.mode = AppMode::Terminal;+ self.prompt = None;+ self.confirmation = None;+ self.context_menu = None;+ self.copy = None;+ }++ pub fn toggle_collapsed(&mut self, key: TreeNodeKey) {+ if !self.tree_collapsed.remove(&key) {+ self.tree_collapsed.insert(key);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn toast_expiry_is_time_based_even_without_rendered_frames() {+ let now = Instant::now();+ let mut ui = UiState::new(String::new());+ ui.toast = Some(Toast {+ message: "done".into(),+ expires_at: now + Duration::from_secs(3),+ });++ assert_eq!(ui.toast_timeout(now), Some(Duration::from_secs(3)));+ assert!(!ui.expire_toast(now + Duration::from_secs(2)));+ assert!(ui.expire_toast(now + Duration::from_secs(3)));+ assert!(ui.toast.is_none());+ }+}diff --git a/thinkterm-tui/src/view.rs b/thinkterm-tui/src/view.rsnew file mode 100644index 00000000..1010ef4e--- /dev/null+++ b/thinkterm-tui/src/view.rs@@ -0,0 +1,1811 @@+use crate::model::{AppModel, ThreadKey, TreeNodeKey};+use crate::state::{UiState, ViewClass};+use mux::pane::PaneId;+use mux::tab::{PaneStackTab, SplitDirection, Tab, TabId};+use ratatui::layout::Rect;+use std::sync::Arc;+use termwiz::cell::unicode_column_width;++/// A command offered on the tree row it belongs to.+///+/// Every one of these already existed as an `Action` reachable by right click.+/// A touchscreen has no right click, so on a phone none of them could be+/// reached at all; drawing them on the row is what the desktop UI does, and is+/// the only affordance that works for both pointers.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TreeAction {+ /// Everything this row can do, via its existing context menu.+ Menu,+ /// Add the obvious child: a project under a space, a thread under a project.+ Add,+}++impl TreeAction {+ pub fn glyph(self) -> &'static str {+ match self {+ Self::Menu => "⋯",+ Self::Add => "+",+ }+ }+}++/// A command on the tab bar's trailing edge.+///+/// Only what belongs to the window lives here. Zooming and splitting act on a+/// pane, so they are drawn on the pane that owns them.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TabBarControl {+ Menu,+ NewTab,+}++impl TabBarControl {+ pub fn glyph(self) -> &'static str {+ match self {+ Self::Menu => "⋮",+ Self::NewTab => "+",+ }+ }+}++/// A command on one pane's own nav bar.+///+/// These act on a pane, not on the window, which is why they are not on the tab+/// bar. Every one already existed as a key chord; none of them had anywhere to+/// be tapped.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PaneTool {+ /// Carries which of the two it currently means, like `TreeAction::Pin`.+ Zoom {+ zoomed: bool,+ },+ SplitRight,+ SplitDown,+ /// Another terminal in *this* pane's stack, drawn as a second level-2 tab+ /// rather than as a new split.+ NewTab,+}++impl PaneTool {+ pub fn glyph(self) -> &'static str {+ match self {+ Self::Zoom { zoomed: false } => "⤢",+ Self::Zoom { zoomed: true } => "⤡",+ Self::SplitRight => "◫",+ Self::SplitDown => "⊟",+ Self::NewTab => "+",+ }+ }+}++/// One pane's own strip: the panes stacked behind it on the left, what can be+/// done to it on the right.+#[derive(Clone, Debug)]+pub struct PaneNav {+ pub rect: Rect,+ /// One entry per pane in this pane's stack, already positioned.+ pub tabs: Vec<PaneNavTab>,+ pub tools: Vec<(Rect, PaneTool)>,+}++#[derive(Clone, Debug)]+pub struct PaneNavTab {+ pub rect: Rect,+ /// Carried for the same reason `TreeLine::key` is: the hit region answers+ /// the tap, this names what was drawn.+ #[allow(dead_code)]+ pub pane_id: PaneId,+ pub label: String,+ pub active: bool,+ /// Every stack tab offers it, whichever one is showing — a tab strip where+ /// only one tab can be closed is a tab strip you have to click twice.+ pub close: Option<Rect>,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum HitTarget {+ Tree(TreeNodeKey),+ TreeToggle(TreeNodeKey),+ TreeAction(TreeNodeKey, TreeAction),+ NewThread,+ NewProject,+ OpenSettings,+ Tab(TabId),+ CloseTab(TabId),+ TabControl(TabBarControl),+ Pane(PaneId),+ /// Show this pane, which is stacked behind the one currently drawn there.+ PaneNavTab(PaneId),+ PaneNavClose(PaneId),+ PaneTool(PaneId, PaneTool),+ Scrollbar(PaneId),+ Split(usize),+ SidebarResize,+ Detach,+ Attention,+ SidebarToggle,+ ContextMenu(usize),+ Connection(usize),+ Setting(usize),+ DialogConfirm,+ DialogCancel,+}++#[derive(Clone, Debug)]+pub struct HitRegion {+ pub rect: Rect,+ pub target: HitTarget,+}++#[derive(Clone, Debug)]+pub struct TreeLine {+ pub rect: Rect,+ #[allow(dead_code)]+ pub key: TreeNodeKey,+ pub label: String,+ pub depth: u16,+ pub selected: bool,+ pub expandable: bool,+ pub collapsed: bool,+ pub status: Option<&'static str>,+ /// A pinned thread says so with a ★ before its name, on every row. Nothing+ /// else on the row claims that glyph now, so it can only mean one thing.+ pub pinned: bool,+ /// Buttons drawn at the right end of the row, already positioned. Layout+ /// owns the geometry so the glyph and the region that answers a tap cannot+ /// drift apart.+ pub actions: Vec<(Rect, TreeAction)>,+}++#[derive(Clone, Debug)]+pub struct TabLine {+ pub rect: Rect,+ pub label: String,+ pub selected: bool,+ /// The tab's own close button, when the name still had room beside it.+ pub close: Option<Rect>,+}++#[derive(Clone, Debug)]+pub struct PaneView {+ pub pane_id: PaneId,+ /// The grid itself, already excluding anything drawn beside it.+ pub rect: Rect,+ pub scrollbar: Option<Rect>,+ /// The pane's own strip, when it had a row to spare for one.+ pub nav: Option<PaneNav>,+ /// The frame drawn around the pane, when it has one. Encloses the grid, its+ /// scrollbar and its nav bar.+ pub border: Option<Rect>,+}++#[derive(Clone, Debug)]+pub struct SplitView {+ pub index: usize,+ pub rect: Rect,+ pub direction: SplitDirection,+}++#[derive(Clone, Debug)]+pub struct ViewLayout {+ pub screen: Rect,+ pub class: ViewClass,+ pub sidebar: Option<Rect>,+ pub sidebar_header: Option<Rect>,+ pub sidebar_body: Option<Rect>,+ /// The always-visible primary button and settings row, when the sidebar is+ /// tall enough to spare them a row each.+ pub sidebar_new_thread: Option<Rect>,+ /// The heading over the tree, and the add-project button on its right.+ pub sidebar_heading: Option<Rect>,+ pub sidebar_new_project: Option<Rect>,+ pub sidebar_settings: Option<Rect>,+ pub sidebar_resize: Option<Rect>,+ pub sidebar_toggle: Option<Rect>,+ pub tab_bar: Rect,+ pub content: Rect,+ pub status: Rect,+ pub tree_lines: Vec<TreeLine>,+ pub tabs: Vec<TabLine>,+ /// Trailing tab-bar buttons, already positioned.+ pub tab_controls: Vec<(Rect, TabBarControl)>,+ pub panes: Vec<PaneView>,+ pub splits: Vec<SplitView>,+ pub hits: Vec<HitRegion>,+ pub dialog: Option<Rect>,+ pub context_menu: Option<Rect>,+}++impl Default for ViewLayout {+ fn default() -> Self {+ Self {+ screen: Rect::default(),+ class: ViewClass::Desktop,+ sidebar: None,+ sidebar_header: None,+ sidebar_body: None,+ sidebar_new_thread: None,+ sidebar_heading: None,+ sidebar_new_project: None,+ sidebar_settings: None,+ sidebar_resize: None,+ sidebar_toggle: None,+ tab_bar: Rect::default(),+ content: Rect::default(),+ status: Rect::default(),+ tree_lines: vec![],+ tabs: vec![],+ tab_controls: vec![],+ panes: vec![],+ splits: vec![],+ hits: vec![],+ dialog: None,+ context_menu: None,+ }+ }+}++impl ViewLayout {+ pub fn hit(&self, x: u16, y: u16) -> Option<&HitTarget> {+ let position = (x, y).into();+ // Overlays are appended last and must win over the terminal below.+ self.hits+ .iter()+ .rev()+ .find(|hit| hit.rect.contains(position))+ .map(|hit| &hit.target)+ }++ pub fn pane_at(&self, x: u16, y: u16) -> Option<&PaneView> {+ let position = (x, y).into();+ self.panes.iter().find(|pane| pane.rect.contains(position))+ }+}++pub fn classify(width: u16, narrow_width: u16) -> ViewClass {+ if width <= narrow_width {+ ViewClass::Narrow+ } else if width < narrow_width.saturating_add(24) {+ ViewClass::Compact+ } else {+ ViewClass::Desktop+ }+}++pub fn compute_view(+ area: Rect,+ model: &AppModel,+ ui: &UiState,+ tab: Option<&Arc<Tab>>,+) -> ViewLayout {+ let mut view = ViewLayout {+ screen: area,+ class: classify(area.width, ui.narrow_width),+ ..Default::default()+ };+ if area.width == 0 || area.height == 0 {+ return view;+ }++ let narrow = view.class == ViewClass::Narrow;+ // A finger needs more than one row to land on reliably, so a screen being+ // pointed at with one spends a second row on the bar that carries every+ // button — and buys that row back from the footer, which without a keyboard+ // was spending it to name key chords. Messages still get a row, but only+ // while there is a message to put in it.+ //+ // Tying this to the layout being narrow is only ever a guess: the same+ // phone turned sideways reports enough columns to look like a desktop and+ // still has no mouse. The guess is the default; the setting is the answer.+ let touch = ui.touch_targets.unwrap_or(narrow);+ let header_height = if touch && area.height >= 6 {+ 2+ } else {+ u16::from(area.height >= 3)+ };+ let status_height = if touch {+ u16::from(area.height >= 2 && (!ui.status.is_empty() || ui.toast.is_some()))+ } else {+ u16::from(area.height >= 2)+ };+ view.status = Rect::new(+ area.x,+ area.bottom().saturating_sub(status_height),+ area.width,+ status_height,+ );+ let middle_y = area.y.saturating_add(header_height);+ let middle_height = area.height.saturating_sub(header_height + status_height);++ // Too narrow to seat the tree beside a usable terminal, the tree takes the+ // whole screen for as long as it is asked for. Refusing to draw it at all+ // is what used to happen, and it left the toggle button on screen with+ // nothing to toggle — no way to reach another thread from a phone.+ // Narrow enough that a tree beside a terminal leaves neither of them+ // usable. Whether the tree is *actually* covering the screen also depends+ // on it being asked for — see `tree_covers_screen` below.+ let overlay = view.class == ViewClass::Narrow;+ let sidebar_allowed = ui.sidebar_visible;+ let sidebar_width = if sidebar_allowed {+ match view.class {+ ViewClass::Desktop => ui+ .sidebar_width+ .clamp(18, 36)+ .min(area.width.saturating_sub(24))+ .max(1),+ ViewClass::Compact => 18u16.min(area.width.saturating_sub(24)).max(1),+ ViewClass::Narrow => area.width,+ }+ } else {+ 0+ };++ if sidebar_width > 0 {+ let sidebar = Rect::new(area.x, area.y, sidebar_width, area.height - status_height);+ let resize = Rect::new(+ area.x + sidebar_width,+ area.y,+ 1,+ area.height - status_height,+ );+ view.sidebar = Some(sidebar);+ view.sidebar_header = Some(Rect::new(+ sidebar.x,+ sidebar.y,+ sidebar.width,+ header_height,+ ));+ if let Some(header) = view.sidebar_header {+ view.sidebar_toggle = Some(header);+ view.hits.push(HitRegion {+ rect: header,+ target: HitTarget::SidebarToggle,+ });+ }+ // The desktop UI keeps its two most-used commands permanently in view,+ // one at each end of the tree: a primary button to start work, and+ // settings where a settings button belongs. Both existed only inside+ // the ⋮ menu here, which on a phone is an extra tap for the two things+ // reached most often. They are only worth their rows once the sidebar+ // is tall enough that the tree still has somewhere to go.+ let mut body = Rect::new(sidebar.x, middle_y, sidebar.width, middle_height);+ if middle_height >= 5 && sidebar.width >= MIN_LABEL_COLUMNS {+ let new_thread = Rect::new(body.x, body.y, body.width, 1);+ view.sidebar_new_thread = Some(new_thread);+ view.hits.push(HitRegion {+ rect: new_thread,+ target: HitTarget::NewThread,+ });+ let settings = Rect::new(body.x, body.bottom() - 1, body.width, 1);+ view.sidebar_settings = Some(settings);+ view.hits.push(HitRegion {+ rect: settings,+ target: HitTarget::OpenSettings,+ });+ body = Rect::new(body.x, body.y + 1, body.width, body.height - 2);+ // A heading over the tree, with the one command that belongs to the+ // tree as a whole beside it. Adding a project is otherwise reachable+ // only by first selecting the space it goes in, which is a tap spent+ // on saying where before you can say what.+ if body.height >= 4 {+ let heading = Rect::new(body.x, body.y, body.width, 1);+ let button = if touch { 3u16 } else { 2u16 };+ view.sidebar_new_project =+ Some(Rect::new(heading.right() - button, heading.y, button, 1));+ view.sidebar_heading = Some(heading);+ if let Some(rect) = view.sidebar_new_project {+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::NewProject,+ });+ }+ body = Rect::new(body.x, body.y + 1, body.width, body.height - 1);+ }+ }+ view.sidebar_body = Some(body);+ if overlay {+ // The tree covers the screen, so there is no divider to drag and+ // nothing of the terminal to see. `content` still describes the+ // grid the terminal *has* — the whole width, since there is no+ // sidebar beside it once the tree is dismissed.+ //+ // It used to be zeroed here, which read as "this renderer has no+ // viewport": a phone held in portrait is exactly the case where the+ // tree covers the screen, so a phone could never take the size from+ // whatever else was attached, and the terminal it opened was still+ // the other device's shape. Panes are skipped below rather than+ // sized to nothing.+ view.tab_bar = Rect::new(area.x, area.y, 0, header_height);+ view.content = Rect::new(area.x, middle_y, area.width, middle_height);+ } else {+ view.sidebar_resize = Some(resize);+ view.hits.push(HitRegion {+ rect: resize,+ target: HitTarget::SidebarResize,+ });+ view.tab_bar = Rect::new(+ resize.right(),+ area.y,+ area.right().saturating_sub(resize.right()),+ header_height,+ );+ view.content = Rect::new(+ resize.right(),+ middle_y,+ area.right().saturating_sub(resize.right()),+ middle_height,+ );+ }+ } else {+ view.tab_bar = Rect::new(area.x, area.y, area.width, header_height);+ view.content = Rect::new(area.x, middle_y, area.width, middle_height);+ let toggle_width = if touch { 6 } else { 4 };+ if header_height > 0 && area.width >= toggle_width {+ let toggle = Rect::new(area.x, area.y, toggle_width, header_height);+ view.sidebar_toggle = Some(toggle);+ view.hits.push(HitRegion {+ rect: toggle,+ target: HitTarget::SidebarToggle,+ });+ }+ }++ if let Some(body) = view.sidebar_body {+ compute_tree(model, ui, body, &mut view);+ }+ let tabs_area = if view.sidebar.is_none() {+ view.sidebar_toggle.map_or(view.tab_bar, |toggle| {+ Rect::new(+ toggle.right(),+ view.tab_bar.y,+ view.tab_bar.right().saturating_sub(toggle.right()),+ view.tab_bar.height,+ )+ })+ } else {+ view.tab_bar+ };+ compute_tabs(model, tabs_area, &mut view);+ // Skipped only when the tree is genuinely on top of them. Testing `overlay`+ // alone was wrong: a narrow screen with the tree *dismissed* is the normal+ // way to use a phone zoomed in, and it left the terminal undrawn — a tab+ // bar over an empty screen. `content` still says how big the panes are+ // either way, which is what gets advertised to the server.+ if let (Some(tab), false) = (tab, tree_covers_terminal(&view)) {+ compute_panes(tab, ui, view.content, &mut view);+ }++ if view.status.width >= 8 {+ let detach = Rect::new(+ view.status.right() - 7,+ view.status.y,+ 7,+ view.status.height,+ );+ view.hits.push(HitRegion {+ rect: detach,+ target: HitTarget::Detach,+ });+ }+ if model.attention_count() > 0 && view.status.width >= 18 {+ let attention = Rect::new(+ view.status.right() - 17,+ view.status.y,+ 9,+ view.status.height,+ );+ view.hits.push(HitRegion {+ rect: attention,+ target: HitTarget::Attention,+ });+ }++ compute_overlays(ui, &mut view);+ view+}++/// Whether the tree is drawn *on top of* the terminal rather than beside it.+///+/// Both halves matter. Narrow alone is not enough — a narrow screen with the+/// tree dismissed is the ordinary way a phone is used once it is zoomed in, and+/// treating that as "covered" leaves a tab bar over an empty screen.+fn tree_covers_terminal(view: &ViewLayout) -> bool {+ view.class == ViewClass::Narrow && view.sidebar.is_some()+}++fn compute_tree(model: &AppModel, ui: &UiState, body: Rect, view: &mut ViewLayout) {+ #[derive(Clone)]+ struct Candidate {+ key: TreeNodeKey,+ label: String,+ depth: u16,+ selected: bool,+ expandable: bool,+ collapsed: bool,+ status: Option<&'static str>,+ pinned: bool,+ }++ let touch = ui.touch_targets.unwrap_or(view.class == ViewClass::Narrow);+ let selected = model.selected_key();+ let mut all = Vec::new();+ for (domain_name, snapshot) in model.domains() {+ let domain_key = TreeNodeKey::Domain(domain_name.to_string());+ let domain_collapsed = ui.tree_collapsed.contains(&domain_key);+ all.push(Candidate {+ key: domain_key.clone(),+ label: domain_name.to_string(),+ depth: 0,+ selected: false,+ expandable: true,+ collapsed: domain_collapsed,+ status: None,+ pinned: false,+ });+ if domain_collapsed {+ continue;+ }++ for space in &snapshot.spaces {+ let space_key = TreeNodeKey::Space {+ domain_name: domain_name.to_string(),+ space_id: space.id.clone(),+ };+ let space_collapsed = ui.tree_collapsed.contains(&space_key);+ let projects = snapshot+ .projects+ .iter()+ .filter(|project| project.space_id == space.id)+ .collect::<Vec<_>>();+ all.push(Candidate {+ key: space_key.clone(),+ label: space.name.clone(),+ depth: 1,+ selected: false,+ expandable: !projects.is_empty(),+ collapsed: space_collapsed,+ status: None,+ pinned: false,+ });+ if space_collapsed {+ continue;+ }++ for project in projects {+ let project_key = TreeNodeKey::Project {+ domain_name: domain_name.to_string(),+ project_id: project.id.clone(),+ };+ let project_collapsed = ui.tree_collapsed.contains(&project_key);+ all.push(Candidate {+ key: project_key.clone(),+ label: project.name.clone(),+ depth: 2,+ selected: false,+ expandable: !project.threads.is_empty(),+ collapsed: project_collapsed,+ status: None,+ pinned: false,+ });+ if project_collapsed {+ continue;+ }+ for thread in &project.threads {+ let key = ThreadKey {+ domain_name: domain_name.to_string(),+ server_id: snapshot.server_id.clone(),+ thread_id: thread.id.clone(),+ };+ let status = model.row(&key).map(|row| row.status_marker());+ all.push(Candidate {+ key: TreeNodeKey::Thread(key.clone()),+ label: thread.name.clone(),+ depth: 3,+ selected: selected == Some(&key),+ expandable: false,+ collapsed: false,+ status,+ pinned: thread.is_pinned,+ });+ }+ }+ }+ }++ let available = body.height as usize;+ if available == 0 || all.is_empty() {+ return;+ }+ let selected_index = all.iter().position(|line| line.selected).unwrap_or(0);+ let requested = ui.sidebar_scroll.min(all.len().saturating_sub(1));+ let start = if selected_index < requested || selected_index >= requested + available {+ selected_index+ .saturating_sub(available / 2)+ .min(all.len().saturating_sub(available))+ } else {+ requested.min(all.len().saturating_sub(available))+ };++ // Every row's buttons are the same width so a column of them lines up, and+ // a finger gets a wider one than a mouse needs.+ let button = if touch { 3u16 } else { 2u16 };+ for (offset, line) in all.into_iter().skip(start).take(available).enumerate() {+ let rect = Rect::new(body.x, body.y + offset as u16, body.width, 1);+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::Tree(line.key.clone()),+ });++ // Every row carries the same buttons whether or not it is selected.+ // Showing them only on the selected row meant the sidebar's controls+ // appeared and vanished as the selection moved, and no row could be+ // read as "this is what a row can do".+ //+ // Which buttons: one that opens everything else, plus — where a row has+ // an obvious child — one that adds it. A per-row pin and a per-row+ // delete used to be here and are gone: two glyphs whose meaning had to+ // be guessed, one of them a red ✕ repeated down a list of names, which+ // reads as a warning rather than as a control. Both still live in the ⋯+ // menu, where they are spelled out in words.+ let wanted: &[TreeAction] = match &line.key {+ TreeNodeKey::Domain(_) => &[TreeAction::Menu],+ TreeNodeKey::Space { .. } => &[TreeAction::Add, TreeAction::Menu],+ TreeNodeKey::Project { .. } => &[TreeAction::Add, TreeAction::Menu],+ TreeNodeKey::Thread(_) => &[TreeAction::Menu],+ };+ let mut actions = Vec::new();+ if rect.width >= MIN_LABEL_COLUMNS + button * wanted.len() as u16 {+ let mut edge = rect.right();+ for kind in wanted.iter().rev() {+ edge -= button;+ let hit = Rect::new(edge, rect.y, button, rect.height);+ view.hits.push(HitRegion {+ rect: hit,+ target: HitTarget::TreeAction(line.key.clone(), *kind),+ });+ actions.push((hit, *kind));+ }+ // Laid out right to left; handed on left to right, so the order a+ // caller sees is the order the eye sees.+ actions.reverse();+ }+ if line.expandable {+ let toggle_x = rect.x.saturating_add(line.depth.saturating_mul(2));+ if toggle_x < rect.right() {+ view.hits.push(HitRegion {+ rect: Rect::new(toggle_x, rect.y, 2.min(rect.right() - toggle_x), 1),+ target: HitTarget::TreeToggle(line.key.clone()),+ });+ }+ }+ view.tree_lines.push(TreeLine {+ rect,+ key: line.key,+ label: line.label,+ depth: line.depth,+ selected: line.selected,+ expandable: line.expandable,+ collapsed: line.collapsed,+ status: line.status,+ pinned: line.pinned,+ actions,+ });+ }+}++/// Columns a tree row keeps for its own name before it will host any buttons.+const MIN_LABEL_COLUMNS: u16 = 12;++fn compute_tabs(model: &AppModel, area: Rect, view: &mut ViewLayout) {+ if area.height == 0 || area.width == 0 {+ return;+ }+ // Laid out right to left in the order they are worth keeping, so a bar too+ // narrow for all of them loses the splits before it loses the menu that can+ // still reach everything.+ let width = tab_bar_control_width(area.height);+ let mut edge = area.right();+ for control in TAB_BAR_CONTROLS {+ if edge.saturating_sub(area.x) < MIN_TAB_COLUMNS + width {+ break;+ }+ edge -= width;+ let rect = Rect::new(edge, area.y, width, area.height);+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::TabControl(control),+ });+ view.tab_controls.push((rect, control));+ }+ let tabs_right = edge;+ let selected = model.selected_tab().map(|tab| tab.tab_id);+ let mut x = area.x;+ for (index, tab) in model.tabs_for_selected_thread().iter().enumerate() {+ if x >= tabs_right {+ break;+ }+ let title = if tab.title.trim().is_empty() {+ "shell"+ } else {+ tab.title.trim()+ };+ let label = format!(" {}:{} ", index + 1, title);+ let desired = unicode_column_width(&label, None).min(u16::MAX as usize) as u16;+ // Room for the tab's own close button, but only where the name still+ // has somewhere to go afterwards.+ let close_width = tab_bar_control_width(area.height);+ let want_close = tabs_right.saturating_sub(x) >= desired + close_width;+ let width = (desired + if want_close { close_width } else { 0 }).min(tabs_right - x);+ if width == 0 {+ break;+ }+ let rect = Rect::new(x, area.y, width, area.height);+ let close = want_close.then(|| {+ let rect = Rect::new(rect.right() - close_width, rect.y, close_width, rect.height);+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::CloseTab(tab.tab_id),+ });+ rect+ });+ view.tabs.push(TabLine {+ rect,+ label,+ selected: selected == Some(tab.tab_id),+ close,+ });+ // Pushed before the close button above so the narrower target wins the+ // hit test — `hit` searches from the back.+ view.hits.insert(+ view.hits.len().saturating_sub(usize::from(close.is_some())),+ HitRegion {+ rect,+ target: HitTarget::Tab(tab.tab_id),+ },+ );+ x = x.saturating_add(width);+ }+}++/// Trailing tab-bar controls, most worth keeping first. A bar too narrow for+/// all of them drops from the end, so the menu — which can still reach+/// everything below it — is the last to go.+pub const TAB_BAR_CONTROLS: [TabBarControl; 2] = [TabBarControl::Menu, TabBarControl::NewTab];++/// Columns the tab bar keeps for tabs before it will host any control.+const MIN_TAB_COLUMNS: u16 = 10;++/// Width of one tab-bar control. A bar with room for two rows is a bar meant to+/// be touched, so its buttons widen to match their new height.+pub fn tab_bar_control_width(height: u16) -> u16 {+ if height > 1 {+ 4+ } else {+ 3+ }+}++/// Sizes at which a pane can afford to give space to chrome.+///+/// Both of these are paid for out of the grid, and on a small pane that is the+/// difference between a shell prompt fitting on one line and wrapping into+/// nonsense. A frame costs two columns and two rows, a scrollbar one column —+/// worth it on a desktop split, ruinous on a phone that has just been split in+/// half. The thresholds are what "there is room to spare" means here.+const SCROLLBAR_MIN_COLUMNS: u16 = 34;+/// A frame is cheaper than it looks, because the pane's nav bar is drawn *on*+/// its top edge rather than under it — the way a titled box works. So the frame+/// costs one row (the bottom edge) and two columns beyond what the bar already+/// spends, not two rows and two columns. That is affordable on a phone, which+/// is why these are low.+/// Tied to what the nav bar already needs, plus the one row and two columns the+/// frame adds. A pane that can afford a bar can afford a frame, so the two+/// never disagree — a split where one half is framed and the other is not reads+/// as broken rather than as economical.+const BORDER_MIN_COLUMNS: u16 = MIN_LABEL_COLUMNS + 2;+const BORDER_MIN_ROWS: u16 = PANE_NAV_MIN_ROWS + 1;++/// Rows a pane keeps for its grid before it will spend one on its own nav bar.+///+/// Deliberately almost nothing. This started at eight, which on a phone meant+/// the shorter half of a split silently lost its bar — and with it every+/// control that pane had, since the bar is the only place a finger can reach+/// zoom, split, close and new-terminal. A pane you cannot act on is worse than+/// a pane one row shorter, and a split where only one half has a bar reads as+/// broken. Two rows of grid is the floor; below that the pane is unusable for+/// reasons the bar has nothing to do with.+const PANE_NAV_MIN_ROWS: u16 = 3;++/// Widest a level-2 tab may grow, so one long title cannot take the row from+/// the rest of the stack.+const PANE_NAV_TAB_MAX_COLUMNS: u16 = 18;++fn compute_panes(tab: &Arc<Tab>, ui: &UiState, area: Rect, view: &mut ViewLayout) {+ if area.width == 0 || area.height == 0 {+ return;+ }+ let touch = ui.touch_targets.unwrap_or(view.class == ViewClass::Narrow);+ let panes = tab.iter_panes();+ let pane_count = panes.len();+ for positioned in panes {+ let left = positioned.left.min(area.width as usize);+ let top = positioned.top.min(area.height as usize);+ let width = positioned+ .width+ .min(area.width.saturating_sub(left as u16) as usize) as u16;+ let height = positioned+ .height+ .min(area.height.saturating_sub(top as u16) as usize) as u16;+ let rect = Rect::new(+ area.x.saturating_add(left as u16),+ area.y.saturating_add(top as u16),+ width,+ height,+ );+ if rect.is_empty() {+ continue;+ }+ // Only where there is another pane to be told apart from. A lone pane+ // already has the window's own edges; framing it spends a row and two+ // columns to draw a line around the only thing on screen.+ let framed = ui.pane_borders+ && pane_count > 1+ && rect.width >= BORDER_MIN_COLUMNS+ && rect.height >= BORDER_MIN_ROWS;+ let border = framed.then_some(rect);+ let pane_id = positioned.pane.pane_id();+ // The bar sits *on* the frame's top edge, between its corners, so a+ // framed pane pays one row for the bar and one for the bottom edge+ // rather than one for each of three lines.+ let bar_area = if framed {+ Rect::new(rect.x + 1, rect.y, rect.width - 2, rect.height)+ } else {+ rect+ };+ // Above the grid, never over it, for the same reason as the scrollbar:+ // the row it takes is a row the terminal is then told it does not have.+ let nav = compute_pane_nav(+ pane_id,+ &tab.pane_stack_tabs(pane_id),+ positioned.is_zoomed,+ ui.pane_nav_bar,+ touch,+ bar_area,+ view,+ );+ let bar_rows = nav.as_ref().map_or(0, |nav| nav.rect.height);+ let rect = if framed {+ // The top edge is already spent on the bar (or is a plain edge when+ // there is no bar), so the grid starts one row down either way.+ Rect::new(+ rect.x + 1,+ rect.y + 1,+ rect.width - 2,+ rect.height.saturating_sub(2),+ )+ } else {+ Rect::new(+ rect.x,+ rect.y + bar_rows,+ rect.width,+ rect.height - bar_rows,+ )+ };+ // The scrollbar lives beside the grid, never over it: the column it+ // takes is a column the terminal is then told it does not have, so a+ // program's own right margin still lands where it drew it.+ let scrollbar = (ui.pane_scrollbars && rect.width >= SCROLLBAR_MIN_COLUMNS).then(|| {+ let rect = Rect::new(rect.right() - 1, rect.y, 1, rect.height);+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::Scrollbar(pane_id),+ });+ rect+ });+ let rect = if scrollbar.is_some() {+ Rect::new(rect.x, rect.y, rect.width - 1, rect.height)+ } else {+ rect+ };+ view.panes.push(PaneView {+ pane_id,+ rect,+ scrollbar,+ nav,+ border,+ });+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::Pane(pane_id),+ });+ }++ for split in tab.iter_splits() {+ let Some(rect) =+ clipped_split_rect(area, split.left, split.top, split.size, split.direction)+ else {+ continue;+ };+ view.splits.push(SplitView {+ index: split.index,+ rect,+ direction: split.direction,+ });+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::Split(split.index),+ });+ }+}++/// Lay out one pane's own strip, and say how much of its rectangle is left.+///+/// Tools are placed right to left in the order they are worth keeping, so a+/// pane too narrow for all four drops the splits first. That is the opposite of+/// the desktop's order and deliberately so: on a phone, a pane that has just+/// been split needs to be able to un-split itself by zooming far more than it+/// needs to split again.+fn compute_pane_nav(+ pane_id: PaneId,+ stack: &[PaneStackTab],+ zoomed: bool,+ enabled: bool,+ touch: bool,+ rect: Rect,+ view: &mut ViewLayout,+) -> Option<PaneNav> {+ if !enabled || rect.height < PANE_NAV_MIN_ROWS || rect.width < MIN_LABEL_COLUMNS {+ return None;+ }+ let bar = Rect::new(rect.x, rect.y, rect.width, 1);+ let button = if touch { 3u16 } else { 2u16 };++ let zoom = PaneTool::Zoom { zoomed };+ let priority = [+ zoom,+ PaneTool::NewTab,+ PaneTool::SplitRight,+ PaneTool::SplitDown,+ ];+ let order = [+ zoom,+ PaneTool::SplitRight,+ PaneTool::SplitDown,+ PaneTool::NewTab,+ ];+ let room = (bar.width.saturating_sub(MIN_LABEL_COLUMNS) / button) as usize;+ let kept = &priority[..room.min(priority.len())];++ let mut tools = Vec::new();+ let mut edge = bar.right();+ for kind in order.iter().rev() {+ if !kept.contains(kind) {+ continue;+ }+ edge -= button;+ let hit = Rect::new(edge, bar.y, button, bar.height);+ view.hits.push(HitRegion {+ rect: hit,+ target: HitTarget::PaneTool(pane_id, *kind),+ });+ tools.push((hit, *kind));+ }+ tools.reverse();++ let mut tabs = Vec::new();+ let mut x = bar.x;+ for entry in stack {+ if x >= edge {+ break;+ }+ let title = if entry.title.trim().is_empty() {+ "shell"+ } else {+ entry.title.trim()+ };+ // No icon before the name. `▯` was there to mark a terminal, and on a+ // phone whose font does not carry U+25AF it drew a tofu box that read+ // as a bug. The name is doing the naming already.+ let label = format!(" {title} ");+ let desired = unicode_column_width(&label, None)+ .min(u16::MAX as usize)+ .min(PANE_NAV_TAB_MAX_COLUMNS as usize) as u16;+ let want_close = edge.saturating_sub(x) >= desired + button;+ let width = (desired + if want_close { button } else { 0 }).min(edge - x);+ if width == 0 {+ break;+ }+ let rect = Rect::new(x, bar.y, width, bar.height);+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::PaneNavTab(entry.pane_id),+ });+ // Pushed after the tab so the narrower target wins the hit test —+ // `hit` searches from the back.+ let close = want_close.then(|| {+ let rect = Rect::new(rect.right() - button, rect.y, button, rect.height);+ view.hits.push(HitRegion {+ rect,+ target: HitTarget::PaneNavClose(entry.pane_id),+ });+ rect+ });+ tabs.push(PaneNavTab {+ rect,+ pane_id: entry.pane_id,+ label,+ active: entry.is_active,+ close,+ });+ x = x.saturating_add(width);+ }++ Some(PaneNav {+ rect: bar,+ tabs,+ tools,+ })+}++fn clipped_split_rect(+ area: Rect,+ left: usize,+ top: usize,+ size: usize,+ direction: SplitDirection,+) -> Option<Rect> {+ let left = left.min(area.width as usize);+ let top = top.min(area.height as usize);+ let remaining_width = area.width as usize - left;+ let remaining_height = area.height as usize - top;+ if remaining_width == 0 || remaining_height == 0 || size == 0 {+ return None;+ }++ let (width, height) = match direction {+ SplitDirection::Horizontal => (1, size.min(remaining_height)),+ SplitDirection::Vertical => (size.min(remaining_width), 1),+ };+ Some(Rect::new(+ area.x.saturating_add(left as u16),+ area.y.saturating_add(top as u16),+ width as u16,+ height as u16,+ ))+}++fn compute_overlays(ui: &UiState, view: &mut ViewLayout) {+ if let Some(menu) = &ui.context_menu {+ let width = menu+ .entries+ .iter()+ .map(|entry| unicode_column_width(&entry.label, None) as u16 + 4)+ .max()+ .unwrap_or(12)+ .clamp(12, view.screen.width.max(12));+ let height = (menu.entries.len() as u16 + 2).min(view.screen.height);+ let x = menu.anchor.0.min(view.screen.right().saturating_sub(width));+ let y = menu+ .anchor+ .1+ .min(view.screen.bottom().saturating_sub(height));+ let rect = Rect::new(x, y, width, height);+ view.context_menu = Some(rect);+ for (index, _) in menu.entries.iter().enumerate() {+ let row = rect.y.saturating_add(1 + index as u16);+ if row >= rect.bottom().saturating_sub(1) {+ break;+ }+ view.hits.push(HitRegion {+ rect: Rect::new(rect.x + 1, row, rect.width.saturating_sub(2), 1),+ target: HitTarget::ContextMenu(index),+ });+ }+ }++ if ui.mode == crate::state::AppMode::Connections {+ let width = view.screen.width.saturating_sub(4).clamp(1, 72);+ let height = (ui.connections.len() as u16 + 4)+ .min(view.screen.height.saturating_sub(2).max(1))+ .max(5.min(view.screen.height));+ let rect = Rect::new(+ view.screen.x + view.screen.width.saturating_sub(width) / 2,+ view.screen.y + view.screen.height.saturating_sub(height) / 2,+ width,+ height,+ );+ view.dialog = Some(rect);+ for (index, _) in ui.connections.iter().enumerate() {+ let row = rect.y.saturating_add(2 + index as u16);+ if row >= rect.bottom().saturating_sub(1) {+ break;+ }+ view.hits.push(HitRegion {+ rect: Rect::new(rect.x + 1, row, rect.width.saturating_sub(2), 1),+ target: HitTarget::Connection(index),+ });+ }+ } else if ui.mode == crate::state::AppMode::Settings {+ let width = view.screen.width.saturating_sub(4).clamp(1, 64);+ let height = 10.min(view.screen.height.saturating_sub(2).max(1));+ let rect = Rect::new(+ view.screen.x + view.screen.width.saturating_sub(width) / 2,+ view.screen.y + view.screen.height.saturating_sub(height) / 2,+ width,+ height,+ );+ view.dialog = Some(rect);+ for index in 0..5 {+ let row = rect.y.saturating_add(2 + index as u16);+ if row < rect.bottom().saturating_sub(1) {+ view.hits.push(HitRegion {+ rect: Rect::new(rect.x + 1, row, rect.width.saturating_sub(2), 1),+ target: HitTarget::Setting(index),+ });+ }+ }+ } else if ui.prompt.is_some() || ui.confirmation.is_some() {+ let width = view.screen.width.saturating_sub(4).clamp(1, 64);+ let height = if ui.confirmation.is_some() { 8 } else { 6 }+ .min(view.screen.height.saturating_sub(2).max(1));+ let rect = Rect::new(+ view.screen.x + view.screen.width.saturating_sub(width) / 2,+ view.screen.y + view.screen.height.saturating_sub(height) / 2,+ width,+ height,+ );+ view.dialog = Some(rect);+ if ui.confirmation.is_some() && rect.height >= 3 {+ let button_y = rect.bottom().saturating_sub(2);+ let half = rect.width.saturating_sub(2) / 2;+ view.hits.push(HitRegion {+ rect: Rect::new(rect.x + 1, button_y, half, 1),+ target: HitTarget::DialogConfirm,+ });+ view.hits.push(HitRegion {+ rect: Rect::new(rect.x + 1 + half, button_y, rect.width - 2 - half, 1),+ target: HitTarget::DialogCancel,+ });+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::state::{ConnectionItem, ConnectionStatus};+ use codec::{ThinkTermSessionProject, ThinkTermSessionSpace, ThinkTermSessionState};++ fn stack(titles: &[&str], active: usize) -> Vec<PaneStackTab> {+ titles+ .iter()+ .enumerate()+ .map(|(index, title)| PaneStackTab {+ pane_id: index + 1,+ title: (*title).to_string(),+ is_active: index == active,+ })+ .collect()+ }++ fn nav(rect: Rect, stack: &[PaneStackTab], zoomed: bool, touch: bool) -> (PaneNav, ViewLayout) {+ let mut view = ViewLayout::default();+ let nav = compute_pane_nav(1, stack, zoomed, true, touch, rect, &mut view)+ .expect("a pane this size has room for its own bar");+ (nav, view)+ }++ #[test]+ fn a_pane_bar_carries_its_stack_on_the_left_and_its_tools_on_the_right() {+ let (bar, view) = nav(+ Rect::new(0, 0, 60, 20),+ &stack(&["shell", "vim"], 0),+ false,+ false,+ );+ assert_eq!(bar.rect, Rect::new(0, 0, 60, 1), "one row, full width");++ let tools = bar.tools.iter().map(|(_, t)| *t).collect::<Vec<_>>();+ assert_eq!(+ tools,+ vec![+ PaneTool::Zoom { zoomed: false },+ PaneTool::SplitRight,+ PaneTool::SplitDown,+ PaneTool::NewTab,+ ],+ "drawn left to right in a fixed order"+ );+ assert!(+ bar.tools.windows(2).all(|w| w[0].0.x < w[1].0.x),+ "and positioned in that order"+ );++ assert_eq!(bar.tabs.len(), 2);+ assert!(bar.tabs[0].rect.right() <= bar.tabs[1].rect.x);+ assert!(+ bar.tabs[1].rect.right() <= bar.tools[0].0.x,+ "stack tabs stop where the tools begin"+ );++ // Every terminal in the stack offers to close, not only the one showing.+ assert!(bar.tabs[0].active && bar.tabs[0].close.is_some());+ assert!(!bar.tabs[1].active && bar.tabs[1].close.is_some());++ let close = bar.tabs[0].close.unwrap();+ assert_eq!(+ view.hit(close.x, close.y),+ Some(&HitTarget::PaneNavClose(1)),+ "the close button wins over the tab it sits in"+ );+ assert_eq!(+ view.hit(bar.tabs[1].rect.x, 0),+ Some(&HitTarget::PaneNavTab(2)),+ "and the pane behind is one tap away"+ );+ for (rect, tool) in &bar.tools {+ assert_eq!(+ view.hit(rect.x, rect.y),+ Some(&HitTarget::PaneTool(1, *tool))+ );+ }+ }++ #[test]+ fn a_narrowing_pane_keeps_zoom_longest_and_drops_the_splits_first() {+ let entries = stack(&["shell"], 0);+ let kept = |width: u16| {+ nav(Rect::new(0, 0, width, 20), &entries, false, false)+ .0+ .tools+ .iter()+ .map(|(_, tool)| *tool)+ .collect::<Vec<_>>()+ };+ let zoom = PaneTool::Zoom { zoomed: false };+ assert_eq!(+ kept(60),+ vec![+ zoom,+ PaneTool::SplitRight,+ PaneTool::SplitDown,+ PaneTool::NewTab+ ]+ );+ assert_eq!(kept(19), vec![zoom, PaneTool::SplitRight, PaneTool::NewTab]);+ assert_eq!(kept(17), vec![zoom, PaneTool::NewTab]);+ assert_eq!(kept(15), vec![zoom]);+ assert_eq!(kept(13), Vec::new());+ }++ #[test]+ fn the_zoom_button_says_which_way_it_goes() {+ let entries = stack(&["shell"], 0);+ let glyph = |zoomed| {+ nav(Rect::new(0, 0, 60, 20), &entries, zoomed, false)+ .0+ .tools[0]+ .1+ .glyph()+ };+ assert_eq!(glyph(false), "⤢");+ assert_eq!(glyph(true), "⤡");+ }++ #[test]+ fn a_pane_with_no_row_to_spare_keeps_all_of_them_for_its_grid() {+ let entries = stack(&["shell"], 0);+ let mut view = ViewLayout::default();+ assert!(+ compute_pane_nav(+ 1,+ &entries,+ false,+ true,+ false,+ Rect::new(0, 0, 60, 2),+ &mut view+ )+ .is_none(),+ "a pane with no grid left to speak of goes without"+ );++ assert!(+ compute_pane_nav(+ 1,+ &entries,+ false,+ true,+ false,+ Rect::new(0, 0, 11, 20),+ &mut view+ )+ .is_none(),+ "and so does one with no room for a name"+ );+ assert!(+ compute_pane_nav(+ 1,+ &entries,+ false,+ false,+ false,+ Rect::new(0, 0, 60, 20),+ &mut view+ )+ .is_none(),+ "turning it off leaves nothing behind"+ );+ assert!(view.hits.is_empty(), "and no targets either");++ // The short half of a split is exactly the pane that used to lose its+ // bar, and with it every control it had.+ let mut short = ViewLayout::default();+ assert!(+ compute_pane_nav(+ 1,+ &entries,+ false,+ true,+ false,+ Rect::new(0, 0, 60, 7),+ &mut short+ )+ .is_some(),+ "a seven-row pane keeps its controls"+ );+ }++ #[test]+ fn touch_targets_widen_the_pane_buttons_without_costing_a_second_row() {+ let entries = stack(&["shell"], 0);+ let (mouse, _) = nav(Rect::new(0, 0, 60, 20), &entries, false, false);+ let (touch, _) = nav(Rect::new(0, 0, 60, 20), &entries, false, true);+ assert_eq!(mouse.rect.height, 1);+ assert_eq!(touch.rect.height, 1);+ assert_eq!(mouse.tools[0].0.width, 2);+ assert_eq!(touch.tools[0].0.width, 3);+ }++ fn model_with_threads() -> AppModel {+ let mut model = AppModel::default();+ model.apply_snapshot(+ "server",+ ThinkTermSessionState {+ server_id: "runtime".into(),+ generation: 1,+ spaces: vec![ThinkTermSessionSpace {+ id: "space".into(),+ name: "Space".into(),+ ..Default::default()+ }],+ projects: vec![ThinkTermSessionProject {+ id: "project".into(),+ space_id: "space".into(),+ name: "Project".into(),+ threads: ["Thread 1", "Thread 2", "Thread 3"]+ .into_iter()+ .enumerate()+ .map(|(index, name)| codec::ThinkTermSessionThread {+ id: format!("t{index}"),+ project_id: "project".into(),+ name: name.into(),+ ..Default::default()+ })+ .collect(),+ ..Default::default()+ }],+ ..Default::default()+ },+ );+ model+ }++ #[test]+ fn view_classes_are_deterministic() {+ assert_eq!(classify(64, 64), ViewClass::Narrow);+ assert_eq!(classify(65, 64), ViewClass::Compact);+ assert_eq!(classify(87, 64), ViewClass::Compact);+ assert_eq!(classify(88, 64), ViewClass::Desktop);+ }++ /// A phone reporting 88 columns is not a desktop, and the only way to say+ /// so is to raise the threshold; the classes have to move with it.+ #[test]+ fn raising_the_narrow_threshold_moves_every_class_with_it() {+ assert_eq!(classify(88, 64), ViewClass::Desktop);+ assert_eq!(classify(88, 90), ViewClass::Narrow);+ assert_eq!(classify(100, 90), ViewClass::Compact);+ assert_eq!(classify(114, 90), ViewClass::Desktop);+ }++ #[test]+ fn top_bar_exposes_new_tab_and_main_menu_mouse_targets() {+ let model = model_with_threads();+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);+ assert_eq!(+ view.hit(98, 0),+ Some(&HitTarget::TabControl(TabBarControl::Menu))+ );+ assert_eq!(+ view.hit(95, 0),+ Some(&HitTarget::TabControl(TabBarControl::NewTab))+ );+ assert_eq!(view.hit(1, 0), Some(&HitTarget::SidebarToggle));+ }++ #[test]+ fn every_settings_row_has_an_exact_modal_hit() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.mode = crate::state::AppMode::Settings;+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);+ let dialog = view.dialog.unwrap();+ for index in 0..5 {+ assert_eq!(+ view.hit(dialog.x + 2, dialog.y + 2 + index as u16),+ Some(&HitTarget::Setting(index))+ );+ }+ }++ #[test]+ fn each_thread_row_hits_only_its_own_stable_id() {+ let model = model_with_threads();+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);+ let threads = view+ .tree_lines+ .iter()+ .filter(|line| matches!(line.key, TreeNodeKey::Thread(_)))+ .collect::<Vec<_>>();+ assert_eq!(threads.len(), 3);+ for (index, line) in threads.iter().enumerate() {+ // Probe the name, not the far edge: the row's right-hand columns+ // now belong to its own buttons.+ let hit = view.hit(line.rect.x, line.rect.y);+ let HitTarget::Tree(TreeNodeKey::Thread(key)) = hit.unwrap() else {+ panic!("thread row did not resolve to a thread target")+ };+ assert_eq!(key.thread_id, format!("t{index}"));+ }+ }++ /// The commands that used to need a right click — which a touchscreen does+ /// not have — are now on the row itself. Only the row being worked on+ /// carries them, so the list stays a list.+ #[test]+ fn every_row_offers_the_same_commands_as_buttons() {+ let model = model_with_threads();+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);++ for line in &view.tree_lines {+ let expected = match &line.key {+ TreeNodeKey::Domain(_) | TreeNodeKey::Thread(_) => vec![TreeAction::Menu],+ TreeNodeKey::Space { .. } | TreeNodeKey::Project { .. } => {+ vec![TreeAction::Add, TreeAction::Menu]+ }+ };+ assert_eq!(+ line.actions.iter().map(|(_, a)| *a).collect::<Vec<_>>(),+ expected,+ "{}: the same buttons whether or not it is selected",+ line.label+ );+ for (rect, action) in &line.actions {+ assert_eq!(+ view.hit(rect.x, rect.y),+ Some(&HitTarget::TreeAction(line.key.clone(), *action))+ );+ }+ }+ assert_eq!(+ view.tree_lines.iter().filter(|line| line.selected).count(),+ 1,+ "exactly one row is being worked on"+ );+ }++ #[test]+ fn the_tree_is_headed_by_the_one_command_that_belongs_to_all_of_it() {+ let model = model_with_threads();+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);++ let heading = view.sidebar_heading.expect("a tall sidebar gets a heading");+ let add = view.sidebar_new_project.expect("and an add-project button");+ assert_eq!(heading.height, 1);+ assert_eq!(add.right(), heading.right(), "the button sits on its right");+ assert_eq!(view.hit(add.x, add.y), Some(&HitTarget::NewProject));++ let body = view.sidebar_body.expect("the tree still has a body");+ assert_eq!(+ body.y,+ heading.bottom(),+ "the tree starts below the heading"+ );+ assert!(+ view.tree_lines.iter().all(|line| line.rect.y >= body.y),+ "and no row is drawn over it"+ );+ assert_eq!(+ view.hit(heading.x, heading.y),+ None,+ "the heading is a label"+ );+ }++ /// A pinned thread has to look pinned from across the list, selected or+ /// not. Nothing else on the row claims ★ now, so it can only mean one thing.+ #[test]+ fn pinning_is_marked_on_every_row_that_is_pinned() {+ let mut model = AppModel::default();+ model.apply_snapshot(+ "server",+ ThinkTermSessionState {+ server_id: "runtime".into(),+ generation: 1,+ spaces: vec![ThinkTermSessionSpace {+ id: "space".into(),+ name: "Space".into(),+ ..Default::default()+ }],+ projects: vec![ThinkTermSessionProject {+ id: "project".into(),+ space_id: "space".into(),+ name: "Project".into(),+ threads: ["one", "two"]+ .into_iter()+ .map(|id| codec::ThinkTermSessionThread {+ id: id.into(),+ project_id: "project".into(),+ name: id.into(),+ is_pinned: true,+ ..Default::default()+ })+ .collect(),+ ..Default::default()+ }],+ ..Default::default()+ },+ );+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);++ let threads = view+ .tree_lines+ .iter()+ .filter(|line| matches!(line.key, TreeNodeKey::Thread(_)))+ .collect::<Vec<_>>();+ assert_eq!(threads.len(), 2);+ assert!(+ threads.iter().all(|line| line.pinned),+ "both threads are pinned, so both say so"+ );+ }++ /// A button that covers the name it belongs to is worse than no button, so+ /// even at the narrowest sidebar the row keeps its reading space.+ #[test]+ fn buttons_never_eat_into_the_space_a_name_needs() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_width = 18;+ let view = compute_view(Rect::new(0, 0, 46, 30), &model, &ui, None);+ let body = view.sidebar_body.expect("a sidebar");+ for line in &view.tree_lines {+ let leftmost = line+ .actions+ .iter()+ .map(|(rect, _)| rect.x)+ .min()+ .unwrap_or(line.rect.right());+ assert!(+ leftmost.saturating_sub(body.x) >= MIN_LABEL_COLUMNS,+ "{:?} left only {} columns for its name",+ line.key,+ leftmost - body.x+ );+ }+ }++ #[test]+ fn only_the_active_thread_is_painted_as_selected() {+ let model = model_with_threads();+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);+ let selected = view+ .tree_lines+ .iter()+ .filter(|line| line.selected)+ .collect::<Vec<_>>();+ assert_eq!(selected.len(), 1);+ assert!(matches!(selected[0].key, TreeNodeKey::Thread(_)));+ }++ #[test]+ fn narrow_view_gives_the_terminal_every_column_once_the_tree_is_dismissed() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_visible = false;+ let view = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(view.class, ViewClass::Narrow);+ assert!(view.sidebar.is_none());+ assert!(view.tree_lines.is_empty());+ assert_eq!(view.hit(1, 0), Some(&HitTarget::SidebarToggle));+ // Two rows of header, and no footer at all while there is nothing to+ // say: the terminal keeps the row the key-chord hint used to hold.+ assert_eq!(view.content, Rect::new(0, 2, 40, 18));+ }++ /// Every button on a touch screen is worth two rows, and a finger that+ /// misses by one row must still land on the thing it aimed at.+ #[test]+ fn narrow_view_gives_every_button_the_full_height_of_a_two_row_bar() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_visible = false;+ let view = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(view.tab_bar.height, 2);+ for row in 0..2 {+ assert_eq!(+ view.hit(1, row),+ Some(&HitTarget::SidebarToggle),+ "row {row}"+ );+ assert_eq!(+ view.hit(37, row),+ Some(&HitTarget::TabControl(TabBarControl::Menu)),+ "row {row}"+ );+ assert_eq!(+ view.hit(33, row),+ Some(&HitTarget::TabControl(TabBarControl::NewTab)),+ "row {row}"+ );+ }+ // The toggle is wider here than the four columns a mouse gets.+ assert_eq!(view.hit(5, 1), Some(&HitTarget::SidebarToggle));+ }++ /// The same phone turned sideways reports enough columns to look like a+ /// desktop and still has no mouse, so the setting has to beat the guess in+ /// both directions.+ #[test]+ fn touch_targets_follow_the_setting_rather_than_the_width() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_visible = false;++ // Wide enough to be a desktop by every other measure.+ let wide = Rect::new(0, 0, 154, 32);+ assert_eq!(+ compute_view(wide, &model, &ui, None).class,+ ViewClass::Desktop+ );+ assert_eq!(compute_view(wide, &model, &ui, None).tab_bar.height, 1);+ ui.touch_targets = Some(true);+ let touched = compute_view(wide, &model, &ui, None);+ assert_eq!(touched.tab_bar.height, 2);+ assert_eq!(touched.hit(1, 1), Some(&HitTarget::SidebarToggle));++ // ...and a narrow screen driven by a mouse gets the compact bar back.+ ui.touch_targets = Some(false);+ let narrow = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(narrow.class, ViewClass::Narrow);+ assert_eq!(narrow.tab_bar.height, 1);+ }++ /// A message still needs somewhere to go; it just does not get to keep a+ /// row of the terminal when there is nothing to report.+ #[test]+ fn narrow_view_reclaims_the_footer_row_only_while_it_is_empty() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_visible = false;+ let quiet = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(quiet.status.height, 0);++ ui.status = "Viewport: something went wrong".to_string();+ let noisy = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(noisy.status.height, 1);+ assert_eq!(noisy.content.height, quiet.content.height - 1);+ }++ /// The toggle used to sit on a narrow screen with nothing to toggle: the+ /// tree was refused at that width, so there was no way to reach another+ /// thread from a phone. Asking for it now covers the screen with it.+ /// Zooming a phone in until the screen is narrow, with the tree dismissed,+ /// is the ordinary way it is used — and it left the terminal undrawn: a tab+ /// bar over an empty screen.+ #[test]+ fn a_narrow_screen_with_the_tree_dismissed_still_draws_its_terminal() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_visible = false;+ let view = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(view.class, ViewClass::Narrow);+ assert!(view.sidebar.is_none(), "the tree was dismissed");+ assert!(+ !tree_covers_terminal(&view),+ "so it is not covering anything"+ );+ assert_eq!(view.content.width, 40, "and the terminal has the screen");++ let mut covered = view.clone();+ covered.sidebar = Some(Rect::new(0, 0, 40, 20));+ assert!(tree_covers_terminal(&covered));+ covered.class = ViewClass::Desktop;+ assert!(!tree_covers_terminal(&covered), "beside, not on top");+ }++ #[test]+ fn narrow_view_shows_the_tree_as_a_full_width_overlay_when_asked() {+ let model = model_with_threads();+ let ui = UiState::new(String::new());+ let view = compute_view(Rect::new(0, 0, 40, 20), &model, &ui, None);+ assert_eq!(view.class, ViewClass::Narrow);+ assert_eq!(view.sidebar, Some(Rect::new(0, 0, 40, 20)));+ assert!(!view.tree_lines.is_empty());+ assert!(view.panes.is_empty(), "the tree is over the top of them");+ // But the grid the terminal has is still described, so a phone held in+ // portrait can take the size from whatever else is attached rather than+ // reading as a renderer with no viewport at all.+ assert_eq!(view.content.width, 40);+ assert!(view.sidebar_resize.is_none());+ assert_eq!(view.hit(1, 0), Some(&HitTarget::SidebarToggle));+ }++ #[test]+ fn hidden_sidebar_returns_all_content_columns_and_keeps_a_toggle() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.sidebar_visible = false;+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);+ assert!(view.sidebar.is_none());+ assert_eq!(view.content, Rect::new(0, 1, 100, 28));+ assert_eq!(view.hit(1, 0), Some(&HitTarget::SidebarToggle));+ assert!(view.tabs.iter().all(|tab| tab.rect.x >= 4));+ }++ #[test]+ fn connection_rows_have_exact_overlay_hits() {+ let model = model_with_threads();+ let mut ui = UiState::new(String::new());+ ui.mode = crate::state::AppMode::Connections;+ ui.connections = (0..3)+ .map(|index| ConnectionItem {+ name: format!("server-{index}"),+ label: format!("Server {index}"),+ detail: String::new(),+ status: ConnectionStatus::Disconnected,+ connectable: true,+ })+ .collect();+ let view = compute_view(Rect::new(0, 0, 100, 30), &model, &ui, None);+ let dialog = view.dialog.unwrap();+ for index in 0..3 {+ assert_eq!(+ view.hit(dialog.x + 2, dialog.y + 2 + index as u16),+ Some(&HitTarget::Connection(index))+ );+ }+ }++ #[test]+ fn split_rectangles_are_clipped_to_the_remaining_viewport() {+ let area = Rect::new(10, 5, 20, 8);+ let horizontal = clipped_split_rect(area, 19, 6, 8, SplitDirection::Horizontal).unwrap();+ assert!(horizontal.right() <= area.right());+ assert!(horizontal.bottom() <= area.bottom());++ let vertical = clipped_split_rect(area, 16, 7, 20, SplitDirection::Vertical).unwrap();+ assert!(vertical.right() <= area.right());+ assert!(vertical.bottom() <= area.bottom());++ assert!(clipped_split_rect(area, 20, 0, 8, SplitDirection::Horizontal).is_none());+ assert!(clipped_split_rect(area, 0, 8, 8, SplitDirection::Vertical).is_none());+ }+}diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rsindex 6ab2a1c0..701fa9d6 100644--- a/wezterm-client/src/client.rs+++ b/wezterm-client/src/client.rs@@ -30,14 +30,16 @@ use std::os::unix::process::CommandExt;#[cfg(windows)]use std::os::windows::io::{AsRawSocket, AsSocket, BorrowedSocket, RawSocket};use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::mpsc::channel;-use std::sync::Arc;+use std::sync::{Arc, RwLock};use std::thread;use std::time::Duration;use thiserror::Error;use wezterm_uds::UnixStream;+static NEXT_CONNECTION_GENERATION: AtomicU64 = AtomicU64::new(1);+#[derive(Error, Debug)]#[error("Timeout")]struct Timeout;@@ -76,6 +78,11 @@ pub struct Client {/// button.reconnect_suspended: Arc<AtomicBool>,resume_reconnect_tx: std::sync::mpsc::Sender<()>,+ remote_server_id: Arc<RwLock<Option<String>>>,+ /// Process-unique identity of the currently attached transport. A+ /// reconnect gets a fresh value so queued unilateral messages from the+ /// superseded reader cannot be mistaken for current server state.+ connection_generation: Arc<AtomicU64>,}impl Client {@@ -91,6 +98,14 @@ impl Client {pub fn resume_reconnect(&self) {let _ = self.resume_reconnect_tx.send(());}++ pub fn remote_server_id(&self) -> Option<String> {+ self.remote_server_id.read().unwrap().clone()+ }++ pub fn connection_generation(&self) -> u64 {+ self.connection_generation.load(Ordering::Acquire)+ }}#[derive(Error, Debug, Clone, PartialEq, Eq)]@@ -225,6 +240,7 @@ async fn process_unilateral_inner_async(fn process_unilateral(local_domain_id: Option<DomainId>,+ connection_generation: u64,decoded: DecodedPdu,) -> anyhow::Result<()> {let local_domain_id = match local_domain_id {@@ -347,6 +363,46 @@ fn process_unilateral(.detach();return Ok(());}+ Pdu::ThinkTermSessionState(_) => {+ let Pdu::ThinkTermSessionState(state) = decoded.pdu else {+ unreachable!("matched ThinkTermSessionState above");+ };+ promise::spawn::spawn_into_main_thread(async move {+ let mux = Mux::try_get().ok_or_else(|| anyhow!("no more mux"))?;+ let domain = mux+ .get_domain(local_domain_id)+ .ok_or_else(|| anyhow!("no such domain {}", local_domain_id))?;+ crate::domain::deliver_thinkterm_session(+ domain.domain_name(),+ connection_generation,+ state,+ );+ anyhow::Result::<()>::Ok(())+ })+ .detach();+ return Ok(());+ }+ Pdu::ClientViewportState(_) => {+ let Pdu::ClientViewportState(state) = decoded.pdu else {+ unreachable!("matched ClientViewportState above");+ };+ promise::spawn::spawn_into_main_thread(async move {+ let mux = Mux::try_get().ok_or_else(|| anyhow!("no more mux"))?;+ let domain = mux+ .get_domain(local_domain_id)+ .ok_or_else(|| anyhow!("no such domain {}", local_domain_id))?;+ let domain = domain+ .downcast_ref::<ClientDomain>()+ .ok_or_else(|| anyhow!("domain {} is not a ClientDomain", local_domain_id))?;+ if domain.connection_generation() != Some(connection_generation) {+ return Ok(());+ }+ domain.process_remote_viewport_state(state);+ anyhow::Result::<()>::Ok(())+ })+ .detach();+ return Ok(());+ }Pdu::TabResized(_) | Pdu::TabAddedToWindow(_) => {log::trace!("resync due to {:?}", decoded.pdu);promise::spawn::spawn_into_main_thread(async move {@@ -390,14 +446,21 @@ enum NotReconnectableError {fn client_thread(reconnectable: &mut Reconnectable,local_domain_id: Option<DomainId>,+ connection_generation: u64,rx: &mut Receiver<ReaderMessage>,) -> anyhow::Result<()> {- block_on(client_thread_async(reconnectable, local_domain_id, rx))+ block_on(client_thread_async(+ reconnectable,+ local_domain_id,+ connection_generation,+ rx,+ ))}async fn client_thread_async(reconnectable: &mut Reconnectable,local_domain_id: Option<DomainId>,+ connection_generation: u64,rx: &mut Receiver<ReaderMessage>,) -> anyhow::Result<()> {let mut next_serial = 1u64;@@ -476,6 +539,7 @@ async fn client_thread_async(Ok(ReaderMessage::Readable) => {match Pdu::decode_async(&mut stream, Some(next_serial)).await {Ok(decoded) => {+ crate::domain::wake_thinkterm_frontend();log::debug!("decoded serial {} {}",decoded.serial,@@ -484,7 +548,7 @@ async fn client_thread_async(if pending_ping.map_or(false, |(serial, _)| serial == decoded.serial) {pending_ping = None;} else if decoded.serial == 0 {- process_unilateral(local_domain_id, decoded)+ process_unilateral(local_domain_id, connection_generation, decoded).context("processing unilateral PDU from server").map_err(|e| {log::error!("process_unilateral: {:?}", e);@@ -1150,6 +1214,9 @@ impl Client {let reconnect_suspended = Arc::new(AtomicBool::new(false));let suspended_flag = Arc::clone(&reconnect_suspended);let (resume_reconnect_tx, resume_reconnect_rx) = channel::<()>();+ let remote_server_id = Arc::new(RwLock::new(None));+ let connection_generation = Arc::new(AtomicU64::new(0));+ let reader_connection_generation = Arc::clone(&connection_generation);thread::spawn(move || {const BASE_INTERVAL: Duration = Duration::from_secs(1);@@ -1177,7 +1244,14 @@ impl Client {'client: loop {let session_started = std::time::Instant::now();- if let Err(e) = client_thread(&mut reconnectable, local_domain_id, &mut receiver) {+ let generation = NEXT_CONNECTION_GENERATION.fetch_add(1, Ordering::AcqRel);+ reader_connection_generation.store(generation, Ordering::Release);+ if let Err(e) = client_thread(+ &mut reconnectable,+ local_domain_id,+ generation,+ &mut receiver,+ ) {if !reconnectable.reconnectable() || local_domain_id.is_none() {log::debug!("client thread ended: {}", e);break;@@ -1339,6 +1413,7 @@ impl Client {.ok();}).detach();+ crate::domain::wake_thinkterm_frontend();break;}Err(err) => {@@ -1426,6 +1501,8 @@ impl Client {is_reconnecting,reconnect_suspended,resume_reconnect_tx,+ remote_server_id,+ connection_generation,}}@@ -1456,6 +1533,7 @@ impl Client {is_proxy: false,}).await?;+ *self.remote_server_id.write().unwrap() = Some(info.server_id.clone());Ok(info)}Ok(info) => {@@ -1507,7 +1585,7 @@ impl Client {self.local_domain_id}- fn compute_unix_domain(+ pub fn resolve_default_unix_domain(prefer_mux: bool,class_name: &str,) -> anyhow::Result<config::UnixDomain> {@@ -1549,7 +1627,7 @@ impl Client {prefer_mux: bool,class_name: &str,) -> anyhow::Result<Self> {- let unix_dom = Self::compute_unix_domain(prefer_mux, class_name)?;+ let unix_dom = Self::resolve_default_unix_domain(prefer_mux, class_name)?;Self::new_unix_domain(None, &unix_dom, initial, ui, no_auto_start)}@@ -1649,6 +1727,23 @@ impl Client {MutateThinkTermTree,ThinkTermTreeState);+ rpc!(+ get_thinkterm_session_state,+ GetThinkTermSessionState = (),+ ThinkTermSessionState+ );+ rpc!(+ ensure_thinkterm_thread,+ EnsureThinkTermThread,+ EnsureThinkTermThreadResponse+ );+ rpc!(set_client_viewport, SetClientViewport, ClientViewportState);+ rpc!(set_client_view, SetClientView, UnitResponse);+ rpc!(+ claim_client_viewport,+ ClaimClientViewport,+ ClientViewportState+ );rpc!(write_to_pane, WriteToPane, UnitResponse);rpc!(send_paste, SendPaste, UnitResponse);rpc!(key_down, SendKeyDown, UnitResponse);@@ -1711,7 +1806,7 @@ mod tests {#[test]fn remote_mux_command_defaults_to_thinkterm_with_wezterm_fallback() {let cmd = Reconnectable::remote_mux_command(&None, "cli --prefer-mux proxy");- assert!(cmd.contains("thinkterm cli --prefer-mux proxy"), "{cmd}");- assert!(cmd.contains("wezterm cli --prefer-mux proxy"), "{cmd}");+ assert!(cmd.contains("thinkterm cli --prefer-mux proxy"), "{}", cmd);+ assert!(cmd.contains("wezterm cli --prefer-mux proxy"), "{}", cmd);}}diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex 52e9bf57..751f9d09 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -25,6 +25,8 @@ pub struct ClientInner {remote_to_local_window: Mutex<HashMap<WindowId, WindowId>>,remote_to_local_tab: Mutex<HashMap<TabId, TabId>>,remote_to_local_pane: Mutex<HashMap<PaneId, PaneId>>,+ /// Authoritative per-remote-tab viewport ownership pushed by the server.+ remote_viewports: Mutex<HashMap<TabId, codec::ClientViewportState>>,/// Remote pane-stack id -> stable local pane-stack id. Remote and local/// stack ids live in different id spaces; translating (rather than/// adopting) avoids collisions with locally-created stacks while keeping@@ -274,6 +276,38 @@ impl ClientInner {map.get(&remote_tab_id).copied()}+ fn update_remote_viewport(&self, state: codec::ClientViewportState) -> bool {+ let mut states = self.remote_viewports.lock().unwrap();+ if states+ .get(&state.tab_id)+ .is_some_and(|prior| prior.generation > state.generation)+ {+ return false;+ }+ states.insert(state.tab_id, state);+ true+ }++ pub fn remote_viewport_state(+ &self,+ remote_tab_id: TabId,+ ) -> Option<codec::ClientViewportState> {+ self.remote_viewports+ .lock()+ .unwrap()+ .get(&remote_tab_id)+ .cloned()+ }++ pub fn owns_remote_viewport(&self, remote_tab_id: TabId) -> Option<bool> {+ let state = self.remote_viewport_state(remote_tab_id)?;+ Some(state.owner.as_ref() == Some(&self.client.client_id))+ }++ fn clear_remote_viewports(&self) {+ self.remote_viewports.lock().unwrap().clear();+ }+pub fn is_local(&self) -> bool {self.client.is_local}@@ -349,6 +383,7 @@ impl ClientInner {remote_to_local_window: Mutex::new(HashMap::new()),remote_to_local_tab: Mutex::new(HashMap::new()),remote_to_local_pane: Mutex::new(HashMap::new()),+ remote_viewports: Mutex::new(HashMap::new()),remote_to_local_stack: Mutex::new(HashMap::new()),focused_remote_pane_id: Mutex::new(None),focus_advised_at: Mutex::new(None),@@ -537,17 +572,30 @@ fn mux_notify_client_domain(local_domain_id: DomainId, notif: MuxNotification) -/// trees are dropped.pub type ThinkTermTreeSink = fn(domain_name: &str, tree: codec::ThinkTermTree);+/// Receives the authoritative tree-plus-live-topology view exported by one+/// mux server. Thin frontends keep it separate per client-domain name.+pub type ThinkTermSessionSink =+ fn(domain_name: &str, connection_generation: u64, state: codec::ThinkTermSessionState);+/// Announces a fresh connection to a server, before anything is asked of it.////// Trees do not carry which connection they belong to, and the client has to/// know: everything it believes about a server's tree describes the previous/// connection, and a server that comes back having lost or rolled back its own/// copy must be able to say so rather than be dismissed as out of date.-pub type ThinkTermConnectSink = fn(domain_name: &str);+pub type ThinkTermConnectSink = fn(domain_name: &str, connection_generation: u64);++/// Wakes a blocking thin frontend as soon as the transport reader receives+/// anything. The actual PDU is still processed on the main-thread executor;+/// this hook only breaks the frontend out of `poll_input(None)` so that the+/// executor can run without a fixed polling timer.+pub type ThinkTermFrontendWakeSink = fn();lazy_static::lazy_static! {static ref THINKTERM_TREE_SINK: Mutex<Option<ThinkTermTreeSink>> = Mutex::new(None);static ref THINKTERM_CONNECT_SINK: Mutex<Option<ThinkTermConnectSink>> = Mutex::new(None);+ static ref THINKTERM_SESSION_SINK: Mutex<Option<ThinkTermSessionSink>> = Mutex::new(None);+ static ref THINKTERM_FRONTEND_WAKE_SINK: Mutex<Option<ThinkTermFrontendWakeSink>> = Mutex::new(None);}pub fn set_thinkterm_tree_sink(sink: ThinkTermTreeSink) {@@ -558,6 +606,21 @@ pub fn set_thinkterm_connect_sink(sink: ThinkTermConnectSink) {THINKTERM_CONNECT_SINK.lock().unwrap().replace(sink);}+pub fn set_thinkterm_session_sink(sink: ThinkTermSessionSink) {+ THINKTERM_SESSION_SINK.lock().unwrap().replace(sink);+}++pub fn set_thinkterm_frontend_wake_sink(sink: ThinkTermFrontendWakeSink) {+ THINKTERM_FRONTEND_WAKE_SINK.lock().unwrap().replace(sink);+}++pub(crate) fn wake_thinkterm_frontend() {+ let sink = *THINKTERM_FRONTEND_WAKE_SINK.lock().unwrap();+ if let Some(sink) = sink {+ sink();+ }+}+pub(crate) fn deliver_thinkterm_tree(domain_name: &str, tree: codec::ThinkTermTree) {let sink = *THINKTERM_TREE_SINK.lock().unwrap();if let Some(sink) = sink {@@ -565,10 +628,21 @@ pub(crate) fn deliver_thinkterm_tree(domain_name: &str, tree: codec::ThinkTermTr}}-pub(crate) fn deliver_thinkterm_connected(domain_name: &str) {+pub(crate) fn deliver_thinkterm_connected(domain_name: &str, connection_generation: u64) {let sink = *THINKTERM_CONNECT_SINK.lock().unwrap();if let Some(sink) = sink {- sink(domain_name);+ sink(domain_name, connection_generation);+ }+}++pub(crate) fn deliver_thinkterm_session(+ domain_name: &str,+ connection_generation: u64,+ state: codec::ThinkTermSessionState,+) {+ let sink = *THINKTERM_SESSION_SINK.lock().unwrap();+ if let Some(sink) = sink {+ sink(domain_name, connection_generation, state);}}@@ -662,6 +736,57 @@ impl ClientDomain {inner.local_to_remote_tab(local_tab_id)}+ pub fn remote_to_local_tab_id(&self, remote_tab_id: TabId) -> Option<TabId> {+ let inner = self.inner()?;+ inner.remote_to_local_tab_id(remote_tab_id)+ }++ pub fn remote_server_id(&self) -> Option<String> {+ self.inner()?.client.remote_server_id()+ }++ pub fn connection_generation(&self) -> Option<u64> {+ Some(self.inner()?.client.connection_generation())+ }++ pub fn remote_viewport_state(&self, local_tab_id: TabId) -> Option<codec::ClientViewportState> {+ let inner = self.inner()?;+ let remote_tab_id = inner.local_to_remote_tab(local_tab_id)?;+ inner.remote_viewport_state(remote_tab_id)+ }++ pub fn owns_remote_viewport(&self, local_tab_id: TabId) -> Option<bool> {+ let inner = self.inner()?;+ let remote_tab_id = inner.local_to_remote_tab(local_tab_id)?;+ inner.owns_remote_viewport(remote_tab_id)+ }++ pub fn process_remote_viewport_state(&self, state: codec::ClientViewportState) {+ let Some(inner) = self.inner() else {+ return;+ };+ if !inner.update_remote_viewport(state.clone()) {+ return;+ }+ if let Some(local_tab_id) = inner.remote_to_local_tab_id(state.tab_id) {+ Mux::get().notify(MuxNotification::FrontendLeaseChanged(+ mux::FrontendViewportState {+ tab_id: local_tab_id,+ owner: state.owner,+ canonical_size: state.canonical_size,+ view: state.view.map(|view| mux::FrontendView {+ scroll: view+ .scroll+ .into_iter()+ .map(|entry| (entry.pane_id, entry.lines_from_bottom))+ .collect(),+ }),+ generation: state.generation,+ },+ ));+ }+ }+pub fn get_client_inner_for_domain(domain_id: DomainId) -> anyhow::Result<Arc<ClientInner>> {let mux = Mux::get();let domain = mux@@ -688,6 +813,7 @@ impl ClientDomain {/// to do everything a first attach does and not only re-pull the panes.pub async fn reattach(domain_id: DomainId, ui: ConnectionUI) -> anyhow::Result<()> {let inner = Self::get_client_inner_for_domain(domain_id)?;+ inner.clear_remote_viewports();let domain = Mux::get().get_domain(domain_id);// A reconnect begins a new connection generation. The revision@@ -699,7 +825,7 @@ impl ClientDomain {// the announcement is at worst dropped as stale and put right by that// same fetch.if let Some(domain) = &domain {- deliver_thinkterm_connected(domain.domain_name());+ deliver_thinkterm_connected(domain.domain_name(), inner.client.connection_generation());}let panes = inner.client.list_panes().await?;@@ -779,6 +905,144 @@ impl ClientDomain {Ok(())}+ /// Pull the mux server's authoritative tree-plus-live-topology view.+ pub async fn fetch_thinkterm_session_state(+ &self,+ ) -> anyhow::Result<codec::ThinkTermSessionState> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let state = inner.client.get_thinkterm_session_state().await?;+ deliver_thinkterm_session(+ self.config.name(),+ inner.client.connection_generation(),+ state.clone(),+ );+ Ok(state)+ }++ /// Ask the authoritative mux server to choose (or create) a landing+ /// Thread and ensure that its workspace contains a live terminal. The+ /// following resync installs the remote-to-local tab and pane mappings so+ /// callers can immediately render the returned Thread.+ pub async fn ensure_thinkterm_thread(+ &self,+ preferred_thread_id: Option<codec::TtThreadId>,+ size: wezterm_term::TerminalSize,+ ) -> anyhow::Result<codec::EnsureThinkTermThreadResponse> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let response = inner+ .client+ .ensure_thinkterm_thread(codec::EnsureThinkTermThread {+ preferred_thread_id,+ size,+ })+ .await?;+ self.resync().await?;+ Ok(response)+ }++ /// Report the viewport for a locally mirrored tab to the frontend mux.+ pub async fn set_client_viewport(+ &self,+ local_tab_id: TabId,+ viewport: codec::ClientViewport,+ ) -> anyhow::Result<codec::ClientViewportState> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let remote_tab_id = inner+ .local_to_remote_tab(local_tab_id)+ .ok_or_else(|| anyhow!("tab {local_tab_id} has no remote mapping"))?;+ let viewport = match viewport {+ codec::ClientViewport::CellGrid { size } => codec::ClientViewport::CellGrid { size },+ codec::ClientViewport::Native { size, panes } => {+ let mut remote_panes = Vec::with_capacity(panes.len());+ for pane in panes {+ let local = Mux::get()+ .get_pane(pane.pane_id)+ .ok_or_else(|| anyhow!("no such local pane {}", pane.pane_id))?;+ let remote = local+ .downcast_ref::<ClientPane>()+ .filter(|client| client.domain_id() == self.local_domain_id)+ .ok_or_else(|| {+ anyhow!("pane {} is not owned by this domain", pane.pane_id)+ })?+ .remote_pane_id();+ remote_panes.push(codec::ClientPaneViewport {+ pane_id: remote,+ size: pane.size,+ });+ }+ codec::ClientViewport::Native {+ size,+ panes: remote_panes,+ }+ }+ };+ let state = inner+ .client+ .set_client_viewport(codec::SetClientViewport {+ tab_id: remote_tab_id,+ viewport,+ })+ .await?;+ self.process_remote_viewport_state(state.clone());+ Ok(state)+ }++ /// Offer what this renderer is looking at, for other renderers on the same+ /// tab to follow. The server ignores it unless this client owns the tab's+ /// viewport, so it is safe to send whenever the view changes.+ /// `view` must already carry pane ids in the server's namespace — see+ /// `ClientPane::remote_pane_id`, which the caller has in hand while it is+ /// reading each pane's scroll position anyway.+ pub async fn set_client_view(+ &self,+ local_tab_id: TabId,+ view: codec::ClientView,+ ) -> anyhow::Result<()> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let remote_tab_id = inner+ .local_to_remote_tab(local_tab_id)+ .ok_or_else(|| anyhow!("tab {local_tab_id} has no remote mapping"))?;+ inner+ .client+ .set_client_view(codec::SetClientView {+ tab_id: remote_tab_id,+ view,+ })+ .await?;+ Ok(())+ }++ /// Claim a previously advertised viewport after a real frontend-only+ /// interaction (for example, dragging a split). The server chooses the+ /// owner and geometry and returns the authoritative result.+ pub async fn claim_client_viewport(+ &self,+ local_tab_id: TabId,+ ) -> anyhow::Result<codec::ClientViewportState> {+ let inner = self+ .inner()+ .ok_or_else(|| anyhow!("domain is not attached"))?;+ let remote_tab_id = inner+ .local_to_remote_tab(local_tab_id)+ .ok_or_else(|| anyhow!("tab {local_tab_id} has no remote mapping"))?;+ let state = inner+ .client+ .claim_client_viewport(codec::ClaimClientViewport {+ tab_id: remote_tab_id,+ })+ .await?;+ self.process_remote_viewport_state(state.clone());+ Ok(state)+ }+pub fn process_remote_window_title_change(&self, remote_window_id: WindowId, title: String) {if let Some(inner) = self.inner() {if let Some(local_window_id) = inner.remote_to_local_window(remote_window_id) {@@ -933,6 +1197,7 @@ impl ClientDomain {entry.pane_id,entry.size,&entry.title,+ entry.alt_screen,));mux.add_pane(&pane).expect("failed to add pane to mux");pane@@ -945,6 +1210,7 @@ impl ClientDomain {entry.pane_id,entry.size,&entry.title,+ entry.alt_screen,));log::debug!("domain: {} attaching to remote pane {:?} -> local pane_id {}",@@ -1206,6 +1472,7 @@ impl Domain for ClientDomain {result.pane_id,result.size,"thinkterm",+ false,));mux.add_pane(&pane)?;@@ -1394,6 +1661,7 @@ impl Domain for ClientDomain {result.pane_id,size,"thinkterm",+ false,));let tab = Arc::new(Tab::new(&size));tab.assign_pane(&pane);@@ -1571,6 +1839,7 @@ impl Domain for ClientDomain {result.pane_id,result.size,"thinkterm",+ false,));let pane_index = match tab@@ -1712,7 +1981,10 @@ impl ClientDomain {// Announce the new connection before asking it anything, so that the// answer — and any push that overtakes it — is measured against this// connection rather than the last one.- deliver_thinkterm_connected(self.config.name());+ let connection_generation = self+ .connection_generation()+ .ok_or_else(|| anyhow!("domain detached immediately after attach"))?;+ deliver_thinkterm_connected(self.config.name(), connection_generation);// The sidebar structure lives on the server. Fetching it is not worth// failing an otherwise-good attach over: without it the Space simplydiff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex efeb8115..b8419bd4 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -85,6 +85,25 @@ fn decide_resize(}}+fn decide_resize_for_viewport(+ owns_viewport: Option<bool>,+ last_requested: Option<TerminalSize>,+ dimensions: RenderableDimensions,+ target: TerminalSize,+) -> ResizeDecision {+ if owns_viewport != Some(true) {+ // A passive renderer shows the canonical server grid. Do not first+ // reflow locally and then get snapped back by the next server push.+ // `None` is not permission: it is the attach-time interval before the+ // server has answered the first viewport advertisement.+ return ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ };+ }+ decide_resize(last_requested, dimensions, target)+}+/// Delivery state of the palette advisory RPC.////// A single worker task owns all sending for a pane, and it always sends the@@ -177,6 +196,7 @@ pub struct ClientPane {mouse: Arc<Mutex<MouseState>>,clipboard: Mutex<Option<Arc<dyn Clipboard>>>,mouse_grabbed: Mutex<bool>,+ alt_screen: Mutex<bool>,requested_size: Mutex<Option<TerminalSize>>,ignore_next_kill: Mutex<bool>,user_vars: Mutex<HashMap<String, String>>,@@ -284,6 +304,7 @@ impl ClientPane {remote_pane_id: PaneId,size: TerminalSize,title: &str,+ alt_screen: bool,) -> Self {let local_pane_id = alloc_pane_id();let writer = PaneWriter {@@ -353,6 +374,7 @@ impl ClientPane {palette: Mutex::new(palette),clipboard: Mutex::new(None),mouse_grabbed: Mutex::new(false),+ alt_screen: Mutex::new(alt_screen),requested_size: Mutex::new(Some(size)),ignore_next_kill: Mutex::new(false),unseen_output: Mutex::new(false),@@ -366,6 +388,7 @@ impl ClientPane {match pdu {Pdu::GetPaneRenderChangesResponse(mut delta) => {*self.mouse_grabbed.lock() = delta.mouse_grabbed;+ *self.alt_screen.lock() = delta.alt_screen;let bonus_lines = std::mem::take(&mut delta.bonus_lines);let client = { Arc::clone(&self.renderable.lock().inner.borrow().client) };@@ -511,6 +534,14 @@ impl ClientPane {self.remote_tab_id.load(Ordering::Relaxed)}+ pub fn remote_viewport_state(&self) -> Option<codec::ClientViewportState> {+ self.client.remote_viewport_state(self.remote_tab_id())+ }++ pub fn owns_remote_viewport(&self) -> Option<bool> {+ self.client.owns_remote_viewport(self.remote_tab_id())+ }+pub(crate) fn set_remote_tab_id(&self, remote_tab_id: TabId) {self.remote_tab_id.store(remote_tab_id, Ordering::Relaxed);}@@ -642,6 +673,7 @@ impl Pane for ClientPane {}fn send_paste(&self, text: &str) -> anyhow::Result<()> {+ Mux::get().record_input_for_current_identity();let client = Arc::clone(&self.client);let remote_pane_id = self.remote_pane_id;self.renderable@@ -712,7 +744,16 @@ impl Pane for ClientPane {let render = self.renderable.lock();let mut inner = render.inner.borrow_mut();let advertised = inner.dimensions;- let decision = decide_resize(prior_requested, advertised, size);+ let decision = decide_resize_for_viewport(+ self.client.owns_remote_viewport(self.remote_tab_id()),+ prior_requested,+ advertised,+ size,+ );+ // A passive renderer displays the server's canonical grid. It+ // must neither reshape its local RenderableDimensions nor send a+ // resize that the server will reject; doing the former alone+ // creates a local/server invalidate loop and visible flicker.requested.replace(size);if decision.converge_local_surface {@@ -775,6 +816,7 @@ impl Pane for ClientPane {}fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> {+ Mux::get().record_input_for_current_identity();let input_serial;{let renderable = self.renderable.lock();@@ -849,6 +891,7 @@ impl Pane for ClientPane {}fn mouse_event(&self, event: MouseEvent) -> anyhow::Result<()> {+ Mux::get().record_input_for_current_identity();self.mouse.lock().append(event);if MouseState::next(Arc::clone(&self.mouse)) {self.renderable.lock().inner.borrow_mut().update_last_send();@@ -881,8 +924,7 @@ impl Pane for ClientPane {}fn is_alt_screen_active(&self) -> bool {- // FIXME: retrieve this from the remote- false+ *self.alt_screen.lock()}fn get_current_working_dir(&self, _policy: CachePolicy) -> Option<Url> {@@ -1098,6 +1140,40 @@ mod test {});}++ #[test]+ fn passive_different_sized_client_keeps_the_canonical_surface_stable() {+ let canonical = size(132, 40, 96);+ let passive_window = size(80, 24, 96);++ assert_eq!(+ decide_resize_for_viewport(+ Some(false),+ Some(passive_window),+ dimensions(canonical),+ passive_window,+ ),+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ },+ "a non-owner must neither publish nor locally reflow to its different window size"+ );+ }++ #[test]+ fn unknown_viewport_ownership_waits_for_the_server() {+ let canonical = size(132, 40, 96);+ let attaching_window = size(80, 24, 96);++ assert_eq!(+ decide_resize_for_viewport(None, None, dimensions(canonical), attaching_window,),+ ResizeDecision {+ converge_local_surface: false,+ send_rpc: false,+ }+ );+ }}#[cfg(test)]diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex c30a5cba..513e6cfe 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -99,6 +99,7 @@ textwrap.workspace = truethiserror.workspace = truetiny-skia.workspace = truethinkterm-syntax = { path = "../thinkterm-syntax" }+thinkterm-core.workspace = truetrash.workspace = trueumask.workspace = trueunicode-normalization.workspace = truediff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftlindex d421e5b8..0e8aa840 100644--- a/wezterm-gui/i18n/en-US.ftl+++ b/wezterm-gui/i18n/en-US.ftl@@ -90,6 +90,9 @@ settings-system-download-folder = Use the System Downloads Foldersettings-system-download-folder-description = Clears the chosen folder so downloads follow this computer's own setting.settings-remote-drop-destination = Remote Drop Destinationsettings-remote-drop-destination-description = Where files dropped onto a remote terminal are uploaded. Use cwd for the shell's current directory.+settings-notifications-heading = Notifications+settings-notification-sounds = Notification Sounds+settings-notification-sounds-description = Play a short sound when a thread you are not watching finishes, or starts waiting on you.settings-terminal-heading = Effective terminal configsettings-terminal-font-size = Font Sizesettings-terminal-font-size-description = Current effective value from the WezTerm-compatible config.@@ -357,6 +360,9 @@ settings-download-picker-title = Choose a download foldersettings-status-download-path = Downloads are saved to { $path }settings-status-download-error = Unable to save the download folder: { $error }settings-status-window-restore-on = Main window frame restore enabled for new macOS windows.+settings-status-notification-sounds-on = Notification sounds enabled.+settings-status-notification-sounds-off = Notification sounds turned off.+settings-status-notification-sounds-error = Could not save the notification sound setting: { $error }settings-status-window-restore-off = Main window frame restore disabled for new macOS windows.settings-status-window-restore-error = Unable to save window restore setting: { $error }settings-status-renderer = Main window renderer set to { $renderer }; restart ThinkTerm to apply it.diff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftlindex 4a1ff820..688a43b2 100644--- a/wezterm-gui/i18n/fr-FR.ftl+++ b/wezterm-gui/i18n/fr-FR.ftl@@ -90,6 +90,9 @@ settings-system-download-folder = Utiliser le dossier Téléchargements du systsettings-system-download-folder-description = Efface le dossier choisi afin que les téléchargements suivent le réglage de cet ordinateur.settings-remote-drop-destination = Destination du dépôt distantsettings-remote-drop-destination-description = Emplacement d’envoi des fichiers déposés sur un terminal distant. Utilisez cwd pour le dossier courant du shell.+settings-notifications-heading = Notifications+settings-notification-sounds = Sons de notification+settings-notification-sounds-description = Émettre un son bref lorsqu’un fil que vous ne regardez pas se termine ou attend une réponse.settings-terminal-heading = Configuration effective du terminalsettings-terminal-font-size = Taille de policesettings-terminal-font-size-description = Valeur effective actuelle issue de la configuration compatible WezTerm.@@ -357,6 +360,9 @@ settings-download-picker-title = Choisir un dossier de téléchargementsettings-status-download-path = Les téléchargements sont enregistrés dans { $path }settings-status-download-error = Impossible d’enregistrer le dossier de téléchargement : { $error }settings-status-window-restore-on = Restauration de la taille et position activée pour les nouvelles fenêtres macOS.+settings-status-notification-sounds-on = Sons de notification activés.+settings-status-notification-sounds-off = Sons de notification désactivés.+settings-status-notification-sounds-error = Impossible d’enregistrer le réglage des sons de notification : { $error }settings-status-window-restore-off = Restauration de la taille et position désactivée pour les nouvelles fenêtres macOS.settings-status-window-restore-error = Impossible d’enregistrer la restauration de fenêtre : { $error }settings-status-renderer = Moteur de rendu principal défini sur { $renderer } ; redémarrez ThinkTerm pour l’appliquer.diff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftlindex 45d8cf19..beac9f42 100644--- a/wezterm-gui/i18n/ja-JP.ftl+++ b/wezterm-gui/i18n/ja-JP.ftl@@ -90,6 +90,9 @@ settings-system-download-folder = システムのダウンロードフォルダsettings-system-download-folder-description = 選択したフォルダーを解除し、このコンピューターの設定に従います。settings-remote-drop-destination = リモートへのドロップ先settings-remote-drop-destination-description = リモートターミナルへドロップしたファイルのアップロード先です。cwd でシェルの現在のディレクトリを指定できます。+settings-notifications-heading = 通知+settings-notification-sounds = 通知音+settings-notification-sounds-description = 見ていないスレッドが完了したとき、または入力待ちになったときに短い音を鳴らします。settings-terminal-heading = 有効なターミナル設定settings-terminal-font-size = フォントサイズsettings-terminal-font-size-description = WezTerm 互換設定から得た現在の有効値です。@@ -357,6 +360,9 @@ settings-download-picker-title = ダウンロードフォルダーを選択settings-status-download-path = ダウンロードの保存先:{ $path }settings-status-download-error = ダウンロードフォルダーを保存できません:{ $error }settings-status-window-restore-on = 新しい macOS ウィンドウで位置とサイズの復元を有効にしました。+settings-status-notification-sounds-on = 通知音を有効にしました。+settings-status-notification-sounds-off = 通知音を無効にしました。+settings-status-notification-sounds-error = 通知音の設定を保存できませんでした: { $error }settings-status-window-restore-off = 新しい macOS ウィンドウで位置とサイズの復元を無効にしました。settings-status-window-restore-error = ウィンドウ復元設定を保存できません:{ $error }settings-status-renderer = メインウィンドウのレンダラーを { $renderer } に設定しました。ThinkTerm の再起動後に適用されます。diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftlindex 1ce08c9a..beb81c9a 100644--- a/wezterm-gui/i18n/zh-CN.ftl+++ b/wezterm-gui/i18n/zh-CN.ftl@@ -90,6 +90,9 @@ settings-system-download-folder = 使用系统下载文件夹settings-system-download-folder-description = 清除所选文件夹,让下载遵循此电脑的系统设置。settings-remote-drop-destination = 远程拖放目标settings-remote-drop-destination-description = 拖到远程终端的文件上传位置。使用 cwd 表示 shell 当前目录。+settings-notifications-heading = 通知+settings-notification-sounds = 提示音+settings-notification-sounds-description = 当你没在看的 thread 干完了、或者开始等你输入时,响一声。settings-terminal-heading = 当前终端配置settings-terminal-font-size = 字号settings-terminal-font-size-description = WezTerm 兼容配置中的当前有效值。@@ -357,6 +360,9 @@ settings-download-picker-title = 选择下载文件夹settings-status-download-path = 下载将保存到 { $path }settings-status-download-error = 无法保存下载文件夹:{ $error }settings-status-window-restore-on = 已为新的 macOS 窗口启用主窗口位置与大小恢复。+settings-status-notification-sounds-on = 已开启提示音。+settings-status-notification-sounds-off = 已关闭提示音。+settings-status-notification-sounds-error = 无法保存提示音设置:{ $error }settings-status-window-restore-off = 已为新的 macOS 窗口关闭主窗口位置与大小恢复。settings-status-window-restore-error = 无法保存窗口恢复设置:{ $error }settings-status-renderer = 主窗口渲染器已设为 { $renderer };重启 ThinkTerm 后生效。diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex 63fb2666..06d47d8e 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -130,6 +130,8 @@ impl GuiFrontEnd {// Server-side only: a GUI mux owns no ThinkTerm tree. The// remote tree arrives as a pushed PDU, not as a notification.MuxNotification::ThinkTermTreeChanged => {}+ MuxNotification::ThinkTermSessionChanged => {}+ MuxNotification::FrontendLeaseChanged(_) => {}MuxNotification::TabAddedToWindow { .. } => {}MuxNotification::PaneRemoved(_) => {}MuxNotification::WindowInvalidated(_) => {}diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 37d742a5..50d3447b 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -1032,7 +1032,7 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->wezterm_client::domain::set_thinkterm_tree_sink(|domain_name, tree| {crate::workspace_threads::ingest_remote_tree(domain_name, tree);});- wezterm_client::domain::set_thinkterm_connect_sink(|domain_name| {+ wezterm_client::domain::set_thinkterm_connect_sink(|domain_name, _connection_generation| {crate::workspace_threads::note_remote_connected(domain_name);});@@ -1063,7 +1063,6 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->default_domain_name.as_deref(),opts.workspace.as_deref(),)?;-// First, let's see if we can ask an already running wezterm to do this.// We must do this before we start the gui frontend as the scheduler// requirements are different.diff --git a/wezterm-gui/src/native_paths.rs b/wezterm-gui/src/native_paths.rsindex 3c0d2e52..05cfc5b1 100644--- a/wezterm-gui/src/native_paths.rs+++ b/wezterm-gui/src/native_paths.rs@@ -1,9 +1,7 @@use std::path::PathBuf;pub(crate) fn data_dir() -> PathBuf {- dirs_next::data_dir()- .unwrap_or_else(|| config::HOME_DIR.join(".local/share"))- .join("ThinkTerm")+ thinkterm_core::frontend_data_dir()}pub(crate) fn data_file(name: &str) -> PathBuf {diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex bdc13484..2a07620d 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -292,6 +292,9 @@ pub(crate) struct NativeWorkspaceSettings {/// path. Empty means [`DEFAULT_REMOTE_DROP_DESTINATION`]; the literal/// `cwd` means the shell's current directory at drop time.pub(crate) remote_drop_destination: String,+ /// Play a short sound when a thread you are not watching finishes, or when+ /// one starts waiting on you.+ pub(crate) notification_sounds_enabled: bool,}impl Default for NativeWorkspaceSettings {@@ -300,6 +303,7 @@ impl Default for NativeWorkspaceSettings {remote_sftp_idle_minutes: DEFAULT_REMOTE_SFTP_IDLE_MINUTES,remote_download_directory: String::new(),remote_drop_destination: String::new(),+ notification_sounds_enabled: true,}}}@@ -699,6 +703,10 @@ pub(crate) fn pane_header_font_size() -> f64 {.clamp(10.0, 28.0)}+pub(crate) fn notification_sounds_enabled() -> bool {+ load().workspaces.notification_sounds_enabled+}+pub(crate) fn bottom_quote_interval_minutes(settings: &ThinkTermNativeSettings) -> u32 {settings.terminaldiff --git a/wezterm-gui/src/secret.rs b/wezterm-gui/src/secret.rsindex 891a4e2b..ef813b32 100644--- a/wezterm-gui/src/secret.rs+++ b/wezterm-gui/src/secret.rs@@ -1,135 +1,3 @@-//! At-rest encryption for stored secrets (currently SSH passwords).-//!-//! Secrets are encrypted with AES-256-GCM using a per-machine random key kept-//! in ThinkTerm's native data directory as `secret.key` (mode 0600). The encrypted value is-//! stored in `ssh_hosts.json` as `enc:v1:<base64(nonce|tag|ciphertext)>` so the-//! JSON never contains plaintext. This protects against casual disclosure-//! (sync/backups/prying eyes); anyone with both the key file and the ciphertext-//! can still decrypt, which is the documented trade-off for a key-on-disk-//! scheme (vs the macOS Keychain).+//! Frontend wrapper for the shared ThinkTerm secret store.-use anyhow::{Context, Result};-use base64::engine::general_purpose::STANDARD;-use base64::Engine;-use openssl::symm::{decrypt_aead, encrypt_aead, Cipher};-use std::fs;-use std::io::Write;-use std::path::PathBuf;--const MARKER: &str = "enc:v1:";-const IV_LEN: usize = 12;-const TAG_LEN: usize = 16;--fn key_path() -> PathBuf {- crate::native_paths::data_file("secret.key")-}--/// Load the 32-byte key, generating and persisting one (0600) if absent.-fn load_or_create_key() -> Result<[u8; 32]> {- let path = key_path();- if let Ok(bytes) = fs::read(&path) {- if bytes.len() == 32 {- let mut key = [0u8; 32];- key.copy_from_slice(&bytes);- return Ok(key);- }- }-- let mut key = [0u8; 32];- openssl::rand::rand_bytes(&mut key).context("generate secret key")?;- if let Some(parent) = path.parent() {- fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;- }- write_key_file(&path, &key)?;- Ok(key)-}--#[cfg(unix)]-fn write_key_file(path: &std::path::Path, key: &[u8]) -> Result<()> {- use std::os::unix::fs::OpenOptionsExt;- let mut file = fs::OpenOptions::new()- .write(true)- .create(true)- .truncate(true)- .mode(0o600)- .open(path)- .with_context(|| format!("create {}", path.display()))?;- file.write_all(key)- .with_context(|| format!("write {}", path.display()))?;- Ok(())-}--#[cfg(not(unix))]-fn write_key_file(path: &std::path::Path, key: &[u8]) -> Result<()> {- fs::write(path, key).with_context(|| format!("write {}", path.display()))-}--/// True if `value` is an encrypted blob produced by [`encrypt`].-pub fn is_encrypted(value: &str) -> bool {- value.starts_with(MARKER)-}--/// Encrypt `plaintext` into the `enc:v1:...` storage form.-pub fn encrypt(plaintext: &str) -> Result<String> {- let key = load_or_create_key()?;- let mut iv = [0u8; IV_LEN];- openssl::rand::rand_bytes(&mut iv).context("generate nonce")?;- let mut tag = [0u8; TAG_LEN];- let ciphertext = encrypt_aead(- Cipher::aes_256_gcm(),- &key,- Some(&iv),- &[],- plaintext.as_bytes(),- &mut tag,- )- .context("aes-256-gcm encrypt")?;-- let mut blob = Vec::with_capacity(IV_LEN + TAG_LEN + ciphertext.len());- blob.extend_from_slice(&iv);- blob.extend_from_slice(&tag);- blob.extend_from_slice(&ciphertext);- Ok(format!("{MARKER}{}", STANDARD.encode(&blob)))-}--/// Decrypt a value produced by [`encrypt`]. Returns `None` if it is not an-/// encrypted blob or cannot be decrypted.-pub fn decrypt(stored: &str) -> Option<String> {- let blob = STANDARD.decode(stored.strip_prefix(MARKER)?).ok()?;- if blob.len() < IV_LEN + TAG_LEN {- return None;- }- let key = load_or_create_key().ok()?;- let (iv, rest) = blob.split_at(IV_LEN);- let (tag, ciphertext) = rest.split_at(TAG_LEN);- let plaintext =- decrypt_aead(Cipher::aes_256_gcm(), &key, Some(iv), &[], ciphertext, tag).ok()?;- String::from_utf8(plaintext).ok()-}--/// Decrypt an encrypted value, or pass through a legacy plaintext value-/// (one not produced by [`encrypt`]).-pub fn reveal(stored: &str) -> String {- if is_encrypted(stored) {- decrypt(stored).unwrap_or_default()- } else {- stored.to_string()- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn round_trip() {- let secret = "hunter2 · 密码 🔒";- let enc = encrypt(secret).unwrap();- assert!(is_encrypted(&enc));- assert_ne!(enc, secret);- assert_eq!(decrypt(&enc).as_deref(), Some(secret));- assert_eq!(reveal(&enc), secret);- // Legacy plaintext passes through.- assert_eq!(reveal("plain"), "plain");- }-}+pub use thinkterm_core::secret::{encrypt, is_encrypted, reveal};diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex dc517772..75ddc414 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -376,6 +376,7 @@ enum SettingsAction {ClearImportFields,ToggleImportField(ImportFieldId),ToggleMainWindowFrameRestore,+ ToggleNotificationSounds,ToggleDeveloperMode,ToggleFallbackContextMenu,ShowOnboardingNow,@@ -2923,6 +2924,27 @@ impl SettingsWindow {}}}+ SettingsAction::ToggleNotificationSounds => {+ self.ui.open_dropdown = None;+ self.native_settings.workspaces.notification_sounds_enabled =+ !self.native_settings.workspaces.notification_sounds_enabled;+ match crate::native_settings::save(&self.native_settings) {+ Ok(()) => {+ self.status = if self.native_settings.workspaces.notification_sounds_enabled+ {+ crate::i18n::tr("settings-status-notification-sounds-on")+ } else {+ crate::i18n::tr("settings-status-notification-sounds-off")+ };+ }+ Err(err) => {+ self.status = settings_tr(+ "settings-status-notification-sounds-error",+ &[("error", format!("{err:#}"))],+ );+ }+ }+ }SettingsAction::ToggleMainRendererMenu => {self.ui.open_dropdown =if self.ui.open_dropdown == Some(SettingsDropdown::MainRenderer) {@@ -4241,9 +4263,16 @@ impl SettingsWindow {let row_count = 4;let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);let card_height = self.settings_card_height(row_count);+ // Notification sounds are not a remote-files concern, so they get their+ // own card rather than being filed under that heading.+ let sounds_row_count = 1;+ let sounds_title_y = card_y + card_height + self.settings_section_card_gap();+ let sounds_card_y = sounds_title_y + self.settings_section_card_gap().min(54.0);+ let sounds_first_row_y = sounds_card_y + self.settings_card_top_padding();+ let sounds_card_height = self.settings_card_height(sounds_row_count);self.ui.content_scroll.set_extents(self.content_viewport_extent(),- self.settings_content_extent(card_y + scroll + card_height),+ self.settings_content_extent(sounds_card_y + scroll + sounds_card_height),);self.draw_text(@@ -4314,6 +4343,28 @@ impl SettingsWindow {crate::native_settings::DEFAULT_REMOTE_DROP_DESTINATION,SettingsAction::RemoteDropDestinationInput,true,+ )?;++ self.draw_text(+ layers,+ &ui_font,+ x,+ sounds_title_y,+ &crate::i18n::tr("settings-notifications-heading"),+ palette.muted_text,+ max_width,+ )?;+ self.paint_group_card(layers, x, sounds_card_y, max_width, sounds_card_height)?;+ self.paint_toggle_setting_row(+ layers,+ row_x,+ sounds_first_row_y,+ row_width,+ &crate::i18n::tr("settings-notification-sounds"),+ &crate::i18n::tr("settings-notification-sounds-description"),+ self.native_settings.workspaces.notification_sounds_enabled,+ SettingsAction::ToggleNotificationSounds,+ true,)}diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rsindex a6dbcec8..12a1504d 100644--- a/wezterm-gui/src/ssh_hosts.rs+++ b/wezterm-gui/src/ssh_hosts.rs@@ -7,7 +7,7 @@use anyhow::{bail, Context, Result};use config::keyassignment::{SpawnCommand, SpawnTabDomain};-use config::{SshDomain, SshMultiplexing};+use config::SshDomain;use filedescriptor::FileDescriptor;use mux::domain::Domain;use mux::ssh::RemoteSshDomain;@@ -21,79 +21,10 @@ use std::path::{Path, PathBuf};use std::sync::Arc;use wezterm_ssh::{Session, SessionEvent};-pub type SshHostId = String;--pub const DEFAULT_MOSH_SERVER_COMMAND: &str = "mosh-server new -s -l LANG=en_US.UTF-8";--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-pub struct SshHostSpec {- /// Display name shown on the host card / sidebar row.- pub label: String,- /// Hostname or IP address of the remote server.- pub host: String,- #[serde(default)]- pub port: Option<u16>,- #[serde(default)]- pub username: Option<String>,- /// Path to an SSH identity (private key) file, if any.- #[serde(default)]- pub identity_file: Option<String>,- /// Optional stored password used to auto-answer the password prompt on- /// connect. New values are stored encrypted (`enc:v1:...`); legacy- /// plaintext values are still accepted by the connection layer.- #[serde(default)]- pub password: Option<String>,- /// Extra `ssh_config` option overrides (key -> value).- #[serde(default)]- pub ssh_options: HashMap<String, String>,- /// Use WezTerm's multiplexed SSH (persistent, reconnecting) when true.- /// That requires `wezterm` installed on the remote; default to direct- /// `ssh` (like `thinkterm ssh`) so password auth + the shell work anywhere.- #[serde(default)]- pub multiplexing: bool,- /// Override the default `ssh:<host>` workspace name.- #[serde(default)]- pub default_workspace: Option<String>,- /// When true, run a one-shot `cat /etc/os-release` after connecting to- /// detect the distro and pick its icon. User-controlled (opt-in).- #[serde(default = "default_true")]- pub detect_os: bool,- /// `/etc/os-release` `ID` detected after connecting; drives the OS icon.- #[serde(default)]- pub detected_distro: Option<String>,- /// When true, connect with Mosh instead of WezTerm's SSH domain. ThinkTerm- /// first tries an integrated SSH bootstrap (`mosh-server new ...`) so the- /// stored password can be used; if that fails, it falls back to the- /// external `mosh` wrapper for manual interaction.- #[serde(default)]- pub use_mosh: bool,- /// Remote command used by an integrated mosh bootstrap path to start- /// `mosh-server`. Kept configurable because different servers may need- /// environment overrides or a non-default binary path.- #[serde(default = "default_mosh_server_command")]- pub mosh_server_command: String,-}--fn default_true() -> bool {- true-}--fn default_mosh_server_command() -> String {- DEFAULT_MOSH_SERVER_COMMAND.to_string()-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum SshHostSource {- ThinkTerm,- System,-}--#[derive(Debug, Clone)]-pub struct SshHostEntry {- pub id: SshHostId,- pub source: SshHostSource,- pub spec: SshHostSpec,-}+pub use thinkterm_core::ssh_hosts::{+ default_mosh_server_command, SshHostEntry, SshHostId, SshHostSource, SshHostSpec,+ DEFAULT_MOSH_SERVER_COMMAND,+};#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]struct SshHostRecord {@@ -506,50 +437,12 @@ pub async fn build_integrated_mosh_spawn(spec: &SshHostSpec) -> Result<SpawnComm/// snapshotted SSH layout (which records the pane's domain name) can be/// re-materialized after [`register_saved_hosts`] re-registers the domain.pub fn ssh_domain_name(spec: &SshHostSpec) -> String {- format!("ssh:{}", endpoint(spec))+ thinkterm_core::ssh_hosts::ssh_domain_name(spec)}/// Translate a stored host spec into a `config::SshDomain`.pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {- let mut ssh_option = HashMap::new();- for (key, value) in &spec.ssh_options {- ssh_option.insert(key.to_lowercase(), value.clone());- }- if let Some(identity) = &spec.identity_file {- if !identity.trim().is_empty() {- ssh_option.insert("identityfile".to_string(), identity.clone());- }- }- // Default connect timeout so an unreachable host fails fast instead of- // hanging on the OS default TCP timeout. Users can override via ssh_options.- ssh_option- .entry("connecttimeout".to_string())- .or_insert_with(|| "10".to_string());-- let remote_address = match spec.port {- Some(port) => format!("{}:{port}", spec.host),- None => spec.host.clone(),- };-- SshDomain {- name: ssh_domain_name(spec),- remote_address,- username: spec.username.clone(),- multiplexing: if spec.multiplexing {- SshMultiplexing::WezTerm- } else {- SshMultiplexing::None- },- ssh_option,- // The derived Default is all-zero here: the documented Some(100ms)- // predictive-echo threshold (and the read timeout) only apply when- // the domain is deserialized from lua config. Without them, mux- // sessions built from the host store never show local-echo- // predictions, no matter how laggy the link.- local_echo_threshold_ms: config::default_local_echo_threshold_ms(),- timeout: config::default_read_timeout(),- ..Default::default()- }+ thinkterm_core::ssh_hosts::build_ssh_domain(spec)}fn register_ssh_domain(spec: &SshHostSpec) -> Result<()> {diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex b4d24b13..6dec176e 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -1286,6 +1286,11 @@ pub struct TermWindow {/// Terminal dimensionsterminal_size: TerminalSize,pub mux_window_id: MuxWindowId,+ /// A viewport claim is in flight; a second click must not queue another.+ frontend_viewport_claim_pending: bool,+ /// The tab this window last described to the server, so a switch to a tab+ /// it has never described says so before anyone has to click.+ last_described_tab: Option<TabId>,pub mux_window_id_for_subscriptions: Arc<Mutex<MuxWindowId>>,pub render_metrics: RenderMetrics,render_state: Option<RenderState>,@@ -2020,6 +2025,8 @@ impl TermWindow {crate::workspace_threads::space_note_vault(&active_space_id).is_some();let myself = Self {+ frontend_viewport_claim_pending: false,+ last_described_tab: None,created: Instant::now(),connection_name,last_fps_check_time: Instant::now(),@@ -2978,6 +2985,18 @@ impl TermWindow {// Server-side only; the remote tree reaches this process// as a pushed ThinkTermTreeState PDU instead.}+ MuxNotification::ThinkTermSessionChanged => {+ // Consumed by mux-server connections attached to this GUI.+ }+ MuxNotification::FrontendLeaseChanged(state) => {+ let mux = Mux::get();+ if mux.window_containing_tab(state.tab_id) == Some(self.mux_window_id) {+ if self.owns_frontend_viewport() {+ self.resize_mux_tabs_to_current_terminal_size();+ }+ window.invalidate();+ }+ }MuxNotification::PaneFocused(pane_id) => {// Also handled by clientpaneself.refresh_thread_work_for_pane(pane_id);@@ -3411,6 +3430,14 @@ impl TermWindow {return true;}}+ MuxNotification::FrontendLeaseChanged(ref state) => {+ let mux = Mux::get();+ if mux.window_containing_tab(state.tab_id) == Some(mux_window_id) {+ // fall through+ } else {+ return true;+ }+ }MuxNotification::Alert {alert: Alert::ToastNotification { .. },..@@ -3422,6 +3449,7 @@ impl TermWindow {| MuxNotification::WorkspaceRenamed { .. }| MuxNotification::Empty| MuxNotification::ThinkTermTreeChanged+ | MuxNotification::ThinkTermSessionChanged| MuxNotification::WindowWorkspaceChanged(_) => return true,MuxNotification::Alert {alert: Alert::PaletteChanged { .. },@@ -4680,7 +4708,7 @@ impl TermWindow {}};- let title = match title {+ let mut title = match title {Some(title) => title,None => {if let (Some(pos), Some(tab)) = (active_pane, active_tab) {@@ -4701,6 +4729,23 @@ impl TermWindow {}};+ if let Some(state) = Mux::get()+ .get_active_tab_for_window(self.mux_window_id)+ .and_then(|tab| tab.get_active_pane())+ .and_then(|pane| {+ pane.downcast_ref::<wezterm_client::pane::ClientPane>()+ .and_then(|pane| {+ pane.remote_viewport_state()+ .filter(|_| pane.owns_remote_viewport() == Some(false))+ })+ })+ {+ title.push_str(&format!(+ " · VIEW {}×{} · input to take control",+ state.canonical_size.cols, state.canonical_size.rows+ ));+ }+if let Some(window) = self.window.as_ref() {window.set_title(&title);diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex e089781c..b398618b 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -77,7 +77,7 @@ fn space_destructive_menu_items(let mut children = vec![ContextMenuItem::item_with_icon(crate::i18n::tr("menu-space-disconnect-short"),- ContextMenuIcon::Unplug,+ ContextMenuIcon::Disconnect,KeyAssignment::DeleteSpace(space.id.clone()),),ContextMenuItem::item_with_icon(@@ -1221,6 +1221,18 @@ impl super::TermWindow {log::trace!("{:?}", event);let pane = self.get_active_pane_or_overlay();+ // Whoever is touching a window is the one looking at it, and the server+ // hands the frontend viewport over on input it can see. A click or a+ // scroll in a pane that has not asked for mouse reporting never leaves+ // this process, so without this a window sat down at and used kept+ // drawing at the size some other device left behind.+ if matches!(+ event.kind,+ WMEK::Press(_) | WMEK::VertWheel(_) | WMEK::HorzWheel(_)+ ) {+ self.claim_frontend_viewport_for_interaction();+ }+self.current_mouse_event.replace(event.clone());if self.consume_context_menu_suppressed_release(&event) {@@ -4582,7 +4594,7 @@ impl super::TermWindow {tr_with_name("menu-delete-space", &space.name)},if space.is_remote {- ContextMenuIcon::Unplug+ ContextMenuIcon::Disconnect} else {ContextMenuIcon::Delete},diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex e1da69c1..d8bb9af7 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -1,13 +1,17 @@use crate::resize_increment_calculator::ResizeIncrementCalculator;+use crate::termwindow::TermWindowNotif;use crate::ui::rescale_ui_usize;use crate::utilsprites::RenderMetrics;use ::window::{Dimensions, ResizeIncrement, Window, WindowOps, WindowState};use config::{ConfigHandle, DimensionContext};-use mux::pane::PaneId;+use mux::pane::{Pane, PaneId};use mux::tab::PositionedPane;use mux::Mux;use std::collections::HashMap;use std::rc::Rc;+use std::sync::Arc;+use wezterm_client::domain::ClientDomain;+use wezterm_client::pane::ClientPane;use wezterm_font::FontConfiguration;use wezterm_term::TerminalSize;@@ -24,6 +28,213 @@ pub enum ScaleChange {}impl super::TermWindow {+ fn tab_owns_frontend_viewport(&self, tab: &Arc<mux::tab::Tab>) -> bool {+ if let Some(owns) = tab.get_active_pane().and_then(|pane| {+ pane.downcast_ref::<ClientPane>()+ .map(ClientPane::owns_remote_viewport)+ }) {+ return owns == Some(true);+ }+ Mux::get().current_identity_owns_frontend_lease(tab.tab_id())+ }++ pub(crate) fn owns_frontend_viewport(&self) -> bool {+ let mux = Mux::get();+ mux.get_active_tab_for_window(self.mux_window_id)+ .map_or(true, |tab| self.tab_owns_frontend_viewport(&tab))+ }++ /// Take the viewport because someone is using this window right now.+ ///+ /// The server hands the lease over on *input*, and a click or a scroll in a+ /// pane that is not asking for mouse reporting never reaches the server at+ /// all — it is handled here. So a window you sat down at and clicked in+ /// kept drawing at whatever size the phone that last typed had left it,+ /// until something incidental (toggling the sidebar) happened to re-report+ /// the geometry. Interacting with a window is the plainest possible+ /// statement that it is the one being looked at.+ ///+ /// Nothing happens when this window already owns the viewport, which is the+ /// overwhelmingly common case, so the cost on an ordinary click is one+ /// comparison.+ pub(crate) fn claim_frontend_viewport_for_interaction(&mut self) {+ if self.frontend_viewport_claim_pending || self.owns_frontend_viewport() {+ return;+ }+ let mux = Mux::get();+ let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) else {+ return;+ };+ let Some(active_pane) = tab.get_active_pane() else {+ return;+ };+ let Some(client_pane) = active_pane.downcast_ref::<ClientPane>() else {+ return;+ };+ let Some(domain) = mux.get_domain(client_pane.domain_id()) else {+ return;+ };+ if !domain.is::<ClientDomain>() {+ return;+ }+ let tab_id = tab.tab_id();+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ // Advertise before claiming, in that order, in one go. The server can+ // only hand the viewport to a client whose geometry it already holds,+ // and this window advertises for the *active* tab only — so a tab+ // switched to while another device held the lease was never described+ // at all, and clicking in it claimed nothing. That is the tab that then+ // sat at the other device's size with no way back short of resizing the+ // window.+ let viewport = self.active_frontend_viewport();+ self.frontend_viewport_claim_pending = true;+ promise::spawn::spawn(async move {+ let claimed = match domain.downcast_ref::<ClientDomain>() {+ Some(domain) => {+ if let Some(viewport) = viewport {+ if let Err(err) = domain.set_client_viewport(tab_id, viewport).await {+ log::warn!("advertising the viewport before claiming it: {err:#}");+ }+ }+ domain.claim_client_viewport(tab_id).await.is_ok()+ }+ None => false,+ };+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.frontend_viewport_claim_pending = false;+ if claimed {+ // The lease is ours now, so the resize this window has been+ // wanting all along is finally allowed through.+ term_window.resize_mux_tabs_to_current_terminal_size();+ term_window.invalidate_window();+ }+ })));+ Ok::<(), anyhow::Error>(())+ })+ .detach();+ }++ /// How this window would describe itself to the server right now.+ ///+ /// `None` when the active tab is not backed by a remote mux, which is the+ /// case where there is no lease to hold in the first place.+ fn active_frontend_viewport(&self) -> Option<codec::ClientViewport> {+ let mux = Mux::get();+ let tab = mux.get_active_tab_for_window(self.mux_window_id)?;+ let active_pane = tab.get_active_pane()?;+ let client_pane = active_pane.downcast_ref::<ClientPane>()?;+ let domain_id = client_pane.domain_id();+ // A window that does not hold the lease describes only its overall+ // grid: its per-pane split of that grid is not the one in force, and+ // offering it would ask the server to act on a layout nobody is+ // looking at.+ let panes = if self.tab_owns_frontend_viewport(&tab) {+ self.get_panes_to_render()+ .into_iter()+ .filter_map(|positioned| {+ let pane = positioned.pane.downcast_ref::<ClientPane>()?;+ if pane.domain_id() != domain_id {+ return None;+ }+ let font_scale = self.pane_font_scale(positioned.pane.pane_id());+ let metrics = if font_scale.to_bits() == self.fonts.get_font_scale().to_bits() {+ self.render_metrics+ } else {+ self.pane_font_resources(font_scale).ok()?.1+ };+ Some(codec::ClientPaneViewport {+ pane_id: positioned.pane.pane_id(),+ size: self.terminal_size_for_positioned_pane(&positioned, metrics),+ })+ })+ .collect()+ } else {+ Vec::new()+ };+ Some(codec::ClientViewport::Native {+ size: self.terminal_size,+ panes,+ })+ }++ fn report_active_frontend_viewport(&self) {+ let mux = Mux::get();+ let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) else {+ return;+ };+ let Some(active_pane) = tab.get_active_pane() else {+ return;+ };+ let tab_id = tab.tab_id();++ if let Some(client_pane) = active_pane.downcast_ref::<ClientPane>() {+ let Some(domain) = mux.get_domain(client_pane.domain_id()) else {+ return;+ };+ if !domain.is::<ClientDomain>() {+ return;+ }+ let Some(viewport) = self.active_frontend_viewport() else {+ return;+ };+ promise::spawn::spawn(async move {+ let Some(domain) = domain.downcast_ref::<ClientDomain>() else {+ return Ok::<(), anyhow::Error>(());+ };+ domain.set_client_viewport(tab_id, viewport).await?;+ Ok(())+ })+ .detach();+ return;+ }++ // This GUI is itself hosting the authoritative mux. Register its+ // LocalPane viewport under the GUI's normal ClientId just like a+ // remote renderer. Otherwise the first attached TUI silently becomes+ // owner while the GUI continues resizing the same PTYs directly.+ let Some(client_id) = mux.active_identity() else {+ return;+ };+ let panes = if self.tab_owns_frontend_viewport(&tab) {+ self.get_panes_to_render()+ .into_iter()+ .filter(|positioned| !positioned.pane.is_remote_mirror())+ .filter_map(|positioned| {+ let font_scale = self.pane_font_scale(positioned.pane.pane_id());+ let metrics = if font_scale.to_bits() == self.fonts.get_font_scale().to_bits() {+ self.render_metrics+ } else {+ match self.pane_font_resources(font_scale) {+ Ok((_, metrics)) => metrics,+ Err(err) => {+ log::warn!("cannot calculate local viewport: {err:#}");+ return None;+ }+ }+ };+ Some(mux::FrontendPaneViewport {+ pane_id: positioned.pane.pane_id(),+ size: self.terminal_size_for_positioned_pane(&positioned, metrics),+ })+ })+ .collect()+ } else {+ Vec::new()+ };+ if let Err(err) = mux.set_client_viewport(+ &client_id,+ tab_id,+ mux::FrontendViewport::Native {+ size: self.terminal_size,+ panes,+ },+ ) {+ log::warn!("cannot publish local GUI viewport: {err:#}");+ }+ }+fn normalized_font_scale_value(&self, font_scale: Option<f64>) -> Option<f64> {let global_scale = self.fonts.get_font_scale();font_scale@@ -335,6 +546,9 @@ impl super::TermWindow {}fn sync_active_mux_tab_pane_sizes(&self) {+ if !self.owns_frontend_viewport() {+ return;+ }for pos in self.get_panes_to_render() {if let Err(err) = self.sync_positioned_pane_font_size(&pos) {log::error!(@@ -361,14 +575,21 @@ impl super::TermWindow {}pub(crate) fn resize_mux_tabs_to_current_terminal_size(&mut self) {+ if !self.owns_frontend_viewport() {+ self.report_active_frontend_viewport();+ return;+ }let mux = Mux::get();if let Some(window) = mux.get_window(self.mux_window_id) {for tab in window.iter() {- tab.resize(self.terminal_size);+ if self.tab_owns_frontend_viewport(tab) {+ tab.resize(self.terminal_size);+ }}}self.reapply_collapsed_panes_for_window();self.force_sync_active_mux_tab_pane_sizes();+ self.report_active_frontend_viewport();}/// Repair a missed/deferred sidebar reflow before terminal geometry is@@ -383,6 +604,22 @@ impl super::TermWindow {if self.content_view_foreground() {return;}+ // Before the ownership gate, because a tab this window has never+ // described is precisely a tab it cannot own. This window advertises+ // for the active tab only, so switching tabs — or closing one, which+ // activates its neighbour — used to leave the newly shown tab+ // undescribed, and therefore unclaimable, at whatever size the device+ // that last held it had chosen. Saying so once per change is enough.+ let active_tab = Mux::get()+ .get_active_tab_for_window(self.mux_window_id)+ .map(|tab| tab.tab_id());+ if self.last_described_tab != active_tab {+ self.last_described_tab = active_tab;+ self.report_active_frontend_viewport();+ }+ if !self.owns_frontend_viewport() {+ return;+ }let mux = Mux::get();let Some(tab) = mux.get_active_tab_for_window(self.mux_window_id) else {@@ -577,6 +814,7 @@ impl super::TermWindow {self.resize_mux_tabs_to_current_terminal_size();}} else {+ self.report_active_frontend_viewport();log::trace!("terminal size unchanged; syncing active pane geometry");if !self.content_view_foreground() {self.sync_pane_font_sizes();diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rsindex 44120fdc..bf054f8b 100644--- a/wezterm-gui/src/termwindow/ui/context_menu.rs+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs@@ -1010,7 +1010,7 @@ fn menu_icon(icon: &ContextMenuIcon) -> Option<SvgIcon> {ContextMenuIcon::Terminal => Some(SvgIcon::Terminal),ContextMenuIcon::Undo => Some(SvgIcon::RotateCcw),ContextMenuIcon::Unpin => Some(SvgIcon::PinOff),- ContextMenuIcon::Unplug => Some(SvgIcon::Unplug),+ ContextMenuIcon::Disconnect => Some(SvgIcon::Unlink2),ContextMenuIcon::Vault => Some(SvgIcon::FolderTree),ContextMenuIcon::Warning => Some(SvgIcon::CircleAlert),}diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex 7c4c4dbd..fc2df3ea 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -52,7 +52,6 @@ pub enum SvgIcon {Pin,PinOff,Plus,- Unplug,RotateCcw,RotateCw,Save,@@ -75,6 +74,7 @@ pub enum SvgIcon {SpellCheck,Terminal,Trash2,+ Unlink2,X,}@@ -176,7 +176,7 @@ impl SvgIcon {Self::Pencil => include_bytes!("../../../../third_party/lucide/icons/pencil.svg"),Self::Pin => include_bytes!("../../../../third_party/lucide/icons/pin.svg"),Self::PinOff => include_bytes!("../../../../third_party/lucide/icons/pin-off.svg"),- Self::Unplug => include_bytes!("../../../../third_party/lucide/icons/unplug.svg"),+ Self::Unlink2 => include_bytes!("../../../../third_party/lucide/icons/unlink-2.svg"),Self::Plus => include_bytes!("../../../../third_party/lucide/icons/plus.svg"),Self::RotateCcw => {include_bytes!("../../../../third_party/lucide/icons/rotate-ccw.svg")@@ -540,7 +540,7 @@ mod tests {SvgIcon::Pin,SvgIcon::PinOff,SvgIcon::Plus,- SvgIcon::Unplug,+ SvgIcon::Unlink2,SvgIcon::RotateCcw,SvgIcon::RotateCw,SvgIcon::Search,diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 24022920..f0caabd0 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -210,6 +210,17 @@ impl WorkspaceThreadWorkStatus {}}+impl From<WorkspaceThreadWorkStatus> for codec::ThinkTermSessionWorkStatus {+ fn from(status: WorkspaceThreadWorkStatus) -> Self {+ match status {+ WorkspaceThreadWorkStatus::Idle => Self::Idle,+ WorkspaceThreadWorkStatus::Running => Self::Running,+ WorkspaceThreadWorkStatus::NeedsAttention => Self::NeedsAttention,+ WorkspaceThreadWorkStatus::FinishedUnseen => Self::FinishedUnseen,+ }+ }+}+/// A thread whose work finished without being seen or needs attention,/// across every Space; feeds the sidebar notification bell.#[derive(Debug, Clone, PartialEq, Eq)]@@ -226,6 +237,20 @@ pub struct ThreadWorkNotification {struct WorkspaceThreadWorkChange {changed: bool,should_persist: bool,+ /// What this transition is worth saying out loud, if anything. Set only on+ /// the observation that first crosses into the state, so re-scanning a+ /// thread that has not moved stays quiet without any extra bookkeeping.+ announce: Option<WorkAnnouncement>,+}++/// A transition is at most one of these, so a single field makes it impossible+/// to announce two things about the same moment.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum WorkAnnouncement {+ /// Work that was running has stopped.+ Finished,+ /// Something is waiting on the user.+ NeedsInput,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -351,6 +376,9 @@ lazy_static::lazy_static! {static THREAD_STORE_PERSIST_SCHEDULED: AtomicBool = AtomicBool::new(false);static THREAD_STORE_PERSIST_DIRTY: AtomicBool = AtomicBool::new(false);static NEXT_SPACE_OWNER_ID: AtomicU64 = AtomicU64::new(1);+fn publish_thinkterm_session_changed() {+ wezterm_mux_server_impl::thinkterm_session::publish_changed();+}pub fn workspace_thread_store_path() -> PathBuf {crate::native_paths::data_file("workspace_threads.json")@@ -1397,16 +1425,68 @@ fn schedule_work_status_recheck(workspace: String, delay: Duration) {});}+/// The bundled prompts. Regenerate them with `assets/sounds/synth.py`; they are+/// synthesised rather than sourced so nothing here is licensed from anyone.+static DONE_WAV: &[u8] = include_bytes!("../../assets/sounds/done.wav");+static NEEDS_INPUT_WAV: &[u8] = include_bytes!("../../assets/sounds/needs-input.wav");++/// Silences every prompt regardless of the setting. Test runners have no+/// business making noise, and neither does a machine someone is presenting on.+const DISABLE_SOUND_ENV: &str = "THINKTERM_DISABLE_SOUND";++/// Whether a transition is worth a sound, given what the user is already+/// looking at.+///+/// Watching the thread that just finished means the news arrived by eye+/// already, and a sound on top of that is just noise. Everything else happened+/// out of sight, which is the entire point of the feature.+fn should_announce(changed_workspace: &str, active_workspace: &str) -> bool {+ changed_workspace != active_workspace+}++fn announce_work(workspace: &str, announcement: WorkAnnouncement) {+ if std::env::var_os(DISABLE_SOUND_ENV).is_some() {+ return;+ }+ if !crate::native_settings::notification_sounds_enabled() {+ return;+ }+ if !should_announce(workspace, &Mux::get().active_workspace()) {+ return;+ }+ let wav = match announcement {+ WorkAnnouncement::Finished => DONE_WAV,+ WorkAnnouncement::NeedsInput => NEEDS_INPUT_WAV,+ };+ // The connection is main-thread only. Every caller of+ // `refresh_thread_work_for_workspace` is on it today, and staying silent is+ // the right answer if that ever stops being true.+ use ::window::ConnectionOps;+ match ::window::Connection::get() {+ Some(connection) => connection.play_sound(wav),+ None => log::debug!("no window connection on this thread; notification stays silent"),+ }+}+pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {let observed = scan_workspace_work_status(workspace);let observed = debounce_work_status(workspace, observed);- let mut store = THREAD_STORE.lock();- let Some(change) = store.observe_thread_work_for_workspace(workspace, observed) else {- return false;+ let change = {+ let mut store = THREAD_STORE.lock();+ let Some(change) = store.observe_thread_work_for_workspace(workspace, observed) else {+ return false;+ };+ change};+ if let Some(announcement) = change.announce {+ announce_work(workspace, announcement);+ }if change.should_persist {schedule_workspace_thread_store_persist();}+ if change.changed {+ publish_thinkterm_session_changed();+ }change.changed}@@ -1428,6 +1508,9 @@ pub fn acknowledge_thread_work_for_workspace(workspace: &str) -> bool {if change.should_persist {persist_locked(&store);}+ if change.changed && !change.should_persist {+ publish_thinkterm_session_changed();+ }change.changed}@@ -1439,6 +1522,9 @@ pub fn acknowledge_thread_work_for_thread(thread_id: &str) -> bool {if change.should_persist {persist_locked(&store);}+ if change.changed && !change.should_persist {+ publish_thinkterm_session_changed();+ }change.changed}@@ -1486,6 +1572,9 @@ pub fn acknowledge_thread_work_for_workspace_deferred(workspace: &str) -> bool {if change.should_persist {schedule_workspace_thread_store_persist();}+ if change.changed {+ publish_thinkterm_session_changed();+ }change.changed}@@ -4306,6 +4395,7 @@ impl WorkspaceThreadStore {return WorkspaceThreadWorkChange {changed,should_persist,+ announce: None,};}}@@ -4313,6 +4403,7 @@ impl WorkspaceThreadStore {WorkspaceThreadWorkChange {changed: false,should_persist: false,+ announce: None,}}@@ -4327,6 +4418,7 @@ impl WorkspaceThreadStore {return WorkspaceThreadWorkChange {changed,should_persist,+ announce: None,};}}@@ -4334,6 +4426,7 @@ impl WorkspaceThreadStore {WorkspaceThreadWorkChange {changed: false,should_persist: false,+ announce: None,}}@@ -4820,6 +4913,7 @@ impl WorkspaceThread {WorkspaceThreadWorkChange {changed,should_persist,+ announce: None,}}WorkspaceThreadWorkStatus::NeedsAttention => {@@ -4828,14 +4922,22 @@ impl WorkspaceThread {WorkspaceThreadWorkChange {changed,should_persist: false,+ // `changed` is already "this is the first time we have seen+ // it waiting", which is exactly when it is worth saying.+ announce: changed.then_some(WorkAnnouncement::NeedsInput),}}WorkspaceThreadWorkStatus::Idle | WorkspaceThreadWorkStatus::FinishedUnseen => {let was_running = self.work_is_running;let had_attention = self.work_needs_attention;let mut should_persist = false;+ let mut finished_now = false;if was_running {- should_persist = !self.work_finished_unseen;+ // The same condition that decides whether this is worth+ // writing to disk decides whether it is worth announcing:+ // both mean "it had not already finished".+ finished_now = !self.work_finished_unseen;+ should_persist = finished_now;self.work_finished_unseen = true;}self.work_is_running = false;@@ -4843,6 +4945,7 @@ impl WorkspaceThread {WorkspaceThreadWorkChange {changed: was_running || had_attention,should_persist,+ announce: finished_now.then_some(WorkAnnouncement::Finished),}}}@@ -4857,6 +4960,7 @@ fn persist_locked(store: &WorkspaceThreadStore) {if let Err(err) = save_workspace_thread_store(store) {log::warn!("failed to save ThinkTerm thread store: {err:#}");}+ publish_thinkterm_session_changed();}fn schedule_workspace_thread_store_persist() {@@ -6664,6 +6768,118 @@ mod tests {);}+ fn work_store_with_one_thread() -> WorkspaceThreadStore {+ let mut store = test_store();+ let session = WorkspaceThread::new(+ "project-1".to_string(),+ "main".to_string(),+ Some("workspace-1".to_string()),+ );+ store.projects.push(test_project(+ "project-1",+ "thinkterm",+ PathBuf::from("/tmp/thinkterm"),+ vec![session],+ ));+ store+ }++ fn observe(+ store: &mut WorkspaceThreadStore,+ status: WorkspaceThreadWorkStatus,+ ) -> Option<WorkAnnouncement> {+ store+ .observe_thread_work_for_workspace("workspace-1", status)+ .unwrap()+ .announce+ }++ /// The status is re-scanned on a timer, so the same finished thread is+ /// observed over and over. Announcing every observation would turn one+ /// completed job into a stream of dings.+ #[test]+ fn finishing_announces_once_per_run_not_once_per_scan() {+ let mut store = work_store_with_one_thread();++ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::Running),+ None+ );+ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::Idle),+ Some(WorkAnnouncement::Finished)+ );+ // Still finished, still idle — and now silent.+ assert_eq!(observe(&mut store, WorkspaceThreadWorkStatus::Idle), None);+ assert_eq!(observe(&mut store, WorkspaceThreadWorkStatus::Idle), None);++ // A second run of work earns a second announcement.+ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::Running),+ None+ );+ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::Idle),+ Some(WorkAnnouncement::Finished)+ );+ }++ /// Going idle without ever having run is a thread that did nothing, not a+ /// thread that finished something.+ #[test]+ fn going_idle_without_running_announces_nothing() {+ let mut store = work_store_with_one_thread();+ assert_eq!(observe(&mut store, WorkspaceThreadWorkStatus::Idle), None);+ }++ #[test]+ fn needing_input_announces_once_until_it_clears() {+ let mut store = work_store_with_one_thread();++ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::NeedsAttention),+ Some(WorkAnnouncement::NeedsInput)+ );+ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::NeedsAttention),+ None+ );++ // Work resumes, so the next time it gets stuck it is news again.+ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::Running),+ None+ );+ assert_eq!(+ observe(&mut store, WorkspaceThreadWorkStatus::NeedsAttention),+ Some(WorkAnnouncement::NeedsInput)+ );+ }++ /// Acknowledging is the user saying they already know; it must not double+ /// as news.+ #[test]+ fn acknowledging_announces_nothing() {+ let mut store = work_store_with_one_thread();+ observe(&mut store, WorkspaceThreadWorkStatus::Running);+ observe(&mut store, WorkspaceThreadWorkStatus::Idle);++ assert_eq!(+ store+ .acknowledge_thread_work_for_workspace("workspace-1")+ .announce,+ None+ );+ }++ /// A sound for the thread already on screen is noise: the news arrived by+ /// eye before it could arrive by ear.+ #[test]+ fn the_workspace_being_watched_stays_silent() {+ assert!(!should_announce("workspace-1", "workspace-1"));+ assert!(should_announce("workspace-1", "workspace-2"));+ }+#[test]fn pending_notifications_list_attention_first_and_skip_idle_running() {let mut store = test_store();diff --git a/wezterm-mux-server-impl/Cargo.toml b/wezterm-mux-server-impl/Cargo.tomlindex f7be112f..c1bc85c4 100644--- a/wezterm-mux-server-impl/Cargo.toml+++ b/wezterm-mux-server-impl/Cargo.toml@@ -29,6 +29,7 @@ smol.workspace = truetempfile.workspace = truetermwiz = { workspace=true, features=["use_serde"] }url.workspace = true+uuid = { workspace = true, features = ["v4"] }wezterm-client.workspace = truewezterm-term = { workspace=true, features=["use_serde"] }wezterm-uds.workspace = truediff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rsindex 65e2a742..b86137a5 100644--- a/wezterm-mux-server-impl/src/dispatch.rs+++ b/wezterm-mux-server-impl/src/dispatch.rs@@ -213,6 +213,19 @@ where.await?;stream.flush().await.context("flushing PDU to client")?;}+ Ok(Item::Notif(MuxNotification::ThinkTermSessionChanged)) => {+ let state = crate::thinkterm_session::snapshot()?;+ Pdu::ThinkTermSessionState(state)+ .encode_async(&mut stream, 0)+ .await?;+ stream.flush().await.context("flushing PDU to client")?;+ }+ Ok(Item::Notif(MuxNotification::FrontendLeaseChanged(state))) => {+ Pdu::ClientViewportState(crate::sessionhandler::codec_viewport_state(state))+ .encode_async(&mut stream, 0)+ .await?;+ stream.flush().await.context("flushing PDU to client")?;+ }Ok(Item::Notif(MuxNotification::ActiveWorkspaceChanged(_))) => {}Ok(Item::Notif(MuxNotification::Empty)) => {}Err(err) => {diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rsindex 5be3cb21..bb3bed83 100644--- a/wezterm-mux-server-impl/src/lib.rs+++ b/wezterm-mux-server-impl/src/lib.rs@@ -9,6 +9,7 @@ pub mod dispatch;pub mod local;pub mod pki;pub mod sessionhandler;+pub mod thinkterm_session;pub mod thinkterm_tree;fn client_domains(config: &config::ConfigHandle) -> Vec<ClientDomainConfig> {diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 6204807f..b9d0a97a 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -1,13 +1,17 @@use crate::PKI;use anyhow::{anyhow, Context};use codec::*;+use config::keyassignment::SpawnTabDomain;use config::TermConfig;use mux::client::ClientId;use mux::domain::SplitSource;use mux::pane::{CachePolicy, Pane, PaneId};use mux::renderable::{RenderableDimensions, StableCursorPosition};use mux::tab::TabId;-use mux::{Mux, PaletteSessionId};+use mux::{+ ClientRegistrationId, FrontendPaneViewport, FrontendViewport, FrontendViewportState, Mux,+ PaletteSessionId,+};use promise::spawn::spawn_into_main_thread;use std::collections::HashMap;use std::sync::{Arc, Mutex};@@ -18,6 +22,14 @@ use wezterm_term::color::ColorPalette;use wezterm_term::terminal::Alert;use wezterm_term::StableRowIndex;+lazy_static::lazy_static! {+ /// Serializes the authoritative tree decision with the live-workspace+ /// check and spawn. Without this, two clients opening the same empty+ /// Thread concurrently can each create its first tab.+ static ref THINKTERM_MATERIALIZE: futures::lock::Mutex<()> =+ futures::lock::Mutex::new(());+}+#[derive(Clone)]pub struct PduSender {func: Arc<dyn Fn(DecodedPdu) -> anyhow::Result<()> + Send + Sync>,@@ -43,6 +55,7 @@ pub(crate) struct PerPane {working_dir: Option<Url>,dimensions: RenderableDimensions,mouse_grabbed: bool,+ alt_screen: bool,/// Outer None means that this connection has never received application/// palette state for the pane. Inner None is an explicit reset to the/// client's own configured palette.@@ -71,6 +84,11 @@ impl PerPane {changed = true;}+ let alt_screen = pane.is_alt_screen_active();+ if alt_screen != self.alt_screen {+ changed = true;+ }+let dims = pane.get_dimensions();if dims != self.dimensions {changed = true;@@ -137,11 +155,13 @@ impl PerPane {self.working_dir = working_dir.clone();self.dimensions = dims;self.mouse_grabbed = mouse_grabbed;+ self.alt_screen = alt_screen;let bonus_lines = bonus_lines.into();Some(GetPaneRenderChangesResponse {pane_id: pane.pane_id(),mouse_grabbed,+ alt_screen,dirty_lines: all_dirty_lines.iter().cloned().collect(),dimensions: dims,cursor_position,@@ -229,6 +249,68 @@ fn apply_client_palette(pane: &Arc<dyn Pane>, palette: Option<ColorPalette>) ->Ok(())}+pub(crate) fn codec_viewport_state(state: FrontendViewportState) -> ClientViewportState {+ ClientViewportState {+ tab_id: state.tab_id,+ owner: state.owner,+ canonical_size: state.canonical_size,+ view: state.view.map(|view| codec::ClientView {+ scroll: view+ .scroll+ .into_iter()+ .map(|(pane_id, lines_from_bottom)| codec::ClientPaneScroll {+ pane_id,+ lines_from_bottom,+ })+ .collect(),+ }),+ generation: state.generation,+ }+}++fn mux_view(view: codec::ClientView) -> mux::FrontendView {+ mux::FrontendView {+ scroll: view+ .scroll+ .into_iter()+ .map(|entry| (entry.pane_id, entry.lines_from_bottom))+ .collect(),+ }+}++fn mux_viewport(viewport: ClientViewport) -> FrontendViewport {+ match viewport {+ ClientViewport::CellGrid { size } => FrontendViewport::CellGrid { size },+ ClientViewport::Native { size, panes } => FrontendViewport::Native {+ size,+ panes: panes+ .into_iter()+ .map(|pane| FrontendPaneViewport {+ pane_id: pane.pane_id,+ size: pane.size,+ })+ .collect(),+ },+ }+}++fn claim_viewport_for_pane(+ mux: &Mux,+ client_id: Option<&Arc<ClientId>>,+ registration: Option<ClientRegistrationId>,+ pane_id: PaneId,+) -> anyhow::Result<TabId> {+ let (_domain_id, _window_id, tab_id) = mux+ .resolve_pane_id(pane_id)+ .ok_or_else(|| anyhow!("no such pane {pane_id}"))?;+ if let (Some(client_id), Some(registration)) = (client_id, registration) {+ if !mux.registered_client_had_tab_input(client_id, registration, tab_id) {+ anyhow::bail!("client connection was superseded");+ }+ }+ Ok(tab_id)+}+fn activate_client_palette(mux: &Mux,pane: &Arc<dyn Pane>,@@ -271,6 +353,7 @@ pub struct SessionHandler {to_write_tx: PduSender,per_pane: HashMap<TabId, Arc<Mutex<PerPane>>>,client_id: Option<Arc<ClientId>>,+ client_registration: Option<ClientRegistrationId>,palette_session_id: Option<PaletteSessionId>,proxy_client_id: Option<ClientId>,}@@ -280,8 +363,10 @@ impl Drop for SessionHandler {if let Some(session_id) = self.palette_session_id.take() {schedule_palette_session_cleanup(session_id, "client disconnect");}- if let Some(client_id) = self.client_id.take() {- Mux::get().unregister_client(&client_id);+ if let (Some(client_id), Some(registration)) =+ (self.client_id.take(), self.client_registration.take())+ {+ Mux::get().unregister_client(&client_id, registration);}}}@@ -292,6 +377,7 @@ impl SessionHandler {to_write_tx,per_pane: HashMap::new(),client_id: None,+ client_registration: None,palette_session_id: None,proxy_client_id: None,}@@ -326,9 +412,35 @@ impl SessionHandler {let palette_session_id = self.palette_session_id;log::trace!("recv {} {}", serial, decoded.pdu.pdu_name());- if let Some(client_id) = &self.client_id {+ if let (Some(client_id), Some(registration)) = (&self.client_id, self.client_registration) {if decoded.pdu.is_user_input() {- Mux::get().client_had_input(client_id);+ let mux = Mux::get();+ mux.registered_client_had_input(client_id, registration);+ // Whoever last acted *on a terminal* decides how big it is —+ // typing, pasting, a mouse event a program asked for. Not a+ // resize: a renderer reports its pane sizes on its first frame,+ // so counting that made opening a second client take the grid+ // away from the one someone was using. Without+ // this the first renderer to attach kept the tab at its own+ // size for as long as it stayed connected, so picking up a+ // phone while a desktop was still open left the phone reading a+ // grid shaped for the desktop and unable to do anything about+ // it. Claiming needs a viewport this client has already+ // advertised, so a client that has yet to draw changes nothing.+ if let Some(tab_id) = decoded+ .pdu+ .is_terminal_interaction()+ .then(|| decoded.pdu.pane_id())+ .flatten()+ .and_then(|pane_id| mux.resolve_pane_id(pane_id))+ .map(|(_, _, tab_id)| tab_id)+ {+ if let Err(err) =+ mux.claim_registered_client_viewport(client_id, registration, tab_id)+ {+ log::trace!("input did not move the viewport for tab {tab_id}: {err:#}");+ }+ }}}@@ -401,12 +513,14 @@ impl SessionHandler {}self.palette_session_id =Some(Mux::get().register_palette_session(client_id.as_ref()));- self.client_id.replace(client_id.clone());- spawn_into_main_thread(async move {- let mux = Mux::get();- mux.register_client(client_id);- })- .detach();+ if let (Some(old_client), Some(old_registration)) =+ (self.client_id.take(), self.client_registration.take())+ {+ Mux::get().unregister_client(&old_client, old_registration);+ }+ let registration = Mux::get().register_client(client_id.clone());+ self.client_id.replace(client_id);+ self.client_registration.replace(registration);}send_response(Ok(Pdu::UnitResponse(UnitResponse {})))}@@ -415,6 +529,7 @@ impl SessionHandler {configured_palette,}) => {let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {@@ -424,6 +539,12 @@ impl SessionHandler {let pane = mux.get_pane(pane_id).ok_or_else(|| anyhow::anyhow!("pane {pane_id} not found"))?;+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ pane_id,+ )?;if let Some(palette) = configured_palette {if let Some(palette) = mux.advise_client_palette(@@ -536,13 +657,22 @@ impl SessionHandler {Pdu::WriteToPane(WriteToPane { pane_id, data }) => {let sender = self.to_write_tx.clone();let per_pane = self.per_pane(pane_id);+ let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {let mux = Mux::get();+ let _identity = mux.with_identity(client_id.clone());let pane = mux.get_pane(pane_id).ok_or_else(|| anyhow!("no such pane {}", pane_id))?;+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ pane_id,+ )?;activate_client_palette(&mux, &pane, palette_session_id)?;pane.writer().write_all(&data)?;maybe_push_pane_changes(&pane, sender, per_pane)?;@@ -595,13 +725,22 @@ impl SessionHandler {Pdu::SendPaste(SendPaste { pane_id, data }) => {let sender = self.to_write_tx.clone();let per_pane = self.per_pane(pane_id);+ let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {let mux = Mux::get();+ let _identity = mux.with_identity(client_id.clone());let pane = mux.get_pane(pane_id).ok_or_else(|| anyhow!("no such pane {}", pane_id))?;+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ pane_id,+ )?;activate_client_palette(&mux, &pane, palette_session_id)?;pane.send_paste(&data)?;maybe_push_pane_changes(&pane, sender, per_pane)?;@@ -716,10 +855,18 @@ impl SessionHandler {}Pdu::ActivatePaneDirection(ActivatePaneDirection { pane_id, direction }) => {+ let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {let mux = Mux::get();+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ pane_id,+ )?;let (_domain_id, _window_id, tab_id) = mux.resolve_pane_id(pane_id).ok_or_else(|| anyhow!("no such pane {}", pane_id))?;@@ -753,17 +900,37 @@ impl SessionHandler {pane_id,size,}) => {+ let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {let mux = Mux::get();+ if let (Some(client_id), Some(registration)) =+ (client_id.as_ref(), registration)+ {+ match mux.registered_client_may_resize_tab(+ client_id,+ registration,+ containing_tab_id,+ ) {+ None => anyhow::bail!("client connection was superseded"),+ Some(false) => {+ return Ok(Pdu::UnitResponse(UnitResponse {}));+ }+ Some(true) => {}+ }+ }let pane = mux.get_pane(pane_id).ok_or_else(|| anyhow!("no such pane {}", pane_id))?;- pane.resize(size)?;let tab = mux.get_tab(containing_tab_id).ok_or_else(|| anyhow!("no such tab {}", containing_tab_id))?;+ if !tab.contains_pane(pane_id) {+ anyhow::bail!("pane {pane_id} is not in tab {containing_tab_id}");+ }+ pane.resize(size)?;tab.rebuild_splits_sizes_from_contained_panes();Ok(Pdu::UnitResponse(UnitResponse {}))},@@ -780,13 +947,22 @@ impl SessionHandler {}) => {let sender = self.to_write_tx.clone();let per_pane = self.per_pane(pane_id);+ let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {let mux = Mux::get();+ let _identity = mux.with_identity(client_id.clone());let pane = mux.get_pane(pane_id).ok_or_else(|| anyhow!("no such pane {}", pane_id))?;+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ pane_id,+ )?;activate_client_palette(&mux, &pane, palette_session_id)?;pane.key_down(event.key, event.modifiers)?;@@ -811,13 +987,22 @@ impl SessionHandler {Pdu::SendMouseEvent(SendMouseEvent { pane_id, event }) => {let sender = self.to_write_tx.clone();let per_pane = self.per_pane(pane_id);+ let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {catch(move || {let mux = Mux::get();+ let _identity = mux.with_identity(client_id.clone());let pane = mux.get_pane(pane_id).ok_or_else(|| anyhow!("no such pane {}", pane_id))?;+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ pane_id,+ )?;activate_client_palette(&mux, &pane, palette_session_id)?;// The client coalesces rapid wheel motion into a single// event with an accumulated amount, but the terminal@@ -877,6 +1062,7 @@ impl SessionHandler {Pdu::ActivatePaneInStack(request) => {let client_id = self.client_id.clone();+ let registration = self.client_registration;spawn_into_main_thread(async move {let mux = Mux::get();let _identity = mux.with_identity(client_id.clone());@@ -884,6 +1070,12 @@ impl SessionHandler {let pane = mux.get_pane(request.pane_id).ok_or_else(|| anyhow!("no such pane {}", request.pane_id))?;+ claim_viewport_for_pane(+ &mux,+ client_id.as_ref(),+ registration,+ request.pane_id,+ )?;let (_domain_id, _window_id, tab_id) = mux.resolve_pane_id(request.pane_id).ok_or_else(|| anyhow!("no such pane {}", request.pane_id))?;@@ -919,6 +1111,88 @@ impl SessionHandler {})));}+ Pdu::GetThinkTermSessionState(_) => {+ send_response(crate::thinkterm_session::snapshot().map(Pdu::ThinkTermSessionState));+ }++ Pdu::EnsureThinkTermThread(request) => {+ let client_id = self.client_id.clone();+ spawn_into_main_thread(async move {+ schedule_ensure_thinkterm_thread(request, send_response, client_id);+ })+ .detach();+ }++ Pdu::SetClientViewport(SetClientViewport { tab_id, viewport }) => {+ let client_id = self.client_id.clone();+ let registration = self.client_registration;+ spawn_into_main_thread(async move {+ catch(+ move || {+ let client_id = client_id.ok_or_else(|| {+ anyhow!("SetClientViewport requires an identified client")+ })?;+ let registration = registration.ok_or_else(|| {+ anyhow!("SetClientViewport requires a live client registration")+ })?;+ let mux = Mux::get();+ let state = mux+ .set_registered_client_viewport(+ &client_id,+ registration,+ tab_id,+ mux_viewport(viewport),+ )?+ .ok_or_else(|| anyhow!("client connection was superseded"))?;+ Ok(Pdu::ClientViewportState(codec_viewport_state(state)))+ },+ send_response,+ )+ })+ .detach();+ }++ // Offering a view is not a claim: a renderer that is not driving is+ // ignored, so this can be sent freely without stealing the lease.+ Pdu::SetClientView(codec::SetClientView { tab_id, view }) => {+ let client_id = self.client_id.clone();+ spawn_into_main_thread(async move {+ catch(+ move || {+ let client_id = client_id.ok_or_else(|| {+ anyhow!("SetClientView requires an identified client")+ })?;+ Mux::get().set_client_view(&client_id, tab_id, mux_view(view));+ Ok(Pdu::UnitResponse(UnitResponse {}))+ },+ send_response,+ )+ })+ .detach();+ }+ Pdu::ClaimClientViewport(ClaimClientViewport { tab_id }) => {+ let client_id = self.client_id.clone();+ let registration = self.client_registration;+ spawn_into_main_thread(async move {+ catch(+ move || {+ let client_id = client_id.ok_or_else(|| {+ anyhow!("ClaimClientViewport requires an identified client")+ })?;+ let registration = registration.ok_or_else(|| {+ anyhow!("ClaimClientViewport requires a live client registration")+ })?;+ let state = Mux::get()+ .claim_registered_client_viewport(&client_id, registration, tab_id)?+ .ok_or_else(|| anyhow!("client connection was superseded"))?;+ Ok(Pdu::ClientViewportState(codec_viewport_state(state)))+ },+ send_response,+ )+ })+ .detach();+ }+Pdu::MutateThinkTermTree(MutateThinkTermTree { ops }) => {// mutate() broadcasts to every connection when the batch// changed something; the direct response here is what lets the@@ -1062,6 +1336,7 @@ impl SessionHandler {send_response(Ok(Pdu::GetCodecVersionResponse(GetCodecVersionResponse {codec_vers: CODEC_VERSION,version_string: config::wezterm_version().to_owned(),+ server_id: Mux::get().runtime_server_id().to_string(),executable_path,config_file_path: std::env::var_os("WEZTERM_CONFIG_FILE").map(Into::into),@@ -1205,6 +1480,9 @@ impl SessionHandler {| Pdu::TabAddedToWindow { .. }| Pdu::GetPaneRenderableDimensionsResponse { .. }| Pdu::ThinkTermTreeState { .. }+ | Pdu::ThinkTermSessionState { .. }+ | Pdu::EnsureThinkTermThreadResponse { .. }+ | Pdu::ClientViewportState { .. }| Pdu::ErrorResponse { .. } => {send_response(Err(anyhow!("expected a request, got {:?}", decoded.pdu)))}@@ -1227,6 +1505,66 @@ fn schedule_domain_spawn_v2<SND>(.detach();}+fn schedule_ensure_thinkterm_thread<SND>(+ request: EnsureThinkTermThread,+ send_response: SND,+ client_id: Option<Arc<ClientId>>,+) where+ SND: Fn(anyhow::Result<Pdu>) + 'static,+{+ promise::spawn::spawn(async move {+ send_response(ensure_thinkterm_thread(request, client_id).await)+ })+ .detach();+}++async fn ensure_thinkterm_thread(+ request: EnsureThinkTermThread,+ client_id: Option<Arc<ClientId>>,+) -> anyhow::Result<Pdu> {+ let _materialize = THINKTERM_MATERIALIZE.lock().await;+ let mux = Mux::get();+ let _identity = mux.with_identity(client_id);+ let landing = crate::thinkterm_tree::ensure_landing(request.preferred_thread_id.as_deref())?;++ let has_live_pane = mux+ .iter_windows_in_workspace(&landing.workspace)+ .into_iter()+ .filter_map(|window_id| mux.get_window(window_id))+ .any(|window| window.iter().any(|tab| !tab.iter_all_panes().is_empty()));++ let spawned = if has_live_pane {+ false+ } else {+ let command_dir = match landing.project_path.trim() {+ "" => None,+ path if path.starts_with("wezterm-mux://") => None,+ path => Some(path.to_string()),+ };+ mux.spawn_tab_or_window(+ None,+ SpawnTabDomain::DefaultDomain,+ None,+ command_dir,+ request.size,+ None,+ landing.workspace.clone(),+ None,+ )+ .await?;+ crate::thinkterm_session::publish_changed();+ true+ };++ Ok(Pdu::EnsureThinkTermThreadResponse(+ EnsureThinkTermThreadResponse {+ thread_id: landing.thread_id,+ workspace: landing.workspace,+ spawned,+ },+ ))+}+fn schedule_split_pane<SND>(split: SplitPane, send_response: SND, client_id: Option<Arc<ClientId>>)whereSND: Fn(anyhow::Result<Pdu>) + 'static,diff --git a/wezterm-mux-server-impl/src/thinkterm_session.rs b/wezterm-mux-server-impl/src/thinkterm_session.rsnew file mode 100644index 00000000..d7bfe142--- /dev/null+++ b/wezterm-mux-server-impl/src/thinkterm_session.rs@@ -0,0 +1,118 @@+//! Authoritative ThinkTerm session snapshots built by the mux server.+//!+//! The persisted tree supplies Space/Project/Thread identity and ordering;+//! the live mux supplies the exact window/tab/pane mapping. No client cache or+//! GUI projection participates in this view.++use codec::{+ ThinkTermSessionProject, ThinkTermSessionSpace, ThinkTermSessionState, ThinkTermSessionTab,+ ThinkTermSessionThread, ThinkTermSessionWorkStatus,+};+use mux::{Mux, MuxNotification};+use std::sync::atomic::{AtomicU64, Ordering};+use wezterm_term::Progress;++static GENERATION: AtomicU64 = AtomicU64::new(1);++pub fn snapshot() -> anyhow::Result<ThinkTermSessionState> {+ let tree = crate::thinkterm_tree::snapshot();+ let mux = Mux::get();++ let spaces = tree+ .spaces+ .iter()+ .map(|space| ThinkTermSessionSpace {+ id: space.id.clone(),+ name: space.name.clone(),+ is_default: false,+ domain: None,+ })+ .collect();++ let projects = tree+ .projects+ .iter()+ .map(|project| ThinkTermSessionProject {+ id: project.id.clone(),+ space_id: project.space_id.clone(),+ name: project.name.clone(),+ path: project.path.clone(),+ threads: project+ .threads+ .iter()+ .map(|thread| {+ let workspace = thread+ .materialized_workspace_name+ .as_deref()+ .or(thread.planned_workspace_name.as_deref());+ let mut tabs = Vec::new();+ let mut running = false;+ let mut needs_attention = false;+ if let Some(workspace) = workspace {+ for window_id in mux.iter_windows_in_workspace(workspace) {+ let Some(window) = mux.get_window(window_id) else {+ continue;+ };+ let active_tab = window.get_active().map(|tab| tab.tab_id());+ tabs.extend(window.iter().map(|tab| {+ let panes = tab.iter_all_panes();+ for pane in &panes {+ match pane.get_progress() {+ Progress::None => {}+ Progress::Percentage(_) | Progress::Indeterminate => {+ running = true;+ }+ Progress::Error(_) => needs_attention = true,+ }+ }+ ThinkTermSessionTab {+ window_id,+ tab_id: tab.tab_id(),+ pane_ids: panes+ .into_iter()+ .map(|pane| pane.pane_id())+ .collect(),+ title: tab.get_title(),+ is_active: active_tab == Some(tab.tab_id()),+ }+ }));+ }+ }+ ThinkTermSessionThread {+ id: thread.id.clone(),+ project_id: thread.project_id.clone(),+ name: thread.name.clone(),+ planned_workspace_name: thread.planned_workspace_name.clone(),+ materialized_workspace_name: thread.materialized_workspace_name.clone(),+ is_pinned: thread.is_pinned,+ is_unread: thread.is_unread,+ work_status: if thread.is_unread {+ ThinkTermSessionWorkStatus::FinishedUnseen+ } else if needs_attention {+ ThinkTermSessionWorkStatus::NeedsAttention+ } else if running {+ ThinkTermSessionWorkStatus::Running+ } else {+ ThinkTermSessionWorkStatus::Idle+ },+ tabs,+ }+ })+ .collect(),+ })+ .collect();++ Ok(ThinkTermSessionState {+ server_id: mux.runtime_server_id().to_string(),+ tree_revision: tree.revision,+ generation: GENERATION.fetch_add(1, Ordering::AcqRel),+ spaces,+ projects,+ })+}++/// Kept as the notification bridge for topology/tree callers. The payload is+/// always rebuilt from server-owned state when dispatch sends it.+pub fn publish_changed() {+ Mux::notify_from_any_thread(MuxNotification::ThinkTermSessionChanged);+}diff --git a/wezterm-mux-server-impl/src/thinkterm_tree.rs b/wezterm-mux-server-impl/src/thinkterm_tree.rsindex 0dc34fbe..64ca8206 100644--- a/wezterm-mux-server-impl/src/thinkterm_tree.rs+++ b/wezterm-mux-server-impl/src/thinkterm_tree.rs@@ -11,11 +11,21 @@//! buy at this size (tens of KB) that an atomic file replace does not.use anyhow::{Context, Result};-use codec::{apply_op, ensure_unique_thread_names, ThinkTermTree, TreeOp};+use codec::{+ apply_op, ensure_unique_thread_names, ThinkTermTree, TreeOp, TtProject, TtSpace, TtThread,+};use mux::{Mux, MuxNotification};use std::io::Write;use std::path::{Path, PathBuf};use std::sync::Mutex;+use uuid::Uuid;++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LandingRecord {+ pub thread_id: String,+ pub workspace: String,+ pub project_path: String,+}lazy_static::lazy_static! {static ref TREE: Mutex<ThinkTermTree> = Mutex::new(load_or_default());@@ -101,6 +111,143 @@ pub fn snapshot() -> ThinkTermTree {TREE.lock().unwrap().clone()}+fn new_id(kind: &str) -> String {+ format!("{kind}-{}", Uuid::new_v4())+}++fn workspace_name(project_id: &str, thread_id: &str) -> String {+ format!("thinkterm:{project_id}:{thread_id}")+}++/// Resolve a landing Thread against the authoritative tree. Missing+/// Default/Home/main rows are created here, never reconstructed from a client+/// cache. The operation is idempotent: once a usable Thread exists, repeated+/// calls only return it.+fn ensure_landing_in_tree(+ tree: &mut ThinkTermTree,+ preferred_thread_id: Option<&str>,+) -> (LandingRecord, bool) {+ let mut changed = false;+ let selected = preferred_thread_id+ .and_then(|preferred| {+ tree.projects+ .iter()+ .enumerate()+ .find_map(|(project_index, project)| {+ project+ .threads+ .iter()+ .position(|thread| thread.id == preferred)+ .map(|thread_index| (project_index, thread_index))+ })+ })+ .or_else(|| {+ tree.projects+ .iter()+ .enumerate()+ .find_map(|(project_index, project)| {+ (!project.threads.is_empty()).then_some((project_index, 0))+ })+ });++ let (project_index, thread_index) = match selected {+ Some(selected) => selected,+ None => {+ if tree.spaces.is_empty() {+ tree.spaces.push(TtSpace {+ id: new_id("space"),+ name: "Default".to_string(),+ });+ }++ let project_index = tree+ .projects+ .iter()+ .position(|project| tree.spaces.iter().any(|space| space.id == project.space_id));+ let project_index = match project_index {+ Some(index) => index,+ None => {+ let space_id = tree.spaces[0].id.clone();+ tree.projects.push(TtProject {+ id: new_id("project"),+ space_id,+ name: "Home".to_string(),+ path: "~".to_string(),+ threads: vec![],+ });+ tree.projects.len() - 1+ }+ };++ let project_id = tree.projects[project_index].id.clone();+ tree.projects[project_index].threads.push(TtThread {+ id: new_id("thread"),+ project_id,+ name: "main".to_string(),+ planned_workspace_name: None,+ materialized_workspace_name: None,+ last_active_at: 0,+ is_pinned: false,+ is_unread: false,+ });+ changed = true;+ (+ project_index,+ tree.projects[project_index].threads.len() - 1,+ )+ }+ };++ let project = &mut tree.projects[project_index];+ let project_id = project.id.clone();+ let thread = &mut project.threads[thread_index];+ let workspace = thread+ .materialized_workspace_name+ .clone()+ .or_else(|| thread.planned_workspace_name.clone())+ .unwrap_or_else(|| workspace_name(&project_id, &thread.id));+ if thread.materialized_workspace_name.as_deref() != Some(&workspace)+ || thread.planned_workspace_name.is_some()+ {+ thread.planned_workspace_name = None;+ thread.materialized_workspace_name = Some(workspace.clone());+ changed = true;+ }++ (+ LandingRecord {+ thread_id: thread.id.clone(),+ workspace,+ project_path: project.path.clone(),+ },+ changed,+ )+}++/// Ensure a server-owned landing Thread and persist it before any terminal is+/// spawned into its workspace. A server restart may leave a valid tree with+/// no live topology; retaining the row IDs while recreating the shell is the+/// intended recovery behavior.+pub fn ensure_landing(preferred_thread_id: Option<&str>) -> Result<LandingRecord> {+ let (landing, changed) = {+ let mut guard = TREE.lock().unwrap();+ let mut candidate = guard.clone();+ let (landing, changed) = ensure_landing_in_tree(&mut candidate, preferred_thread_id);+ if changed {+ ensure_unique_thread_names(&mut candidate);+ candidate.revision = candidate.revision.saturating_add(1);+ save_to_path(&tree_path(), &candidate)+ .context("persist authoritative ThinkTerm landing")?;+ *guard = candidate;+ }+ (landing, changed)+ };+ if changed {+ Mux::notify_from_any_thread(MuxNotification::ThinkTermTreeChanged);+ }+ Ok(landing)+}+fn apply_and_persist(current: &ThinkTermTree,ops: &[TreeOp],@@ -170,7 +317,7 @@ mod test {project_id: "p1".into(),space_id: "s1".into(),name: "thinkterm".into(),- path: "/home/x/github/ThinkTerm".into(),+ path: "/srv/projects/example".into(),}));assert!(apply_op(@@ -284,4 +431,50 @@ mod test {assert_eq!(current.space("s1").unwrap().name, "Work");assert_eq!(current.revision, 0);}++ #[test]+ fn landing_bootstraps_default_home_main_once() {+ let mut tree = ThinkTermTree::default();+ let (first, changed) = ensure_landing_in_tree(&mut tree, None);+ assert!(changed);+ assert_eq!(tree.spaces.len(), 1);+ assert_eq!(tree.spaces[0].name, "Default");+ assert_eq!(tree.projects.len(), 1);+ assert_eq!(tree.projects[0].name, "Home");+ assert_eq!(tree.projects[0].path, "~");+ assert_eq!(tree.projects[0].threads.len(), 1);+ assert_eq!(tree.projects[0].threads[0].name, "main");+ assert_eq!(first.thread_id, tree.projects[0].threads[0].id);++ let (second, changed) = ensure_landing_in_tree(&mut tree, None);+ assert!(!changed);+ assert_eq!(second, first);+ assert_eq!(tree.spaces.len(), 1);+ assert_eq!(tree.projects.len(), 1);+ assert_eq!(tree.projects[0].threads.len(), 1);+ }++ #[test]+ fn landing_honors_an_existing_preferred_thread() {+ let mut tree = sample();+ let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("t1"));+ assert!(!changed);+ assert_eq!(landing.thread_id, "t1");+ assert_eq!(landing.workspace, "thinkterm:p1:t1");+ assert_eq!(landing.project_path, "/srv/projects/example");+ }++ #[test]+ fn landing_after_an_authoritative_empty_tree_uses_fresh_ids() {+ let mut tree = ThinkTermTree {+ revision: 9,+ ..ThinkTermTree::default()+ };+ let (landing, changed) = ensure_landing_in_tree(&mut tree, Some("stale-thread"));+ assert!(changed);+ assert_ne!(landing.thread_id, "stale-thread");+ assert!(landing.thread_id.starts_with("thread-"));+ assert!(tree.spaces[0].id.starts_with("space-"));+ assert!(tree.projects[0].id.starts_with("project-"));+ }}diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.tomlindex 3ecd55d0..2608015e 100644--- a/wezterm/Cargo.toml+++ b/wezterm/Cargo.toml@@ -43,6 +43,7 @@ tempfile.workspace = truetermwiz-funcs.workspace = truetermwiz.workspace = truetextwrap.workspace =true+thinkterm-tui = { path = "../thinkterm-tui" }umask.workspace = trueurl.workspace = truewezterm-client.workspace = truediff --git a/wezterm/src/main.rs b/wezterm/src/main.rsindex 52a2a776..17260054 100644--- a/wezterm/src/main.rs+++ b/wezterm/src/main.rs@@ -225,6 +225,9 @@ enum SubCommand {#[command(name = "connect", about = "Connect to ThinkTerm multiplexer")]Connect(ConnectCommand),+ #[command(name = "tui", about = "Open the ThinkTerm terminal interface")]+ Tui(TuiCommand),+#[command(name = "ls-fonts", about = "Display information about fonts")]LsFonts(LsFontsCommand),@@ -259,6 +262,22 @@ enum SubCommand {},}+#[derive(Debug, Parser, Clone, Default)]+struct TuiCommand {+ /// Mux client domains to show. Defaults to Local when omitted; remote+ /// domains can also be attached later from the Connections panel.+ #[arg(value_name = "DOMAIN")]+ domains: Vec<String>,++ /// Window class used to discover a running ThinkTerm GUI socket.+ #[arg(long, default_value = wezterm_gui_subcommands::DEFAULT_WINDOW_CLASS)]+ class: String,++ /// Override the independent ThinkTerm TUI settings file.+ #[arg(long, value_name = "PATH")]+ tui_config: Option<std::path::PathBuf>,+}+use termwiz::escape::osc::{ITermDimension, ITermFileData, ITermProprietary, OperatingSystemCommand,};@@ -870,6 +889,14 @@ fn run() -> anyhow::Result<()> {SubCommand::Cli(cli) => cli::run_cli(&opts, cli),SubCommand::Record(cmd) => cmd.run(init_config(&opts)?),SubCommand::Replay(cmd) => cmd.run(),+ SubCommand::Tui(cmd) => thinkterm_tui::run(+ init_config(&opts)?,+ thinkterm_tui::TuiOptions {+ domains: cmd.domains,+ class_name: cmd.class,+ tui_config_path: cmd.tui_config,+ },+ ),SubCommand::ShellCompletion { shell } => {let rendered = render_shell_completion(shell)?;std::io::stdout().write_all(rendered.as_bytes())?;diff --git a/window/Cargo.toml b/window/Cargo.tomlindex 50250c89..e0daa750 100644--- a/window/Cargo.toml+++ b/window/Cargo.toml@@ -59,6 +59,7 @@ winapi = { workspace=true, features = ["imm","libloaderapi","objbase",+ "playsoundapi","shellscalingapi","shobjidl","shobjidl_core",diff --git a/window/src/connection.rs b/window/src/connection.rsindex a505c3e7..43961f65 100644--- a/window/src/connection.rs+++ b/window/src/connection.rs@@ -79,6 +79,21 @@ pub trait ConnectionOps {/// Perform the system beep/notification soundfn beep(&self) {}+ /// Play a WAV held in memory, without blocking.+ ///+ /// This is fire-and-forget on purpose: a prompt that fails to sound must+ /// never disturb the work it was reporting on, so every implementation+ /// swallows its errors into the log. A platform with no way to play one+ /// stays silent, which is the same outcome the user gets by turning the+ /// sounds off.+ ///+ /// The bytes are `'static` because playback outlives this call on every+ /// platform: Windows keeps reading the caller's buffer for the duration of+ /// an async `PlaySound`, and the unix implementation hands it to a thread.+ /// `include_bytes!` already yields exactly this, so the bound costs the+ /// callers nothing and removes the lifetime hazard entirely.+ fn play_sound(&self, _wav: &'static [u8]) {}+/// Returns information about the screensfn screens(&self) -> anyhow::Result<Screens> {anyhow::bail!("Unable to query screen information");diff --git a/window/src/lib.rs b/window/src/lib.rsindex 2b746b40..816c3b88 100644--- a/window/src/lib.rs+++ b/window/src/lib.rs@@ -219,6 +219,7 @@ pub enum ContextMenuIcon {Copy,Cut,Delete,+ Disconnect,Edit,Expand,ExternalLink,@@ -249,7 +250,6 @@ pub enum ContextMenuIcon {Terminal,Undo,Unpin,- Unplug,Vault,Warning,Window,@@ -282,6 +282,11 @@ impl ContextMenuIcon {Self::Copy => "doc.on.doc",Self::Cut => "scissors",Self::Delete => "trash",+ // The Finder gesture for "stop using this server, it stays up".+ // A plug symbol would read better but every spelling of one is too+ // new to rely on, and the fallback bitmap looks nothing like its+ // neighbours.+ Self::Disconnect => "eject",Self::Edit => "pencil",Self::Expand => "rectangle.expand.vertical",Self::ExternalLink => "arrow.up.right.square",@@ -312,9 +317,6 @@ impl ContextMenuIcon {Self::Terminal => "terminal",Self::Undo => "arrow.uturn.backward",Self::Unpin => "pin.slash",- // Only in recent SF Symbols releases; older systems fall through to- // the bundled Lucide unplug glyph, which is the same picture.- Self::Unplug => "powerplug.portrait.slash",Self::Warning => "exclamationmark.circle",Self::Window => "macwindow",}@@ -333,6 +335,7 @@ impl ContextMenuIcon {Self::Copy => include_bytes!("../../third_party/lucide/icons/copy.svg"),Self::Cut => include_bytes!("../../third_party/lucide/icons/scissors.svg"),Self::Delete => include_bytes!("../../third_party/lucide/icons/trash-2.svg"),+ Self::Disconnect => include_bytes!("../../third_party/lucide/icons/unlink-2.svg"),Self::Edit => include_bytes!("../../third_party/lucide/icons/pencil.svg"),Self::Expand => include_bytes!("../../third_party/lucide/icons/expand.svg"),Self::ExternalLink => {@@ -370,7 +373,6 @@ impl ContextMenuIcon {Self::Terminal => include_bytes!("../../third_party/lucide/icons/terminal.svg"),Self::Undo => include_bytes!("../../third_party/lucide/icons/undo.svg"),Self::Unpin => include_bytes!("../../third_party/lucide/icons/pin-off.svg"),- Self::Unplug => include_bytes!("../../third_party/lucide/icons/unplug.svg"),Self::Vault => include_bytes!("../../third_party/lucide/icons/folder-tree.svg"),Self::Warning => include_bytes!("../../third_party/lucide/icons/circle-alert.svg"),Self::Window => include_bytes!("../../third_party/lucide/icons/panels-top-left.svg"),diff --git a/window/src/os/macos/connection.rs b/window/src/os/macos/connection.rsindex 32c3a462..10a30e39 100644--- a/window/src/os/macos/connection.rs+++ b/window/src/os/macos/connection.rs@@ -11,7 +11,8 @@ use crate::Appearance;use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSScreen};use cocoa::base::{id, nil};use cocoa::foundation::{NSArray, NSInteger};-use objc::runtime::{Object, BOOL, YES};+use objc::rc::StrongPtr;+use objc::runtime::{Object, BOOL, NO, YES};use objc::*;use serde::Deserialize;use std::cell::RefCell;@@ -205,6 +206,35 @@ impl ConnectionOps for Connection {}}+ fn play_sound(&self, wav: &'static [u8]) {+ unsafe {+ // NSData borrows the bytes; NSSound copies what it needs during+ // initWithData:, so the borrow does not have to outlive this call.+ let data: id = msg_send![+ class!(NSData),+ dataWithBytes: wav.as_ptr()+ length: wav.len()+ ];+ if data.is_null() {+ log::warn!("could not wrap {} bytes of audio for NSSound", wav.len());+ return;+ }+ let sound: id = msg_send![class!(NSSound), alloc];+ let sound: id = msg_send![sound, initWithData: data];+ if sound.is_null() {+ log::warn!("NSSound rejected the audio data");+ return;+ }+ let sound = StrongPtr::new(sound);+ // -play returns immediately and NSSound keeps itself alive for the+ // duration, so dropping our reference here does not cut it short.+ let started: BOOL = msg_send![*sound, play];+ if started == NO {+ log::warn!("NSSound refused to play");+ }+ }+ }+fn screens(&self) -> anyhow::Result<Screens> {let mut by_name = HashMap::new();let mut virtual_rect = euclid::rect(0, 0, 0, 0);diff --git a/window/src/os/windows/connection.rs b/window/src/os/windows/connection.rsindex 79c122c9..bc5954b2 100644--- a/window/src/os/windows/connection.rs+++ b/window/src/os/windows/connection.rs@@ -15,6 +15,7 @@ use std::rc::Rc;use winapi::shared::minwindef::*;use winapi::shared::windef::*;use winapi::shared::winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS};+use winapi::um::playsoundapi::{PlaySoundW, SND_ASYNC, SND_MEMORY, SND_NODEFAULT};use winapi::um::shellscalingapi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};use winapi::um::winbase::INFINITE;use winapi::um::wingdi::{@@ -112,6 +113,23 @@ impl ConnectionOps for Connection {}}+ fn play_sound(&self, wav: &'static [u8]) {+ unsafe {+ // SND_MEMORY reads the WAV image out of our buffer rather than a+ // file, and SND_ASYNC means it keeps reading after we return —+ // which is exactly why the bytes have to be 'static. SND_NODEFAULT+ // keeps a rejected buffer from turning into the system ding.+ if PlaySoundW(+ wav.as_ptr() as *const u16,+ null_mut(),+ SND_MEMORY | SND_ASYNC | SND_NODEFAULT,+ ) == 0+ {+ log::warn!("PlaySound refused {} bytes of audio", wav.len());+ }+ }+ }+fn screens(&self) -> anyhow::Result<Screens> {let mut info = ScreenInfoHelper::new()?;info.enumerate();diff --git a/window/src/os/x_and_wayland.rs b/window/src/os/x_and_wayland.rsindex 6d477dbe..d41b14fd 100644--- a/window/src/os/x_and_wayland.rs+++ b/window/src/os/x_and_wayland.rs@@ -36,6 +36,57 @@ pub enum Window {Wayland(WaylandWindow),}+/// Players that accept a WAV on stdin, and the argument each needs to be told+/// to read it from there. Nothing is written to disk and no decoder is+/// involved, which is the whole reason the bundled sounds are WAV rather than+/// the MP3 that comparable tools ship: MP3 would drag in a chain of optional+/// decoders and a temporary file on this platform alone.+const WAV_PLAYERS: &[(&str, &[&str])] = &[("paplay", &[]), ("pw-play", &["-"])];++fn play_wav(wav: &'static [u8]) {+ use std::io::Write;+ use std::process::{Command, Stdio};++ let spawned = std::thread::Builder::new()+ .name("thinkterm-sound".to_string())+ .spawn(move || {+ for (player, args) in WAV_PLAYERS {+ let child = Command::new(player)+ .args(*args)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn();+ let mut child = match child {+ Ok(child) => child,+ Err(err) => {+ log::debug!("{player} is unavailable: {err}");+ continue;+ }+ };+ if let Some(mut stdin) = child.stdin.take() {+ // Dropping stdin at the end of this block is what signals+ // end-of-stream. A player that gives up early (no sink, or+ // a format it dislikes) closes the pipe first, and that+ // broken pipe is not worth reporting.+ let _ = stdin.write_all(wav);+ }+ // Waiting here rather than detaching is what keeps a zombie+ // from accumulating for every notification.+ match child.wait() {+ Ok(status) if status.success() => return,+ Ok(status) => log::debug!("{player} exited with {status}"),+ Err(err) => log::debug!("could not wait for {player}: {err}"),+ }+ }+ log::debug!("no WAV player available; the notification stays silent");+ });++ if let Err(err) = spawned {+ log::warn!("could not start the sound thread: {err}");+ }+}+impl Connection {pub(crate) fn create_new() -> anyhow::Result<Connection> {#[cfg(feature = "wayland")]@@ -168,6 +219,12 @@ impl ConnectionOps for Connection {}}+ fn play_sound(&self, wav: &'static [u8]) {+ // Audio does not go through the display server, so both arms share one+ // implementation instead of each growing its own copy.+ play_wav(wav);+ }+fn screens(&self) -> anyhow::Result<Screens> {match self {Self::X11(x) => x.screens(),