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
//! The network thread: an ssh session to the host, an exec channel running
//! `thinkterm cli --prefer-mux proxy`, and the PDU bytes flowing both ways.
//! Beside it, once a connection, the host desktop's tab icons are read on
//! channels of their own (`icons`).
//!
//! One tokio thread per connection. Bytes to send arrive on an unbounded
//! channel and are written in order; everything that comes back -- data,
//! stderr, the exit status, the close -- is delivered to the core thread
//! through the callback it gave us, which must not block.
//!
//! An unknown host key ends the transport before authentication. The shell
//! asks for explicit approval and retries with that exact fingerprint pinned.
//! A remembered key that changes is always rejected.
use crate::icons;
use anyhow::{anyhow, Context, Result};
use russh::client::{self, Handler};
use russh::keys::{HashAlg, PrivateKeyWithHashAlg, PublicKeyOrCertificate};
use russh::ChannelMsg;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use thinkterm_tab_icons::WireCatalog;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
#[derive(Debug, Clone)]
pub enum Auth {
/// An OpenSSH private key file on disk (the probe's throwaway key).
KeyPath(String),
/// A private key in OpenSSH or PEM text, with its passphrase if any.
KeyPem {
pem: String,
passphrase: Option<String>,
},
Password(String),
}
#[derive(Debug, Clone)]
pub struct SshParams {
pub request_id: String,
pub host: String,
pub port: u16,
pub user: String,
pub auth: Auth,
/// The host key fingerprint seen last time (`SHA256:...`), if any.
pub known_host: Option<String>,
/// The command to exec; empty means the default proxy invocation.
pub remote_command: String,
/// Seconds between keep-alives; 0 sends none.
pub keepalive_secs: u64,
}
pub enum Out {
Bytes(Vec<u8>),
Close,
}
#[derive(Debug)]
pub enum Net {
/// Transport stopped before authentication; only explicit approval may retry.
HostKeyRequired {
request_id: String,
fingerprint: String,
},
Connected,
Data(Vec<u8>),
Stderr(String),
Exit(u32),
/// The host's tab icon cards, read beside the protocol, or why not.
TabIcons(Result<WireCatalog, String>),
Closed(String),
}
struct HostKeyCheck {
known: Option<String>,
seen: Arc<Mutex<Option<String>>>,
}
impl Handler for HostKeyCheck {
type Error = anyhow::Error;
async fn check_server_key(&mut self, key: &PublicKeyOrCertificate) -> Result<bool> {
let fingerprint = match key {
PublicKeyOrCertificate::PublicKey { key, .. } => {
key.fingerprint(HashAlg::Sha256).to_string()
}
PublicKeyOrCertificate::Certificate(cert) => {
cert.public_key().fingerprint(HashAlg::Sha256).to_string()
}
};
*self.seen.lock().unwrap() = Some(fingerprint.clone());
match &self.known {
Some(known) if known != &fingerprint => Err(anyhow!(
"the host's key changed: expected {known}, got {fingerprint}. If the host was reinstalled, forget it and add it again"
)),
Some(_) => Ok(true),
None => Err(anyhow!("host key approval required before authentication")),
}
}
}
/// Asked of the user's login shell: where the host keeps its ThinkTerm.
/// An exec session runs with the daemon's bare PATH (on macOS without
/// /usr/local/bin, where the desktop's CLI lives); the login shell's
/// profile sets the user's own. The usual places come after, for a
/// profile that sets nothing. Prints the path, or exits 127.
const PROBE: &str = "for b in thinkterm wezterm; do \
p=$(command -v \"$b\" 2>/dev/null) && { printf %s\\\\n \"$p\"; exit 0; }; done; \
for p in \"$HOME/.local/bin/thinkterm\" /usr/local/bin/thinkterm /opt/homebrew/bin/thinkterm \
/Applications/ThinkTerm.app/Contents/MacOS/thinkterm; do \
[ -x \"$p\" ] && { printf %s\\\\n \"$p\"; exit 0; }; done; exit 127";
/// A word for the remote shell, whatever is in it.
fn shell_quote(word: &str) -> String {
format!("'{}'", word.replace('\'', "'\\''"))
}
/// The CLI's path on the host, from the probe. Only the probe runs in
/// the login shell: a profile may print, and on the channel that
/// carries the protocol that would be corruption. The last line that
/// looks like a path is the answer, whatever came before it.
async fn find_cli(session: &client::Handle<HostKeyCheck>) -> Result<String> {
let mut probe = bounded("opening the probe channel", session.channel_open_session()).await?;
let command = format!("exec \"${{SHELL:-/bin/sh}}\" -lc '{PROBE}'");
bounded("probing for thinkterm", probe.exec(true, command)).await?;
let (mut out, mut err, mut status) = (Vec::new(), String::new(), None);
loop {
match tokio::time::timeout(STEP, probe.wait()).await {
Ok(Some(ChannelMsg::Data { data })) => out.extend_from_slice(&data),
Ok(Some(ChannelMsg::ExtendedData { data, .. })) => {
err.push_str(&String::from_utf8_lossy(&data));
}
Ok(Some(ChannelMsg::ExitStatus { exit_status })) => status = Some(exit_status),
Ok(Some(ChannelMsg::Close)) | Ok(None) => break,
Ok(Some(_)) => {}
Err(_) => anyhow::bail!("probing for thinkterm timed out"),
}
}
let text = String::from_utf8_lossy(&out);
let found = text
.lines()
.rev()
.map(str::trim)
.find(|l| l.starts_with('/') && (l.ends_with("/thinkterm") || l.ends_with("/wezterm")));
match found {
Some(path) => Ok(path.to_string()),
None => {
let err = err.trim();
let detail = if err.is_empty() {
match status {
Some(127) | None => String::new(),
Some(code) => format!(" (the shell exited with {code})"),
}
} else {
format!(": {}", err.lines().last().unwrap_or(""))
};
anyhow::bail!(
"no thinkterm on the host{detail}. Install it there, or set the host's remote command"
)
}
}
}
/// The longest a command beside the protocol may take, all told.
const OUTPUT_DEADLINE: Duration = Duration::from_secs(60);
/// What `command` prints, on a channel of its own beside the protocol's;
/// more than `limit` bytes is an error. A command that runs on (a forced
/// command in place of the shell, a profile that waits) is ended with its
/// channel.
async fn output(session: &client::Handle<HostKeyCheck>, command: String, limit: usize) -> Result<Vec<u8>> {
let mut channel = bounded("opening a channel", session.channel_open_session()).await?;
let mut out = Vec::new();
let read = async {
bounded("exec", channel.exec(true, command)).await?;
loop {
match tokio::time::timeout(STEP, channel.wait()).await {
Ok(Some(ChannelMsg::Data { data })) => {
out.extend_from_slice(&data);
anyhow::ensure!(out.len() <= limit, "more than {limit} bytes");
}
Ok(Some(ChannelMsg::Close)) | Ok(None) => return Ok::<(), anyhow::Error>(()),
Ok(Some(_)) => {}
Err(_) => anyhow::bail!("no answer"),
}
}
};
// Each message re-arms the step's timeout; this bounds them all.
let read = match tokio::time::timeout(OUTPUT_DEADLINE, read).await {
Ok(read) => read,
Err(_) => Err(anyhow!("no end in {} s", OUTPUT_DEADLINE.as_secs())),
};
if read.is_err() {
let _ = channel.close().await;
}
read.map(|()| out)
}
/// The host desktop's tab icon cards, as its server gives a page them
/// (`icons`): its settings, then the glyphs it imported that they name.
async fn tab_icons(session: &client::Handle<HostKeyCheck>) -> Result<WireCatalog> {
// Room for what a login profile prints before the file.
let out = output(session, icons::settings_command(), icons::SETTINGS_LIMIT + 64 * 1024).await?;
let cards = icons::desktop_cards(&out).ok_or_else(|| anyhow!("no answer from /bin/sh on the host"))?;
let hashes = icons::imported(&cards);
// Glyphs that cannot be read are left out and the cards kept, as the
// host's server sends them to a page.
let svgs = match hashes.is_empty() {
true => Default::default(),
false => output(session, icons::svgs_command(&hashes), icons::svgs_limit(hashes.len()))
.await
.map(|out| icons::imported_svgs(&out, &hashes))
.unwrap_or_default(),
};
Ok(cards.wire(|hash| svgs.get(hash).cloned()))
}
/// Start the connection on its own thread. Returns the sender for bytes
/// to write; dropping it (or sending `Out::Close`) ends the session.
pub fn spawn(params: SshParams, deliver: Box<dyn Fn(Net) + Send>) -> UnboundedSender<Out> {
let (out_tx, out_rx) = unbounded_channel();
std::thread::Builder::new()
.name("thinkterm-net".into())
.spawn(move || {
let runtime = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(err) => {
deliver(Net::Closed(format!("tokio runtime: {err}")));
return;
}
};
let outcome = runtime.block_on(run(params, out_rx, &deliver));
let reason = match outcome {
Ok(reason) => reason,
Err(err) => format!("{err:#}"),
};
deliver(Net::Closed(reason));
})
.expect("spawning the network thread");
out_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>,
deliver: &dyn Fn(Net),
) -> Result<String> {
let config = Arc::new(client::Config {
inactivity_timeout: None,
keepalive_interval: (params.keepalive_secs > 0).then(|| Duration::from_secs(params.keepalive_secs)),
keepalive_max: 3,
..Default::default()
});
let seen = Arc::new(Mutex::new(None));
let handler = HostKeyCheck {
known: params.known_host.clone(),
seen: Arc::clone(&seen),
};
let dial = tokio::time::timeout(
STEP,
client::connect(config, (params.host.as_str(), params.port), handler),
)
.await
.context("connecting timed out")?;
if dial.is_err() && params.known_host.is_none() {
if let Some(fingerprint) = seen.lock().unwrap().clone() {
deliver(Net::HostKeyRequired {
request_id: params.request_id.clone(),
fingerprint,
});
}
}
let mut session = dial.context("ssh transport")?;
let auth = match ¶ms.auth {
Auth::KeyPath(path) => {
let key = russh::keys::load_secret_key(path, None)
.with_context(|| format!("loading the key {path}"))?;
bounded(
"publickey auth",
session.authenticate_publickey(
¶ms.user,
PrivateKeyWithHashAlg::new(Arc::new(key), None),
),
)
.await?
}
Auth::KeyPem { pem, passphrase } => {
let key = russh::keys::decode_secret_key(pem, passphrase.as_deref())
.context("reading the private key")?;
bounded(
"publickey auth",
session.authenticate_publickey(
¶ms.user,
PrivateKeyWithHashAlg::new(Arc::new(key), None),
),
)
.await?
}
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 = bounded("opening a session channel", session.channel_open_session()).await?;
let command = if params.remote_command.trim().is_empty() {
let cli = find_cli(&session).await?;
format!("exec {} cli --prefer-mux proxy", shell_quote(&cli))
} else {
params.remote_command.clone()
};
let command = command.as_str();
bounded("exec", channel.exec(true, command)).await?;
deliver(Net::Connected);
// A write waits for the remote's window, and the window only grows
// through messages the reader takes in; russh parks its session loop
// on a full inbound queue. So the writer runs apart from the reader,
// and a stalled write never stops the reading.
let (mut reader, writer) = channel.split();
let mut sender = tokio::spawn(async move {
while let Some(out) = out_rx.recv().await {
match out {
Out::Bytes(bytes) => writer
.data(&bytes[..])
.await
.context("writing to the channel")?,
Out::Close => break,
}
}
let _ = writer.eof().await;
let _ = writer.close().await;
Ok::<(), anyhow::Error>(())
});
// What the command last said and how it ended: the reason a session
// that dies at once gives, instead of a bare "ended".
let (mut last_err, mut exit) = (String::new(), None);
// The host's tab icons come on channels of their own while the
// terminal is already in use.
let cards = tab_icons(&session);
tokio::pin!(cards);
let mut cards_read = false;
loop {
tokio::select! {
read = &mut cards, if !cards_read => {
cards_read = true;
deliver(Net::TabIcons(read.map_err(|err| format!("{err:#}"))));
}
sent = &mut sender => {
let _ = session
.disconnect(russh::Disconnect::ByApplication, "closed", "")
.await;
return match sent {
Ok(Ok(())) => Ok("closed by the client".into()),
Ok(Err(err)) => Err(err),
Err(err) => Err(anyhow!("the writer ended: {err}")),
};
}
msg = reader.wait() => match msg {
Some(ChannelMsg::Data { data }) => deliver(Net::Data(data.to_vec())),
Some(ChannelMsg::ExtendedData { data, .. }) => {
let text = String::from_utf8_lossy(&data).to_string();
if let Some(line) = text.lines().rev().find(|l| !l.trim().is_empty()) {
last_err = line.trim().to_string();
}
deliver(Net::Stderr(text))
}
Some(ChannelMsg::ExitStatus { exit_status }) => {
exit = Some(exit_status);
deliver(Net::Exit(exit_status))
}
Some(ChannelMsg::Eof) => {}
Some(ChannelMsg::Close) | None => {
sender.abort();
let mut reason = String::from("the remote command ended");
if let Some(code) = exit.filter(|c| *c != 0) {
reason.push_str(&format!(" with status {code}"));
}
if !last_err.is_empty() {
reason.push_str(&format!(": {last_err}"));
}
return Ok(reason);
}
Some(_) => {}
},
}
}
}
#[cfg(test)]
mod host_key_tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
struct PasswordServer(Arc<AtomicUsize>);
impl russh::server::Handler for PasswordServer {
type Error = anyhow::Error;
async fn auth_password(&mut self, _: &str, password: &str) -> Result<russh::server::Auth> {
assert_eq!(password, "test-secret");
self.0.fetch_add(1, Ordering::SeqCst);
Ok(russh::server::Auth::Accept)
}
}
#[tokio::test]
async fn unknown_and_changed_keys_never_receive_credentials() {
let key = russh::keys::PrivateKey::random(
&mut crate::SysRng(ring::rand::SystemRandom::new()),
russh::keys::Algorithm::Ed25519,
)
.unwrap();
let fingerprint = key.public_key().fingerprint(HashAlg::Sha256).to_string();
let config = Arc::new(russh::server::Config {
keys: vec![key],
auth_rejection_time: Duration::ZERO,
auth_rejection_time_initial: Some(Duration::ZERO),
..Default::default()
});
// The same real SSH transport is exercised with no pin, a mismatched
// pin and the explicitly approved pin. No UI or transport mock.
for (known_host, expected_auth, expected_challenge) in [
(None, 0, true),
(Some("SHA256:wrong".to_string()), 0, false),
(Some(fingerprint.clone()), 1, false),
] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let count = Arc::new(AtomicUsize::new(0));
let server_count = count.clone();
let server_config = config.clone();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
if let Ok(session) =
russh::server::run_stream(server_config, stream, PasswordServer(server_count))
.await
{
let _ = session.await;
}
});
let (_sender, receiver) = unbounded_channel();
let events = std::cell::RefCell::new(Vec::new());
let params = SshParams {
request_id: "attempt-42".into(),
host: "127.0.0.1".into(),
port,
user: "test".into(),
auth: Auth::Password("test-secret".into()),
known_host,
remote_command: "test".into(),
keepalive_secs: 0,
};
// The server intentionally refuses opening a session after auth.
let result = tokio::time::timeout(
Duration::from_secs(3),
run(params, receiver, &|event| events.borrow_mut().push(event)),
)
.await;
assert!(result
.expect("transport completes within the test deadline")
.is_err());
assert_eq!(count.load(Ordering::SeqCst), expected_auth);
let challenges: Vec<_> = events
.borrow()
.iter()
.filter_map(|event| match event {
Net::HostKeyRequired {
request_id,
fingerprint,
} => Some((request_id.clone(), fingerprint.clone())),
_ => None,
})
.collect();
assert_eq!(
challenges,
if expected_challenge {
vec![("attempt-42".into(), fingerprint.clone())]
} else {
vec![]
}
);
server.abort();
let _ = server.await;
}
}
}