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: the layout on the canvas, and a test that walks the mirror
RoversXed58df3582e9
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.mdindex 76f8f8e5..e2daaa4c 100644--- a/docs/thinkterm/web-access.md+++ b/docs/thinkterm/web-access.md@@ -99,19 +99,27 @@ on a laptop; `ci/macos-package.sh --build` builds it.## What the first version does not do-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 input+Images (kitty, sixel, iTerm2) are not drawn. The page shows the tab the+desktop shows, every pane of it in the desktop's split layout, and follows+the desktop's focus by default: a strip along the top lists the server's+tabs and, for the tab on show, its panes; clicking one focuses it here and+on the desktop, and the switch at the right of the strip pins the page to+what it is showing instead. The tab keeps the desktop's size -- the page+letterboxes it, and clips when the desktop's grid is larger, saying so on+the status line -- even while the page types; the fit button (or+Ctrl+Shift+F) reshapes the tab to this window until the desktop next takes+it. The strip's other buttons open a new tab beside this one, split the+focused pane to the right or below, zoom it, and close it (asking twice);+Ctrl+Shift with an arrow moves the focus between panes. In Handoff mode a+page that does not hold the terminal can look but not type, and offers to+take over. 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.A dropped socket is reopened by the page itself, with a backoff, on the same-pane; the status line says so while it is down. It gives up only when there-is nothing to come back to -- the pane was closed, or the server speaks a+tab; the status line says so while it is down. It gives up only when there+is nothing to come back to -- the server has no panes, or speaks adifferent protocol version -- and says which.## Fontsdiff --git a/docs/thinkterm/web-baseline.md b/docs/thinkterm/web-baseline.mdindex a2080b95..a2fc0153 100644--- a/docs/thinkterm/web-baseline.md+++ b/docs/thinkterm/web-baseline.md@@ -1,6 +1,7 @@# Browser client: performance baseline-Measured 2026-09-09 on `web-client` after 6473846, on an Apple-silicon Mac,+Measured 2026-09-09 on `web-client` (one-pane numbers after 6473846, the+four-pane run after the mirror landed), on an Apple-silicon Mac,headless Chrome (`--headless=new --enable-unsafe-webgpu`), release server,release bundle through `ci/build-web.sh` with `wasm-opt -Oz` (binaryen 132).Three runs of `thinkterm-web/smoke/bench.sh`; the spread between runs is@@ -65,6 +66,13 @@ starting between the echoed command and its first line, not a paint.intermediate state, so a burst that finishes between two fetches is onerepaint; this is not a stress test.+## Four panes, a screen of fresh CJK in each++Three splits, then the CJK screen sent to all four at once: 4 frames, gaps+17 ms, no long task, RSS +10 MB over the one-pane run. Four panes' quads+go through the same allocator and draw call as one pane's; the fallback+budget is shared, so the last pane's glyphs may arrive a frame later.+## After all of itRenderer RSS 273-285 MB (+25-35 MB over idle: atlas, scrollback, caches);diff --git a/thinkterm-web/smoke/bench.js b/thinkterm-web/smoke/bench.jsindex 7411a456..8e3abeaa 100644--- a/thinkterm-web/smoke/bench.js+++ b/thinkterm-web/smoke/bench.js@@ -154,6 +154,17 @@ const INSTRUMENT = `const cjk_other = line(`clear; cat ${cjkFile2}`);const seq = line("seq 1 20000");const trickle = line('python3 -c "import time\nfor i in range(300): print(i, flush=True); time.sleep(0.01)"');+ // Four panes: three splits, then the CJK screen into every one of them.+ // `sendPrefix` names pane 0; the others are addressed by replacing it.+ const toPane = (id) => sendPrefix.replace(/--pane-id \d+/, `--pane-id ${id}`);+ const cliPrefix = sendPrefix.replace(/ send-text.*$/, "");+ const fourPanes = () => {+ execSync(`${cliPrefix} split-pane --pane-id 0 --right`, { stdio: "ignore" });+ execSync(`${cliPrefix} split-pane --pane-id 0 --bottom`, { stdio: "ignore" });+ execSync(`${cliPrefix} split-pane --pane-id 1 --bottom`, { stdio: "ignore" });+ const ids = JSON.parse(execSync(`${cliPrefix} list --format json`, { encoding: "utf8" })).map((p) => p.pane_id);+ return ids.map((id) => `printf '%s\\n' 'clear; cat ${cjkFile}' | ${toPane(id)}`).join(" & ") + " & wait";+ };const results = {bundle: wasmRes, load: { dom_content_loaded_ms: Math.round(nav.domContentLoadedEventEnd), first_status_ms: tFirst, attached_ms: tAttached },idle_after_attach: await scenario("idle 3 s", null, 3000),@@ -162,6 +173,7 @@ const INSTRUMENT = `cjk_cold_other: await profiled(() => scenario("a second screen of different fresh CJK", cjk_other, 3000)),trickle: await scenario("300 lines, one every 10 ms", trickle, 5000),ascii_scroll: await scenario("seq 1 20000", seq, 6000),+ four_panes_cjk: await scenario("four panes, a screen of CJK in each", fourPanes(), 4000),idle_after: await scenario("idle 3 s after", null, 3000),metrics: await metrics().then((m) => ({ js_heap_mb: +(m.JSHeapUsedSize / 1048576).toFixed(1), documents: m.Documents, nodes: m.Nodes })),logs,diff --git a/thinkterm-web/smoke/bench.sh b/thinkterm-web/smoke/bench.shindex c4f7f1a1..deee16ab 100755--- a/thinkterm-web/smoke/bench.sh+++ b/thinkterm-web/smoke/bench.sh@@ -30,5 +30,8 @@ SEND="env HOME=$HOME THINKTERM_NO_PRIVACY_DISCLAIM=1 $CLI send-text --no-paste -status=0HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/bench.js" "$URL" "$SEND" --timeout 60000 || status=$?for p in $(pgrep -f "$T/web.lua" || true); do kill "$p"; done-rm -rf "$T"+# The server may still be closing its files; a leftover directory is not+# worth a failure.+sleep 0.5+rm -rf "$T" 2>/dev/null || trueexit $statusdiff --git a/thinkterm-web/smoke/tabs-test.js b/thinkterm-web/smoke/tabs-test.jsindex 00e0209c..58054828 100644--- a/thinkterm-web/smoke/tabs-test.js+++ b/thinkterm-web/smoke/tabs-test.js@@ -1,7 +1,14 @@-// 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.+// End-to-end check of the page's tabs and panes, driven through tabs.sh+// (not part of the served bundle). With two tabs on the server the page+// lists both, a click switches, typing lands in the new pane, and with+// following turned back on a focus change on the server side moves the+// page back. Then the strip's buttons: a split appears in the page's+// layout (read from `canvas.dataset.layout`) with the divider one cell+// past the first pane, a real mouse click into the second pane focuses it+// and makes the server's active pane follow, typing lands there and not+// beside it, the panes' sizes on the server are unchanged by any of it,+// zoom and close do what they say, and a new tab takes the page with it.+// Last, the listener is switched off and on: the split comes back.//// node tabs-test.js <url> <cli prefix> <out.png>//@@ -33,32 +40,97 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });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 = {};+ const layout = async () => JSON.parse(await ev("document.getElementById('term').dataset.layout || '{}'"));+ const click = (action) => ev(`document.querySelector('[data-action=${JSON.stringify(action)}]').click(); 1`);+ const type = async (text) => { 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 ${JSON.stringify(text)}) fire(ch, ch === ' ' ? 'Space' : 'Key' + ch.toUpperCase()); fire('Enter', 'Enter'); return 1; })()`); await sleep(1200); };+ const has = (pane, text) => new RegExp(text).test(sh(`${cli} get-text --pane-id ${pane}`));+ const list = () => JSON.parse(sh(`${cli} list --format json`));+ const sizes = () => list().map((p) => [p.pane_id, p.size.cols + "x" + p.size.rows]);+ const fail = (what) => { throw new Error(what); };+await send("Page.navigate", { url }, s);- await until("attach", "/this browser has|following/.test(document.getElementById('status').textContent)", 20000);+ await until("attach", "/this browser has|mirroring|following/.test(document.getElementById('status').textContent)", 20000);++ // --- tabs: two on the server, click the other, type, follow backout.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.+ const first = await ev("document.querySelector('#tabs .tab.current').dataset.pane");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 until("switch", `document.querySelector('#tabs .tab.current').dataset.pane !== ${JSON.stringify(first)}`);await sleep(400);- out.current_after_click = await ev("document.querySelector('#tabs .tab.current').dataset.pane");+ const second = 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 type("echo TAB2-OK");+ if (!has(second, "TAB2-OK") || has(first, "TAB2-OK")) fail("typing after a tab click went to the wrong pane");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)}`);+ sh(`${cli} activate-pane --pane-id ${first}`);+ await until("follow back", `document.querySelector('#tabs .tab.current').dataset.pane === ${JSON.stringify(first)}`);+ out.tabs = "ok";++ // --- split: the layout has two placements and one divider+ const before = sizes();+ await click("split-right");+ await until("two panes", "document.querySelectorAll('#tabs .pane').length === 2", 8000);await sleep(400);- out.current_after_focus = await ev("document.querySelector('#tabs .tab.current').dataset.pane");- out.status_after_focus = await status();+ let l = await layout();+ if (l.panes.length !== 2) fail("expected two placements: " + JSON.stringify(l));+ const [a, b] = l.panes[0].left < l.panes[1].left ? [l.panes[0], l.panes[1]] : [l.panes[1], l.panes[0]];+ if (b.left !== a.left + a.cols + 1) fail(`second pane at ${b.left}, expected ${a.left + a.cols + 1}`);+ if (l.dividers.length !== 1 || l.dividers[0].col !== a.left + a.cols) fail("divider not in the gap cell: " + JSON.stringify(l.dividers));+ if (l.focused !== b.id) fail("the new pane is not focused");+ out.split = { a: [a.id, a.cols, a.rows], b: [b.id, b.cols, b.rows], divider: l.dividers[0] };++ // --- a real click into the left pane focuses it, on the server too+ const rect = await ev("(r => [r.left, r.top])(document.getElementById('term').getBoundingClientRect())");+ const px = rect[0] + (a.left + Math.floor(a.cols / 2)) * l.cell[0] + 2;+ const py = rect[1] + (a.top + 3) * l.cell[1] + 2;+ await send("Input.dispatchMouseEvent", { type: "mousePressed", x: px, y: py, button: "left", clickCount: 1 }, s);+ await send("Input.dispatchMouseEvent", { type: "mouseReleased", x: px, y: py, button: "left", clickCount: 1 }, s);+ await until("focus moved", `document.querySelector('#tabs .pane.current').dataset.pane === ${JSON.stringify(String(a.id))}`);+ await sleep(300);+ const active = list().find((p) => p.is_active);+ if (!active || active.pane_id !== a.id) fail("the server's active pane did not follow the click: " + JSON.stringify(list().map((p) => [p.pane_id, p.is_active])));+ await type("echo CLICKED");+ if (!has(a.id, "CLICKED") || has(b.id, "CLICKED")) fail("typing after a click went to the wrong pane");+ const after = sizes();+ if (JSON.stringify(after) !== JSON.stringify(sizes())) fail("sizes changed while the page typed");+ out.click = { focused: a.id, sizes_after: after };++ // --- zoom, unzoom, close (twice), new tab+ await click("zoom");+ await until("zoomed", "document.querySelector('[data-action=zoom]').classList.contains('on')", 8000);+ l = await layout();+ if (l.zoomed !== a.id || l.panes.length !== 1 || l.dividers.length !== 0) fail("zoom not reflected: " + JSON.stringify(l));+ await click("zoom");+ await until("unzoomed", "!document.querySelector('[data-action=zoom]').classList.contains('on')", 8000);+ await click("close");+ if ((await ev("document.querySelector('[data-action=close]').textContent")) !== "close pane?") fail("close did not ask");+ await click("close");+ await until("one pane", "document.querySelectorAll('#tabs .pane').length === 0", 8000);+ if (list().some((p) => p.pane_id === a.id)) fail("the pane was not closed");+ out.zoom_close = "ok";+ await click("new-tab");+ await until("three tabs", "document.querySelectorAll('#tabs .tab').length === 3", 8000);+ const newest = Math.max(...list().map((p) => p.pane_id));+ await until("moved to the new tab", `document.querySelector('#tabs .tab.current').dataset.pane === ${JSON.stringify(String(newest))}`);+ out.new_tab = newest;++ // --- reconnect keeps a split+ await click("split-below");+ await until("two panes again", "document.querySelectorAll('#tabs .pane').length === 2", 8000);+ sh(`${cli} web-server off`);+ await until("disconnected", "/reconnect/.test(document.getElementById('status').textContent)", 10000);+ await sleep(1200);+ sh(`${cli} web-server on`);+ await until("back", "/this browser has|mirroring/.test(document.getElementById('status').textContent)", 25000);+ await sleep(600);+ l = await layout();+ if (l.panes.length !== 2) fail("the split did not survive the reconnect: " + JSON.stringify(l));+ await type("echo BACK");+ if (!has(l.focused, "BACK")) fail("typing after the reconnect went nowhere");+ out.reconnect = "ok";+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));+ out.logs = logs.filter((l) => !/^\s*$/.test(l) && !/INFO/.test(l)).slice(-6);+ console.log(JSON.stringify(out));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.shindex a9a5781b..37f2058f 100755--- a/thinkterm-web/smoke/tabs.sh+++ b/thinkterm-web/smoke/tabs.sh@@ -30,5 +30,8 @@ URL=$($CLI web-token mint --label tabs --ttl 1h --url-only 2>/dev/null | head -1status=0HOME=$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"+# The server may still be closing its files; a leftover directory is not+# worth a failure.+sleep 0.5+rm -rf "$T" 2>/dev/null || trueexit $statusdiff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 9d4d7d4a..2c0bb747 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -1265,8 +1265,69 @@ impl App {Some(target.clone())}+ /// What the page has laid out, as JSON on the canvas element for the+ /// smoke tests and anyone else curious: `canvas.dataset.layout`.+ /// Rewritten whenever the strip is, which is whenever it changes.+ fn publish_layout(inner: &Inner) {+ let lease = inner.link.lease();+ let dpr = inner.dpr.max(0.1);+ let (cw, ch) = (+ inner.glyphs.metrics.cell_size.width as f64 / dpr,+ inner.glyphs.metrics.cell_size.height as f64 / dpr,+ );+ let mut json = format!(+ "{{\"tab\":{},\"canvas\":[{},{}],\"cell\":[{cw:.3},{ch:.3}],\"focused\":{},\"owner\":{},\"may_type\":{},\"fit\":{},\"following\":{}",+ inner.tab_id,+ inner.cols,+ inner.rows,+ inner.focused_pane,+ lease.owns_viewport(),+ lease.may_type(),+ lease.fit,+ inner.following,+ );+ match &inner.tab_layout {+ Some(layout) => {+ json.push_str(&format!(",\"cols\":{},\"rows\":{},\"zoomed\":", layout.cols, layout.rows));+ match layout.zoomed {+ Some(id) => json.push_str(&id.to_string()),+ None => json.push_str("null"),+ }+ json.push_str(",\"panes\":[");+ for (i, p) in layout.panes.iter().enumerate() {+ if i > 0 {+ json.push(',');+ }+ json.push_str(&format!(+ "{{\"id\":{},\"left\":{},\"top\":{},\"cols\":{},\"rows\":{},\"content\":[{},{}]}}",+ p.pane_id, p.frame.left, p.frame.top, p.frame.cols, p.frame.rows, p.content.0, p.content.1+ ));+ }+ json.push_str("],\"dividers\":[");+ for (i, d) in layout.dividers.iter().enumerate() {+ if i > 0 {+ json.push(',');+ }+ match *d {+ crate::layout::Divider::Col { col, top, rows } => {+ json.push_str(&format!("{{\"col\":{col},\"top\":{top},\"rows\":{rows}}}"))+ }+ crate::layout::Divider::Row { row, left, cols } => {+ json.push_str(&format!("{{\"row\":{row},\"left\":{left},\"cols\":{cols}}}"))+ }+ }+ }+ json.push(']');+ }+ None => json.push_str(",\"cols\":null,\"rows\":null,\"zoomed\":null,\"panes\":[],\"dividers\":[]"),+ }+ json.push('}');+ let _ = inner.canvas.set_attribute("data-layout", &json);+ }+/// Draw the tab strip from what the page knows.fn render_strip(inner: &Inner) {+ Self::publish_layout(inner);let (Some(strip), Some(layout)) = (&inner.strip, &inner.layout) else {return;};@@ -1370,10 +1431,15 @@ impl App {return;}}- let fresh = {+ let (fresh, changed) = {let mut inner = self.inner.borrow_mut();inner.layout = Some(list);+ let before = (inner.focused_pane, inner.tab_layout.clone());let fresh = Self::apply_layout(&mut inner, layout, want);+ let changed = tab_changed+ || !fresh.is_empty()+ || before.0 != inner.focused_pane+ || before.1 != inner.tab_layout;if tab_changed {inner.selecting = false;inner.ime_anchor = None;@@ -1385,7 +1451,7 @@ impl App {doc.set_title(&format!("{} — ThinkTerm", inner.title()));}Self::render_strip(&inner);- fresh+ (fresh, changed)};// A pane's first push comes when something asks after it: one// liveness poll each, and the answer is not waited for.@@ -1406,8 +1472,12 @@ impl App {if tab_changed {self.resize();}- self.refresh_status();- self.request_frame();+ // A listing that changed nothing (the timer's, mostly) is not a+ // reason to paint.+ if changed {+ self.refresh_status();+ self.request_frame();+ }}/// Make `inner.panes` match `layout`, focusing `want` if it is drawn