Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

thinkterm-web: sidebar smoke test, probe fields and docs

RoversXc74a27e95af6
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.md
index e2daaa4c..1c3b4d3c 100644
--- a/docs/thinkterm/web-access.md
+++ b/docs/thinkterm/web-access.md
@@ -97,30 +97,69 @@ environment variable point it elsewhere, for instance at a development
checkout. `ci/deploy.sh` refuses to package without the bundle in CI and warns
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 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 input
-method's hidden field follows the terminal cursor, including scrolling and
-resizing, so the browser can place its candidate window there; pre-edit
-text and its underline are not yet drawn in the grid.
+## What the page shows
+
+The page is the desktop, as far as the wire allows. Its chrome is the
+desktop's: the 40 px tab row of 160 px capsules (the tabs of the window on
+show; `+` opens one, the x on a tab closes it, asking twice), a bar above
+every pane like the desktop's pane nav bar (the pane's capsule with its
+title -- a bare shell is "Terminal" -- and, on the right, new tab, split
+down, split right and zoom; a stack's members are its capsules), and on the
+left the sidebar described below. The palette is the desktop's dark set;
+`?theme=light` picks the other. There is no status line: refusals and
+reconnects are a passing remark at the bottom right, and a page that does
+not hold the terminal in Handoff mode sees the desktop's card ("Terminal is
+being used on another device -- Click or scroll to continue") over the
+mirror, which stays visible.
+
+The tab keeps the desktop's size and shape. The page's own font size is
+derived from the desktop's cell so that a cell here is as large as one
+there, and the desktop's pixel geometry (the bar above each pane, the
+padding around the grid) lands on the page one to one; the page clips when
+the tab is larger than the window and says so in the tab row. `?font=`
+pins a size instead; Ctrl+Shift+F fits the tab to this window until the
+desktop next takes it. Every claim the page makes is pane by pane
+(`ClientViewport::Native`): taking the terminal over from the desktop
+changes no pane's grid, and a tab a CLI laid out gets the same rows above
+each pane the desktop would leave.
+
+Taking the terminal works as it does on the desktop: a click, a scroll or a
+keystroke in a pane takes it, and the first one is not lost -- the click's
+focus is passed on and the key is typed once the server has handed over.
+Chrome clicks (tabs, bars, sidebar) never take it. Ctrl+Shift+T asks
+explicitly; Ctrl+Shift with an arrow moves the focus between panes.
+
+The sidebar is the server's own tree of Spaces, Projects and Threads
+(`ThinkTermSessionState`, `ThinkTermTree`), drawn like the desktop's with
+the same status marks: a spinner while an agent in the thread works, an
+alert when one waits on you, a check when it finished unseen, a dot
+otherwise. Clicking a thread shows its active tab, or has the server create
+its terminal in the project's directory (`EnsureThinkTermThread`); New
+Thread, the `+` on a project, double-click to rename, pin, delete (asking
+twice; its programs end), a new project from a path (`~/dir` or `/dir`, with
+a `main` thread) and archive/restore all send the desktop's own tree
+operations, and a refusal -- the server answers only with its tree, so one
+is inferred from it -- is a remark. Windows no thread claims are listed
+under "Other windows" so nothing is out of reach. The panel's width is
+dragged at its edge and kept per browser; the button at the start of the
+tab row hides it.
+
+One thing to know: a desktop's own sidebar is its own store. It mirrors a
+server's tree only for Spaces bound to a remote host, and its local session
+host is excluded, so a page attached to the desktop's own machine sees the
+server's tree, not the desktop's sidebar, until the desktop is taught to
+keep its local Space on that server too. Against a remote mux server the
+page and the desktop show the same tree.
+
+Images (kitty, sixel, iTerm2) are not drawn; the cursor does not blink. The
+input method's hidden field follows the terminal cursor, including
+scrolling and resizing, so the browser can place its candidate window
+there; pre-edit text 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
-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 a
-different protocol version -- and says which.
+tab; the remark stays while it is down. It gives up only when there is
+nothing to come back to -- the server has no panes, or speaks a different
+protocol version -- and says which.
## Fonts
diff --git a/thinkterm-web/smoke/bench.js b/thinkterm-web/smoke/bench.js
index 8e3abeaa..788bff7a 100644
--- a/thinkterm-web/smoke/bench.js
+++ b/thinkterm-web/smoke/bench.js
@@ -71,7 +71,7 @@ const INSTRUMENT = `
await send("Performance.enable", {}, s);
await send("Page.addScriptToEvaluateOnNewDocument", { source: INSTRUMENT }, s);
const ev = async (expr) => (await send("Runtime.evaluate", { expression: expr, returnByValue: true }, s)).result?.value;
- const status = () => ev("document.getElementById('status')?.textContent || ''");
+ const status = () => ev("document.getElementById('status')?.dataset.summary || ''");
const snap = async () => ({ ...(await ev("JSON.stringify(window.__tt)").then(JSON.parse)), heap: await ev("performance.memory ? performance.memory.usedJSHeapSize : null") });
const metrics = async () => Object.fromEntries((await send("Performance.getMetrics", {}, s)).metrics.map((m) => [m.name, m.value]));
const rendererRss = () => {
diff --git a/thinkterm-web/smoke/sidebar-test.js b/thinkterm-web/smoke/sidebar-test.js
new file mode 100644
index 00000000..1a2a0871
--- /dev/null
+++ b/thinkterm-web/smoke/sidebar-test.js
@@ -0,0 +1,92 @@
+// The sidebar end to end, against a throwaway server: the landing tree
+// appears after "New Thread", a second thread is created, renamed, pinned
+// and deleted, a project is created from a path and its `main` thread
+// spawns there, and archiving the last project is refused with a remark.
+// node sidebar-test.js <url> <cli prefix> <out.png>
+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); }, 120000).unref();
+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-side-`);
+const chrome = spawn(chromePath, ["--headless=new", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=1400,800", "--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 rows = async () => JSON.parse(await ev("document.getElementById('side')?.dataset.rows || '[]'"));
+ const threads = async () => (await rows()).filter((r) => r.kind === "thread");
+ const until = async (what, fn, ms = 10000) => { const t = Date.now(); while (Date.now() - t < ms) { const v = await fn(); if (v) return v; await sleep(120); } throw new Error("timeout waiting for " + what + ": rows=" + JSON.stringify(await rows()) + " status=" + (await ev("document.getElementById('status').textContent"))); };
+ const click = (sel) => ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; el.click(); return true; })()`);
+ const dblclick = (sel) => ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; el.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 2 })); return true; })()`);
+ const typeInto = async (text) => { await ev(`(() => { const i = document.querySelector('#side input'); i.value = ${JSON.stringify(text)}; i.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); return 1; })()`); };
+ const list = () => JSON.parse(sh(`${cli} list --format json`));
+ const fail = (what) => { throw new Error(what); };
+ const out = {};
+
+ await send("Page.navigate", { url }, s);
+ await until("attach", async () => /this browser has|mirroring|following/.test(await ev("document.getElementById('status').dataset.summary || ''")), 20000);
+ await sleep(800);
+ out.rows_at_start = (await rows()).map((r) => r.kind);
+ if (!(await rows()).some((r) => r.kind === "others")) fail("the CLI window is not listed under Other windows");
+
+ // --- New Thread on an empty tree: the landing thread
+ await click("[data-action=new-thread]");
+ const landing = await until("landing thread on show", async () => (await threads()).find((t) => t.selected), 15000);
+ out.landing = landing;
+ const ws1 = list().find((p) => /^thinkterm:/.test(p.workspace));
+ if (!ws1) fail("no window in a thread workspace: " + JSON.stringify(list().map((p) => p.workspace)));
+
+ // --- a second thread in the same project, renamed, pinned, deleted
+ await click("[data-action=new-thread]");
+ const second = await until("second thread", async () => (await threads()).find((t) => t.id !== landing.id), 15000);
+ await until("second thread on show", async () => (await threads()).find((t) => t.id === second.id)?.selected, 15000);
+ await dblclick(`[data-action=rename-thread][data-thread="${second.id}"]`);
+ await until("rename field", () => ev("!!document.querySelector('#side input.rename')"));
+ await typeInto("renamed by the page");
+ await until("renamed", async () => (await threads()).find((t) => t.id === second.id)?.name === "renamed by the page");
+ await click(`[data-action=pin][data-thread="${second.id}"]`);
+ await until("pinned", async () => { const r = await rows(); const i = r.findIndex((x) => x.kind === "pinned"); const t = r.find((x) => x.kind === "thread" && x.id === second.id); return i >= 0 && t && t.pinned && r.indexOf(t) > i; });
+ const before = list().length;
+ await click(`[data-action=delete][data-thread="${second.id}"]`);
+ if (!/delete\?/.test(await ev(`document.querySelector('[data-action=delete][data-thread="${second.id}"]').textContent`))) fail("delete did not ask");
+ await click(`[data-action=delete][data-thread="${second.id}"]`);
+ await until("deleted", async () => !(await threads()).some((t) => t.id === second.id), 15000);
+ await until("its pane is gone", () => list().length < before, 15000);
+ out.thread_ops = "ok";
+
+ // --- a project from a path: its main thread spawns there
+ const dir = fs.mkdtempSync(`${os.tmpdir()}/tt-proj-`);
+ await click("[data-action=new-project]");
+ await until("path field", () => ev("!!document.querySelector('#side .path input')"));
+ await typeInto(dir);
+ const project = await until("project row", async () => (await rows()).find((r) => r.kind === "project" && r.name === require("path").basename(dir)), 15000);
+ const main = await until("main thread on show", async () => (await threads()).find((t) => t.project === project.id && t.selected), 15000);
+ out.project = { name: project.name, main: main.name };
+ await until("cwd is the project", () => list().some((p) => p.cwd && p.cwd.replace(/\/$/, "").endsWith(dir.replace(/^\/private/, "").replace(/\/$/, ""))), 15000);
+
+ // --- archiving: the second project can go, the last one cannot
+ await click(`[data-action=archive][data-project="${project.id}"]`);
+ await until("archived", async () => (await rows()).some((r) => r.kind === "archived" && r.count === 1), 15000);
+ const last = (await rows()).find((r) => r.kind === "project" && !r.archived);
+ await click(`[data-action=archive][data-project="${last.id}"]`);
+ await until("refusal shown", () => ev("/last project/.test(document.getElementById('status').textContent) && !document.getElementById('status').hasAttribute('hidden')"), 10000);
+ out.archive = "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) && !/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/sidebar.sh b/thinkterm-web/smoke/sidebar.sh
new file mode 100755
index 00000000..53e432ae
--- /dev/null
+++ b/thinkterm-web/smoke/sidebar.sh
@@ -0,0 +1,37 @@
+#!/bin/sh
+# The sidebar, end to end: a release server with an empty tree under a
+# throwaway HOME, the release bundle, headless Chrome.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/sidebar.sh [out.png]
+#
+# Prints the JSON sidebar-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18091
+OUT=${1:-/tmp/thinkterm-sidebar.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 sidebar --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/sidebar-test.js" "$URL" "$CLI" "$OUT" || status=$?
+for p in $(pgrep -f "$T/web.lua" || true); do kill "$p"; done
+# 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 || true
+exit $status
diff --git a/thinkterm-web/smoke/tabs-test.js b/thinkterm-web/smoke/tabs-test.js
index 58054828..589e64a7 100644
--- a/thinkterm-web/smoke/tabs-test.js
+++ b/thinkterm-web/smoke/tabs-test.js
@@ -37,7 +37,7 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
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 status = () => ev("document.getElementById('status')?.dataset.summary || ''");
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 || '{}'"));
@@ -49,7 +49,7 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
const fail = (what) => { throw new Error(what); };
await send("Page.navigate", { url }, s);
- await until("attach", "/this browser has|mirroring|following/.test(document.getElementById('status').textContent)", 20000);
+ await until("attach", "/this browser has|mirroring|following/.test((document.getElementById('status').dataset.summary || ''))", 20000);
// --- tabs: two on the server, click the other, type, follow back
out.strip_at_start = await until("two tabs", "document.querySelectorAll('#tabs .tab').length === 2 && document.getElementById('tabs').innerText");
@@ -58,18 +58,18 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
await until("switch", `document.querySelector('#tabs .tab.current').dataset.pane !== ${JSON.stringify(first)}`);
await sleep(400);
const second = await ev("document.querySelector('#tabs .tab.current').dataset.pane");
- out.follow_after_click = await ev("document.querySelector('#tabs .follow').textContent");
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()");
+ // The page always follows the desktop's focus.
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();
+ const L = "JSON.parse(document.getElementById('term').dataset.layout || '{}')";
await click("split-right");
- await until("two panes", "document.querySelectorAll('#tabs .pane').length === 2", 8000);
+ await until("two panes", `(${L}.panes || []).length === 2`, 8000);
await sleep(400);
let l = await layout();
if (l.panes.length !== 2) fail("expected two placements: " + JSON.stringify(l));
@@ -82,10 +82,11 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
// --- 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;
+ // Below the pane's bar (the top ~47 px of a frame are its nav bar).
+ const py = rect[1] + (a.top + 5) * 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 until("focus moved", `document.querySelector('.nav.focused')?.dataset.nav === ${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])));
@@ -97,15 +98,16 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
// --- zoom, unzoom, close (twice), new tab
await click("zoom");
- await until("zoomed", "document.querySelector('[data-action=zoom]').classList.contains('on')", 8000);
+ await until("zoomed", `${L}.zoomed != null`, 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);
+ await until("unzoomed", `${L}.zoomed == null`, 8000);
+ const closeBtn = "document.querySelector('.nav.focused .cap.current .x')";
+ await ev(`${closeBtn}.click(); 1`);
+ if ((await ev(`${closeBtn}.textContent`)) !== "close?") fail("close did not ask");
+ await ev(`${closeBtn}.click(); 1`);
+ await until("one pane", `(${L}.panes || []).length === 1`, 8000);
if (list().some((p) => p.pane_id === a.id)) fail("the pane was not closed");
out.zoom_close = "ok";
await click("new-tab");
@@ -116,12 +118,12 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
// --- reconnect keeps a split
await click("split-below");
- await until("two panes again", "document.querySelectorAll('#tabs .pane').length === 2", 8000);
+ await until("two panes again", `(${L}.panes || []).length === 2`, 8000);
sh(`${cli} web-server off`);
- await until("disconnected", "/reconnect/.test(document.getElementById('status').textContent)", 10000);
+ await until("disconnected", "/reconnect/.test((document.getElementById('status').dataset.summary || ''))", 10000);
await sleep(1200);
sh(`${cli} web-server on`);
- await until("back", "/this browser has|mirroring/.test(document.getElementById('status').textContent)", 25000);
+ await until("back", "/this browser has|mirroring/.test((document.getElementById('status').dataset.summary || ''))", 25000);
await sleep(600);
l = await layout();
if (l.panes.length !== 2) fail("the split did not survive the reconnect: " + JSON.stringify(l));