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
mobile: ten medium findings of the review
RoversXd5c5623f8ad0
diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt b/android/app/src/main/java/com/roversx/thinkterm/HostStore.ktindex 375d9818..591d33fd 100644--- a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt@@ -171,10 +171,10 @@ class HostStore(context: Context) {port = o.optInt("port", 22),user = o.optString("user"),auth = o.optString("auth", "key"),- knownHost = o.optString("knownHost").ifEmpty { null },+ knownHost = o.stringOrNull("knownHost"),remoteCommand = o.optString("remoteCommand"),group = o.optString("group"),- publicKey = o.optString("publicKey").ifEmpty { null },+ publicKey = o.stringOrNull("publicKey"),lastConnected = if (o.isNull("lastConnected")) null else o.optLong("lastConnected"),)}@@ -187,6 +187,11 @@ class HostStore(context: Context) {private companion object {const val KEY = "hosts.v1"+ /// A string field, or null for one absent, null or empty --+ /// `optString` would read a JSON null as the word "null".+ fun JSONObject.stringOrNull(key: String): String? =+ if (!has(key) || isNull(key)) null else optString(key).ifEmpty { null }+const val SECRETS = "thinkterm-secrets"/// Keystore-backed preferences. A file whose keyset the keystorediff --git a/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt b/android/app/src/main/java/com/roversx/thinkterm/Sidebar.ktindex 8de4bb20..f59b0cfd 100644--- a/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/Sidebar.kt@@ -108,10 +108,11 @@ private fun SidebarTree(model: TerminalModel, onDismiss: () -> Unit, onEditHost:LaunchedEffect(Unit) { model.refreshViews() }LaunchedEffect(editing) {- val id = editing?.id- if (editing == null || editing.kind == "none" || id == null || renaming != null) return@LaunchedEffect+ // A new project has no id yet: the same field, asking for the+ // name of what is about to exist.+ if (editing == null || editing.kind == "none" || renaming != null) return@LaunchedEffectrenameText = ""- renaming = editing.kind to id+ renaming = editing.kind to (editing.id ?: "")}Column(Modifier.fillMaxSize()) {@@ -302,7 +303,7 @@ private fun SidebarTree(model: TerminalModel, onDismiss: () -> Unit, onEditHost:if (renaming != null) {AlertDialog(onDismissRequest = { model.sideKey("Escape", ""); renaming = null },- title = { Text(tr("rename")) },+ title = { Text(tr(if (renaming?.first == "new-project") "project.new" else "rename")) },text = { OutlinedTextField(value = renameText, onValueChange = { renameText = it }, label = { Text(tr("f.name")) }, singleLine = true) },confirmButton = { TextButton(onClick = { model.sideKey("Enter", renameText); renaming = null }) { Text(tr("save")) } },dismissButton = { TextButton(onClick = { model.sideKey("Escape", ""); renaming = null }) { Text(tr("cancel")) } },diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.ktindex af0816de..d8a335ff 100644--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt@@ -113,6 +113,9 @@ class TerminalModel(/// The view sets these so the core can ask for the keyboard and the/// selection can be redrawn when the screen changes.var onFocusRequested: (() -> Unit)? = null+ /// The connection changed under an open IME composition: the view+ /// lets it go, so it does not land in whatever comes next.+ var onDropComposition: (() -> Unit)? = nullvar onScreenChanged: (() -> Unit)? = nullvar onHideKeyboard: (() -> Unit)? = null/// A selection stands: where its copy chip goes, in dp from the@@ -459,6 +462,7 @@ class TerminalModel(}if (status.startsWith("connecting") || status.contains("reconnect") || status.startsWith("disconnected")) {composing = null+ onDropComposition?.invoke()}changePending.set(true)}diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalView.ktindex 9c35365f..b87a941a 100644--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalView.kt@@ -44,7 +44,10 @@ class TerminalHostView(context: Context, private val model: TerminalModel) : Fratexture.isOpaque = falseaddView(texture, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))addView(input, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))- model.onFocusRequested = { input.focusAndShowKeyboard() }+ // The App asks for focus after a press, a finished rename and+ // every answered request; on a phone that must not raise the+ // keyboard (a tap does that itself), only keep it where it is.+ model.onFocusRequested = { if (input.keyboardShown()) input.requestFocus() }model.onHideKeyboard = { input.hideKeyboard() }texture.surfaceTextureListener = object : TextureView.SurfaceTextureListener {override fun onSurfaceTextureAvailable(st: SurfaceTexture, width: Int, height: Int) {@@ -114,17 +117,18 @@ class TerminalHostView(context: Context, private val model: TerminalModel) : Fraclass TerminalInputView(context: Context, private val model: TerminalModel) : View(context) {private val settings get() = model.settingsprivate val slop = ViewConfiguration.get(context).scaledTouchSlop- private val tapTimeout = ViewConfiguration.getTapTimeout().toLong() * 2private val longPressTimeout = ViewConfiguration.getLongPressTimeout().toLong()private val minFling = ViewConfiguration.get(context).scaledMinimumFlingVelocity * 4private val main = Handler(Looper.getMainLooper())private var downX = 0fprivate var downY = 0fprivate var lastY = 0f- private var downAt = 0Lprivate var dragging = falseprivate var pinching = falseprivate var pinchStart = 1f+ /// The fingers' distance when the pinch began: the scale is measured+ /// from there, not from one event to the next.+ private var pinchSpan = 0fprivate var rowRemainder = 0fprivate var velocity: VelocityTracker? = nullprivate val scroller = OverScroller(context)@@ -156,6 +160,7 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vioverride fun onScaleBegin(d: ScaleGestureDetector): Boolean {if (!settings.pinchZoom) return falsepinchStart = 1f+ pinchSpan = d.currentSpanpinching = truedropLongPress()return true@@ -163,11 +168,13 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vioverride fun onScale(d: ScaleGestureDetector): Boolean {// One font step per 15% of scale, either way, as on iOS.- while (d.scaleFactor > pinchStart * 1.15f) {+ if (pinchSpan <= 0f) return true+ val scale = d.currentSpan / pinchSpan+ while (scale > pinchStart * 1.15f) {pinchStart *= 1.15fmodel.stepFont(1.0)}- while (d.scaleFactor < pinchStart / 1.15f) {+ while (scale < pinchStart / 1.15f) {pinchStart /= 1.15fmodel.stepFont(-1.0)}@@ -184,6 +191,24 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : ViisFocusableInTouchMode = trueisClickable = truemodel.onScreenChanged = { if (anchor != null) screen = null }+ model.onDropComposition = { dropComposition() }+ }++ fun keyboardShown(): Boolean =+ rootWindowInsets?.isVisible(android.view.WindowInsets.Type.ime()) == true++ /// The connection changed: an open composition is let go here and in+ /// the core, whose latch would otherwise swallow every key of the+ /// next connection, and the IME starts over.+ private fun dropComposition() {+ val open = composing != null+ composing = null+ model.composing = null+ model.core.setComposing(false)+ if (open) {+ val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager+ imm.restartInput(this)+ }}fun focusAndShowKeyboard() {@@ -214,7 +239,6 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : VidownX = event.xdownY = event.ylastY = event.y- downAt = event.eventTimedragging = falseselecting = falsetwoFingerStartY = null@@ -234,6 +258,20 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vi}}+ MotionEvent.ACTION_POINTER_UP -> {+ // The finger that stays is the one the scroll follows+ // from here, or the rows between the two would go past+ // in one jump. Its lift is no tap: the two-finger mark+ // stays set.+ if (event.pointerCount == 2) {+ val staying = if (event.actionIndex == 0) 1 else 0+ downX = event.getX(staying)+ downY = event.getY(staying)+ lastY = downY+ dragging = false+ }+ }+MotionEvent.ACTION_MOVE -> {velocity?.addMovement(event)if (selecting) {@@ -274,7 +312,9 @@ class TerminalInputView(context: Context, private val model: TerminalModel) : Vi} else if (settings.smoothScroll) {fling()}- } else if (!pinching && twoFingerStartY == null && event.eventTime - downAt < tapTimeout) {+ } else if (!pinching && twoFingerStartY == null) {+ // Any press that neither dragged nor turned into a+ // long press is a tap, however long it was held.tap()}velocity?.recycle()diff --git a/ios/Sources/Sidebar.swift b/ios/Sources/Sidebar.swiftindex 60b7af3e..15a4178d 100644--- a/ios/Sources/Sidebar.swift+++ b/ios/Sources/Sidebar.swift@@ -48,13 +48,18 @@ struct SidebarPanel: View {}}.onChange(of: model.sidebar?.editing) { _, editing in- guard let editing, editing.kind != "none", let id = editing.id else { return }+ // A new project has no id yet: the same field, asking for the+ // name of what is about to exist.+ guard let editing, editing.kind != "none" else { return }if renaming == nil {renameText = ""- renaming = (editing.kind, id)+ renaming = (editing.kind, editing.id ?? "")}}- .alert(tr("rename"), isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {+ .alert(+ renaming?.kind == "new-project" ? tr("project.new") : tr("rename"),+ isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })+ ) {TextField(tr("f.name"), text: $renameText)Button(tr("save")) {model.sideKey("Enter", value: renameText)diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swiftindex d05c510d..373e8d1c 100644--- a/ios/Sources/TerminalModel.swift+++ b/ios/Sources/TerminalModel.swift@@ -850,9 +850,12 @@ private final class NotifySink: Notify, @unchecked Sendable {self.model?.showCopied()}}- func onFocusInput() {- DispatchQueue.main.async { self.model?.focusKeyboard() }- }+ /// The App asks for the input's focus after a press, a finished+ /// rename and every answered request. On a phone that would raise+ /// the keyboard over half the screen at each of them, so the ask is+ /// honoured only while the keyboard is already up -- and then the+ /// input is already first responder. A tap raises it on its own.+ func onFocusInput() {}func onImeAnchor(left: Double, top: Double, width: Double, height: Double) {DispatchQueue.main.async {self.model?.cursorRect = CGRect(x: left, y: top, width: width, height: height)diff --git a/thinkterm-mobile/src/painter.rs b/thinkterm-mobile/src/painter.rsindex a7b10ec1..02dcb1be 100644--- a/thinkterm-mobile/src/painter.rs+++ b/thinkterm-mobile/src/painter.rs@@ -4,7 +4,6 @@use anyhow::{ensure, Result};use std::sync::Arc;-use std::time::Instant;use thinkterm_web::raster::{GlyphPlatform, ScratchGeometry, TextPainter};/// Implemented by the shell. Called on the core thread, synchronously,@@ -34,21 +33,20 @@ pub trait GlyphPainter: Send + Sync {pub struct GlyphSeams {painter: Arc<dyn GlyphPainter>,- start: Instant,}impl GlyphSeams {pub fn new(painter: Box<dyn GlyphPainter>) -> Self {Self {painter: Arc::from(painter),- start: Instant::now(),}}}impl GlyphPlatform for GlyphSeams {+ /// The platform's clock: the frame budget's deadline is set on it.fn now_ms(&self) -> f64 {- self.start.elapsed().as_secs_f64() * 1000.0+ crate::platform::monotonic_ms()}fn painter(&self, geometry: &ScratchGeometry, _families: &str) -> Result<Box<dyn TextPainter>> {diff --git a/thinkterm-mobile/src/platform.rs b/thinkterm-mobile/src/platform.rsindex 54dd5185..63bffeae 100644--- a/thinkterm-mobile/src/platform.rs+++ b/thinkterm-mobile/src/platform.rs@@ -22,8 +22,15 @@ struct Interval {cb: Box<dyn FnMut()>,}+/// Milliseconds since the process's first look at the clock. The App's+/// frame budget takes its deadline from the platform and checks it in+/// the glyph cache, so both must read this one clock.+pub fn monotonic_ms() -> f64 {+ static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();+ START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1000.0+}+pub struct MobilePlatform {- start: Instant,spawner: LocalSpawner,notify: Arc<dyn Notify>,timers: RefCell<Vec<Timer>>,@@ -45,7 +52,6 @@ impl MobilePlatform {.unwrap_or(0x9E37_79B9_7F4A_7C15)| 1;Self {- start: Instant::now(),spawner,notify,timers: RefCell::new(Vec::new()),@@ -137,7 +143,7 @@ impl MobilePlatform {impl Platform for MobilePlatform {fn monotonic_ms(&self) -> f64 {- self.start.elapsed().as_secs_f64() * 1000.0+ monotonic_ms()}fn wall_ms(&self) -> f64 {diff --git a/thinkterm-mobile/src/ssh.rs b/thinkterm-mobile/src/ssh.rsindex 9c0e0937..c4020ca8 100644--- a/thinkterm-mobile/src/ssh.rs+++ b/thinkterm-mobile/src/ssh.rs@@ -119,6 +119,25 @@ pub fn spawn(params: SshParams, deliver: Box<dyn Fn(Net) + Send>) -> UnboundedSeout_tx}+/// How long any one step of the handshake may take. The transport's+/// own keepalive only starts once the login is through, so until then+/// this is the only thing that ends a server that stops answering.+const STEP: Duration = Duration::from_secs(15);++async fn bounded<T, E>(+ what: &'static str,+ fut: impl std::future::Future<Output = std::result::Result<T, E>>,+) -> Result<T>+where+ E: std::error::Error + Send + Sync + 'static,+{+ match tokio::time::timeout(STEP, fut).await {+ Ok(Ok(value)) => Ok(value),+ Ok(Err(err)) => Err(anyhow::Error::new(err).context(what)),+ Err(_) => Err(anyhow!("{what} timed out")),+ }+}+async fn run(params: SshParams,mut out_rx: UnboundedReceiver<Out>,@@ -136,7 +155,7 @@ async fn run(seen: Arc::clone(&seen),};let dial = tokio::time::timeout(- Duration::from_secs(15),+ STEP,client::connect(config, (params.host.as_str(), params.port), handler),).await@@ -152,44 +171,44 @@ async fn run(Auth::KeyPath(path) => {let key = russh::keys::load_secret_key(path, None).with_context(|| format!("loading the key {path}"))?;- session- .authenticate_publickey(+ bounded(+ "publickey auth",+ session.authenticate_publickey(¶ms.user,PrivateKeyWithHashAlg::new(Arc::new(key), None),- )- .await- .context("publickey auth")?+ ),+ )+ .await?}Auth::KeyPem { pem, passphrase } => {let key = russh::keys::decode_secret_key(pem, passphrase.as_deref()).context("reading the private key")?;- session- .authenticate_publickey(+ bounded(+ "publickey auth",+ session.authenticate_publickey(¶ms.user,PrivateKeyWithHashAlg::new(Arc::new(key), None),- )- .await- .context("publickey auth")?+ ),+ )+ .await?}- Auth::Password(password) => session- .authenticate_password(¶ms.user, password.as_str())- .await- .context("password auth")?,+ Auth::Password(password) => bounded(+ "password auth",+ session.authenticate_password(¶ms.user, password.as_str()),+ )+ .await?,};if !auth.success() {anyhow::bail!("the host refused the login for {}", params.user);}- let mut channel = session- .channel_open_session()- .await- .context("opening a session channel")?;+ let mut channel = bounded("opening a session channel", session.channel_open_session()).await?;let command = if params.remote_command.trim().is_empty() {DEFAULT_COMMAND} else {params.remote_command.as_str()};- channel.exec(true, command).await.context("exec")?;+ bounded("exec", channel.exec(true, command)).await?;deliver(Net::Connected);// A write waits for the remote's window, and the window only growsdiff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex dca28151..685515ad 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -4604,7 +4604,9 @@ impl<P: Platform, L: Link> App<P, L> {/// The panes as this page would claim them: the desktop's rule for/// each, at its own cell where it has its own font.fn native_panes(inner: &Inner<P, L>, layout: &crate::layout::TabLayout) -> Vec<codec::ClientPaneViewport> {- let nav_rows = Self::nav_rows(inner);+ // The bar's rows for *this* layout: on a switch the one on show is+ // still the outgoing tab's, and a phone shows a lone pane bare.+ let nav_rows = Self::nav_rows_for(inner, layout.panes.len());let mut panes = layout.viewport(nav_rows);let root = inner.glyphs.metrics.cell_size;let nav = Self::nav_dev(inner) as f64;