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
thinkterm-web: models for the desktop-aligned page
RoversXa39cd74f014a
diff --git a/thinkterm-web/src/attach.rs b/thinkterm-web/src/attach.rsindex 896db532..a36c7ac2 100644--- a/thinkterm-web/src/attach.rs+++ b/thinkterm-web/src/attach.rs@@ -25,7 +25,7 @@ pub struct Attached {/// `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.-pub async fn attach(link: &WsLink, size: Option<TerminalSize>) -> Result<Attached> {+pub async fn attach(link: &WsLink, size: Option<TerminalSize>, nav_rows: usize) -> Result<Attached> {let version = request(link,Pdu::GetCodecVersion(codec::GetCodecVersion {}),@@ -80,34 +80,22 @@ pub async fn attach(link: &WsLink, size: Option<TerminalSize>) -> Result<Attache// 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);+ // 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);+ }}- 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);- }+ link.report_viewport(entry.tab_id).await?;request(link,@@ -177,6 +165,7 @@ pub async fn reattach(tab_id: TabId,focused: PaneId,size: Option<TerminalSize>,+ nav_rows: usize,) -> Result<codec::ListPanesResponse> {let version = request(link,@@ -226,17 +215,19 @@ pub async fn reattach(.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 tab_size = tab.root_size().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(tab_size);- lease.reported_canonical = None;+ lease.canonical_size = Some(laid.size);+ lease.reported_viewport = None;+ lease.set_native(&laid, nav_rows);lease.fit = false;}- link.report_canonical(tab_id).await?;+ link.report_viewport(tab_id).await?;Ok(panes)}diff --git a/thinkterm-web/src/icons.rs b/thinkterm-web/src/icons.rsnew file mode 100644index 00000000..80b29717--- /dev/null+++ b/thinkterm-web/src/icons.rs@@ -0,0 +1,54 @@+//! The lucide icons the desktop draws its chrome with, as inline SVG.+//! The same files `wezterm-gui/src/termwindow/ui/icons.rs` embeds; they+//! take their colour from CSS `color` and their size from CSS.++macro_rules! lucide {+ ($($name:literal),* $(,)?) => {+ pub fn svg(name: &str) -> &'static str {+ match name {+ $($name => include_str!(concat!("../../third_party/lucide/icons/", $name, ".svg")),)*+ _ => "",+ }+ }+ };+}++lucide!(+ "square-terminal",+ "x",+ "plus",+ "square-split-horizontal",+ "square-split-vertical",+ "maximize-2",+ "minimize-2",+ "loader-circle",+ "circle-alert",+ "circle-check",+ "panel-left",+ "folder",+ "folder-open",+ "folder-plus",+ "chevron-right",+ "chevron-down",+ "pin",+ "pin-off",+ "trash-2",+ "circle-plus",+ "layers",+ "ellipsis",+ "archive",+ "archive-restore",+ "globe",+ "link-2",+);++#[cfg(test)]+mod tests {+ #[test]+ fn every_named_icon_is_an_svg() {+ for name in ["square-terminal", "x", "plus", "maximize-2", "loader-circle", "panel-left", "trash-2"] {+ assert!(super::svg(name).starts_with("<svg"), "{name}");+ }+ assert_eq!(super::svg("no-such-icon"), "");+ }+}diff --git a/thinkterm-web/src/layout.rs b/thinkterm-web/src/layout.rsindex 692fdd91..84aaadd3 100644--- a/thinkterm-web/src/layout.rs+++ b/thinkterm-web/src/layout.rs@@ -32,6 +32,13 @@ impl Rect {}}+/// A pane in a stack, for the stack's row of capsules.+#[derive(Debug, Clone, PartialEq)]+pub struct StackMember {+ pub pane_id: PaneId,+ pub title: String,+}+/// One pane to draw.#[derive(Debug, Clone, PartialEq)]pub struct PanePlacement {@@ -50,6 +57,8 @@ pub struct PanePlacement {pub physical_top: StableRowIndex,pub size: TerminalSize,pub workspace: String,+ /// Every pane sharing this frame, the drawn one included, in order.+ pub stack: Vec<StackMember>,}/// The gap cell between two panes.@@ -80,6 +89,40 @@ pub struct TabLayout {pub hidden: Vec<PaneId>,}+impl TabLayout {+ /// What the desktop would claim for this layout: every drawn pane in+ /// the frame the split tree gives it, with `nav_rows` of the frame+ /// kept for the bar above the pane, as the desktop keeps them for+ /// its own (`ClientViewport::Native`). With the bar the desktop's+ /// height this is the layout the desktop already has, and claiming+ /// it resizes nothing; a `CellGrid` claim would grow each pane to+ /// its frame.+ pub fn viewport(&self, nav_rows: usize) -> Vec<codec::ClientPaneViewport> {+ let cell_w = self.size.pixel_width.checked_div(self.cols).unwrap_or(0);+ let cell_h = self.size.pixel_height.checked_div(self.rows).unwrap_or(0);+ self.panes+ .iter()+ .map(|p| codec::ClientPaneViewport {+ pane_id: p.pane_id,+ size: TerminalSize {+ rows: p.frame.rows.saturating_sub(nav_rows).max(1),+ cols: p.frame.cols,+ pixel_width: p.frame.cols * cell_w,+ pixel_height: p.frame.rows.saturating_sub(nav_rows).max(1) * cell_h,+ dpi: self.size.dpi,+ },+ frame: TerminalSize {+ rows: p.frame.rows,+ cols: p.frame.cols,+ pixel_width: p.frame.cols * cell_w,+ pixel_height: p.frame.rows * cell_h,+ dpi: self.size.dpi,+ },+ })+ .collect()+ }+}+/// Every pane in a tab, left to right, top to bottom, stacks included.pub fn leaves(node: &PaneNode) -> Vec<&PaneEntry> {match node {@@ -101,7 +144,7 @@ pub fn tab_containing(list: &ListPanesResponse, pane_id: PaneId) -> Option<&Pane.find(|tab| leaves(tab).iter().any(|e| e.pane_id == pane_id))}-fn placement(entry: &PaneEntry, frame: Rect) -> PanePlacement {+fn placement(entry: &PaneEntry, frame: Rect, stack: Vec<StackMember>) -> PanePlacement {PanePlacement {pane_id: entry.pane_id,tab_id: entry.tab_id,@@ -115,9 +158,14 @@ fn placement(entry: &PaneEntry, frame: Rect) -> PanePlacement {physical_top: entry.physical_top,size: entry.size,workspace: entry.workspace.clone(),+ stack,}}+fn member(entry: &PaneEntry) -> StackMember {+ StackMember { pane_id: entry.pane_id, title: entry.title.clone() }+}+fn walk(node: &PaneNode,frame: Rect,@@ -127,12 +175,13 @@ fn walk() {match node {PaneNode::Empty => {}- PaneNode::Leaf(entry) => panes.push(placement(entry, frame)),+ PaneNode::Leaf(entry) => panes.push(placement(entry, frame, vec![member(entry)])),PaneNode::Stack(stack) => {let active = stack.active.min(stack.panes.len().saturating_sub(1));+ let members: Vec<StackMember> = stack.panes.iter().map(member).collect();for (i, entry) in stack.panes.iter().enumerate() {if i == active {- panes.push(placement(entry, frame));+ panes.push(placement(entry, frame, members.clone()));} else {hidden.push(entry.pane_id);}@@ -171,7 +220,29 @@ fn walk(/// Lay a tab out. `None` for an empty tab.pub fn layout(node: &PaneNode) -> Option<TabLayout> {- let size = node.root_size()?;+ layout_in(node, None, 0)+}++/// Lay a tab out, knowing the tab's own size when the server has said+/// it. A split's sizes are its frames and compose to the tab; a lone+/// pane (or stack) only lists the pane's grid, which is the frame less+/// the bar above it. Without the server's word the frame is taken to be+/// that grid plus `nav_rows`, as whoever laid it out with a bar would+/// have left it -- never the grid itself, since claiming a frame the+/// size of the pane would shrink the pane by the bar's rows each time.+pub fn layout_in(node: &PaneNode, tab_size: Option<TerminalSize>, nav_rows: usize) -> Option<TabLayout> {+ let listed = node.root_size()?;+ let size = match node {+ PaneNode::Split { .. } => listed,+ _ => tab_size.unwrap_or_else(|| {+ let rows = listed.rows + nav_rows;+ TerminalSize {+ rows,+ pixel_height: listed.pixel_height.checked_div(listed.rows).unwrap_or(0) * rows,+ ..listed+ }+ }),+ };let (window_id, tab_id) = node.window_and_tab_ids()?;let root = Rect {left: 0,@@ -289,6 +360,52 @@ mod tests {assert_positions_agree(&node, &l);}+ #[test]+ fn the_viewport_claims_each_pane_at_its_own_grid_in_its_frame() {+ // The desktop keeps 3 rows of each frame for its nav bar: the+ // listed size is 21 rows in a 24-row frame.+ let mut a = pane(1, 40, 24, 0, 0, false);+ a.size = size(40, 21);+ let mut b = pane(2, 39, 24, 41, 0, true);+ b.size = size(39, 21);+ let node = split(+ SplitDirection::Horizontal,+ size(40, 24),+ size(39, 24),+ PaneNode::Leaf(a),+ PaneNode::Leaf(b),+ );+ let l = layout(&node).unwrap();+ let v = l.viewport(3);+ assert_eq!(v.len(), 2);+ assert_eq!(v[0].size, size(40, 21), "the frame less the bar's rows: the grid the pane has");+ assert_eq!(l.viewport(2)[0].size, size(40, 22), "a shorter bar would give the pane a row");+ assert_eq!(v[0].frame, size(40, 24), "the frame the split gives it");+ assert_eq!(v[1].frame, size(39, 24));+ assert_eq!(v[0].frame.cols + v[1].frame.cols + 1, l.cols, "frames compose to the tab");+ assert_eq!(v[0].frame.pixel_width, 40 * 8, "pixels from the tab's cell");+ }++ #[test]+ fn a_lone_pane_s_frame_is_its_tab_not_its_grid() {+ let node = PaneNode::Leaf(pane(1, 80, 21, 0, 0, true));+ let told = layout_in(&node, Some(size(80, 24)), 3).unwrap();+ assert_eq!((told.rows, told.panes[0].frame.rows, told.panes[0].content.1), (24, 24, 21));+ let guessed = layout_in(&node, None, 3).unwrap();+ assert_eq!(guessed.rows, 24, "the grid plus the bar's rows");+ assert_eq!(guessed.size.pixel_height, 24 * 16);+ assert_eq!(guessed.viewport(3)[0].size, size(80, 21), "so a claim leaves the pane as it is");+ // A split's frames are its own word.+ let split = split(+ SplitDirection::Horizontal,+ size(40, 24),+ size(39, 24),+ PaneNode::Leaf(pane(1, 40, 21, 0, 0, false)),+ PaneNode::Leaf(pane(2, 39, 21, 41, 0, true)),+ );+ assert_eq!(layout_in(&split, Some(size(80, 30)), 3).unwrap().rows, 24);+ }+#[test]fn a_side_by_side_split_leaves_one_gap_cell_for_the_divider() {// 40 | 39 = 80 cols, the divider on column 40.diff --git a/thinkterm-web/src/lease.rs b/thinkterm-web/src/lease.rsindex f80d1127..8f5949df 100644--- a/thinkterm-web/src/lease.rs+++ b/thinkterm-web/src/lease.rs@@ -1,6 +1,7 @@//! Who owns the tab this browser mirrors, as the server has told us. Pure,//! so it is tested natively; the WebSocket link keeps one and feeds it.+use std::collections::HashMap;use thinkterm_proto::{ClientId, TabId};use wezterm_term::TerminalSize;@@ -18,14 +19,31 @@ pub struct Lease {/// 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.+ /// The viewport 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+ /// shape the desktop has since left.+ pub reported_viewport: Option<codec::ClientViewport>,+ /// The drawn layout as the desktop would claim it (`TabLayout::viewport`);+ /// empty only before the tab is first listed. Kept across a canonical+ /// size push: the listing that follows it replaces the panes, and a+ /// stale pane-by-pane claim is refused and retried as the grid,+ /// whereas a bare grid claim would resize every pane to its frame.+ pub native: Vec<codec::ClientPaneViewport>,+ /// The tab size `native`'s frames compose to: the listing's. A claim+ /// at any other size goes as a bare grid, since frames that do not+ /// compose to the root are refused.+ pub native_root: Option<TerminalSize>,+ /// The page's own grid is what it claims: set when an interaction+ /// here takes the terminal, as the desktop's own window shape wins+ /// when it takes it. Cleared when a push shows the tab in someone+ /// else's hands, and the page follows the desktop's size again.pub fit: bool,+ /// Every tab's own size the server has told us, whichever tab it+ /// was for. A lone pane's listing does not say how big its tab is+ /// (the pane is smaller by its bar), and a report with the wrong+ /// root would resize the tab to it.+ pub tab_sizes: HashMap<TabId, TerminalSize>,}fn same_client(a: &ClientId, b: &ClientId) -> bool {@@ -56,6 +74,7 @@ impl Lease {}pub fn apply_viewport(&mut self, state: &codec::ClientViewportState) {+ self.tab_sizes.insert(state.tab_id, state.canonical_size);if Some(state.tab_id) != self.tab_id {return;}@@ -87,16 +106,39 @@ impl Lease {}}- /// 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)+ /// Whether a terminal-area interaction must claim before it acts. In+ /// Handoff the server refuses even a focus change from a renderer that+ /// does not hold the terminal -- also when nobody does, since a page+ /// that has reported a viewport is a screen, not a CLI. In TmuxLatest+ /// input claims on its own and focus changes are always accepted.+ pub fn needs_claim(&self) -> bool {+ matches!(self.mode, Some(codec::FrontendAccessMode::Handoff)) && !self.owns_viewport()+ }++ /// The panes as the desktop would claim them, from a listing.+ pub fn set_native(&mut self, layout: &crate::layout::TabLayout, nav_rows: usize) {+ self.native = layout.viewport(nav_rows);+ self.native_root = Some(layout.size);+ }++ /// The viewport to claim the tab with: the page's own grid when an+ /// interaction here holds the terminal (`fit`), else the desktop's+ /// canonical size, so a follower's report changes nothing. Pane by+ /// pane when the listed frames compose to that size -- then every+ /// pane keeps the rows above it for its bar -- and as a bare grid+ /// otherwise (the size just changed; the next listing catches up).+ pub fn claim_viewport(&self) -> Option<codec::ClientViewport> {+ let size = if self.fit || (self.ownerless() && self.canonical_size.is_none()) {+ self.reported.or(self.canonical_size)?} else {- self.canonical_size.or(self.reported)+ self.canonical_size.or(self.reported)?+ };+ let composes = !self.native.is_empty()+ && self.native_root.is_some_and(|r| r.cols == size.cols && r.rows == size.rows);+ if composes {+ Some(codec::ClientViewport::Native { size, panes: self.native.clone() })+ } else {+ Some(codec::ClientViewport::CellGrid { size })}}}@@ -164,6 +206,7 @@ mod tests {};lease.apply_viewport(&state(8, Some(id(1))));assert!(!lease.owns_viewport(), "another tab's owner is not ours");+ assert!(lease.tab_sizes.contains_key(&8), "but its size is remembered");lease.apply_viewport(&state(7, Some(id(1))));assert!(lease.owns_viewport());}@@ -195,33 +238,82 @@ mod claim_tests {tab_owner: None,canonical_size: Some(size(120, 40)),reported: Some(size(96, 30)),- reported_canonical: None,+ reported_viewport: None,+ native: vec![],+ native_root: None,fit: false,+ tab_sizes: HashMap::new(),}}+ fn grid(l: &Lease) -> Option<TerminalSize> {+ match l.claim_viewport()? {+ codec::ClientViewport::CellGrid { size } => Some(size),+ codec::ClientViewport::Native { .. } => None,+ }+ }+ fn pane(pane_id: usize, cols: usize, rows: usize) -> codec::ClientPaneViewport {+ codec::ClientPaneViewport { pane_id, size: size(cols, rows - 3), frame: size(cols, rows) }+ }#[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_eq!(grid(&l), 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() {+ fn only_a_fit_or_an_unsized_ownerless_tab_takes_the_page_s_own_grid() {let mut l = lease(codec::FrontendAccessMode::TmuxLatest);- assert_eq!(l.claim_size(), Some(size(96, 30)));+ assert_eq!(grid(&l), Some(size(120, 40)), "ownerless but sized: the tab's own");+ l.canonical_size = None;+ assert_eq!(grid(&l), Some(size(96, 30)), "nothing known: the page's");+ l.canonical_size = Some(size(120, 40));l.tab_owner = Some(id(2));l.fit = true;- assert_eq!(l.claim_size(), Some(size(96, 30)));+ assert_eq!(grid(&l), 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)));+ assert_eq!(grid(&l), Some(size(120, 40)));+ }++ #[test]+ fn a_listed_tab_is_claimed_pane_by_pane_until_its_size_moves() {+ let mut l = lease(codec::FrontendAccessMode::TmuxLatest);+ l.tab_owner = Some(id(2));+ l.native = vec![pane(1, 59, 40), pane(2, 60, 40)];+ l.native_root = Some(size(120, 40));+ match l.claim_viewport() {+ Some(codec::ClientViewport::Native { size: root, panes }) => {+ assert_eq!(root, size(120, 40));+ assert_eq!(panes.len(), 2);+ assert_eq!(panes[0].size, size(59, 37), "the pane's grid, not its frame");+ }+ other => panic!("expected a native claim, got {other:?}"),+ }+ l.fit = true;+ assert_eq!(grid(&l), Some(size(96, 30)), "a fit is always the page's grid");+ l.fit = false;+ 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::TmuxLatest, owner: None, generation: 3 },+ };+ l.apply_viewport(&state);+ assert_eq!(l.native.len(), 2, "the panes wait for the next listing");+ assert_eq!(+ l.claim_viewport(),+ Some(codec::ClientViewport::CellGrid { size: size(100, 50) }),+ "frames of the old size would not compose: the bare grid until the next listing"+ );}#[test]@@ -230,7 +322,7 @@ mod claim_tests {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)));+ assert_eq!(grid(&l), Some(size(120, 40)));l.owner = Some(id(1));assert!(l.may_type());l.fit = true;diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex 3e4368ff..d5457eee 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -8,8 +8,12 @@ pub mod chrome;pub mod fallback;pub mod ime;pub mod keymap;+pub mod icons;pub mod layout;pub mod lease;+pub mod navbar;+pub mod sidebar;+pub mod tree;pub mod viewport;#[cfg(target_arch = "wasm32")]diff --git a/thinkterm-web/src/link.rs b/thinkterm-web/src/link.rsindex 9d4edfbd..bf7b8c72 100644--- a/thinkterm-web/src/link.rs+++ b/thinkterm-web/src/link.rs@@ -461,55 +461,74 @@ impl WsLink {/// `take_over` is the explicit way.pub async fn ensure_owner(&self, tab_id: TabId) -> Result<bool> {{- let lease = self.0.lease.borrow();+ let mut lease = self.0.lease.borrow_mut();if lease.owns_viewport() {return Ok(true);}if !lease.may_type() {return Ok(false);}+ // An interaction here takes the terminal at this page's own+ // shape, as the desktop's window takes it at its own.+ lease.fit = true;}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.+ /// Claim the tab with the viewport `Lease::claim_viewport` says: the+ /// desktop's own shape unless this page is fitting the tab to itself.+ /// A pane-by-pane claim the server will not compose (a stale zoom+ /// position, say) is retried as the bare grid: the hand-over matters+ /// more than the geometry.pub async fn claim(&self, tab_id: TabId) -> Result<bool> {- let size = self+ let viewport = self.0.lease.borrow()- .claim_size()+ .claim_viewport().ok_or_else(|| anyhow!("no viewport has been reported yet"))?;- let state = thinkterm_session::host::request(+ let (viewport, state) = match self.claim_with(tab_id, viewport.clone()).await {+ Ok(state) => (viewport, state),+ Err(err) if matches!(viewport, codec::ClientViewport::Native { .. }) => {+ log::warn!("pane-by-pane claim refused, claiming the grid: {err:#}");+ let grid = codec::ClientViewport::CellGrid { size: viewport.size() };+ let state = self.claim_with(tab_id, grid.clone()).await?;+ (grid, state)+ }+ Err(err) => return Err(err),+ };+ let mut lease = self.0.lease.borrow_mut();+ // A claim is also what the server remembers as this page's report.+ lease.reported_viewport = Some(viewport);+ lease.apply_viewport(&state);+ Ok(lease.owns_viewport())+ }++ async fn claim_with(+ &self,+ tab_id: TabId,+ viewport: codec::ClientViewport,+ ) -> Result<codec::ClientViewportState> {+ thinkterm_session::host::request(self,- Pdu::ClaimClientViewport(codec::ClaimClientViewport {- tab_id,- viewport: codec::ClientViewport::CellGrid { size },- }),+ Pdu::ClaimClientViewport(codec::ClaimClientViewport { tab_id, viewport }),|pdu| match pdu {Pdu::ClientViewportState(state) => Ok(state),other => Err(other),},)- .await?;- let mut lease = self.0.lease.borrow_mut();- lease.apply_viewport(&state);- Ok(lease.owns_viewport())+ .await}- /// Tell the server the tab's own size, so that a claim the server+ /// Tell the server the tab's own shape, 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 = {+ /// types) reshapes nothing. Sent whenever what the page would claim+ /// differs from what it last reported; inert for a follower.+ pub async fn report_viewport(&self, tab_id: TabId) -> Result<()> {+ let viewport = {let lease = self.0.lease.borrow();- if lease.fit {- return Ok(());- }- match lease.canonical_size {- Some(size) if lease.reported_canonical != Some(size) => size,+ match lease.claim_viewport() {+ Some(v) if lease.reported_viewport.as_ref() != Some(&v) => v,_ => return Ok(()),}};@@ -517,7 +536,7 @@ impl WsLink {self,Pdu::SetClientViewport(codec::SetClientViewport {tab_id,- viewport: codec::ClientViewport::CellGrid { size },+ viewport: viewport.clone(),}),|pdu| match pdu {Pdu::ClientViewportState(state) => Ok(state),@@ -526,7 +545,7 @@ impl WsLink {).await?;let mut lease = self.0.lease.borrow_mut();- lease.reported_canonical = Some(size);+ lease.reported_viewport = Some(viewport);lease.apply_viewport(&state);Ok(())}diff --git a/thinkterm-web/src/navbar.rs b/thinkterm-web/src/navbar.rsnew file mode 100644index 00000000..f1b7c343--- /dev/null+++ b/thinkterm-web/src/navbar.rs@@ -0,0 +1,300 @@+//! The strip above each pane: the desktop's pane nav bar+//! (`wezterm-gui/src/termwindow/render/pane.rs`), as HTML laid over the+//! canvas. The geometry is pure and tested natively; the DOM half only+//! builds on wasm.++use crate::layout::{PanePlacement, TabLayout};++/// The desktop's bar in CSS px: the header font's cell times 9/4. With+/// the default 14 pt header font on a 2x Mac that is 94 device px, which+/// is also what the desktop's listings show it reserving (three rows of+/// a 46.67 px cell, the smallest count a 94 px bar needs).+pub const DESKTOP_NAV_CSS: f64 = 47.0;++/// The bar's height on this page. The desktop's, scaled by how far the+/// page's cell is from the desktop's: with the font matched the ratio+/// is one and the bar is the desktop's to the pixel.+pub fn nav_css(page_cell_css: f64, desktop_cell_css: Option<f64>) -> f64 {+ match desktop_cell_css {+ Some(d) if d > 0.0 && page_cell_css > 0.0 => DESKTOP_NAV_CSS * page_cell_css / d,+ _ => DESKTOP_NAV_CSS,+ }+}++/// Rows of a frame the bar takes from the pane, as the desktop counts+/// them (`resize.rs` `terminal_size_for_positioned_pane`): whatever is+/// left below the bar is divided into whole cells.+pub fn nav_rows(nav_dev: f64, cell_h_dev: f64) -> usize {+ if cell_h_dev <= 0.0 {+ return 0;+ }+ (nav_dev / cell_h_dev).ceil() as usize+}++/// How far below its frame's top a pane's content starts, in device+/// px: the bar, but never more than the frame has spare over the pane's+/// own rows. A layout nobody with a bar has laid out (a CLI split) has+/// no spare rows; the bar then sits over the first rows until the next+/// claim from here reshapes the panes with room for it.+pub fn content_offset_dev(place: &PanePlacement, nav_dev: f32, cell_h_dev: f32) -> f32 {+ let spare = place.frame.rows.saturating_sub(place.content.1) as f32 * cell_h_dev;+ nav_dev.min(spare)+}++/// Where a bar goes, in CSS px from the canvas's top-left.+#[derive(Debug, Clone, PartialEq)]+pub struct NavRect {+ pub pane_id: thinkterm_proto::PaneId,+ pub left: f64,+ pub top: f64,+ pub width: f64,+ pub height: f64,+}++/// One bar per drawn pane, spanning the pane's chrome span like the+/// desktop's: to the window's edge where the pane touches the tab's+/// edge (past the padding the grid sits in), half a cell into the+/// divider where it does not, so neighbours tile. `pad_css` is where the+/// grid starts and `width_css` the canvas's width.+pub fn rects(+ layout: &TabLayout,+ cell_css: (f64, f64),+ nav_css: f64,+ pad_css: (f64, f64),+ width_css: f64,+) -> Vec<NavRect> {+ let (cw, ch) = cell_css;+ layout+ .panes+ .iter()+ .map(|p| {+ let left = if p.frame.left == 0 { 0.0 } else { pad_css.0 + p.frame.left as f64 * cw - cw / 2.0 };+ let end = p.frame.left + p.frame.cols;+ let right = if end >= layout.cols {+ width_css.max(pad_css.0 + layout.cols as f64 * cw)+ } else {+ pad_css.0 + end as f64 * cw + cw / 2.0+ };+ // A pane on the tab's top row starts at the window's edge,+ // over the padding, like one at its left edge.+ let top = if p.frame.top == 0 { 0.0 } else { pad_css.1 + p.frame.top as f64 * ch };+ NavRect {+ pane_id: p.pane_id,+ left,+ top,+ width: right - left,+ height: nav_css + (pad_css.1 + p.frame.top as f64 * ch - top),+ }+ })+ .collect()+}++/// A pane's title as the desktop shows it (`ui/mod.rs`+/// `terminal_title_for_display`): a bare shell at its prompt is+/// "Terminal", and a leading busy marker (the spinner some agents put in+/// the title) is lifted off into the `busy` flag.+pub fn display_title(title: &str) -> (&str, bool) {+ let trimmed = title.trim_start();+ let (title, busy) = match trimmed.chars().next() {+ Some(ch) if is_busy_marker(ch) => (trimmed[ch.len_utf8()..].trim_start(), true),+ _ => (trimmed, false),+ };+ let title = title.trim();+ if title.is_empty() || is_default_shell_title(title) {+ ("Terminal", busy)+ } else {+ (title, busy)+ }+}++fn is_busy_marker(ch: char) -> bool {+ // Braille and the half-circle frames Claude Code spins; U+2733 is+ // its idle marker and deliberately not here.+ matches!(ch as u32, 0x2800..=0x28ff | 0x25d0..=0x25d3 | 0xf0130 | 0xf0a9e..=0xf0aa5 | 0xee00..=0xee0b)+}++fn is_default_shell_title(title: &str) -> bool {+ let title = title.rsplit(['/', '\\']).next().unwrap_or(title).to_ascii_lowercase();+ let title = title.strip_suffix(".exe").unwrap_or(&title);+ matches!(+ title,+ "zsh" | "bash" | "sh" | "dash" | "ksh" | "csh" | "tcsh" | "fish" | "nu" | "nushell" | "elvish"+ | "xonsh" | "pwsh" | "powershell" | "cmd"+ )+}++/// What one bar shows.+#[derive(Debug, Clone, PartialEq)]+pub struct NavView {+ pub rect: NavRect,+ pub members: Vec<CapsuleView>,+ pub focused: bool,+ pub zoomed: bool,+ /// The close button was pressed once and waits for the press that means it.+ pub closing: bool,+}++#[derive(Debug, Clone, PartialEq)]+pub struct CapsuleView {+ pub pane_id: thinkterm_proto::PaneId,+ pub title: String,+ pub busy: bool,+ pub current: bool,+}++#[cfg(target_arch = "wasm32")]+mod dom {+ use super::NavView;++ pub struct NavBars {+ root: web_sys::Element,+ }++ fn escape(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ for c in text.chars() {+ match c {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '"' => out.push_str("""),+ c => out.push(c),+ }+ }+ out+ }++ impl NavBars {+ pub fn mount(id: &str) -> Option<Self> {+ let root = web_sys::window()?.document()?.get_element_by_id(id)?;+ Some(Self { root })+ }++ pub fn element(&self) -> &web_sys::Element {+ &self.root+ }++ /// The markup for every bar. The caller keeps the last string and+ /// only sets it when it changed: layouts are re-listed often and+ /// mostly unchanged.+ pub fn html(bars: &[NavView]) -> String {+ let icon = crate::icons::svg;+ let mut html = String::new();+ for bar in bars {+ let class = if bar.focused { "nav focused" } else { "nav" };+ html.push_str(&format!(+ "<div class=\"{class}\" data-nav=\"{}\" style=\"left:{:.2}px;top:{:.2}px;width:{:.2}px;height:{:.2}px\"><span class=\"caps\">",+ bar.rect.pane_id, bar.rect.left, bar.rect.top, bar.rect.width, bar.rect.height+ ));+ for m in &bar.members {+ let class = if m.current { "cap current" } else { "cap" };+ let glyph = if m.busy { format!("<span class=\"spin\">{}</span>", icon("loader-circle")) } else { icon("square-terminal").to_string() };+ let (close_class, close_body) = if bar.closing && m.current {+ ("x danger", "close?")+ } else {+ ("x", icon("x"))+ };+ html.push_str(&format!(+ "<span class=\"{class}\" data-pane=\"{}\" title=\"{}\">{glyph}<span class=\"t\">{}</span><span class=\"{close_class}\" data-action=\"close-pane\" data-pane=\"{}\" title=\"Close this pane and end its program. Asks twice.\">{close_body}</span></span>",+ m.pane_id, escape(&m.title), escape(&m.title), m.pane_id+ ));+ }+ html.push_str("</span><span class=\"acts\">");+ html.push_str(&format!("<span class=\"act\" data-action=\"new-tab\" title=\"New tab\">{}</span>", icon("plus")));+ html.push_str(&format!("<span class=\"act\" data-action=\"split-below\" title=\"Split down\">{}</span>", icon("square-split-vertical")));+ html.push_str(&format!("<span class=\"act\" data-action=\"split-right\" title=\"Split right\">{}</span>", icon("square-split-horizontal")));+ let (zoom_icon, zoom_title) = if bar.zoomed { ("minimize-2", "Unzoom") } else { ("maximize-2", "Zoom this pane to the whole tab") };+ html.push_str(&format!("<span class=\"act\" data-action=\"zoom\" title=\"{zoom_title}\">{}</span>", icon(zoom_icon)));+ html.push_str("</span></div>");+ }+ html+ }++ pub fn set(&self, html: &str) {+ self.root.set_inner_html(html);+ }+ }+}++#[cfg(target_arch = "wasm32")]+pub use dom::NavBars;++#[cfg(test)]+mod tests {+ use super::*;+ use crate::layout::{Rect, StackMember};+ use wezterm_term::TerminalSize;++ fn place(id: usize, left: usize, cols: usize, rows: usize, content_rows: usize) -> PanePlacement {+ PanePlacement {+ pane_id: id,+ tab_id: 1,+ window_id: 0,+ frame: Rect { left, top: 0, cols, rows },+ content: (cols, content_rows),+ is_active: false,+ is_zoomed: false,+ title: String::new(),+ alt_screen: false,+ physical_top: 0,+ size: TerminalSize::default(),+ workspace: String::new(),+ stack: vec![StackMember { pane_id: id, title: String::new() }],+ }+ }++ #[test]+ fn the_bar_takes_the_desktop_s_rows_of_a_frame() {+ // 94 device px over a 46.67 px cell: three rows, like the desktop.+ assert_eq!(nav_rows(94.0, 46.67), 3);+ assert_eq!(nav_rows(46.0, 23.0), 2);+ assert_eq!(nav_rows(47.0, 23.0), 3);+ assert_eq!(nav_rows(47.0, 0.0), 0);+ assert_eq!(nav_css(23.0, Some(23.333)), 47.0 * 23.0 / 23.333);+ assert_eq!(nav_css(23.0, None), 47.0);+ }++ #[test]+ fn content_sits_below_the_bar_but_never_past_the_spare_rows() {+ let laid_out = place(1, 0, 80, 45, 42);+ assert_eq!(content_offset_dev(&laid_out, 94.0, 46.67), 94.0);+ let cli = place(1, 0, 80, 45, 45);+ assert_eq!(content_offset_dev(&cli, 94.0, 46.67), 0.0, "no room: the bar overlaps");+ }++ #[test]+ fn bars_tile_across_the_divider_and_reach_the_tab_s_edges() {+ let layout = TabLayout {+ tab_id: 1,+ window_id: 0,+ workspace: String::new(),+ cols: 80,+ rows: 24,+ size: TerminalSize::default(),+ panes: vec![place(1, 0, 40, 24, 21), place(2, 41, 39, 24, 21)],+ dividers: vec![],+ zoomed: None,+ hidden: vec![],+ };+ let r = rects(&layout, (10.0, 20.0), 47.0, (0.0, 0.0), 800.0);+ assert_eq!((r[0].left, r[0].width), (0.0, 405.0), "to the divider's middle");+ assert_eq!((r[1].left, r[1].width), (405.0, 395.0), "from it to the tab's edge");+ assert_eq!(r[0].height, 47.0);+ // With the grid padded in a wider canvas, the outer bars still+ // reach the window's edges; the inner edge moves with the grid.+ let r = rects(&layout, (10.0, 20.0), 47.0, (10.0, 10.0), 1000.0);+ assert_eq!((r[0].left, r[0].top, r[0].width, r[0].height), (0.0, 0.0, 415.0, 57.0));+ assert_eq!((r[1].left, r[1].width), (415.0, 585.0));+ }++ #[test]+ fn titles_read_like_the_desktop_s() {+ assert_eq!(display_title("zsh"), ("Terminal", false));+ assert_eq!(display_title("/usr/bin/fish"), ("Terminal", false));+ assert_eq!(display_title("pwsh.exe"), ("Terminal", false));+ assert_eq!(display_title("vim notes.md"), ("vim notes.md", false));+ assert_eq!(display_title("\u{25d1} claude"), ("claude", true));+ assert_eq!(display_title("\u{2733} claude"), ("\u{2733} claude", false), "the idle marker stays");+ assert_eq!(display_title(" "), ("Terminal", false));+ }+}diff --git a/thinkterm-web/src/tree.rs b/thinkterm-web/src/tree.rsnew file mode 100644index 00000000..f5c3dd22--- /dev/null+++ b/thinkterm-web/src/tree.rs@@ -0,0 +1,598 @@+//! The sidebar's model: the server's Spaces, Projects and Threads+//! (`ThinkTermSessionState`, with `ThinkTermTree` for what it leaves+//! out), the agents in their panes, and the windows that belong to no+//! thread. Pure, so it is tested natively; `sidebar.rs` draws it.+//!+//! What a row shows follows the desktop (`termwindow/ui/sidebar.rs`):+//! a thread's status is the worst of what its panes are doing --+//! waiting on someone, then working, then finished unseen -- and its dot+//! says whether it is the one on show, unread, pinned, or open.++use codec::{ListPanesResponse, ThinkTermSessionState, ThinkTermSessionThread, ThinkTermTree, TreeOp};+use std::collections::{HashMap, HashSet};+use thinkterm_proto::{AgentState, AgentStatus, PaneId, TabId, WindowId};++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Status {+ Idle,+ Running,+ NeedsAttention,+ Done,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Dot {+ Active,+ Unread,+ Pinned,+ Open,+ Quiet,+}++#[derive(Debug, Clone, PartialEq)]+pub enum Row {+ Space { name: String },+ NewThread,+ Pinned,+ Workspaces,+ Project { id: String, name: String, path: String, collapsed: bool, archived: bool },+ Thread(ThreadRow),+ Archived { count: usize, open: bool },+ Others,+ Window { window_id: WindowId, title: String, selected: bool },+}++#[derive(Debug, Clone, PartialEq)]+pub struct ThreadRow {+ pub id: String,+ pub project_id: String,+ pub name: String,+ pub status: Status,+ pub dot: Dot,+ pub pinned: bool,+ pub unread: bool,+ /// The thread has terminals on the server.+ pub live: bool,+ pub selected: bool,+ /// Its delete button was pressed once and waits for the press that means it.+ pub deleting: bool,+}++#[derive(Default)]+pub struct TreeModel {+ pub session: Option<ThinkTermSessionState>,+ pub tree: Option<ThinkTermTree>,+ pub agents: HashMap<PaneId, AgentState>,+ pub collapsed: HashSet<String>,+ pub archived_open: bool,+ /// Every window on the server, with its workspace and a title.+ windows: Vec<(WindowId, String, String)>,+}++impl TreeModel {+ /// A newer snapshot from the same server, or any from another.+ pub fn apply_session(&mut self, state: ThinkTermSessionState) -> bool {+ if self+ .session+ .as_ref()+ .is_some_and(|prior| prior.server_id == state.server_id && state.generation <= prior.generation)+ {+ return false;+ }+ self.session = Some(state);+ true+ }++ pub fn apply_tree(&mut self, tree: ThinkTermTree) {+ self.tree = Some(tree);+ }++ pub fn apply_agent(&mut self, pane_id: PaneId, status: Option<&AgentStatus>) {+ match status {+ Some(s) => {+ self.agents.insert(pane_id, s.state);+ }+ None => {+ self.agents.remove(&pane_id);+ }+ }+ }++ /// The windows the server has, for the ones no thread claims.+ pub fn apply_panes(&mut self, list: &ListPanesResponse) {+ let mut seen = HashSet::new();+ self.windows.clear();+ for node in &list.tabs {+ let leaves = crate::layout::leaves(node);+ let Some(first) = leaves.first() else {+ continue;+ };+ if !seen.insert(first.window_id) {+ continue;+ }+ let title = list+ .window_titles+ .get(&first.window_id)+ .filter(|t| !t.is_empty())+ .cloned()+ .unwrap_or_else(|| {+ let (title, _) = crate::navbar::display_title(&first.title);+ title.to_string()+ });+ self.windows.push((first.window_id, first.workspace.clone(), title));+ }+ }++ pub fn thread(&self, id: &str) -> Option<&ThinkTermSessionThread> {+ self.session+ .as_ref()?+ .projects+ .iter()+ .flat_map(|p| p.threads.iter())+ .find(|t| t.id == id)+ }++ pub fn project_of(&self, thread_id: &str) -> Option<&codec::ThinkTermSessionProject> {+ self.session+ .as_ref()?+ .projects+ .iter()+ .find(|p| p.threads.iter().any(|t| t.id == thread_id))+ }++ /// The workspace a thread lives in, or would.+ pub fn workspace_of(thread: &ThinkTermSessionThread) -> Option<&str> {+ thread+ .materialized_workspace_name+ .as_deref()+ .or(thread.planned_workspace_name.as_deref())+ }++ /// The worst of what the thread's panes are doing, the desktop's way:+ /// an agent waiting on someone, or a program that failed, outranks+ /// one still working, which outranks having finished unseen.+ pub fn status_of(&self, thread: &ThinkTermSessionThread) -> Status {+ use codec::ThinkTermSessionWorkStatus as W;+ let agents = thread+ .tabs+ .iter()+ .flat_map(|t| t.pane_ids.iter())+ .filter_map(|p| self.agents.get(p));+ let mut working = false;+ for state in agents {+ match state {+ AgentState::Blocked => return Status::NeedsAttention,+ AgentState::Working => working = true,+ _ => {}+ }+ }+ match thread.work_status {+ W::NeedsAttention => Status::NeedsAttention,+ W::Running => Status::Running,+ _ if working => Status::Running,+ W::FinishedUnseen => Status::Done,+ W::Idle if thread.is_unread => Status::Done,+ W::Idle => Status::Idle,+ }+ }++ /// The thread on show: the one holding the tab on show, else the one+ /// whose workspace the page is in.+ pub fn selected_thread(&self, current_tab: TabId, current_workspace: &str) -> Option<&str> {+ let session = self.session.as_ref()?;+ let threads = || session.projects.iter().flat_map(|p| p.threads.iter());+ threads()+ .find(|t| t.tabs.iter().any(|tab| tab.tab_id == current_tab))+ .or_else(|| threads().find(|t| Self::workspace_of(t) == Some(current_workspace)))+ .map(|t| t.id.as_str())+ }++ pub fn rows(&self, current_tab: TabId, current_workspace: &str, current_window: WindowId) -> Vec<Row> {+ self.rows_with(current_tab, current_workspace, current_window, None)+ }++ /// `deleting` is the thread whose delete button waits for its second press.+ pub fn rows_with(+ &self,+ current_tab: TabId,+ current_workspace: &str,+ current_window: WindowId,+ deleting: Option<&str>,+ ) -> Vec<Row> {+ let mut rows = Vec::new();+ let Some(session) = &self.session else {+ return rows;+ };+ let selected = self.selected_thread(current_tab, current_workspace);+ let space_name = session+ .spaces+ .first()+ .map(|s| s.name.clone())+ .unwrap_or_else(|| "Default".to_string());+ rows.push(Row::Space { name: space_name });+ rows.push(Row::NewThread);+ let thread_row = |t: &ThinkTermSessionThread, project_id: &str| {+ let live = !t.tabs.is_empty();+ let is_selected = selected == Some(t.id.as_str());+ let dot = if is_selected {+ Dot::Active+ } else if t.is_unread {+ Dot::Unread+ } else if t.is_pinned {+ Dot::Pinned+ } else if live {+ Dot::Open+ } else {+ Dot::Quiet+ };+ Row::Thread(ThreadRow {+ id: t.id.clone(),+ project_id: project_id.to_string(),+ name: t.name.clone(),+ status: self.status_of(t),+ dot,+ pinned: t.is_pinned,+ unread: t.is_unread,+ live,+ selected: is_selected,+ deleting: deleting == Some(t.id.as_str()),+ })+ };+ let pinned: Vec<Row> = session+ .projects+ .iter()+ .flat_map(|p| p.threads.iter().filter(|t| t.is_pinned).map(move |t| thread_row(t, &p.id)))+ .collect();+ if !pinned.is_empty() {+ rows.push(Row::Pinned);+ rows.extend(pinned);+ }+ rows.push(Row::Workspaces);+ for project in &session.projects {+ let collapsed = self.collapsed.contains(&project.id);+ rows.push(Row::Project {+ id: project.id.clone(),+ name: project.name.clone(),+ path: project.path.clone(),+ collapsed,+ archived: false,+ });+ if !collapsed {+ rows.extend(project.threads.iter().filter(|t| !t.is_pinned).map(|t| thread_row(t, &project.id)));+ }+ }+ // Archived projects are only in the tree.+ let archived: Vec<&codec::TtProject> = self+ .tree+ .as_ref()+ .map(|t| t.projects.iter().filter(|p| p.archived_at.is_some()).collect())+ .unwrap_or_default();+ if !archived.is_empty() {+ rows.push(Row::Archived { count: archived.len(), open: self.archived_open });+ if self.archived_open {+ for p in archived {+ rows.push(Row::Project {+ id: p.id.clone(),+ name: p.name.clone(),+ path: p.path.clone(),+ collapsed: true,+ archived: true,+ });+ }+ }+ }+ // Windows no thread claims, so nothing is out of reach.+ let claimed: HashSet<&str> = session+ .projects+ .iter()+ .flat_map(|p| p.threads.iter())+ .filter_map(Self::workspace_of)+ .collect();+ let others: Vec<Row> = self+ .windows+ .iter()+ .filter(|(_, ws, _)| !claimed.contains(ws.as_str()))+ .map(|(id, _, title)| Row::Window { window_id: *id, title: title.clone(), selected: *id == current_window })+ .collect();+ if !others.is_empty() {+ rows.push(Row::Others);+ rows.extend(others);+ }+ rows+ }+}++/// A write to the tree and what the tree must show afterwards. The+/// server answers a mutation with its tree and nothing else: an op it+/// would not apply (an unknown id, a Space's last project archived) just+/// leaves the tree as it was, so the intent is checked against the+/// answer to turn a silent no-op into a remark.+#[derive(Debug, Clone, PartialEq)]+pub struct Intent {+ pub ops: Vec<TreeOp>,+ pub expect: Expect,+}++#[derive(Debug, Clone, PartialEq)]+pub enum Expect {+ ThreadExists(String),+ ThreadNamed(String, String),+ ThreadPinned(String, bool),+ ThreadGone(String),+ ProjectExists(String),+ ProjectNamed(String, String),+ ProjectArchived(String, bool),+}++impl Expect {+ pub fn check(&self, tree: &ThinkTermTree) -> Result<(), String> {+ let thread = |id: &str| tree.projects.iter().flat_map(|p| p.threads.iter()).find(|t| t.id == id);+ let project = |id: &str| tree.projects.iter().find(|p| p.id == id);+ match self {+ Expect::ThreadExists(id) => thread(id).map(|_| ()).ok_or_else(|| "the server did not create the thread".into()),+ Expect::ThreadNamed(id, name) => match thread(id) {+ Some(t) if &t.name == name => Ok(()),+ // The server keeps names unique within a project: a+ // different name back is its answer, not a refusal.+ Some(t) if t.name.starts_with(name.as_str()) => Ok(()),+ Some(_) => Err("the server kept the old name".into()),+ None => Err("the thread is gone".into()),+ },+ Expect::ThreadPinned(id, pinned) => match thread(id) {+ Some(t) if t.is_pinned == *pinned => Ok(()),+ Some(_) => Err("the server did not change the pin".into()),+ None => Err("the thread is gone".into()),+ },+ Expect::ThreadGone(id) => match thread(id) {+ None => Ok(()),+ Some(_) => Err("the server did not delete the thread".into()),+ },+ Expect::ProjectExists(id) => project(id).map(|_| ()).ok_or_else(|| "the server did not create the project".into()),+ Expect::ProjectNamed(id, name) => match project(id) {+ Some(p) if &p.name == name => Ok(()),+ Some(_) => Err("the server kept the old name".into()),+ None => Err("the project is gone".into()),+ },+ Expect::ProjectArchived(id, archived) => match project(id) {+ Some(p) if p.archived_at.is_some() == *archived => Ok(()),+ Some(_) if *archived => Err("the last project of a Space cannot be archived".into()),+ Some(_) => Err("the server did not restore the project".into()),+ None => Err("the project is gone".into()),+ },+ }+ }+}++/// An id the server adopts: opaque, unique enough, minted here so the+/// thread can be opened without waiting for the answer (the desktop+/// does the same).+pub fn new_id(kind: &str, random: impl Fn() -> u32) -> String {+ format!("{kind}-{:08x}{:08x}{:08x}{:08x}", random(), random(), random(), random())+}++pub fn create_thread(project_id: &str, thread_id: String, now: i64) -> Intent {+ Intent {+ ops: vec![TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id: project_id.to_string(),+ // Empty: the server names it "Thread N".+ name: String::new(),+ workspace: None,+ created_at: now,+ }],+ expect: Expect::ThreadExists(thread_id),+ }+}++/// The directory's own name, as the desktop names a project.+pub fn project_name_for_path(path: &str) -> String {+ let trimmed = path.trim_end_matches('/');+ let name = trimmed.rsplit('/').next().unwrap_or(trimmed);+ if name.is_empty() || name == "~" {+ "Home".to_string()+ } else {+ name.to_string()+ }+}++/// A project at `path` with its `main` thread, in one round trip; the+/// Space is made too when the tree has none yet.+pub fn create_project(space: Option<&str>, project_id: String, thread_id: String, path: &str, now: i64) -> Intent {+ let mut ops = Vec::new();+ let space_id = match space {+ Some(id) => id.to_string(),+ None => {+ let id = format!("space-{}", &project_id[8.min(project_id.len())..]);+ ops.push(TreeOp::CreateSpace { space_id: id.clone(), name: "Default".into() });+ id+ }+ };+ ops.push(TreeOp::CreateProject {+ project_id: project_id.clone(),+ space_id,+ name: project_name_for_path(path),+ path: path.to_string(),+ });+ ops.push(TreeOp::CreateThread {+ thread_id: thread_id.clone(),+ project_id: project_id.clone(),+ name: "main".into(),+ workspace: None,+ created_at: now,+ });+ Intent { ops, expect: Expect::ThreadExists(thread_id) }+}++pub fn rename_thread(id: &str, name: &str, now: i64) -> Intent {+ Intent {+ ops: vec![TreeOp::RenameThread { thread_id: id.to_string(), name: name.to_string(), last_active_at: now }],+ expect: Expect::ThreadNamed(id.to_string(), name.to_string()),+ }+}++pub fn rename_project(id: &str, name: &str) -> Intent {+ Intent {+ ops: vec![TreeOp::RenameProject { project_id: id.to_string(), name: name.to_string() }],+ expect: Expect::ProjectNamed(id.to_string(), name.to_string()),+ }+}++pub fn set_pinned(id: &str, pinned: bool, now: i64) -> Intent {+ Intent {+ ops: vec![TreeOp::SetThreadPinned { thread_id: id.to_string(), pinned, last_active_at: now }],+ expect: Expect::ThreadPinned(id.to_string(), pinned),+ }+}++pub fn delete_thread(id: &str) -> Intent {+ Intent {+ ops: vec![TreeOp::DeleteThread { thread_id: id.to_string() }],+ expect: Expect::ThreadGone(id.to_string()),+ }+}++pub fn archive_project(id: &str, archived: bool, now: i64) -> Intent {+ Intent {+ ops: vec![TreeOp::SetProjectArchived { project_id: id.to_string(), archived_at: archived.then_some(now) }],+ expect: Expect::ProjectArchived(id.to_string(), archived),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use codec::{ThinkTermSessionProject, ThinkTermSessionSpace, ThinkTermSessionTab, ThinkTermSessionWorkStatus};++ #[test]+ fn intents_are_checked_against_the_tree_that_comes_back() {+ let mut tree = ThinkTermTree::default();+ let intent = create_project(None, "project-1".into(), "thread-1".into(), "~/work/site", 5);+ assert_eq!(intent.ops.len(), 3, "space, project, thread");+ for op in &intent.ops {+ assert!(codec::apply_op(&mut tree, op));+ }+ assert_eq!(tree.projects[0].name, "site");+ assert!(intent.expect.check(&tree).is_ok());+ assert!(Expect::ThreadExists("thread-9".into()).check(&tree).is_err());+ // A renamed thread comes back de-duplicated, which is fine.+ codec::apply_op(&mut tree, &rename_thread("thread-1", "work", 6).ops[0]);+ assert!(Expect::ThreadNamed("thread-1".into(), "work".into()).check(&tree).is_ok());+ // Archiving the Space's last project is refused: the tree comes back unchanged.+ let intent = archive_project("project-1", true, 7);+ assert!(!codec::apply_op(&mut tree, &intent.ops[0]));+ assert_eq!(intent.expect.check(&tree).unwrap_err(), "the last project of a Space cannot be archived");+ assert_eq!(project_name_for_path("~"), "Home");+ assert_eq!(project_name_for_path("/srv/app/"), "app");+ assert!(new_id("thread", || 0xabcd).starts_with("thread-0000abcd"));+ }++ fn thread(id: &str, ws: Option<&str>, tabs: Vec<(TabId, Vec<PaneId>)>) -> ThinkTermSessionThread {+ ThinkTermSessionThread {+ id: id.into(),+ project_id: "p1".into(),+ name: id.to_uppercase(),+ planned_workspace_name: None,+ materialized_workspace_name: ws.map(String::from),+ is_pinned: false,+ is_unread: false,+ work_status: ThinkTermSessionWorkStatus::Idle,+ tabs: tabs+ .into_iter()+ .map(|(tab_id, pane_ids)| ThinkTermSessionTab { window_id: 1, tab_id, pane_ids, title: String::new(), is_active: true })+ .collect(),+ }+ }++ fn session(threads: Vec<ThinkTermSessionThread>) -> ThinkTermSessionState {+ ThinkTermSessionState {+ server_id: "s".into(),+ tree_revision: 1,+ generation: 1,+ spaces: vec![ThinkTermSessionSpace { id: "sp".into(), name: "Default".into(), is_default: false, domain: None }],+ projects: vec![ThinkTermSessionProject { id: "p1".into(), space_id: "sp".into(), name: "Home".into(), path: "~".into(), threads }],+ }+ }++ #[test]+ fn rows_follow_the_desktop_s_order_and_pick_the_thread_on_show() {+ let mut m = TreeModel::default();+ let mut pinned = thread("b", Some("ws-b"), vec![]);+ pinned.is_pinned = true;+ assert!(m.apply_session(session(vec![thread("a", Some("ws-a"), vec![(7, vec![70])]), pinned])));+ let rows = m.rows(7, "ws-a", 1);+ let kinds: Vec<&str> = rows+ .iter()+ .map(|r| match r {+ Row::Space { .. } => "space",+ Row::NewThread => "new",+ Row::Pinned => "pinned",+ Row::Workspaces => "workspaces",+ Row::Project { .. } => "project",+ Row::Thread(t) if t.selected => "thread*",+ Row::Thread(_) => "thread",+ _ => "other",+ })+ .collect();+ assert_eq!(kinds, ["space", "new", "pinned", "thread", "workspaces", "project", "thread*"]);+ let Row::Thread(a) = &rows[6] else { panic!() };+ assert_eq!((a.dot, a.live), (Dot::Active, true));+ let Row::Thread(b) = &rows[3] else { panic!() };+ assert_eq!((b.dot, b.live, b.pinned), (Dot::Pinned, false, true));+ // Selection by workspace when the tab is not listed.+ assert_eq!(m.selected_thread(99, "ws-b"), Some("b"));+ }++ #[test]+ fn status_is_the_worst_of_the_panes_and_the_server_s_word() {+ let mut m = TreeModel::default();+ let mut t = thread("a", Some("ws"), vec![(1, vec![10, 11])]);+ assert_eq!(m.status_of(&t), Status::Idle);+ m.agents.insert(10, AgentState::Working);+ assert_eq!(m.status_of(&t), Status::Running);+ m.agents.insert(11, AgentState::Blocked);+ assert_eq!(m.status_of(&t), Status::NeedsAttention);+ m.agents.clear();+ t.work_status = ThinkTermSessionWorkStatus::FinishedUnseen;+ assert_eq!(m.status_of(&t), Status::Done);+ t.work_status = ThinkTermSessionWorkStatus::Idle;+ t.is_unread = true;+ assert_eq!(m.status_of(&t), Status::Done);+ }++ #[test]+ fn a_stale_snapshot_is_ignored_and_orphan_windows_are_listed() {+ let mut m = TreeModel::default();+ let mut s = session(vec![thread("a", Some("thinkterm:p1:a"), vec![])]);+ s.generation = 5;+ assert!(m.apply_session(s.clone()));+ s.generation = 4;+ assert!(!m.apply_session(s.clone()), "older generation from the same server");+ s.server_id = "other".into();+ assert!(m.apply_session(s), "any generation from another server");+ let list = ListPanesResponse {+ tabs: vec![thinkterm_proto::layout::PaneNode::Leaf(thinkterm_proto::layout::PaneEntry {+ window_id: 3,+ tab_id: 30,+ pane_id: 300,+ title: "zsh".into(),+ size: Default::default(),+ working_dir: None,+ is_active_pane: true,+ is_zoomed_pane: false,+ alt_screen: false,+ workspace: "default".into(),+ cursor_pos: Default::default(),+ physical_top: 0,+ top_row: 0,+ left_col: 0,+ tty_name: None,+ })],+ tab_titles: vec![],+ window_titles: Default::default(),+ };+ m.apply_panes(&list);+ let rows = m.rows(30, "default", 3);+ assert!(matches!(rows.last(), Some(Row::Window { window_id: 3, selected: true, title }) if title == "Terminal"));+ assert!(rows.iter().any(|r| matches!(r, Row::Others)));+ }+}diff --git a/thinkterm-web/src/viewport.rs b/thinkterm-web/src/viewport.rsindex 695bc727..10941dde 100644--- a/thinkterm-web/src/viewport.rs+++ b/thinkterm-web/src/viewport.rs@@ -4,6 +4,44 @@ use std::ops::Range;use thinkterm_proto::RenderableDimensions;use wezterm_term::StableRowIndex;+/// The font size (points) this page should use, chosen from the sizes a+/// quarter point apart between 6 and 72 by measuring each one's cell+/// (`cell`, width and height in device px): the one whose cell is nearest+/// the desktop's (`desktop_cell_h`, device px) so the desktop's pixel+/// geometry maps onto the page one to one -- or the current size when no+/// desktop size is known -- then stepped down until the whole tab+/// (`grid`, with the desktop's padding of a cell each side and half a+/// cell above and below) fits `avail`. A mirror that clips is no mirror.+/// Decided from measurements, not by nudging the current size, so it+/// cannot flap. `None` when the current size is the answer.+pub fn choose_size_pt(+ cell: impl Fn(f64) -> Option<(f64, f64)>,+ current: f64,+ desktop_cell_h: Option<f64>,+ grid: Option<(usize, usize)>,+ avail: (f64, f64),+) -> Option<f64> {+ let steps = || (24..=288).map(|q| q as f64 / 4.0);+ let mut pt = match desktop_cell_h {+ Some(want) if want > 0.0 => steps()+ .filter_map(|pt| cell(pt).map(|(_, h)| (pt, (h - want).abs())))+ .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))+ .map(|(pt, _)| pt)+ .unwrap_or(current),+ _ => (current * 4.0).round() / 4.0,+ };+ if let Some((cols, rows)) = grid.filter(|(c, r)| *c > 0 && *r > 0) {+ let fits = |pt: f64| {+ cell(pt).is_none_or(|(w, h)| (cols + 2) as f64 * w <= avail.0 && (rows + 1) as f64 * h <= avail.1)+ };+ while pt > 6.0 && !fits(pt) {+ pt -= 0.25;+ }+ }+ let pt = pt.clamp(6.0, 72.0);+ ((pt - current).abs() >= 0.125).then_some(pt)+}+/// Rows the page shows: the last `rows` of the screen, moved up into the/// scrollback by `scroll_from_bottom` lines.pub fn visible_rows(@@ -65,3 +103,39 @@ mod tests {assert_eq!(visible_rows(&dims(100, 0, 24), 10, 0), 114..124);}}++#[cfg(test)]+mod font_tests {+ use super::*;++ // A font whose cell grows with the size: 0.6 x 1.2 px per point.+ fn cell(pt: f64) -> Option<(f64, f64)> {+ Some(((pt * 0.6).round(), (pt * 1.2).round()))+ }++ #[test]+ fn the_page_takes_the_desktop_s_cell_size_when_it_fits() {+ // The desktop's cell is 34 px tall: 28 pt is the first size whose cell rounds to 34.+ assert_eq!(choose_size_pt(cell, 12.0, Some(34.0), Some((80, 24)), (4000.0, 4000.0)), Some(28.0));+ assert_eq!(choose_size_pt(cell, 28.0, Some(34.0), Some((80, 24)), (4000.0, 4000.0)), None, "already there");+ }++ #[test]+ fn the_tab_must_fit_the_window_with_its_padding() {+ // 82 cells wide at 17 px would need 1394 px; the window has 1000.+ let pt = choose_size_pt(cell, 12.0, Some(34.0), Some((80, 24)), (1000.0, 4000.0)).unwrap();+ assert!(pt < 28.0);+ let (w, _) = cell(pt).unwrap();+ assert!(82.0 * w <= 1000.0, "{pt} pt: {}", 82.0 * w);+ let (w2, _) = cell(pt + 0.25).unwrap();+ assert!(82.0 * w2 > 1000.0, "the next size up would not fit");+ assert_eq!(choose_size_pt(cell, 6.0, Some(34.0), Some((800, 24)), (100.0, 100.0)), None, "never below 6");+ }++ #[test]+ fn without_a_desktop_size_the_current_one_stays_unless_it_does_not_fit() {+ assert_eq!(choose_size_pt(cell, 12.0, None, Some((80, 24)), (4000.0, 4000.0)), None);+ assert_eq!(choose_size_pt(cell, 12.0, Some(0.0), None, (10.0, 10.0)), None, "no grid to fit");+ assert!(choose_size_pt(cell, 12.0, None, Some((80, 24)), (300.0, 4000.0)).unwrap() < 12.0);+ }+}