Skip to content

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.

8.4 KB
Raw Blame
//! The handshake, in the desktop's order, then the lease steps a follower
//! takes: version, identity, the pane list, a viewport report, and the
//! render subscription.

use crate::platform::Link;
use anyhow::{anyhow, bail, Result};
use codec::Pdu;
use crate::chrome::active_pane;
use thinkterm_proto::layout::PaneNode;
use thinkterm_proto::{ClientId, PaneId, RenderableDimensions, TabId};
use thinkterm_session::host::request;
use wezterm_term::TerminalSize;

/// The server's pane list, with every tab whose sizes no screen could have
/// blanked (`PaneNode::is_plausible`). The one way this crate asks for it, so
/// no caller gets the sizes unchecked.
pub async fn list_panes<L: Link>(link: &L) -> Result<codec::ListPanesResponse> {
    let mut panes = request(link, Pdu::ListPanes(codec::ListPanes {}), |pdu| match pdu {
        Pdu::ListPanesResponse(p) => Ok(p),
        other => Err(other),
    })
    .await?;
    crate::layout::blank_implausible_tabs(&mut panes);
    Ok(panes)
}

pub struct Attached {
    pub pane_id: PaneId,
    pub tab_id: TabId,
    pub window_id: thinkterm_proto::WindowId,
    pub workspace: String,
    pub title: String,
    pub dims: RenderableDimensions,
    pub alt_screen: bool,
    pub server_version: String,
    /// The server's identity for this run: a cold start that comes back
    /// to a different one must not trust the ids it remembers.
    pub server_id: String,
}

/// `size` is the grid this page can show, or `None` when it cannot show
/// one yet; only a real size is reported, so a later claim never carries
/// a made-up one.
/// `me` is this client's identity for the server: the platform makes it
/// (it needs a clock and a random number).
pub async fn attach<L: Link>(
    link: &L,
    size: Option<TerminalSize>,
    nav_rows: usize,
    me: ClientId,
) -> Result<Attached> {
    let version = request(
        link,
        Pdu::GetCodecVersion(codec::GetCodecVersion {}),
        |pdu| match pdu {
            Pdu::GetCodecVersionResponse(v) => Ok(v),
            other => Err(other),
        },
    )
    .await?;
    if version.codec_vers != codec::CODEC_VERSION {
        bail!(
            "this page speaks protocol {} but the server speaks {}; update the server or the bundle",
            codec::CODEC_VERSION,
            version.codec_vers
        );
    }

    link.lease_mut().me = Some(me.clone());
    request(
        link,
        Pdu::SetClientId(codec::SetClientId {
            client_id: me,
            is_proxy: false,
        }),
        |pdu| match pdu {
            Pdu::UnitResponse(_) => Ok(()),
            other => Err(other),
        },
    )
    .await?;

    let panes = list_panes(link).await?;
    // The first tab that has a pane, preferring its active one.
    let entry = panes
        .tabs
        .iter()
        .find_map(active_pane)
        .ok_or_else(|| anyhow!("the server has no panes to show"))?;

    // The page's own grid is kept for a later "fit"; what the server hears
    // is the tab's own size, so that whatever it claims for this page
    // (it claims a client's last report when it types) reshapes nothing.
    // The tab's size is not the lone pane's (see `layout_in`), and the
    // report is pane by pane from the first: a bare grid would resize
    // every pane to its frame if this page turns out to hold the tab.
    let laid = crate::layout::tab_containing(&panes, entry.pane_id)
        .and_then(|t| crate::layout::layout_in(t, None, nav_rows));
    let tab_size = laid.as_ref().map(|l| l.size).unwrap_or(entry.size);
    {
        let mut lease = link.lease_mut();
        lease.tab_id = Some(entry.tab_id);
        lease.reported = size;
        lease.canonical_size = Some(tab_size);
        if let Some(laid) = &laid {
            lease.set_native(laid, nav_rows);
        }
    }
    link.report_viewport(entry.tab_id).await?;

    request(
        link,
        Pdu::GetPaneRenderChanges(codec::GetPaneRenderChanges {
            pane_id: entry.pane_id,
        }),
        |pdu| match pdu {
            Pdu::LivenessResponse(_) | Pdu::UnitResponse(_) => Ok(()),
            other => Err(other),
        },
    )
    .await?;

    let rows = entry.size.rows;
    Ok(Attached {
        pane_id: entry.pane_id,
        tab_id: entry.tab_id,
        window_id: entry.window_id,
        workspace: entry.workspace.clone(),
        title: entry.title.clone(),
        dims: RenderableDimensions {
            cols: entry.size.cols,
            viewport_rows: rows,
            scrollback_rows: rows,
            physical_top: entry.physical_top,
            scrollback_top: entry.physical_top,
            dpi: entry.size.dpi,
            pixel_width: entry.size.pixel_width,
            pixel_height: entry.size.pixel_height,
            reverse_video: false,
        },
        alt_screen: entry.alt_screen,
        server_version: version.version_string,
        server_id: version.server_id,
    })
}

/// The server has nothing to show at all.
///
/// Its own type so the reconnect loop can tell "come back later" from
/// "there is nothing to come back to" and stop retrying. A pane that is
/// gone is not that: the page moves to another.
#[derive(Debug)]
pub struct NoPanes;

impl std::fmt::Display for NoPanes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "the server has no panes to show")
    }
}

impl std::error::Error for NoPanes {}

/// The handshake again, on a socket that has just been reopened.
///
/// Not `attach`: that picks a pane, and picking again after a reconnect
/// would silently move the page to whatever is active now. This one
/// prefers the tab it was already showing, then the tab holding the pane
/// it was focused on, and only then the first tab; it fails with
/// [`NoPanes`] when the server has none. The listing comes back for the
/// page to lay the tab out again.
///
/// The identity is the one from the first connection. The server tracks the
/// frontend lease by `ClientId`, so coming back under a new one would hand
/// this page a different seat than the one it left.
pub async fn reattach<L: Link>(
    link: &L,
    tab_id: TabId,
    focused: PaneId,
    size: Option<TerminalSize>,
    nav_rows: usize,
) -> Result<codec::ListPanesResponse> {
    let version = request(
        link,
        Pdu::GetCodecVersion(codec::GetCodecVersion {}),
        |pdu| match pdu {
            Pdu::GetCodecVersionResponse(v) => Ok(v),
            other => Err(other),
        },
    )
    .await?;
    if version.codec_vers != codec::CODEC_VERSION {
        bail!(
            "this page speaks protocol {} but the server speaks {}; update the server or the bundle",
            codec::CODEC_VERSION,
            version.codec_vers
        );
    }

    let me = link
        .lease()
        .me
        .clone()
        .ok_or_else(|| anyhow!("reconnecting without an identity"))?;
    request(
        link,
        Pdu::SetClientId(codec::SetClientId {
            client_id: me,
            is_proxy: false,
        }),
        |pdu| match pdu {
            Pdu::UnitResponse(_) => Ok(()),
            other => Err(other),
        },
    )
    .await?;

    let panes = list_panes(link).await?;
    let tab = panes
        .tabs
        .iter()
        .find(|tab| tab.window_and_tab_ids().is_some_and(|(_, id)| id == tab_id))
        .or_else(|| panes.tabs.iter().find(|tab| contains_pane(tab, focused)))
        .or_else(|| panes.tabs.iter().find(|tab| tab.root_size().is_some()))
        .ok_or(NoPanes)?;
    let (_, tab_id) = tab.window_and_tab_ids().ok_or(NoPanes)?;
    let known = link.lease().tab_sizes.get(&tab_id).copied();
    let laid = crate::layout::layout_in(tab, known, nav_rows).ok_or(NoPanes)?;
    {
        let mut lease = link.lease_mut();
        lease.tab_id = Some(tab_id);
        lease.tab_owner = None;
        lease.reported = size;
        lease.canonical_size = Some(laid.size);
        lease.reported_viewport = None;
        lease.set_native(&laid, nav_rows);
        lease.fit = false;
    }
    link.report_viewport(tab_id).await?;
    Ok(panes)
}

/// Whether a tab's layout still holds this pane.
pub(crate) fn contains_pane(node: &PaneNode, pane_id: PaneId) -> bool {
    match node {
        PaneNode::Empty => false,
        PaneNode::Leaf(entry) => entry.pane_id == pane_id,
        PaneNode::Stack(stack) => stack.panes.iter().any(|e| e.pane_id == pane_id),
        PaneNode::Split { left, right, .. } => {
            contains_pane(left, pane_id) || contains_pane(right, pane_id)
        }
    }
}