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.

thinkterm-web: the tab keeps the desktop's size while the page types

RoversX848ff5db1620
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index a9a8b696..9c750865 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -12,7 +12,6 @@ use codec::Pdu;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
-use thinkterm_session::host::SessionEvents as _;
use termwiz::input::{KeyCode, Modifiers};
use thinkterm_font_web::FontSet;
use thinkterm_proto::{PaneId, TabId};
@@ -490,7 +489,16 @@ impl App {
}
}
Pdu::ClientViewportState(_) | Pdu::FrontendAccessState(_) => {
+ let (link, tab_id) = (inner.link.clone(), inner.tab_id);
drop(inner);
+ // The desktop may have resized: keep the server's copy of
+ // this page's report at the tab's size, or the next
+ // keystroke would claim the old one.
+ wasm_bindgen_futures::spawn_local(async move {
+ if let Err(err) = link.report_canonical(tab_id).await {
+ log::warn!("reporting the tab size: {err:#}");
+ }
+ });
self.refresh_status();
self.request_frame();
}
@@ -684,14 +692,21 @@ impl App {
.as_ref()
.map(|l| (l.cols, l.rows))
.unwrap_or((inner.cols, inner.rows));
+ let lease = inner.link.lease();
let mut text = if owner {
format!("{} · {}x{} · this browser has the terminal", inner.title(), cols, rows)
- } else {
+ } else if !lease.may_type() {
format!(
- "{} · {}x{} · following another device (type or click to take over)",
+ "{} · {}x{} · another device has the terminal (Ctrl+Shift+T to take over)",
inner.title(), cols, rows
)
+ } else {
+ format!("{} · {}x{} · mirroring the desktop", inner.title(), cols, rows)
};
+ if lease.fit {
+ text.push_str(" · fitted to this window (Ctrl+Shift+F again to let go)");
+ }
+ drop(lease);
if cols > inner.cols || rows > inner.rows {
text.push_str(&format!(" · this window fits {}x{}", inner.cols, inner.rows));
}
@@ -721,6 +736,9 @@ impl App {
if inner.composing || inner.disconnected.is_some() {
return false;
}
+ if !Self::may_type(&inner) {
+ return true;
+ }
// Copy and paste chords belong to the page: Cmd+C/V on a Mac,
// Ctrl+Shift+C/V elsewhere. Copy what is selected; let the paste
// event carry the clipboard. Every other Cmd chord is the
@@ -735,6 +753,18 @@ impl App {
return true;
}
KeyCode::Char('v') | KeyCode::Char('V') if cmd || ctrl_shift => return false,
+ // Ctrl+Shift+F fits the tab to this window; Ctrl+Shift+T
+ // takes the terminal over from another device (Handoff mode).
+ KeyCode::Char('f') | KeyCode::Char('F') if ctrl_shift => {
+ drop(inner);
+ self.fit(true);
+ return true;
+ }
+ KeyCode::Char('t') | KeyCode::Char('T') if ctrl_shift => {
+ drop(inner);
+ self.take_over();
+ return true;
+ }
// Ctrl+Shift+arrow moves the focus between the tab's panes,
// locally: dragging the desktop along is a click's job.
KeyCode::LeftArrow | KeyCode::RightArrow | KeyCode::UpArrow | KeyCode::DownArrow
@@ -769,10 +799,24 @@ impl App {
self.inner.borrow_mut().composing = composing;
}
+ /// Whether input may go out at all. In Handoff mode with the
+ /// terminal in someone else's hands the server would drop it; the
+ /// status line says so and offers to take over.
+ fn may_type(inner: &Inner) -> bool {
+ if inner.link.lease().may_type() {
+ return true;
+ }
+ Self::set_status(
+ inner,
+ "another device is using this terminal; press Ctrl+Shift+T to take it over",
+ );
+ false
+ }
+
/// Text the IME composed: bytes, not a paste, so no bracketing.
pub fn text(&self, text: &str) {
let mut inner = self.inner.borrow_mut();
- if inner.disconnected.is_some() {
+ if inner.disconnected.is_some() || !Self::may_type(&inner) {
return;
}
let cell = inner.focused_mut();
@@ -785,7 +829,7 @@ impl App {
pub fn paste(&self, text: &str) {
let mut inner = self.inner.borrow_mut();
- if inner.disconnected.is_some() {
+ if inner.disconnected.is_some() || !Self::may_type(&inner) {
return;
}
let cell = inner.focused_mut();
@@ -963,6 +1007,9 @@ impl App {
self.focus_pane(hit.pane_id, advise);
}
let mut inner = self.inner.borrow_mut();
+ if what == Pointer::Down && !Self::may_type(&inner) {
+ return;
+ }
let Some(cell) = inner.panes.get(&hit.pane_id) else {
return;
};
@@ -1253,40 +1300,28 @@ impl App {
Self::set_status(&inner, "the server has no panes to show");
return;
};
- let (link, size, tab_changed) = {
+ let (link, tab_changed) = {
let mut inner = self.inner.borrow_mut();
if inner.switching || inner.disconnected.is_some() {
return;
}
let tab_changed = layout.tab_id != inner.tab_id;
inner.switching = tab_changed;
- let reported = inner.link.lease().reported;
- (inner.link.clone(), reported, tab_changed)
+ (inner.link.clone(), tab_changed)
};
if tab_changed {
- // The lease is per tab: a follower's report, never a claim.
- // Typing or clicking claims, as at attach.
+ // The lease is per tab: a follower's report of the tab's own
+ // size, never a claim. Typing or clicking claims, as at attach.
let outcome: Result<()> = async {
- if let Some(size) = size {
- let state = thinkterm_session::host::request(
- &link,
- Pdu::SetClientViewport(codec::SetClientViewport {
- tab_id: layout.tab_id,
- viewport: codec::ClientViewport::CellGrid { size },
- }),
- |pdu| match pdu {
- Pdu::ClientViewportState(s) => Ok(s),
- other => Err(other),
- },
- )
- .await?;
+ {
let mut lease = link.lease_mut();
lease.tab_id = Some(layout.tab_id);
- lease.apply_viewport(&state);
- } else {
- link.lease_mut().tab_id = Some(layout.tab_id);
+ lease.tab_owner = None;
+ lease.canonical_size = Some(layout.size);
+ lease.reported_canonical = None;
+ lease.fit = false;
}
- Ok(())
+ link.report_canonical(layout.tab_id).await
}
.await;
let mut inner = self.inner.borrow_mut();
@@ -1481,6 +1516,56 @@ impl App {
});
}
+ /// Reshape the tab to this window's grid (`on`), or go back to the
+ /// desktop's size (`off`): a claim either way, at the size the lease
+ /// then picks.
+ pub fn fit(self: &Rc<Self>, on: bool) {
+ let (link, tab_id) = {
+ let inner = self.inner.borrow();
+ inner.link.lease_mut().fit = on;
+ (inner.link.clone(), inner.tab_id)
+ };
+ let app = Rc::clone(self);
+ wasm_bindgen_futures::spawn_local(async move {
+ match link.claim(tab_id).await {
+ Ok(_) => {
+ app.refresh_status();
+ app.request_frame();
+ }
+ Err(err) => {
+ let inner = app.inner.borrow();
+ Self::set_status(&inner, &format!("could not resize the tab: {err:#}"));
+ }
+ }
+ });
+ }
+
+ /// Take the terminal from whichever device holds it (Handoff mode).
+ /// There is no giving it back: the desktop takes it by interacting.
+ pub fn take_over(self: &Rc<Self>) {
+ let (link, tab_id) = {
+ let inner = self.inner.borrow();
+ (inner.link.clone(), inner.tab_id)
+ };
+ let app = Rc::clone(self);
+ wasm_bindgen_futures::spawn_local(async move {
+ match link.claim(tab_id).await {
+ Ok(true) => {
+ app.refresh_status();
+ app.request_frame();
+ }
+ Ok(false) => {
+ let inner = app.inner.borrow();
+ Self::set_status(&inner, "the server did not hand the terminal over");
+ }
+ Err(err) => {
+ let inner = app.inner.borrow();
+ Self::set_status(&inner, &format!("could not take over: {err:#}"));
+ }
+ }
+ });
+ }
+
/// See `GlyphCache::warm`. Called once, after the first frame.
pub fn warm_glyph_canvas(&self) {
self.inner.borrow_mut().glyphs.warm();
@@ -1538,6 +1623,10 @@ impl App {
inner.cols = cols;
inner.rows = rows;
if changed {
+ // The page's grid is its own business: the tab keeps the
+ // desktop's size and this canvas letterboxes it. Only a page
+ // that asked to fit the tab to itself sends its grid, and then
+ // as a claim, because that is what changing the tab's size is.
let size = TerminalSize {
rows,
cols,
@@ -1545,50 +1634,17 @@ impl App {
pixel_height: rows * ch as usize,
dpi: (96.0 * dpr) as u32,
};
- let owner = inner.link.lease().owns_viewport();
- inner.link.lease_mut().reported = Some(size);
- let link = inner.link.clone();
- let (tab_id, pane_id) = (inner.tab_id, inner.focused_pane);
- if owner {
- inner.focused().session.apply_local_resize(size);
- let session = Arc::clone(&inner.focused().session);
- let host = Arc::clone(&inner.host);
- wasm_bindgen_futures::spawn_local(async move {
- let pdu = Pdu::Resize(codec::Resize {
- containing_tab_id: tab_id,
- pane_id,
- size,
- });
- if let Err(err) = thinkterm_session::host::request(&link, pdu, |p| match p {
- Pdu::UnitResponse(_) => Ok(()),
- other => Err(other),
- })
- .await
- {
- // The reflow above was optimistic. Refused, it would
- // show a grid the server does not have, for ever:
- // back to the canonical one, and repaint.
- log::warn!("resize refused: {err:#}");
- if let Some(canonical) = link.lease().canonical_size {
- session.apply_local_resize(canonical);
- session.make_all_stale();
- host.events.pane_output(0);
- }
- }
- });
- } else {
+ let fitting = {
+ let mut lease = inner.link.lease_mut();
+ lease.reported = Some(size);
+ lease.fit && lease.owns_viewport()
+ };
+ if fitting {
+ let link = inner.link.clone();
+ let tab_id = inner.tab_id;
wasm_bindgen_futures::spawn_local(async move {
- let pdu = Pdu::SetClientViewport(codec::SetClientViewport {
- tab_id,
- viewport: codec::ClientViewport::CellGrid { size },
- });
- if let Ok(state) = thinkterm_session::host::request(&link, pdu, |p| match p {
- Pdu::ClientViewportState(s) => Ok(s),
- other => Err(other),
- })
- .await
- {
- link.lease_mut().apply_viewport(&state);
+ if let Err(err) = link.claim(tab_id).await {
+ log::warn!("fitting the tab to this window: {err:#}");
}
});
}
diff --git a/thinkterm-web/src/attach.rs b/thinkterm-web/src/attach.rs
index 4c46759a..877a5f64 100644
--- a/thinkterm-web/src/attach.rs
+++ b/thinkterm-web/src/attach.rs
@@ -77,22 +77,35 @@ pub async fn attach(link: &WsLink, size: Option<TerminalSize>) -> Result<Attache
.find_map(active_pane)
.ok_or_else(|| anyhow!("the server has no panes to show"))?;
- link.lease_mut().tab_id = Some(entry.tab_id);
- if let Some(size) = size {
- let state = request(
- link,
- Pdu::SetClientViewport(codec::SetClientViewport {
- tab_id: entry.tab_id,
- viewport: codec::ClientViewport::CellGrid { size },
- }),
- |pdu| match pdu {
- Pdu::ClientViewportState(s) => Ok(s),
- other => Err(other),
- },
- )
- .await?;
+ // 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.
+ let tab_size = panes
+ .tabs
+ .iter()
+ .find(|tab| crate::layout::leaves(tab).iter().any(|e| e.pane_id == entry.pane_id))
+ .and_then(|tab| tab.root_size())
+ .unwrap_or(entry.size);
+ {
let mut lease = link.lease_mut();
- lease.reported = Some(size);
+ lease.tab_id = Some(entry.tab_id);
+ lease.reported = size;
+ }
+ let state = request(
+ link,
+ Pdu::SetClientViewport(codec::SetClientViewport {
+ tab_id: entry.tab_id,
+ viewport: codec::ClientViewport::CellGrid { size: tab_size },
+ }),
+ |pdu| match pdu {
+ Pdu::ClientViewportState(s) => Ok(s),
+ other => Err(other),
+ },
+ )
+ .await?;
+ {
+ let mut lease = link.lease_mut();
+ lease.reported_canonical = Some(tab_size);
lease.apply_viewport(&state);
}
@@ -206,12 +219,22 @@ pub async fn reattach(
return Err(PaneGone(pane_id).into());
}
- if let Some(size) = size {
+ let tab_size = panes
+ .tabs
+ .iter()
+ .find(|tab| contains_pane(tab, pane_id))
+ .and_then(|tab| tab.root_size());
+ {
+ let mut lease = link.lease_mut();
+ lease.tab_id = Some(tab_id);
+ lease.reported = size;
+ }
+ if let Some(tab_size) = tab_size {
let state = request(
link,
Pdu::SetClientViewport(codec::SetClientViewport {
tab_id,
- viewport: codec::ClientViewport::CellGrid { size },
+ viewport: codec::ClientViewport::CellGrid { size: tab_size },
}),
|pdu| match pdu {
Pdu::ClientViewportState(s) => Ok(s),
@@ -220,8 +243,7 @@ pub async fn reattach(
)
.await?;
let mut lease = link.lease_mut();
- lease.tab_id = Some(tab_id);
- lease.reported = Some(size);
+ lease.reported_canonical = Some(tab_size);
lease.apply_viewport(&state);
}
diff --git a/thinkterm-web/src/lease.rs b/thinkterm-web/src/lease.rs
index 73778492..f80d1127 100644
--- a/thinkterm-web/src/lease.rs
+++ b/thinkterm-web/src/lease.rs
@@ -15,8 +15,17 @@ pub struct Lease {
/// Per-tab owner (TmuxLatest mode).
pub tab_owner: Option<ClientId>,
pub canonical_size: Option<TerminalSize>,
- /// The grid this browser last reported.
+ /// The grid this page could show: its canvas in cells. Never sent as
+ /// a viewport unless `fit` is on; see `claim_size`.
pub reported: Option<TerminalSize>,
+ /// The canonical size this page last told the server about. The
+ /// server claims a client's last report for it when it types, so
+ /// the report must be kept current or a keystroke would reshape the
+ /// tab to a size the desktop has since left.
+ pub reported_canonical: Option<TerminalSize>,
+ /// The page wants the tab at its own grid rather than the desktop's.
+ /// Cleared when a push shows the tab in someone else's hands.
+ pub fit: bool,
}
fn same_client(a: &ClientId, b: &ClientId) -> bool {
@@ -53,6 +62,42 @@ impl Lease {
self.tab_owner = state.owner.clone();
self.canonical_size = Some(state.canonical_size);
self.apply_access(&state.access);
+ if self.fit && !self.owns_viewport() {
+ self.fit = false;
+ }
+ }
+
+ /// Whether the tab (TmuxLatest) or the connection (Handoff) has no
+ /// owner at all.
+ pub fn ownerless(&self) -> bool {
+ match self.mode {
+ Some(codec::FrontendAccessMode::TmuxLatest) => self.tab_owner.is_none(),
+ Some(codec::FrontendAccessMode::Handoff) => self.owner.is_none(),
+ None => true,
+ }
+ }
+
+ /// Whether this page's input will be accepted. In TmuxLatest anyone
+ /// may type (the server hands the tab to whoever does); in Handoff
+ /// only the owner, or anyone when there is none.
+ pub fn may_type(&self) -> bool {
+ match self.mode {
+ Some(codec::FrontendAccessMode::Handoff) => self.owns_viewport() || self.owner.is_none(),
+ _ => true,
+ }
+ }
+
+ /// The grid to claim the tab with. The desktop's own (canonical) size
+ /// unless this page asked to fit the tab to itself or nobody holds
+ /// the tab yet -- so typing here does not reshape what the desktop
+ /// shows. Echoed verbatim: the server's resize is a no-op only when
+ /// every field matches.
+ pub fn claim_size(&self) -> Option<TerminalSize> {
+ if self.fit || self.ownerless() {
+ self.reported.or(self.canonical_size)
+ } else {
+ self.canonical_size.or(self.reported)
+ }
}
}
@@ -123,3 +168,82 @@ mod tests {
assert!(lease.owns_viewport());
}
}
+
+#[cfg(test)]
+mod claim_tests {
+ use super::*;
+
+ fn id(n: usize) -> ClientId {
+ ClientId {
+ hostname: "h".into(),
+ username: "u".into(),
+ pid: 1,
+ epoch: 1,
+ id: n,
+ ssh_auth_sock: None,
+ }
+ }
+ fn size(cols: usize, rows: usize) -> TerminalSize {
+ TerminalSize { cols, rows, pixel_width: cols * 7, pixel_height: rows * 15, dpi: 96 }
+ }
+ fn lease(mode: codec::FrontendAccessMode) -> Lease {
+ Lease {
+ tab_id: Some(1),
+ me: Some(id(1)),
+ mode: Some(mode),
+ owner: None,
+ tab_owner: None,
+ canonical_size: Some(size(120, 40)),
+ reported: Some(size(96, 30)),
+ reported_canonical: None,
+ fit: false,
+ }
+ }
+
+ #[test]
+ fn a_tab_someone_else_holds_is_claimed_at_its_own_size() {
+ let mut l = lease(codec::FrontendAccessMode::TmuxLatest);
+ l.tab_owner = Some(id(2));
+ assert_eq!(l.claim_size(), Some(size(120, 40)), "the desktop's grid, verbatim");
+ assert!(l.may_type(), "TmuxLatest: typing hands the tab over, at that size");
+ }
+
+ #[test]
+ fn an_ownerless_tab_and_a_fit_take_the_page_s_own_grid() {
+ let mut l = lease(codec::FrontendAccessMode::TmuxLatest);
+ assert_eq!(l.claim_size(), Some(size(96, 30)));
+ l.tab_owner = Some(id(2));
+ l.fit = true;
+ assert_eq!(l.claim_size(), Some(size(96, 30)));
+ }
+
+ #[test]
+ fn a_tab_this_page_holds_keeps_the_size_it_was_claimed_at() {
+ let mut l = lease(codec::FrontendAccessMode::TmuxLatest);
+ l.tab_owner = Some(id(1));
+ assert_eq!(l.claim_size(), Some(size(120, 40)));
+ }
+
+ #[test]
+ fn handoff_lets_only_the_owner_type_and_a_push_ends_a_fit() {
+ let mut l = lease(codec::FrontendAccessMode::Handoff);
+ assert!(l.may_type(), "nobody holds the connection");
+ l.owner = Some(id(2));
+ assert!(!l.may_type());
+ assert_eq!(l.claim_size(), Some(size(120, 40)));
+ l.owner = Some(id(1));
+ assert!(l.may_type());
+ l.fit = true;
+ let state = codec::ClientViewportState {
+ tab_id: 1,
+ owner: Some(id(2)),
+ canonical_size: size(100, 50),
+ view: None,
+ generation: 3,
+ access: codec::FrontendAccessState { mode: codec::FrontendAccessMode::Handoff, owner: Some(id(2)), generation: 3 },
+ };
+ l.apply_viewport(&state);
+ assert!(!l.fit, "the tab is in someone else's hands");
+ assert_eq!(l.canonical_size, Some(size(100, 50)));
+ }
+}
diff --git a/thinkterm-web/src/link.rs b/thinkterm-web/src/link.rs
index 226d8130..9d4edfbd 100644
--- a/thinkterm-web/src/link.rs
+++ b/thinkterm-web/src/link.rs
@@ -456,16 +456,31 @@ impl WsLink {
/// Become the tab's viewport owner, if this browser is not already.
/// Called before input goes out, and answered from what the server
- /// says about ownership afterwards.
+ /// says about ownership afterwards. In Handoff mode with the
+ /// terminal in someone else's hands this refuses rather than takes;
+ /// `take_over` is the explicit way.
pub async fn ensure_owner(&self, tab_id: TabId) -> Result<bool> {
- if self.0.lease.borrow().owns_viewport() {
- return Ok(true);
- }
- let size = {
+ {
let lease = self.0.lease.borrow();
- lease.reported.or(lease.canonical_size)
+ if lease.owns_viewport() {
+ return Ok(true);
+ }
+ if !lease.may_type() {
+ return Ok(false);
+ }
}
- .ok_or_else(|| anyhow!("no viewport has been reported yet"))?;
+ self.claim(tab_id).await
+ }
+
+ /// Claim the tab, at the size `Lease::claim_size` says: the desktop's
+ /// own unless this page is fitting the tab to itself.
+ pub async fn claim(&self, tab_id: TabId) -> Result<bool> {
+ let size = self
+ .0
+ .lease
+ .borrow()
+ .claim_size()
+ .ok_or_else(|| anyhow!("no viewport has been reported yet"))?;
let state = thinkterm_session::host::request(
self,
Pdu::ClaimClientViewport(codec::ClaimClientViewport {
@@ -482,6 +497,39 @@ impl WsLink {
lease.apply_viewport(&state);
Ok(lease.owns_viewport())
}
+
+ /// Tell the server the tab's own size, so that a claim the server
+ /// makes for this page (it claims a client's last report when it
+ /// types) reshapes nothing. Sent whenever the canonical size the page
+ /// knows differs from what it last reported; inert for a follower.
+ pub async fn report_canonical(&self, tab_id: TabId) -> Result<()> {
+ let size = {
+ let lease = self.0.lease.borrow();
+ if lease.fit {
+ return Ok(());
+ }
+ match lease.canonical_size {
+ Some(size) if lease.reported_canonical != Some(size) => size,
+ _ => return Ok(()),
+ }
+ };
+ let state = thinkterm_session::host::request(
+ self,
+ Pdu::SetClientViewport(codec::SetClientViewport {
+ tab_id,
+ viewport: codec::ClientViewport::CellGrid { size },
+ }),
+ |pdu| match pdu {
+ Pdu::ClientViewportState(state) => Ok(state),
+ other => Err(other),
+ },
+ )
+ .await?;
+ let mut lease = self.0.lease.borrow_mut();
+ lease.reported_canonical = Some(size);
+ lease.apply_viewport(&state);
+ Ok(())
+ }
}
impl PduLink for WsLink {