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: a tab strip, and following the desktop's focus
RoversX63d27fececfd
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.mdindex b4b93884..76f8f8e5 100644--- a/docs/thinkterm/web-access.md+++ b/docs/thinkterm/web-access.md@@ -99,9 +99,12 @@ on a laptop; `ci/macos-package.sh --build` builds it.## What the first version does not do-Images (kitty, sixel, iTerm2) are not drawn; tabs, splits and the ThinkTerm-tree are not shown -- the page mirrors one pane, chosen when it connects,-and does not follow the desktop to another; the cursor does not blink. The input+Images (kitty, sixel, iTerm2) are not drawn. The page shows one pane at a+time: a strip along the top lists the server's tabs, and the panes of the+tab on show, and a click moves the page there. It follows the desktop's+focus by default; choosing a pane pins the page to it, and the switch at the+right of the strip turns following back on. Splits are not drawn side by+side, and the ThinkTerm tree is not shown; the cursor does not blink. The inputmethod's hidden field follows the terminal cursor, including scrolling andresizing, so the browser can place its candidate window there; pre-edittext and its underline are not yet drawn in the grid.diff --git a/thinkterm-web/smoke/tabs-test.js b/thinkterm-web/smoke/tabs-test.jsnew file mode 100644index 00000000..00e0209c--- /dev/null+++ b/thinkterm-web/smoke/tabs-test.js@@ -0,0 +1,64 @@+// End-to-end check of the tab strip, driven through tabs.sh (not part of+// the served bundle): with two tabs on the server the page lists both, a+// click switches panes and typing lands in the new one, and with following+// turned back on a focus change on the server side moves the page back.+//+// node tabs-test.js <url> <cli prefix> <out.png>+//+// `cli prefix` is a `thinkterm cli` pinned to the same server. Needs the+// `ws` npm package on NODE_PATH and Google Chrome installed.+const { spawn, execSync } = require("child_process");+const http = require("http"); const fs = require("fs"); const os = require("os");+const WebSocket = require("ws");+const [url, cli, outPng] = process.argv.slice(2);+const chromePath = process.env.CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";+const port = 9333 + Math.floor(Math.random() * 500);+setTimeout(() => { console.error("watchdog"); try { chrome.kill(); } catch {} process.exit(4); }, 90000).unref();+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-strip-`);+const chrome = spawn(chromePath, ["--headless=new", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=1240,720", "--hide-scrollbars", "--enable-unsafe-webgpu", "about:blank"], { stdio: "ignore" });+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function browserWs() { for (let i = 0; i < 50; i++) { try { return await new Promise((res, rej) => http.get(`http://127.0.0.1:${port}/json/version`, (r) => { let b = ""; r.on("data", (d) => b += d); r.on("end", () => res(JSON.parse(b).webSocketDebuggerUrl)); }).on("error", rej)); } catch { await sleep(200); } } throw new Error("chrome did not come up"); }+const sh = (cmd) => execSync(cmd, { encoding: "utf8" });+(async () => {+ const ws = new WebSocket(await browserWs()); await new Promise((r) => ws.on("open", r));+ let id = 0; const waiting = new Map(); const logs = [];+ ws.on("message", (m) => { const msg = JSON.parse(m); if (msg.id && waiting.has(msg.id)) { waiting.get(msg.id)(msg.result || msg.error); waiting.delete(msg.id); }+ if (msg.method === "Runtime.consoleAPICalled") logs.push(msg.params.args.map((a) => a.value ?? a.description).join(" "));+ if (msg.method === "Runtime.exceptionThrown") logs.push("EXCEPTION " + JSON.stringify(msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text)); });+ const send = (method, params = {}, sessionId) => new Promise((r) => { const i = ++id; waiting.set(i, r); ws.send(JSON.stringify({ id: i, method, params, sessionId })); });+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });+ const s = (await send("Target.attachToTarget", { targetId, flatten: true })).sessionId;+ await send("Runtime.enable", {}, s); await send("Page.enable", {}, s);+ const ev = async (expr) => (await send("Runtime.evaluate", { expression: expr, returnByValue: true }, s)).result?.value;+ const status = () => ev("document.getElementById('status')?.textContent || ''");+ const until = async (what, expr, ms = 10000) => { const t = Date.now(); while (Date.now() - t < ms) { const v = await ev(expr); if (v) return v; await sleep(100); } throw new Error("timeout waiting for " + what + ": " + JSON.stringify({ status: await status(), strip: await ev("document.getElementById('tabs').innerText") })); };+ const out = {};+ await send("Page.navigate", { url }, s);+ await until("attach", "/this browser has|following/.test(document.getElementById('status').textContent)", 20000);+ out.strip_at_start = await until("two tabs", "document.querySelectorAll('#tabs .tab').length === 2 && document.getElementById('tabs').innerText");+ out.current_at_start = await ev("document.querySelector('#tabs .tab.current').dataset.pane");+ // Click the other tab.+ await ev("document.querySelector('#tabs .tab:not(.current)').click()");+ await until("switch", `document.querySelector('#tabs .tab.current').dataset.pane !== ${JSON.stringify(out.current_at_start)}`);+ await sleep(400);+ out.current_after_click = await ev("document.querySelector('#tabs .tab.current').dataset.pane");+ out.follow_after_click = await ev("document.querySelector('#tabs .follow').textContent");+ out.status_after_click = await status();+ // Type into it through the real key path.+ await ev(`(() => { const kbd = document.getElementById('kbd'); kbd.focus(); const fire = (key, code) => kbd.dispatchEvent(new KeyboardEvent('keydown', { key, code, bubbles: true, cancelable: true })); for (const ch of 'echo TAB2-OK') fire(ch, ch === ' ' ? 'Space' : 'Key' + ch.toUpperCase()); fire('Enter', 'Enter'); return 1; })()`);+ await sleep(1500);+ out.pane1_text = sh(`${cli} get-text --pane-id 1`).split("\n").filter((l) => /TAB2-OK/.test(l));+ out.pane0_text = sh(`${cli} get-text --pane-id 0`).split("\n").filter((l) => /TAB2-OK/.test(l));+ // Follow the desktop again, then focus pane 0 from the server side.+ await ev("document.querySelector('#tabs .follow').click()");+ out.follow_after_toggle = await ev("document.querySelector('#tabs .follow').textContent");+ sh(`${cli} activate-pane --pane-id 0`);+ await until("follow back", `document.querySelector('#tabs .tab.current').dataset.pane === ${JSON.stringify(out.current_at_start)}`);+ await sleep(400);+ out.current_after_focus = await ev("document.querySelector('#tabs .tab.current').dataset.pane");+ out.status_after_focus = await status();+ const shot = await send("Page.captureScreenshot", { format: "png" }, s); fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));+ out.logs = logs.filter((l) => !/^\s*$/.test(l)).slice(-8);+ console.log(JSON.stringify(out, null, 1));+ ws.close(); chrome.kill(); process.exit(0);+})().catch((e) => { console.error(e); chrome.kill(); process.exit(1); });diff --git a/thinkterm-web/smoke/tabs.sh b/thinkterm-web/smoke/tabs.shnew file mode 100755index 00000000..a9a5781b--- /dev/null+++ b/thinkterm-web/smoke/tabs.sh@@ -0,0 +1,34 @@+#!/bin/sh+# The tab strip, end to end: a release server with two tabs under a+# throwaway HOME, the release bundle, headless Chrome.+#+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/tabs.sh [out.png]+#+# Prints the JSON tabs-test.js produces; exit status is the test's.+set -eu+cd "$(dirname "$0")/../.."+REPO=$PWD+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release+PORT=18089+OUT=${1:-/tmp/thinkterm-tabs.png}+if lsof -nP -t -i :$PORT >/dev/null 2>&1; then echo "port $PORT busy" >&2; exit 1; fi+REAL_HOME=$HOME+T=$(mktemp -d "${TMPDIR:-/tmp}/tt-tabs.XXXXXX")+cat > "$T/web.lua" <<LUA+return { web_servers = { { bind_address = "127.0.0.1:$PORT" } } }+LUA+export HOME="$T/home"; mkdir -p "$HOME"+export THINKTERM_NO_PRIVACY_DISCLAIM=1+export THINKTERM_WEB_STATIC_DIR="$REPO/thinkterm-web/www"+"$BIN/thinkterm-mux-server" --config-file "$T/web.lua" --daemonize+i=0; until curl -s -o /dev/null "http://127.0.0.1:$PORT/"; do i=$((i+1)); [ $i -lt 50 ] || { echo "server did not come up" >&2; exit 1; }; sleep 0.2; done+# Pinned to this server: without --prefer-mux and this HOME the CLI would+# reach a running GUI instead.+CLI="env HOME=$HOME THINKTERM_NO_PRIVACY_DISCLAIM=1 $BIN/thinkterm --config-file $T/web.lua cli --prefer-mux --no-auto-start"+$CLI spawn --window-id 0 >/dev/null+URL=$($CLI web-token mint --label tabs --ttl 1h --url-only 2>/dev/null | head -1)+status=0+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/tabs-test.js" "$URL" "$CLI" "$OUT" || status=$?+for p in $(pgrep -f "$T/web.lua" || true); do kill "$p"; done+rm -rf "$T"+exit $statusdiff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 44f07af9..67aeebee 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -86,6 +86,7 @@ pub struct Setup {pub cols: usize,pub rows: usize,pub title: String,+ pub strip: Option<crate::chrome::TabStrip>,}pub struct Inner {@@ -135,6 +136,18 @@ pub struct Inner {title: String,/// What to do about an atlas that has run out of room for good.capacity: Capacity,+ /// The server's tabs and panes as last listed, for the strip and for+ /// switching. Refreshed on the pushes that change it and on a timer.+ layout: Option<codec::ListPanesResponse>,+ /// Whether the page moves to whatever pane the desktop focuses. On by+ /// default: a page opened to "see my terminal" wants the one being+ /// used. Choosing a pane here turns it off.+ following: bool,+ strip: Option<crate::chrome::TabStrip>,+ layout_refresh_pending: bool,+ /// A switch is under way; a second request waits for the next push+ /// or click rather than racing it.+ switching: bool,}pub struct App {@@ -185,6 +198,34 @@ pub(crate) fn monotonic_ms() -> f64 {.unwrap_or_else(now_ms)}+/// A session for one pane, configured the way this page runs them.+pub fn build_session(+ host: &Arc<WebHost>,+ pane_id: PaneId,+ tab_id: TabId,+ dims: thinkterm_proto::RenderableDimensions,+ title: &str,+ alt_screen: bool,+) -> Arc<PaneSession<WebHost>> {+ PaneSession::new(+ Arc::clone(host),+ Arc::new(thinkterm_session::Lock::new(+ thinkterm_session::images::ImageStore::default(),+ )),+ thinkterm_session::SessionConfig {+ scrollback_lines: 3500,+ local_echo_threshold_ms: Some(100),+ overlay_lag_indicator: false,+ },+ pane_id,+ Arc::new(std::sync::atomic::AtomicUsize::new(tab_id)),+ 0,+ dims,+ title,+ alt_screen,+ )+}+impl App {pub fn new(setup: Setup) -> Rc<Self> {let inner = Inner {@@ -223,6 +264,11 @@ impl App {quads: HeapQuadAllocator::default(),vertices: Vec::new(),title: setup.title,+ layout: None,+ following: true,+ strip: setup.strip,+ layout_refresh_pending: false,+ switching: false,};let app = Rc::new(Self {inner: RefCell::new(inner),@@ -310,7 +356,7 @@ impl App {}/// The server pushed something for us.- pub fn on_push(&self, pdu: Pdu) {+ pub fn on_push(self: &Rc<Self>, pdu: Pdu) {let inner = self.inner.borrow();match pdu {Pdu::GetPaneRenderChangesResponse(delta) if delta.pane_id == inner.pane_id => {@@ -319,6 +365,27 @@ impl App {Pdu::PaneRemoved(removed) if removed.pane_id == inner.pane_id => {inner.session.set_dead(true);Self::set_status(&inner, "the pane was closed on the server");+ // Something else to show, if the server has anything.+ drop(inner);+ self.refresh_layout();+ }+ // The desktop moved. Followed only while following; a page+ // that chose a pane is not dragged off it.+ Pdu::PaneFocused(focused) if inner.following && focused.pane_id != inner.pane_id => {+ drop(inner);+ self.switch_to_pane(focused.pane_id, false);+ }+ // The strip is stale: a tab came or went, a pane closed+ // elsewhere, a title changed. Listed again, a moment later,+ // so a burst of these is one request.+ Pdu::PaneRemoved(_)+ | Pdu::TabAddedToWindow(_)+ | Pdu::TabTitleChanged(_)+ | Pdu::WindowTitleChanged(_)+ | Pdu::TabResized(_)+ | Pdu::WindowWorkspaceChanged(_) => {+ drop(inner);+ self.refresh_layout_soon();}// Sent once per connection, before the first line change: a// program's OSC 4/10/11 colours. Dropping it would leave the@@ -851,6 +918,271 @@ impl App {self.request_frame();}+ pub fn strip_element(&self) -> Option<web_sys::EventTarget> {+ let inner = self.inner.borrow();+ let strip = inner.strip.as_ref()?;+ let target: &web_sys::EventTarget = strip.element().as_ref();+ Some(target.clone())+ }++ /// Draw the tab strip from what the page knows.+ fn render_strip(inner: &Inner) {+ let (Some(strip), Some(layout)) = (&inner.strip, &inner.layout) else {+ return;+ };+ let tabs = crate::chrome::model(layout, inner.pane_id, &inner.title);+ strip.render(&tabs, inner.following);+ }++ /// List the server's panes again and redraw the strip. If the pane on+ /// show is gone, move to the first tab's pane: a dead pane is not+ /// something to look at.+ pub fn refresh_layout(self: &Rc<Self>) {+ {+ let mut inner = self.inner.borrow_mut();+ if inner.layout_refresh_pending || inner.disconnected.is_some() {+ return;+ }+ inner.layout_refresh_pending = true;+ }+ let app = Rc::clone(self);+ wasm_bindgen_futures::spawn_local(async move {+ let link = app.inner.borrow().link.clone();+ let listed = thinkterm_session::host::request(+ &link,+ Pdu::ListPanes(codec::ListPanes {}),+ |pdu| match pdu {+ Pdu::ListPanesResponse(p) => Ok(p),+ other => Err(other),+ },+ )+ .await;+ let replacement = {+ let mut inner = app.inner.borrow_mut();+ inner.layout_refresh_pending = false;+ match listed {+ Ok(layout) => {+ let gone = crate::chrome::entry(&layout, inner.pane_id).is_none();+ let replacement = if gone {+ crate::chrome::first_choice(&layout)+ } else {+ None+ };+ inner.layout = Some(layout);+ Self::render_strip(&inner);+ replacement+ }+ Err(err) => {+ log::warn!("listing panes: {err:#}");+ None+ }+ }+ };+ if let Some(entry) = replacement {+ app.switch_to(entry).await;+ }+ });+ }++ /// `refresh_layout`, a moment from now, so a burst of pushes is one+ /// listing.+ fn refresh_layout_soon(self: &Rc<Self>) {+ let app = Rc::clone(self);+ let closure = Closure::once_into_js(move || app.refresh_layout());+ if let Some(window) = web_sys::window() {+ let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(+ closure.as_ref().unchecked_ref(),+ 150,+ );+ }+ }++ /// Ask the server again every so often, whatever the pushes said:+ /// pane titles elsewhere change without one.+ pub fn poll_layout(self: &Rc<Self>, every_ms: i32) {+ let weak = Rc::downgrade(self);+ let closure = Closure::<dyn FnMut()>::new(move || {+ if let Some(app) = weak.upgrade() {+ app.refresh_layout();+ }+ });+ if let Some(window) = web_sys::window() {+ if window+ .set_interval_with_callback_and_timeout_and_arguments_0(+ closure.as_ref().unchecked_ref(),+ every_ms,+ )+ .is_ok()+ {+ // One per page, for the life of the page.+ closure.forget();+ }+ }+ }++ /// A click on the strip.+ pub fn on_chrome_click(self: &Rc<Self>, click: crate::chrome::Click) {+ match click {+ crate::chrome::Click::Pane(pane_id) => self.switch_to_pane(pane_id, true),+ crate::chrome::Click::Follow => {+ let mut inner = self.inner.borrow_mut();+ inner.following = !inner.following;+ Self::render_strip(&inner);+ let _ = inner.textarea.focus();+ }+ }+ }++ /// Show `pane_id`. `chosen` is a person's click, which also stops the+ /// page following the desktop; a focus push is not.+ pub fn switch_to_pane(self: &Rc<Self>, pane_id: PaneId, chosen: bool) {+ if chosen {+ self.inner.borrow_mut().following = false;+ }+ let known = self+ .inner+ .borrow()+ .layout+ .as_ref()+ .and_then(|layout| crate::chrome::entry(layout, pane_id));+ let app = Rc::clone(self);+ wasm_bindgen_futures::spawn_local(async move {+ // Listed again either way: the entry carries the pane's size+ // and screen state, and the listing may be seconds old.+ let link = app.inner.borrow().link.clone();+ let fresh = thinkterm_session::host::request(+ &link,+ Pdu::ListPanes(codec::ListPanes {}),+ |pdu| match pdu {+ Pdu::ListPanesResponse(p) => Ok(p),+ other => Err(other),+ },+ )+ .await+ .ok();+ let entry = match fresh {+ Some(layout) => {+ let entry = crate::chrome::entry(&layout, pane_id);+ let mut inner = app.inner.borrow_mut();+ inner.layout = Some(layout);+ Self::render_strip(&inner);+ entry+ }+ None => known,+ };+ match entry {+ Some(entry) => app.switch_to(entry).await,+ None => {+ log::warn!("pane {pane_id} is not on the server");+ Self::render_strip(&app.inner.borrow());+ }+ }+ });+ }++ /// Put another pane on the canvas: report this page's grid against+ /// its tab, subscribe to it, and start a session for it in place of+ /// the old one. Everything that hangs off the session -- input, the+ /// watchdog, the delta queue -- follows, because it all goes through+ /// `inner.session`.+ async fn switch_to(self: &Rc<Self>, entry: thinkterm_proto::layout::PaneEntry) {+ let (link, size) = {+ let mut inner = self.inner.borrow_mut();+ if entry.pane_id == inner.pane_id || inner.switching || inner.disconnected.is_some() {+ return;+ }+ inner.switching = true;+ let size = inner.link.lease().reported;+ (inner.link.clone(), size)+ };+ let outcome: Result<()> = async {+ // The lease is per tab: a follower's report, never a claim.+ // Typing or clicking claims, as at attach.+ if let Some(size) = size {+ let state = thinkterm_session::host::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?;+ let mut lease = link.lease_mut();+ lease.tab_id = Some(entry.tab_id);+ lease.apply_viewport(&state);+ } else {+ link.lease_mut().tab_id = Some(entry.tab_id);+ }+ thinkterm_session::host::request(+ &link,+ Pdu::GetPaneRenderChanges(codec::GetPaneRenderChanges {+ pane_id: entry.pane_id,+ }),+ |pdu| match pdu {+ Pdu::LivenessResponse(_) | Pdu::UnitResponse(_) => Ok(()),+ other => Err(other),+ },+ )+ .await?;+ Ok(())+ }+ .await;+ {+ let mut inner = self.inner.borrow_mut();+ inner.switching = false;+ if let Err(err) = outcome {+ log::warn!("switching to pane {}: {err:#}", entry.pane_id);+ Self::set_status(&inner, &format!("could not switch panes: {err:#}"));+ return;+ }+ let rows = entry.size.rows;+ let dims = thinkterm_proto::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,+ };+ inner.session = build_session(+ &inner.host,+ entry.pane_id,+ entry.tab_id,+ dims,+ &entry.title,+ entry.alt_screen,+ );+ inner.pane_id = entry.pane_id;+ inner.tab_id = entry.tab_id;+ inner.title = entry.title.clone();+ inner.scroll_from_bottom = 0;+ inner.selection = None;+ inner.selecting = false;+ inner.ime_anchor = None;+ // The palette is a pane's; the new one says its own, if it has+ // one, right after the subscription.+ inner.palette = ColorPalette::default();+ // Forces `resize` to see a change: the new pane is reflowed to+ // this grid if the page owns its tab, or reported against it.+ inner.cols = 0;+ if let Some(doc) = web_sys::window().and_then(|w| w.document()) {+ doc.set_title(&format!("{} — ThinkTerm", inner.title));+ }+ Self::render_strip(&inner);+ let _ = inner.textarea.focus();+ }+ self.resize();+ self.refresh_status();+ self.request_frame();+ }+/// See `GlyphCache::warm`. Called once, after the first frame.pub fn warm_glyph_canvas(&self) {self.inner.borrow_mut().glyphs.warm();@@ -986,6 +1318,7 @@ impl App {let title = inner.session.title();if title != inner.title {inner.title = title;+ Self::render_strip(&inner);if let Some(doc) = web_sys::window().and_then(|w| w.document()) {doc.set_title(&format!("{} — ThinkTerm", inner.title));}diff --git a/thinkterm-web/src/attach.rs b/thinkterm-web/src/attach.rsindex c59f3900..4bb86fb3 100644--- a/thinkterm-web/src/attach.rs+++ b/thinkterm-web/src/attach.rs@@ -5,7 +5,8 @@use crate::link::WsLink;use anyhow::{anyhow, bail, Result};use codec::Pdu;-use thinkterm_proto::layout::{PaneEntry, PaneNode};+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;@@ -19,22 +20,6 @@ pub struct Attached {pub server_version: String,}-fn active_pane(node: &PaneNode) -> Option<PaneEntry> {- match node {- PaneNode::Empty => None,- PaneNode::Leaf(e) => Some(e.clone()),- PaneNode::Stack(s) => s.panes.get(s.active).or(s.panes.first()).cloned(),- PaneNode::Split { left, right, .. } => {- let (l, r) = (active_pane(left), active_pane(right));- match (&l, &r) {- (Some(a), _) if a.is_active_pane => l,- (_, Some(b)) if b.is_active_pane => r,- _ => l.or(r),- }- }- }-}-/// `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.diff --git a/thinkterm-web/src/chrome.rs b/thinkterm-web/src/chrome.rsnew file mode 100644index 00000000..973f6400--- /dev/null+++ b/thinkterm-web/src/chrome.rs@@ -0,0 +1,337 @@+//! The chrome around the canvas: a strip of the server's tabs, the panes of+//! the tab on show, and a switch between following the desktop's focus and+//! staying on one pane.+//!+//! It is HTML. The canvas draws the terminal and nothing else; buttons, text+//! and layout are the browser's job, which it does with accessibility,+//! wrapping and zoom for free. The model below is pure so it can be tested+//! natively; only `dom` touches the page.++use codec::ListPanesResponse;+use thinkterm_proto::layout::{PaneEntry, PaneNode};+use thinkterm_proto::{PaneId, TabId};++/// One tab in the strip.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TabView {+ pub tab_id: TabId,+ pub title: String,+ /// The pane a click on the tab shows: the one on show if it is in+ /// this tab, else the tab's active pane.+ pub target: PaneId,+ pub current: bool,+ /// The tab's panes, listed only for the tab on show and only when+ /// there is more than one.+ pub panes: Vec<PaneView>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PaneView {+ pub pane_id: PaneId,+ pub title: String,+ pub current: bool,+}++/// Every pane in a tab, left to right, top to bottom.+pub fn leaves(node: &PaneNode) -> Vec<&PaneEntry> {+ match node {+ PaneNode::Empty => vec![],+ PaneNode::Leaf(entry) => vec![entry],+ PaneNode::Stack(stack) => stack.panes.iter().collect(),+ PaneNode::Split { left, right, .. } => {+ let mut all = leaves(left);+ all.extend(leaves(right));+ all+ }+ }+}++/// The pane a tab is showing: its active one, or the first.+pub fn active_pane(node: &PaneNode) -> Option<PaneEntry> {+ match node {+ PaneNode::Empty => None,+ PaneNode::Leaf(e) => Some(e.clone()),+ PaneNode::Stack(s) => s.panes.get(s.active).or(s.panes.first()).cloned(),+ PaneNode::Split { left, right, .. } => {+ let (l, r) = (active_pane(left), active_pane(right));+ match (&l, &r) {+ (Some(a), _) if a.is_active_pane => l,+ (_, Some(b)) if b.is_active_pane => r,+ _ => l.or(r),+ }+ }+ }+}++/// The entry for a pane, wherever it is.+pub fn entry(layout: &ListPanesResponse, pane_id: PaneId) -> Option<PaneEntry> {+ layout+ .tabs+ .iter()+ .flat_map(leaves)+ .find(|e| e.pane_id == pane_id)+ .cloned()+}++/// What a page shows when it has nothing better: the first tab's pane.+pub fn first_choice(layout: &ListPanesResponse) -> Option<PaneEntry> {+ layout.tabs.iter().find_map(active_pane)+}++/// The strip for a layout, given the pane on show. `current_title` is+/// that pane's title as the page knows it, which is fresher than the+/// listing's copy.+pub fn model(layout: &ListPanesResponse, current: PaneId, current_title: &str) -> Vec<TabView> {+ let mut tabs = Vec::new();+ for (i, node) in layout.tabs.iter().enumerate() {+ let panes = leaves(node);+ let Some(first) = panes.first() else {+ continue;+ };+ let is_current = panes.iter().any(|e| e.pane_id == current);+ let target = if is_current {+ current+ } else {+ active_pane(node).map(|e| e.pane_id).unwrap_or(first.pane_id)+ };+ let title_of = |e: &PaneEntry| {+ if e.pane_id == current {+ current_title.to_string()+ } else {+ e.title.clone()+ }+ };+ let title = layout+ .tab_titles+ .get(i)+ .filter(|t| !t.is_empty())+ .cloned()+ .or_else(|| panes.iter().find(|e| e.pane_id == target).map(|e| title_of(e)))+ .unwrap_or_default();+ let pane_views = if is_current && panes.len() > 1 {+ panes+ .iter()+ .map(|e| PaneView {+ pane_id: e.pane_id,+ title: title_of(e),+ current: e.pane_id == current,+ })+ .collect()+ } else {+ vec![]+ };+ tabs.push(TabView {+ tab_id: first.tab_id,+ title,+ target,+ current: is_current,+ panes: pane_views,+ });+ }+ tabs+}++#[cfg(target_arch = "wasm32")]+mod dom {+ use super::TabView;+ use thinkterm_proto::PaneId;+ use wasm_bindgen::JsCast;++ /// The strip's element and what it draws into it.+ pub struct TabStrip {+ root: web_sys::Element,+ }++ /// What a click on the strip meant.+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]+ pub enum Click {+ Pane(PaneId),+ Follow,+ }++ 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+ }++ /// Titles are shown short; the full one is the tooltip.+ fn short(title: &str) -> String {+ const MAX: usize = 28;+ if title.chars().count() <= MAX {+ title.to_string()+ } else {+ let head: String = title.chars().take(MAX - 1).collect();+ format!("{head}…")+ }+ }++ impl TabStrip {+ 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+ }++ /// Redraw the whole strip. It is a few dozen elements; rebuilding+ /// them is cheaper to get right than diffing them.+ pub fn render(&self, tabs: &[TabView], following: bool) {+ let mut html = String::new();+ for tab in tabs {+ let class = if tab.current { "tab current" } else { "tab" };+ html.push_str(&format!(+ "<span class=\"{class}\" data-pane=\"{}\" title=\"{}\">{}",+ tab.target,+ escape(&tab.title),+ escape(&short(&tab.title))+ ));+ if !tab.panes.is_empty() {+ html.push_str("<span class=\"panes\">");+ for pane in &tab.panes {+ let class = if pane.current { "pane current" } else { "pane" };+ html.push_str(&format!(+ "<span class=\"{class}\" data-pane=\"{}\" title=\"{}\">{}</span>",+ pane.pane_id,+ escape(&pane.title),+ escape(&short(&pane.title))+ ));+ }+ html.push_str("</span>");+ }+ html.push_str("</span>");+ }+ let (class, text, hint) = if following {+ (+ "follow on",+ "following the desktop",+ "This page shows whichever pane the desktop focuses. Click to stay on this one.",+ )+ } else {+ (+ "follow off",+ "staying here",+ "This page stays on this pane. Click to follow the desktop's focus again.",+ )+ };+ html.push_str(&format!(+ "<span class=\"{class}\" data-follow=\"\" title=\"{hint}\">{text}</span>"+ ));+ self.root.set_inner_html(&html);+ }++ /// What a click landed on, if anything the strip owns.+ pub fn click_target(ev: &web_sys::MouseEvent) -> Option<Click> {+ let target: web_sys::Element = ev.target()?.dyn_into().ok()?;+ let hit = target.closest("[data-pane],[data-follow]").ok()??;+ if hit.has_attribute("data-follow") {+ return Some(Click::Follow);+ }+ hit.get_attribute("data-pane")?.parse().ok().map(Click::Pane)+ }+ }+}++#[cfg(target_arch = "wasm32")]+pub use dom::{Click, TabStrip};++#[cfg(test)]+mod tests {+ use super::*;+ use thinkterm_proto::layout::PaneStackEntry;+ use thinkterm_proto::split::{SplitDirection, SplitDirectionAndSize};+ use wezterm_term::TerminalSize;++ fn pane(tab_id: TabId, pane_id: PaneId, title: &str, active: bool) -> PaneEntry {+ PaneEntry {+ window_id: 0,+ tab_id,+ pane_id,+ title: title.to_string(),+ size: TerminalSize::default(),+ working_dir: None,+ is_active_pane: active,+ is_zoomed_pane: false,+ alt_screen: false,+ workspace: "default".to_string(),+ cursor_pos: Default::default(),+ physical_top: 0,+ top_row: 0,+ left_col: 0,+ tty_name: None,+ }+ }++ fn layout() -> ListPanesResponse {+ ListPanesResponse {+ tabs: vec![+ PaneNode::Leaf(pane(1, 10, "zsh", true)),+ PaneNode::Split {+ left: Box::new(PaneNode::Leaf(pane(2, 20, "vim", false))),+ right: Box::new(PaneNode::Leaf(pane(2, 21, "htop", true))),+ node: SplitDirectionAndSize {+ direction: SplitDirection::Horizontal,+ first: TerminalSize::default(),+ second: TerminalSize::default(),+ },+ },+ PaneNode::Empty,+ ],+ tab_titles: vec!["".to_string(), "work".to_string(), "".to_string()],+ window_titles: Default::default(),+ }+ }++ #[test]+ fn a_tab_is_named_by_its_title_or_its_target_pane() {+ let tabs = model(&layout(), 10, "zsh · ~");+ assert_eq!(tabs.len(), 2, "the empty tab is not listed");+ assert_eq!(tabs[0].title, "zsh · ~", "the page's own title is fresher");+ assert_eq!(tabs[1].title, "work");+ assert!(tabs[0].current && !tabs[1].current);+ assert_eq!(tabs[1].target, 21, "a click on the other tab goes to its active pane");+ }++ #[test]+ fn panes_are_listed_only_for_the_tab_on_show_and_only_when_there_are_several() {+ let tabs = model(&layout(), 20, "vim");+ assert!(tabs[0].panes.is_empty());+ assert_eq!(+ tabs[1].panes,+ vec![+ PaneView { pane_id: 20, title: "vim".into(), current: true },+ PaneView { pane_id: 21, title: "htop".into(), current: false },+ ]+ );+ assert_eq!(tabs[1].target, 20, "the tab on show points at the pane on show");+ let tabs = model(&layout(), 10, "zsh");+ assert!(tabs[0].panes.is_empty(), "one pane is not a choice");+ }++ #[test]+ fn a_pane_is_found_wherever_it_is_and_the_first_tab_is_the_default() {+ assert_eq!(entry(&layout(), 21).map(|e| e.tab_id), Some(2));+ assert!(entry(&layout(), 99).is_none());+ assert_eq!(first_choice(&layout()).map(|e| e.pane_id), Some(10));+ let stack = ListPanesResponse {+ tabs: vec![PaneNode::Stack(PaneStackEntry {+ panes: vec![pane(3, 30, "a", false), pane(3, 31, "b", false)],+ active: 1,+ pane_stack_id: None,+ })],+ tab_titles: vec![],+ window_titles: Default::default(),+ };+ assert_eq!(first_choice(&stack).map(|e| e.pane_id), Some(31));+ }+}diff --git a/thinkterm-web/src/input.rs b/thinkterm-web/src/input.rsindex 990c639d..32531a33 100644--- a/thinkterm-web/src/input.rs+++ b/thinkterm-web/src/input.rs@@ -12,7 +12,7 @@ use web_sys::{KeyboardEvent, PointerEvent, WheelEvent,};-fn listen<E: JsCast + 'static>(+pub(crate) fn listen<E: JsCast + 'static>(target: &web_sys::EventTarget,name: &str,handler: impl FnMut(E) + 'static,diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex 74d55aa0..e98e34f7 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -4,6 +4,7 @@//! build everywhere; everything that touches the page is `wasm32` only.pub mod braille;+pub mod chrome;pub mod fallback;pub mod ime;pub mod keymap;diff --git a/thinkterm-web/src/page.rs b/thinkterm-web/src/page.rsindex 7fd8f2d7..ead9d978 100644--- a/thinkterm-web/src/page.rs+++ b/thinkterm-web/src/page.rs@@ -9,15 +9,12 @@ use crate::host::{LocalSpawner, WebClock, WebConfig, WebEvents, WebHost};use crate::link::WsLink;use anyhow::{anyhow, Context, Result};use std::rc::Rc;-use std::sync::atomic::AtomicUsize;use std::sync::Arc;use thinkterm_font_core::FontShaper;use thinkterm_font_web::{Face, FontSet};use thinkterm_render::bitmaps::BitmapImage;use thinkterm_render::pipeline::GpuTexture;use thinkterm_render::quad::HeapQuadAllocator;-use thinkterm_session::pane::PaneSession;-use thinkterm_session::{Lock, SessionConfig};use wasm_bindgen::prelude::*;use wasm_bindgen::JsCast;@@ -211,17 +208,10 @@ async fn start_attached(link: link.clone(),config: WebConfig::default(),});- let session = PaneSession::new(- Arc::clone(&host),- Arc::new(Lock::new(thinkterm_session::images::ImageStore::default())),- SessionConfig {- scrollback_lines: 3500,- local_echo_threshold_ms: Some(100),- overlay_lag_indicator: false,- },+ let session = crate::app::build_session(+ &host,attached.pane_id,- Arc::new(AtomicUsize::new(attached.tab_id)),- 0,+ attached.tab_id,attached.dims,&attached.title,attached.alt_screen,@@ -245,6 +235,7 @@ async fn start_attached(cols,rows,title: attached.title.clone(),+ strip: crate::chrome::TabStrip::mount("tabs"),});host.events.set_wake(app.wake());{@@ -256,6 +247,19 @@ async fn start_attached(link.set_close_handler(move |reason| app.on_close(reason));}crate::input::install(Rc::clone(&app), canvas, textarea);+ // The strip: one listener on its root, so rebuilding its contents+ // costs nothing to keep wired.+ if let Some(root) = app.strip_element() {+ let app = Rc::clone(&app);+ crate::input::listen::<web_sys::MouseEvent>(&root, "click", move |ev| {+ if let Some(click) = crate::chrome::TabStrip::click_target(&ev) {+ ev.prevent_default();+ app.on_chrome_click(click);+ }+ });+ }+ app.refresh_layout();+ app.poll_layout(5_000);let _ = textarea.focus();app.resize();app.request_frame();diff --git a/thinkterm-web/www/index.html b/thinkterm-web/www/index.htmlindex 32a45b6e..6cad8fe5 100644--- a/thinkterm-web/www/index.html+++ b/thinkterm-web/www/index.html@@ -6,7 +6,18 @@<title>ThinkTerm</title><style>html, body { margin: 0; height: 100%; background: #000; color: #ccc; font: 12px system-ui, sans-serif; overflow: hidden; }- #term { position: absolute; inset: 0 0 22px 0; width: 100%; height: calc(100% - 22px); display: block; outline: none; }+ #tabs { position: absolute; left: 0; right: 0; top: 0; height: 28px; display: flex; align-items: center; gap: 4px; padding: 0 6px; background: #111; overflow-x: auto; overflow-y: hidden; white-space: nowrap; user-select: none; scrollbar-width: none; }+ #tabs .tab { display: inline-flex; align-items: center; gap: 6px; padding: 0 10px; height: 20px; line-height: 20px; border-radius: 10px; color: #9a9a9a; cursor: pointer; }+ #tabs .tab:hover { background: #1c1c1c; color: #ddd; }+ #tabs .tab.current { background: #2a2a2a; color: #eee; }+ #tabs .panes { display: inline-flex; gap: 3px; margin-left: 2px; }+ #tabs .pane { padding: 0 7px; height: 16px; line-height: 16px; border-radius: 8px; background: #1a1a1a; color: #9a9a9a; font-size: 11px; cursor: pointer; }+ #tabs .pane:hover { color: #ddd; }+ #tabs .pane.current { background: #3a3a3a; color: #fff; }+ #tabs .follow { margin-left: auto; padding: 0 10px; height: 20px; line-height: 20px; border-radius: 10px; color: #777; cursor: pointer; font-size: 11px; }+ #tabs .follow.on { color: #6cb6ff; }+ #tabs .follow:hover { background: #1c1c1c; }+ #term { position: absolute; inset: 28px 0 22px 0; width: 100%; height: calc(100% - 50px); display: block; outline: none; }#status { position: absolute; left: 0; right: 0; bottom: 0; height: 22px; line-height: 22px; padding: 0 8px; background: #111; color: #9a9a9a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }#status.error { color: #f66; }/* Focus lives here so the IME composes into a real text field; the@@ -15,6 +26,7 @@</style></head><body>+<div id="tabs"></div><canvas id="term"></canvas><textarea id="kbd" wrap="off" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"></textarea><div id="status">loading…</div>