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
use alloc::collections::BTreeMap;
use core::{
fmt,
net::{IpAddr, SocketAddr},
};
use chrono::{DateTime, Utc};
use ts_capabilityversion::CapabilityVersion;
use ts_keys::{DiscoPublicKey, MachinePublicKey, NodePublicKey};
const LAST_SEEN_FORMAT: &str = "%F %T %Z";
/// The unique id of a node.
pub type Id = i64;
/// The stable ID of a node.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StableId(pub String);
/// Timestamps indicating when an offline node was last connected to the control plane. Only applies
/// to nodes that are offline (disconnected from the control plane).
///
/// If populated, most `control` timestamp values are only accurate to a resolution of ~10 minutes
/// for privacy reasons. See each variant for important information on comparison of timestamp
/// values and which clock is used to generate a timestamp.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct NodeLastSeen {
/// The last time the node was connected to the control plane, as reported by the control plane
/// itself. In some cases, the control plane does not report a "last seen" timestamp, just that
/// a node is offline; in those cases, this field will be `None`.
///
/// The timestamp may be rounded to the nearest 10-minute boundary before being reported to this
/// device by the control plane; in other words, many `control` timestamps will be aligned to
/// 10-minute boundaries. This is a privacy-preserving measure implemented by the control plane.
/// Note that we have seen some non-rounded timestamps being reported from the control plane,
/// although it's unclear if this is a bug or by design.
///
/// Note that the timestamp value was generated by the control plane. The control plane's
/// "clock" isn't synchronized with the local device's clock, so the timestamp value may be
/// much more than 5 minutes in the past/future when compared to the `estimated` timestamp/local
/// device clock. Do not directly compare `NodeLastSeen::control` timestamps with
/// `NodeLastSeen::estimated` timestamps.
pub control: Option<DateTime<Utc>>,
/// The last time the node was connected to the control plane, as estimated by this device. The
/// timestamp is roughly the time this device was notified the node was offline by the control
/// plane, using the local device clock.
///
/// Note that the timestamp value was generated by the local device clock. The control plane's
/// "clock" isn't synchronized with the local device's clock, so the timestamp value may differ
/// greatly from the `control` timestamp/control plane clock. Do not directly compare
/// `NodeLastSeen::control` timestamps with `NodeLastSeen::estimated` timestamps.
pub estimated: DateTime<Utc>,
}
impl Default for NodeLastSeen {
fn default() -> Self {
Self {
control: None,
// We intentionally don't fuzz the estimated timestamp value because the Go client code
// doesn't either.
// See: https://github.com/tailscale/tailscale/blob/ee0a03b140021541495b25bdb6642b589431758b/control/controlclient/map.go#L753-L764
estimated: Utc::now(),
}
}
}
impl fmt::Display for NodeLastSeen {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"last seen: {} (by control: ",
self.estimated.format(LAST_SEEN_FORMAT)
)?;
match self.control {
None => write!(f, "unknown)"),
Some(dt) => write!(f, "{})", dt.format(LAST_SEEN_FORMAT)),
}
}
}
impl NodeLastSeen {
/// Construct a new `NodeLastSeen` with an optional "last seen by control" timestamp. The
/// `estimated` timestamp is always set to the current UTC date/time.
pub fn new(control: Option<DateTime<Utc>>) -> Self {
Self {
control,
..Default::default()
}
}
}
/// Whether a node is online (connected to the control plane) or offline (disconnected from the
/// control plane).
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)]
pub enum NodeStatus {
/// The node may be online or offline; the control plane hasn't informed us yet.
#[default]
Unknown,
/// The node is online (connected to the control plane).
Online,
/// The node is offline (disconnected from the control plane).
Offline(NodeLastSeen),
}
impl fmt::Display for NodeStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NodeStatus::Unknown => write!(f, "unknown"),
NodeStatus::Online => write!(f, "online"),
NodeStatus::Offline(nls) => write!(f, "offline, {nls}"),
}
}
}
impl NodeStatus {
/// Construct a new `NodeStatus` from a combination of online and last-seen timestamp.
///
/// The netmap messages we get from the control plane have multiple ways to indicate a peer is
/// online and/or the timestamp the peer was last connected to the control plane. This method
/// wraps the sometimes-painful logic of creating a `NodeStatus` from the various combinations
/// of netmap field values.
pub fn new(online: Option<bool>, last_seen: Option<DateTime<Utc>>) -> Self {
match (online, last_seen) {
(Some(true), None) => Self::Online,
(Some(false), None) => Self::Offline(NodeLastSeen::new(None)),
(Some(false), Some(dt)) | (None, Some(dt)) => {
Self::Offline(NodeLastSeen::new(Some(dt)))
}
(None, None) => Self::Unknown,
(online, last_seen) => {
tracing::warn!(
?online,
?last_seen,
"unexpected combination of online/last_seen states"
);
Self::Unknown
}
}
}
}
/// A node in a tailnet.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Node {
/// The node's id.
pub id: Id,
/// The node's stable id.
pub stable_id: StableId,
/// The node's hostname.
pub hostname: String,
/// The node's capability version.
pub capability_version: CapabilityVersion,
/// Whether the node is connected to the control plane or not. If [`NodeStatus::Unknown`], the
/// control plane hasn't told us yet.
///
/// This field does _not_ indicate whether the node is reachable or visible from this device.
pub status: NodeStatus,
/// The tailnet this node belongs to.
pub tailnet: Option<String>,
/// The node capabilities assigned to this node.
pub node_capabilities: BTreeMap<String, Vec<String>>,
/// The tags assigned to this node.
pub tags: Vec<String>,
/// The address of the node in the tailnet.
pub tailnet_address: TailnetAddress,
/// The node's [`NodePublicKey`].
pub node_key: NodePublicKey,
/// The node key's expiration.
pub node_key_expiry: Option<DateTime<Utc>>,
/// The node's [`MachinePublicKey`], if known.
pub machine_key: Option<MachinePublicKey>,
/// The node's [`DiscoPublicKey`], if known.
pub disco_key: Option<DiscoPublicKey>,
/// The signature of the node's public key with the Tailnet Lock signing key, if Tailnet Lock
/// is enabled and the signature is known.
pub tailnet_lock_key_signature: Option<Vec<u8>>,
/// The routes this node accepts traffic for.
pub accepted_routes: Vec<ipnet::IpNet>,
/// The underlay addresses this node is reachable on (`Endpoints` in Go).
pub underlay_addresses: Vec<SocketAddr>,
/// The DERP region for this node, if known.
pub derp_region: Option<ts_derp::RegionId>,
// ThinkTerm (device info): added.
/// What the node reports about the device it runs on.
pub device: DeviceInfo,
}
// ThinkTerm (device info): added.
/// What a node reports about the device it runs on, from its Hostinfo. A field
/// the node leaves out is empty.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct DeviceInfo {
/// The operating system, as Tailscale names it: "macOS", "iOS", "android", "linux",
/// "windows", ...
pub os: String,
/// The Linux distribution: "debian", "ubuntu", "nixos", ...
pub distro: String,
/// The model of a phone or tablet: "iPhone12,3", "Pixel 3a", ...
pub device_model: String,
}
impl Node {
/// Apply the given partial update to this `Node`.
///
/// # Panics
/// If `update.id` does not match `self.id`. The caller must guarantee this method is only
/// called with [`NodeUpdate`]s for this `Node`.
#[tracing::instrument(skip_all, fields(id = self.stable_id.0, hostname = self.hostname))]
pub fn apply_update(&mut self, update: &NodeUpdate) {
assert_eq!(self.id, update.id, "node update ID != node ID");
if update.status != NodeStatus::Unknown {
tracing::debug!(old_status = %self.status, "peer {}", update.status);
self.status = update.status;
}
if let Some(cap) = update.cap {
tracing::debug!(old=?self.capability_version, new=?cap, "updating capability version");
self.capability_version = cap;
}
if let Some(cap_map) = update.cap_map.as_ref() {
tracing::debug!(old=?self.node_capabilities, new=?cap_map, "updating node capabilities");
self.node_capabilities = cap_map.clone();
}
if let Some(derp_region) = update.derp_region {
tracing::debug!(old=?self.derp_region, new=?derp_region, "updating derp home region");
self.derp_region = Some(derp_region);
}
if let Some(disco_key) = update.disco_key {
tracing::debug!(old=?self.disco_key, new=?disco_key, "updating disco key");
self.disco_key = Some(disco_key);
}
if let Some(node_key) = update.node_key {
tracing::debug!(old=?self.node_key, new=?node_key, "updating node key");
self.node_key = node_key;
}
if let Some(node_key_expiry) = update.node_key_expiry {
tracing::debug!(old=?self.node_key_expiry, new=?node_key_expiry, "updating node key expiry");
self.node_key_expiry = Some(node_key_expiry);
}
if let Some(tl_sig) = &update.tailnet_lock_key_signature {
tracing::debug!(old=?self.tailnet_lock_key_signature, new=?tl_sig, "updating tailnet lock key signature");
self.tailnet_lock_key_signature = Some(tl_sig.clone());
}
if let Some(underlay_addresses) = &update.underlay_addresses {
tracing::debug!(old=?self.underlay_addresses, new=?underlay_addresses, "updating underlay addresses");
self.underlay_addresses = underlay_addresses.clone();
}
}
/// The fully-qualified domain name of the node.
///
/// This is a string of the form `$HOST.$TAILNET_DOMAIN.`. For tailnets controlled by
/// Tailscale's control plane, this usually means `$HOST.tail1234.ts.net.`
///
/// The `trailing_dot` parameter specifies whether to include the trailing dot in the
/// fqdn. This is included by the definition of FQDN, and is the way the Go codebase
/// formats this field, but the parameter is included to allow turning it off for use
/// in contexts that expect it to be absent.
pub fn fqdn(&self, trailing_dot: bool) -> String {
let dot = if trailing_dot { "." } else { "" };
match &self.tailnet {
Some(tailnet) => format!("{}.{tailnet}{dot}", self.hostname),
None => format!("{}{dot}", self.hostname),
}
}
/// The fully-qualified domain name of the node, only returning `Some` if the tailnet
/// component is present.
///
/// See [`Node::fqdn`].
pub fn fqdn_opt(&self, trailing_dot: bool) -> Option<String> {
let dot = if trailing_dot { "." } else { "" };
let tailnet = self.tailnet.as_deref()?;
Some(format!("{}.{tailnet}{dot}", self.hostname))
}
/// Report whether this node matches the given `name`.
///
/// `name` is checked for equality with both this node's bare hostname and its fqdn. A
/// trailing `.` may be present.
pub fn matches_name(&self, name: &str) -> bool {
// This approach is taken to avoid allocating a buffer just for the sake of making this
// comparison: try to chop `.tailnet.` off of the end of `name` and compare the
// remainder to our hostname. If `.tailnet.` doesn't match `name`, we'll end up comparing
// our hostname to `hostname.other_tailnet.`, which won't succeed. If `name` was just the
// hostname, nothing will have been chopped, so the comparison will still be hostname-to-
// hostname.
let name = name.strip_suffix('.').unwrap_or(name);
let name = if let Some(tailnet) = &self.tailnet {
name.strip_suffix(tailnet.as_str())
.and_then(|name| name.strip_suffix('.'))
.unwrap_or(name)
} else {
name
};
name == self.hostname
}
}
/// Addresses for a node within a tailnet.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TailnetAddress {
/// The IPv4 address of the node in the tailnet.
pub ipv4: ipnet::Ipv4Net,
/// The IPv6 address of the node in the tailnet.
pub ipv6: ipnet::Ipv6Net,
}
impl TailnetAddress {
/// Report whether `addr` matches either address in this [`TailnetAddress`].
pub fn contains(&self, addr: IpAddr) -> bool {
match addr {
IpAddr::V4(a) => self.ipv4.addr() == a,
IpAddr::V6(a) => self.ipv6.addr() == a,
}
}
}
impl From<&ts_control_serde::Node<'_>> for Node {
fn from(value: &ts_control_serde::Node) -> Self {
let fqdn_without_trailing_dot = value.name.strip_suffix('.').unwrap_or(value.name);
let (hostname, tailnet) = match fqdn_without_trailing_dot.split_once('.') {
Some((hostname, tailnet)) => (hostname, Some(tailnet.to_owned())),
None => (fqdn_without_trailing_dot, None),
};
Self {
id: value.id,
stable_id: StableId(value.stable_id.0.to_string()),
hostname: hostname.to_owned(),
capability_version: value.cap,
status: NodeStatus::new(value.online, value.last_seen),
tailnet,
node_capabilities: value
.cap_map
.iter()
.map(|(k, v)| (k.to_string(), v.into()))
.collect(),
tags: value
.tags
.as_ref()
.map(|x| x.iter().map(|x| x.to_string()).collect())
.unwrap_or_default(),
tailnet_address: TailnetAddress {
ipv4: value.addresses.0,
ipv6: value.addresses.1,
},
node_key: value.key,
node_key_expiry: value.key_expiry,
machine_key: value.machine,
disco_key: value.disco_key,
tailnet_lock_key_signature: value.key_signature.as_ref().map(|s| Vec::<u8>::from(*s)),
accepted_routes: value
.allowed_ips
.clone()
.unwrap_or_else(|| vec![value.addresses.0.into(), value.addresses.1.into()]),
underlay_addresses: value.endpoints.clone(),
// legacy_derp_string is still in practical use as of 3/2026
#[allow(deprecated)]
derp_region: value
.home_derp
.or(value.legacy_derp_string)
.or_else(|| value.host_info.net_info.as_ref()?.preferred_derp)
.map(|x| ts_derp::RegionId(x.into())),
// ThinkTerm (device info): added.
device: DeviceInfo {
os: value.host_info.os.to_owned(),
distro: value.host_info.distro.to_owned(),
device_model: value.host_info.device_model.to_owned(),
},
}
}
}
/// A partial update to a [`Node`] in a tailnet.
///
/// Devices should reject any `NodeUpdate` that it doesn't have a corresponding [`Node`] for. This
/// type combines multiple different update/patch-style fields from netmap messages into a single
/// type to simplify update handling for interested components, such as the peer tracker.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct NodeUpdate {
/// The node's id.
pub id: Id,
/// Whether this node is online or offline (with last-seen timestamp), according to the control
/// plane. If [`NodeStatus::Unknown`], has not changed.
pub status: NodeStatus,
/// The DERP region for this node. If `None`, has not changed.
pub derp_region: Option<ts_derp::RegionId>,
/// The node's capability version. If `None`, has not changed.
pub cap: Option<CapabilityVersion>,
/// The node's capabilities (node caps, not peer caps). If `None`, has not changed.
pub cap_map: Option<BTreeMap<String, Vec<String>>>,
/// The node's [`NodePublicKey`]. If `None`, has not changed.
pub node_key: Option<NodePublicKey>,
/// The node key's expiration. If `None`, has not changed.
pub node_key_expiry: Option<DateTime<Utc>>,
/// The node's [`DiscoPublicKey`]. If `None`, has not changed.
pub disco_key: Option<DiscoPublicKey>,
/// The node's key signature for Tailnet Lock. If `None`, has not changed.
pub tailnet_lock_key_signature: Option<Vec<u8>>,
/// The underlay addresses this node is reachable on (`Endpoints` in Go). If `None`, has not
/// changed.
pub underlay_addresses: Option<Vec<SocketAddr>>,
}
impl From<&ts_control_serde::PeerChange<'_>> for NodeUpdate {
fn from(value: &ts_control_serde::PeerChange<'_>) -> Self {
let cap_map = value.cap_map.as_ref().map(|m| {
m.iter()
.map(|(name, values)| {
(
String::from(*name),
values
.0
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>(),
)
})
.collect()
});
Self {
id: value.node_id,
status: NodeStatus::new(value.online, value.last_seen),
derp_region: value.derp_region.map(|x| ts_derp::RegionId(x.into())),
cap: value.cap,
cap_map,
node_key: value.key,
node_key_expiry: value.key_expiry,
disco_key: value.disco_key,
tailnet_lock_key_signature: value.key_signature.map(|x| x.into()),
underlay_addresses: value.endpoints.clone(),
}
}
}
// ThinkTerm (device info): the tests are ours.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_node_keeps_what_it_says_about_its_device() {
let phone = ts_control_serde::Node {
name: "phone.example.ts.net.",
host_info: ts_control_serde::HostInfo {
os: "iOS",
device_model: "iPhone15,2",
..Default::default()
},
..Default::default()
};
assert_eq!(
Node::from(&phone).device,
DeviceInfo {
os: "iOS".into(),
distro: String::new(),
device_model: "iPhone15,2".into(),
}
);
let server = ts_control_serde::Node {
host_info: ts_control_serde::HostInfo {
os: "linux",
distro: "debian",
..Default::default()
},
..Default::default()
};
assert_eq!(Node::from(&server).device.distro, "debian");
}
}