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: smoke suites for menus, palette, settings, agents, mobile and sidebar drag

RoversX84d079a8b1fa
diff --git a/thinkterm-web/smoke/agents-test.js b/thinkterm-web/smoke/agents-test.js
new file mode 100644
index 00000000..0df496a4
--- /dev/null
+++ b/thinkterm-web/smoke/agents-test.js
@@ -0,0 +1,128 @@
+// The Agents panel end to end, against a throwaway server: the settings
+// switch puts it on the right and the terminal gives up the room for it,
+// its edge drags without resizing the terminal on every frame, turning it
+// off gives the room back, and the tab row's button is the same switch.
+// node agents-test.js <url> <out.png>
+const { spawn } = require("child_process");
+const http = require("http"); const fs = require("fs"); const os = require("os");
+const WebSocket = require("ws");
+const [url, 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); }, 150000).unref();
+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-agents-`);
+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"); }
+(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 until = async (what, fn, ms = 15000) => { 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); };
+ const click = (sel) => ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; el.click(); return true; })()`);
+ const mouse = (type, x, y, extra = {}) => send("Input.dispatchMouseEvent", { type, x, y, button: "left", clickCount: 1, ...extra }, s);
+ const fail = (what) => { throw new Error(what); };
+ const attached = async () => /this browser has|mirroring|following/.test(await ev("document.getElementById('status').dataset.summary || ''"));
+ const canvasWidth = () => ev("document.querySelector('canvas#term').getBoundingClientRect().width");
+ const agentsW = () => ev("getComputedStyle(document.documentElement).getPropertyValue('--agents-w').trim()");
+ // The switch lives in the settings panel; the gear opens it, and the
+ // backdrop is over the page while it is up, so it is closed again before
+ // anything is dragged.
+ const toggleFromSettings = async () => {
+ if (!(await click("#side [data-action=settings]"))) fail("no gear in the sidebar footer");
+ await until("the settings panel", () => ev("!!document.getElementById('settings')"));
+ await click("#settings [data-section=agents]");
+ if (!(await click("#settings input[data-setting=agents-panel]"))) fail("no agents-panel switch");
+ if (!(await click("#settings .sc"))) fail("no close button");
+ await until("the settings panel to close", () => ev("!document.getElementById('settings')"));
+ };
+ const out = {};
+
+ await send("Page.navigate", { url }, s);
+ await until("attach", attached, 20000);
+ await sleep(900);
+ if (await ev("!!document.getElementById('agents')")) fail("the panel is on before anything asked for it");
+ const wide = await canvasWidth();
+ out.canvas_without = wide;
+
+ // --- (a) the switch puts the panel up and the terminal gives up the room.
+ await toggleFromSettings();
+ await until("the panel", () => ev("!!document.getElementById('agents')"));
+ if (!(await ev("document.body.hasAttribute('data-agents')"))) fail("the body carries no data-agents mark");
+ if (!(await ev("document.querySelector('#tabs [data-action=agents]').classList.contains('on')"))) fail("the tab row's button does not show the panel is on");
+ out.width = await agentsW();
+ if (out.width !== "260px") fail("the panel did not open at its default width: " + out.width);
+ out.summary = await ev("document.querySelector('#agents .hd .sum').textContent");
+ if (out.summary !== "No agents detected") fail("the header does not carry the wasm's summary: " + JSON.stringify(out.summary));
+ out.title = await ev("document.querySelector('#agents .hd .ti').textContent");
+ if (out.title !== "Agents") fail("the header is not titled: " + JSON.stringify(out.title));
+ await until("the terminal to give up the room", async () => Math.abs(wide - (await canvasWidth()) - 260) < 1);
+ out.canvas_with = await canvasWidth();
+ out.panel = "ok";
+
+ // --- (b) the edge drags without resizing the terminal on every frame.
+ // The panel clips what overflows it, so only the part of the 4px handle
+ // inside its padding box can be pressed: the first two columns, the 1px
+ // border taking the one before them.
+ const grab = await ev(`(() => { const aside = document.getElementById('agents');
+ const x = Math.floor(aside.getBoundingClientRect().right - aside.clientWidth) + 1;
+ const el = document.elementFromPoint(x, 400);
+ return { x, on: el ? (el.className || el.id || el.tagName) : null }; })()`);
+ if (grab.on !== "handle") fail(`${grab.x},400 is not the handle but ` + JSON.stringify(grab.on));
+ // 40 px further left is 40 px more panel; the pointer's distance from the
+ // right edge is the width, so this is where it has to end up.
+ const target = (await ev("window.innerWidth")) - 300;
+ // Every change of the canvas's backing store, which is what one terminal
+ // resize costs; the count is read before the release and after it.
+ await ev(`(() => { const c = document.querySelector('canvas#term'); window.__resizes = 0; window.__last = c.width;
+ new MutationObserver(() => { if (c.width !== window.__last) { window.__last = c.width; window.__resizes++; } }).observe(c, { attributes: true, attributeFilter: ['width'] });
+ return c.width; })()`);
+ await mouse("mousePressed", grab.x, 400, { buttons: 1 });
+ for (let x = grab.x - 8; x > target; x -= 8) { await mouse("mouseMoved", x, 400, { buttons: 1 }); await sleep(70); }
+ await mouse("mouseMoved", target, 400, { buttons: 1 });
+ await sleep(300);
+ out.resizes_during_drag = await ev("window.__resizes");
+ const midWidth = await agentsW();
+ await mouse("mouseReleased", target, 400, { buttons: 0 });
+ await sleep(900);
+ out.resizes_after_release = (await ev("window.__resizes")) - out.resizes_during_drag;
+ out.agents_w = await agentsW();
+ out.stored = await ev("localStorage.getItem('thinkterm.agents-width')");
+ if (midWidth !== "300px") fail("the panel did not follow the pointer: " + midWidth);
+ if (out.resizes_during_drag !== 0) fail("the terminal was resized " + out.resizes_during_drag + " times during the drag");
+ if (out.resizes_after_release !== 1) fail("the release should resize the terminal exactly once, not " + out.resizes_after_release);
+ if (out.agents_w !== "300px") fail("the width ended at " + out.agents_w);
+ if (out.stored !== "300") fail("the width stored is " + JSON.stringify(out.stored));
+ out.drag = "ok";
+
+ const shot = await send("Page.captureScreenshot", { format: "png" }, s); fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));
+
+ // --- (c) turning it off gives the room back.
+ await toggleFromSettings();
+ await until("the panel to go", () => ev("!document.getElementById('agents')"));
+ if (await ev("document.body.hasAttribute('data-agents')")) fail("the body kept its data-agents mark");
+ await until("the terminal to take the room back", async () => Math.abs((await canvasWidth()) - wide) < 1);
+ out.canvas_after = await canvasWidth();
+ out.off = "ok";
+
+ // --- (d) the tab row's button is the same switch.
+ if (!(await click("#tabs [data-action=agents]"))) fail("no agents button in the tab row");
+ await until("the panel again", () => ev("!!document.getElementById('agents')"));
+ if ((await agentsW()) !== "300px") fail("the panel did not come back at the width it was dragged to");
+ if (!(await ev("JSON.parse(window.thinkterm.client.settings())['agents-panel']")))
+ fail("the button did not put the preference on");
+ await click("#tabs [data-action=agents]");
+ await until("the panel to go again", () => ev("!document.getElementById('agents')"));
+ out.button = "ok";
+
+ 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/agents.sh b/thinkterm-web/smoke/agents.sh
new file mode 100755
index 00000000..b5aab785
--- /dev/null
+++ b/thinkterm-web/smoke/agents.sh
@@ -0,0 +1,39 @@
+#!/bin/sh
+# The Agents panel, end to end: a release server with an empty tree under a
+# throwaway HOME, the release bundle, headless Chrome, turning the panel on
+# from the settings, dragging its edge, turning it off again, and the tab
+# row's button doing the same.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/agents.sh [out.png]
+#
+# Prints the JSON agents-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18101
+OUT=${1:-/tmp/thinkterm-agents.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-agents.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 agents --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/agents-test.js" "$URL" "$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/menus-test.js b/thinkterm-web/smoke/menus-test.js
new file mode 100644
index 00000000..43a23058
--- /dev/null
+++ b/thinkterm-web/smoke/menus-test.js
@@ -0,0 +1,119 @@
+// The context menus end to end, against a throwaway server: a right-click
+// on the canvas offers the pane's list and its Split Right really splits,
+// a right-click on a thread row offers the thread's and its Pin really
+// pins, a right-click on a capsule offers the tab's, and Escape closes the
+// menu and hands the keyboard back to the terminal.
+// node menus-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-menus-`);
+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 layout = async () => JSON.parse(await ev("document.getElementById('term').dataset.layout || '{}'"));
+ const until = async (what, fn, ms = 12000) => { 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 + ": menu=" + JSON.stringify(await labels()) + " 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 list = () => JSON.parse(sh(`${cli} list --format json`));
+ const fail = (what) => { throw new Error(what); };
+ // Every panel's rows, in order, the headers and separators aside.
+ const labels = () => ev("Array.from(document.querySelectorAll('.menu .mi .lb')).map((e) => e.textContent)");
+ const open = () => ev("!!document.getElementById('menu')");
+ // A real right-click: the press the browser turns into a contextmenu.
+ const rightClick = async (x, y) => {
+ await send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "right", buttons: 2, clickCount: 1 }, s);
+ await send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "right", buttons: 0, clickCount: 1 }, s);
+ };
+ const rightClickOn = async (sel) => {
+ const at = await ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return null; const r = el.getBoundingClientRect();
+ return [Math.round(r.left + Math.min(24, r.width / 2)), Math.round(r.top + r.height / 2)]; })()`);
+ if (!at) fail("nothing to right-click at " + sel);
+ await rightClick(at[0], at[1]);
+ };
+ const key = async (k, code, vk) => { await send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }, s); await send("Input.dispatchKeyEvent", { type: "keyUp", key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }, s); };
+ 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(900);
+
+ // --- (a) the pane's menu, from a right-click in the terminal itself.
+ let l = await until("a laid-out tab", async () => { const v = await layout(); return v.panes && v.panes.length === 1 ? v : null; });
+ const tab = l.tab;
+ // The grid starts a cell in from the left and half a cell down (App::pad);
+ // a few rows below the pane's own bar, mid-pane.
+ const point = await ev(`(() => { const r = document.getElementById('term').getBoundingClientRect();
+ const l = JSON.parse(document.getElementById('term').dataset.layout); const p = l.panes[0];
+ return [Math.round(r.left + l.cell[0] * (1 + p.left + Math.floor(p.cols / 2))), Math.round(r.top + l.cell[1] * (0.5 + p.top + 5))]; })()`);
+ await rightClick(point[0], point[1]);
+ await until("the pane's menu", open);
+ out.pane_labels = await labels();
+ const wanted = ["Copy", "Paste", "Split Right", "Split Left", "Split Down", "Split Up", "Frontend access"];
+ if (JSON.stringify(out.pane_labels) !== JSON.stringify(wanted)) fail("the pane's menu is " + JSON.stringify(out.pane_labels));
+ out.pane_menu = "ok";
+
+ const before = list().filter((p) => p.tab_id === tab).length;
+ if (!(await click('[data-id^="split:right:"]'))) fail("no Split Right row");
+ await until("the menu is gone", async () => !(await open()));
+ await sleep(1500);
+ const panes = list().filter((p) => p.tab_id === tab);
+ if (before !== 1 || panes.length !== 2) fail(`tab ${tab} went from ${before} to ${panes.length} panes`);
+ await until("two placements", async () => (await layout()).panes?.length === 2);
+ out.split = "ok";
+
+ // --- (c) a capsule's menu: with one tab, only the tab it can offer.
+ await rightClickOn("#tabs .tab");
+ await until("the tab's menu", open);
+ out.tab_labels = await labels();
+ if (out.tab_labels[0] !== "New Terminal Tab to Right") fail("the tab's menu is " + JSON.stringify(out.tab_labels) + " over " + (await ev("document.querySelectorAll('#tabs .tab').length")) + " tabs");
+ out.tab_menu = "ok";
+
+ // --- (d) Escape closes it and the terminal has the keyboard again.
+ if (await ev("document.activeElement.id === 'kbd'")) fail("the menu did not take the keyboard");
+ await key("Escape", "Escape", 27);
+ await until("the menu is gone", async () => !(await open()));
+ if (!(await ev("document.activeElement.id === 'kbd'"))) fail("the keyboard did not go back to the terminal: " + (await ev("document.activeElement.id || document.activeElement.className")));
+ out.escape = "ok";
+
+ // --- (b) a thread row's menu, and the pin it offers.
+ await click("[data-action=new-thread]");
+ const thread = await until("the landing thread", async () => (await threads()).find((t) => t.selected), 15000);
+ await rightClickOn(`.row.thread[data-thread="${thread.id}"]`);
+ await until("the thread's menu", open);
+ out.thread_labels = await labels();
+ if (out.thread_labels[0] !== "Pin Thread") fail("the thread's menu is " + JSON.stringify(out.thread_labels));
+ out.thread_menu = "ok";
+
+ if (!(await click('[data-id^="pin:"]'))) fail("no Pin Thread row");
+ await until("the menu is gone", async () => !(await open()));
+ await until("pinned, under the Pinned header", async () => {
+ const r = await rows();
+ const header = r.findIndex((x) => x.kind === "pinned");
+ const t = r.find((x) => x.kind === "thread" && x.id === thread.id);
+ return header >= 0 && t && t.pinned && r.indexOf(t) > header;
+ });
+ out.pin = "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/menus.sh b/thinkterm-web/smoke/menus.sh
new file mode 100755
index 00000000..2aab9c73
--- /dev/null
+++ b/thinkterm-web/smoke/menus.sh
@@ -0,0 +1,40 @@
+#!/bin/sh
+# The context menus, end to end: a release server with an empty tree under
+# a throwaway HOME, the release bundle, headless Chrome, right-clicking the
+# canvas, the tab row and the sidebar.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/menus.sh [out.png]
+#
+# Prints the JSON menus-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18095
+OUT=${1:-/tmp/thinkterm-menus.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-menus.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"
+# Nothing is spawned here: the page makes its own tab when it attaches to
+# an empty server, so the window it shows has exactly one, which is the
+# tab menu this test wants.
+URL=$($CLI web-token mint --label menus --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/menus-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/mobile-test.js b/thinkterm-web/smoke/mobile-test.js
new file mode 100644
index 00000000..d8c56c2d
--- /dev/null
+++ b/thinkterm-web/smoke/mobile-test.js
@@ -0,0 +1,183 @@
+// The phone shape end to end, against a throwaway server, driven with a
+// finger: the page comes up in its mobile shape with the key bar along the
+// bottom and the canvas sized around it, a tap takes the terminal over and
+// asks for the soft keyboard, the bar's keys and its sticky Ctrl reach the
+// pane, a drag scrolls instead of selecting, a swipe from the left edge
+// brings the drawer out and the backdrop puts it away, and a long press
+// opens the pane's menu.
+// node mobile-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); }, 150000).unref();
+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-mobile-`);
+const chrome = spawn(chromePath, ["--headless=new", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=430,920", "--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" });
+/** The phone the page is emulated on. */
+const PHONE = { width: 390, height: 844, deviceScaleFactor: 3, mobile: true };
+/** The key bar's height, as tokens.css and mobile.svelte.ts have it. */
+const BAR = 44;
+
+(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 layout = async () => JSON.parse(await ev("document.getElementById('term').dataset.layout || '{}'"));
+ const summary = () => ev("document.getElementById('status')?.dataset.summary || ''");
+ const until = async (what, fn, ms = 15000) => { 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 + ": status=" + (await ev("document.getElementById('status')?.textContent")) + " summary=" + (await summary())); };
+ const fail = (what) => { throw new Error(what); };
+ // A finger. touchEnd releases every point, so it carries none.
+ const touch = (type, points) => send("Input.dispatchTouchEvent", { type, touchPoints: points }, s);
+ const at = (x, y, i = 0) => ({ x: Math.round(x), y: Math.round(y), id: i });
+ const tap = async (x, y) => { await touch("touchStart", [at(x, y)]); await sleep(60); await touch("touchEnd", []); };
+ // The key bar scrolls sideways: a key past the right edge of a 390 px
+ // phone has to be brought into view before a finger can reach it.
+ const tapOn = async (sel) => {
+ const box = await ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return null;
+ el.scrollIntoView({ block: 'nearest', inline: 'center' }); const r = el.getBoundingClientRect();
+ return [r.left + r.width / 2, r.top + r.height / 2, window.innerWidth, window.innerHeight]; })()`);
+ if (!box) fail("nothing to tap at " + sel);
+ if (box[0] < 0 || box[0] > box[2] || box[1] < 0 || box[1] > box[3]) fail(sel + " is off the screen at " + box[0] + "," + box[1]);
+ await tap(box[0], box[1]);
+ };
+ // A key the way a hardware or soft keyboard sends one, into #kbd.
+ const typeKey = async (ch) => {
+ const code = /^[a-z]$/.test(ch) ? "Key" + ch.toUpperCase() : "";
+ const vk = ch.toUpperCase().charCodeAt(0);
+ await send("Input.dispatchKeyEvent", { type: "keyDown", text: ch, key: ch, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }, s);
+ await send("Input.dispatchKeyEvent", { type: "keyUp", key: ch, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }, s);
+ };
+ const text = (pane) => sh(`${cli} get-text --pane-id ${pane}`);
+ const lastLine = (pane) => text(pane).split("\n").map((l) => l.replace(/\s+$/, "")).filter((l) => l !== "").pop() ?? "";
+ const out = {};
+
+ // The phone, and its touchscreen, before anything is loaded: the page
+ // decides its shape as it mounts and never sees the desktop's window.
+ await send("Emulation.setDeviceMetricsOverride", PHONE, s);
+ await send("Emulation.setTouchEmulationEnabled", { enabled: true }, s);
+ await send("Page.navigate", { url }, s);
+ await until("attach", async () => /this browser has|mirroring|following/.test(await summary()), 25000);
+ await sleep(900);
+
+ // --- (a) the shape: the mark on the body, the bar at the foot of the
+ // window, and a canvas that stops above it.
+ if (!(await ev("document.body.dataset.mobile !== undefined"))) fail("the page is not in its mobile shape");
+ out.mode = "ok";
+
+ const bar = await ev(`(() => { const el = document.getElementById('keybar'); if (!el) return null; const r = el.getBoundingClientRect();
+ return { bottom: r.bottom, height: r.height, keys: document.querySelectorAll('#keybar .k').length, inner: window.innerHeight }; })()`);
+ if (!bar) fail("no key bar");
+ if (bar.inner !== PHONE.height) fail("the window is " + bar.inner + " tall, not the phone's " + PHONE.height);
+ if (Math.abs(bar.bottom - bar.inner) > 1) fail("the key bar ends at " + bar.bottom + ", not at " + bar.inner);
+ if (Math.abs(bar.height - BAR) > 1) fail("the key bar is " + bar.height + " tall");
+ if (bar.keys !== 17) fail("the key bar has " + bar.keys + " keys");
+ const box = await ev(`(() => { const r = document.getElementById('term').getBoundingClientRect();
+ const tabs = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--tabs'));
+ return { height: r.height, want: window.innerHeight - tabs - ${BAR}, width: r.width, inner: window.innerWidth }; })()`);
+ if (Math.abs(box.height - box.want) > 2) fail("the canvas is " + box.height + " tall, not " + box.want);
+ if (Math.abs(box.width - box.inner) > 1) fail("the canvas is " + box.width + " wide, not the window's " + box.inner);
+ out.keybar = "ok";
+
+ // --- (b) a tap in the terminal: the wasm's own press takes it over, and
+ // the page asks for the soft keyboard.
+ const l = await until("a laid-out tab", async () => { const v = await layout(); return v.panes && v.panes.length === 1 ? v : null; });
+ const pane = l.panes[0].id;
+ // The grid starts a cell in from the left and half a cell down (App::pad);
+ // a few rows below the pane's own bar, mid-pane.
+ const point = await ev(`(() => { const r = document.getElementById('term').getBoundingClientRect();
+ const l = JSON.parse(document.getElementById('term').dataset.layout); const p = l.panes[0];
+ return [r.left + l.cell[0] * (1 + p.left + Math.floor(p.cols / 2)), r.top + l.cell[1] * (0.5 + p.top + 5)]; })()`);
+ await ev("document.getElementById('kbd').blur()");
+ await tap(point[0], point[1]);
+ await sleep(500);
+ if (!/this browser has/.test(await summary())) fail("the tap did not take the terminal over: " + (await summary()));
+ if (!(await ev("document.activeElement?.id === 'kbd'"))) fail("the tap did not ask for the soft keyboard: " + (await ev("document.activeElement?.id || document.activeElement?.tagName")));
+ out.tap = "ok";
+
+ // --- (c) a key from the bar reaches the pane.
+ const before = lastLine(pane);
+ await tapOn('#keybar .k[data-key="-"]');
+ await until("the dash in the pane", async () => lastLine(pane).endsWith("-"), 3000);
+ out.key = "ok";
+
+ // A soft keyboard's own keys still go through the wasm's field.
+ await typeKey("l"); await typeKey("s");
+ await until("what was typed", async () => /-ls/.test(text(pane)), 3000);
+ out.typed = "ok";
+
+ // --- (d) Ctrl is sticky: one tap arms it, the next key on #kbd spends it,
+ // and the pane gets Ctrl+C rather than a plain c.
+ await tapOn('#keybar .k[data-key="Control"]');
+ await sleep(120);
+ if (!(await ev(`!!document.querySelector('#keybar .k[data-key="Control"].armed')`))) fail("Ctrl did not arm");
+ await typeKey("c");
+ await sleep(200);
+ if (await ev(`!!document.querySelector('#keybar .k[data-key="Control"].armed')`)) fail("Ctrl stayed armed after the key that spent it");
+ const after = await until("the interrupt", async () => { const line = lastLine(pane); return line !== before + "-ls" || /\^C/.test(text(pane)) ? line : null; }, 4000);
+ if (after.endsWith("c")) fail("a plain c was typed: " + JSON.stringify(after));
+ if (/-ls$/.test(after)) fail("the interrupt never reached the pane: " + JSON.stringify(after));
+ out.ctrl = "ok";
+
+ // --- (e) a drag scrolls. The wasm publishes no viewport offset, so what
+ // is checked here is the page's side of it: the wheel notches it hands
+ // over, and that the wasm never saw the drag as a selection or a click in
+ // another cell (its focus, and the pane's text, are where they were).
+ sh(`printf 'seq 1 200\\n' | ${cli} send-text --pane-id ${pane} --no-paste`);
+ await sleep(1200);
+ const settled = text(pane);
+ const focused = (await layout()).focused;
+ await ev("window.__wheels = 0; document.getElementById('term').addEventListener('wheel', () => { window.__wheels++; }, true);");
+ await touch("touchStart", [at(point[0], point[1])]);
+ for (let dy = 10; dy <= 200; dy += 10) { await touch("touchMove", [at(point[0], point[1] - dy)]); await sleep(16); }
+ await touch("touchEnd", []);
+ await sleep(400);
+ out.wheels = await ev("window.__wheels");
+ if ((await layout()).focused !== focused) fail("the drag moved the focus");
+ if (text(pane) !== settled) fail("the drag typed into the pane");
+ // The offset the wasm scrolled to is not in the layout it publishes, so
+ // the scroll itself cannot be read back from the page.
+ out.scroll = out.wheels > 0 ? "skipped" : "no wheels";
+ if (!(out.wheels > 0)) fail("the drag handed over no wheel notches");
+
+ // --- (f) the drawer: a swipe in from the left edge brings it out, the
+ // backdrop puts it away.
+ await touch("touchStart", [at(4, 420)]);
+ for (const x of [30, 70, 110, 160, 210]) { await touch("touchMove", [at(x, 420)]); await sleep(24); }
+ await touch("touchEnd", []);
+ await until("the drawer out", () => ev("!!document.querySelector('#side.open')"), 3000);
+ const drawer = await ev("(() => { const r = document.getElementById('side').getBoundingClientRect(); return { w: r.width, top: r.top, bottom: r.bottom }; })()");
+ if (!(drawer.w > 0 && drawer.w <= 300)) fail("the drawer is " + drawer.w + " wide");
+ if (!(await ev("!!document.getElementById('scrim')"))) fail("no backdrop behind the drawer");
+ await tap(360, 420);
+ await until("the drawer away", () => ev("!document.querySelector('#side.open')"), 3000);
+ if (await ev("!!document.getElementById('scrim')")) fail("the backdrop outlived the drawer");
+ out.drawer = "ok";
+
+ // --- (g) a long press on the canvas is the pane's menu.
+ await touch("touchStart", [at(point[0], point[1])]);
+ await sleep(700);
+ await touch("touchEnd", []);
+ await until("the pane's menu", () => ev("!!document.getElementById('menu')"), 3000);
+ const labels = await ev("Array.from(document.querySelectorAll('.menu .mi .lb')).map((e) => e.textContent)");
+ if (labels[0] !== "Copy") fail("the long press opened " + JSON.stringify(labels));
+ const row = await ev("(() => { const r = document.querySelector('.menu .mi').getBoundingClientRect(); return r.height; })()");
+ if (Math.abs(row - 40) > 1) fail("a menu row is " + row + " tall, not the 40 a finger needs");
+ out.longpress = "ok";
+
+ const shot = await send("Page.captureScreenshot", { format: "png" }, s); fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));
+ out.logs = logs.filter((x) => !/^\s*$/.test(x) && !/INFO/.test(x)).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/mobile.sh b/thinkterm-web/smoke/mobile.sh
new file mode 100755
index 00000000..1e4d8fb7
--- /dev/null
+++ b/thinkterm-web/smoke/mobile.sh
@@ -0,0 +1,40 @@
+#!/bin/sh
+# The phone shape, end to end: a release server with an empty tree under a
+# throwaway HOME, the release bundle, headless Chrome emulating a 390x844
+# phone with touch, and a finger driving the page -- the key bar, the taps
+# and drags on the canvas, the drawer's swipe and the long press.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/mobile.sh [out.png]
+#
+# Prints the JSON mobile-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18103
+OUT=${1:-/tmp/thinkterm-mobile.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-mobile.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"
+# Nothing is spawned here: the page makes its own tab when it attaches to an
+# empty server, so the window it shows has exactly one pane to type into.
+URL=$($CLI web-token mint --label mobile --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/mobile-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/palette-test.js b/thinkterm-web/smoke/palette-test.js
new file mode 100644
index 00000000..04d1407d
--- /dev/null
+++ b/thinkterm-web/smoke/palette-test.js
@@ -0,0 +1,114 @@
+// The search palette end to end, against a throwaway server: the shortcut
+// opens it with the keyboard in its field, a typed name finds the thread it
+// names, Escape hands the keyboard back to the terminal, a command really
+// splits the page's tab, and a `?lang=` load is in that language.
+// node palette-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); }, 150000).unref();
+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-palette-`);
+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 layout = async () => JSON.parse(await ev("document.getElementById('term').dataset.layout || '{}'"));
+ const until = async (what, fn, ms = 12000) => { 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 + ": palette=" + JSON.stringify(await picks()) + " status=" + (await ev("document.getElementById('status').textContent")) + " logs=" + JSON.stringify(logs.slice(-6))); };
+ const click = (sel) => ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; el.click(); return true; })()`);
+ const list = () => JSON.parse(sh(`${cli} list --format json`));
+ const fail = (what) => { throw new Error(what); };
+ const open = () => ev("!!document.getElementById('palette')");
+ // Every entry on show, in the order the arrows walk them.
+ const picks = () => ev("Array.from(document.querySelectorAll('#palette .pe')).map((e) => [e.dataset.id, e.querySelector('.t').textContent])");
+ const key = async (k, code, vk, modifiers = 0) => {
+ await send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, modifiers }, s);
+ await send("Input.dispatchKeyEvent", { type: "keyUp", key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, modifiers }, s);
+ };
+ // The default shortcut is Cmd+K on a Mac and Ctrl+K everywhere else, which
+ // is exactly what the page decides from the platform.
+ const HOTKEY = process.platform === "darwin" ? 4 : 2;
+ const hotkey = () => key("k", "KeyK", 75, HOTKEY);
+ // Typed the way the field sees it: the palette re-ranks on every input.
+ const type = (text) => ev(`(() => { const q = document.querySelector('#palette .q'); if (!q) return false;
+ q.value = ${JSON.stringify(text)}; q.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
+ 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(900);
+
+ // --- two threads to find: the server's landing one, named "main", and a
+ // second so the ranking has something to beat.
+ await click("[data-action=new-thread]");
+ const landing = await until("the landing thread", async () => (await threads()).find((t) => t.selected), 15000);
+ if (landing.name !== "main") fail("the landing thread is named " + JSON.stringify(landing.name));
+ await click("[data-action=new-thread]");
+ await until("a second thread", async () => (await threads()).length === 2, 15000);
+
+ // --- (a) the shortcut opens it, with the keyboard in its field.
+ await hotkey();
+ await until("the palette", open);
+ if (!(await ev("document.activeElement === document.querySelector('#palette .q')"))) {
+ fail("the field did not take the keyboard: " + (await ev("document.activeElement.id || document.activeElement.className")));
+ }
+ out.open = "ok";
+
+ // --- (b) a typed name finds the thread it names, first of all.
+ await type("mai");
+ const ranked = await until("a ranked list", async () => { const p = await picks(); return p.length > 0 ? p : null; });
+ out.first = ranked[0];
+ if (ranked[0][0] !== `thread:${landing.id}` || ranked[0][1] !== "main") fail("the first entry is " + JSON.stringify(ranked.slice(0, 3)));
+ out.rank = "ok";
+
+ // --- (c) Escape closes it and the terminal has the keyboard again.
+ await key("Escape", "Escape", 27);
+ await until("the palette is gone", async () => !(await open()));
+ if (!(await ev("document.activeElement.id === 'kbd'"))) fail("the keyboard did not go back to the terminal: " + (await ev("document.activeElement.id || document.activeElement.className")));
+ out.escape = "ok";
+
+ // --- (d) a command really acts: Split Right splits the page's tab.
+ const tab = (await layout()).tab;
+ const before = list().filter((p) => p.tab_id === tab).length;
+ await hotkey();
+ await until("the palette", open);
+ await type("split");
+ const commands = await until("a ranked list", async () => { const p = await picks(); return p.length > 0 ? p : null; });
+ if (!/^cmd:split-right/.test(commands[0][0])) fail("the first entry is " + JSON.stringify(commands.slice(0, 3)));
+ await key("Enter", "Enter", 13);
+ await until("the palette is gone", async () => !(await open()));
+ await sleep(1500);
+ const panes = list().filter((p) => p.tab_id === tab);
+ if (before !== 1 || panes.length !== 2) fail(`tab ${tab} went from ${before} to ${panes.length} panes`);
+ out.command = "ok";
+
+ const shot = await send("Page.captureScreenshot", { format: "png" }, s); fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));
+
+ // --- (e) a `?lang=` load is in that language, the palette included.
+ await send("Page.navigate", { url: url.replace("#", "?lang=de-DE#") }, s);
+ out.placeholder = await until("the German palette", async () => {
+ const raw = await ev("window.thinkterm && window.thinkterm.client ? window.thinkterm.client.palette('') : ''");
+ return raw ? JSON.parse(raw).placeholder : null;
+ }, 25000);
+ if (out.placeholder !== "Befehle suchen…") fail("the placeholder is " + JSON.stringify(out.placeholder));
+ out.german = "ok";
+
+ 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/palette.sh b/thinkterm-web/smoke/palette.sh
new file mode 100755
index 00000000..dc199ca2
--- /dev/null
+++ b/thinkterm-web/smoke/palette.sh
@@ -0,0 +1,39 @@
+#!/bin/sh
+# The search palette, end to end: a release server with an empty tree under
+# a throwaway HOME, the release bundle, headless Chrome, the shortcut, the
+# ranking, and a command that really splits.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/palette.sh [out.png]
+#
+# Prints the JSON palette-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18097
+OUT=${1:-/tmp/thinkterm-palette.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-palette.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"
+# Nothing is spawned here: the page makes its own tab when it attaches to
+# an empty server, so the tab a palette command acts on is that one.
+URL=$($CLI web-token mint --label palette --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/palette-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/settings-test.js b/thinkterm-web/smoke/settings-test.js
new file mode 100644
index 00000000..3137409f
--- /dev/null
+++ b/thinkterm-web/smoke/settings-test.js
@@ -0,0 +1,91 @@
+// The settings panel end to end, against a throwaway server: the gear opens
+// it, a fixed size really rasterises the grid at that size, "Follow the
+// desktop" comes back to the size it was, the light theme is painted, and a
+// reload opens on what was chosen.
+// node settings-test.js <url> <cli prefix> <out.png>
+const { spawn } = require("child_process");
+const http = require("http"); const fs = require("fs"); const os = require("os");
+const WebSocket = require("ws");
+const [url, , 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); }, 150000).unref();
+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-settings-`);
+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"); }
+(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 layout = async () => JSON.parse(await ev("document.getElementById('term').dataset.layout || '{}'"));
+ const settings = async () => JSON.parse(await ev("window.thinkterm && window.thinkterm.client ? window.thinkterm.client.settings() : '{}'"));
+ const until = async (what, fn, ms = 12000) => { 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 + ": settings=" + JSON.stringify(await settings()) + " layout=" + JSON.stringify(await layout())); };
+ const click = (sel) => ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; el.click(); return true; })()`);
+ const fail = (what) => { throw new Error(what); };
+ const attached = async () => /this browser has|mirroring|following/.test(await ev("document.getElementById('status').dataset.summary || ''"));
+ const fontPt = async () => (await layout()).font_pt;
+ // The number field commits on change, as it does when the pointer leaves it.
+ const setSize = (pt) => ev(`(() => { const n = document.querySelector('#settings .num'); if (!n || n.disabled) return false;
+ n.value = ${JSON.stringify(String(pt))}; n.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`);
+ const openPanel = async () => {
+ if (!(await click("#side [data-action=settings]"))) fail("no gear in the sidebar footer");
+ await until("the settings panel", () => ev("!!document.getElementById('settings')"));
+ };
+ const out = {};
+
+ await send("Page.navigate", { url }, s);
+ await until("attach", attached, 20000);
+ await sleep(900);
+ const before = await until("a laid-out tab", async () => (await fontPt()) || null);
+ out.font_at_start = before;
+
+ // --- (a) a fixed size really rasterises the grid at that size.
+ await openPanel();
+ await click("#settings [data-section=appearance]");
+ if (!(await click("#settings input[data-font=pinned]"))) fail("no fixed-size choice");
+ if (!(await setSize(14))) fail("the size field is not there or still disabled");
+ await until("the grid at 14 pt", async () => (await fontPt()) === 14);
+ out.pin = "ok";
+
+ // --- (b) "Follow the desktop" comes back to the size it was.
+ if (!(await click("#settings input[data-font=follow]"))) fail("no follow choice");
+ await until(`the grid back at ${before} pt`, async () => (await fontPt()) === before);
+ out.follow = "ok";
+
+ // --- (c) the light theme is the page's to paint.
+ if (!(await ev("(() => { const sel = document.querySelector('#settings select[data-setting=theme]'); if (!sel) return false; sel.value = 'light'; sel.dispatchEvent(new Event('change', { bubbles: true })); return true; })()"))) fail("no theme choice");
+ await until("the light theme", () => ev("document.documentElement.dataset.theme === 'light'"));
+ out.theme = "ok";
+
+ // --- (d) what was chosen survives a reload.
+ await click("#settings [data-section=appearance]");
+ if (!(await click("#settings input[data-font=pinned]"))) fail("no fixed-size choice");
+ if (!(await setSize(14))) fail("the size field is not there or still disabled");
+ await until("the grid at 14 pt again", async () => (await fontPt()) === 14);
+ const shot = await send("Page.captureScreenshot", { format: "png" }, s); fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));
+
+ // A real reload, not a jump to the same address with the token back in
+ // the fragment, which the browser would not reload for at all. The token
+ // is in this tab's session storage by now, so the address is enough.
+ await ev("window.__before = 1");
+ await send("Page.reload", { ignoreCache: true }, s);
+ await until("a fresh document", () => ev("window.__before === undefined"), 20000);
+ await until("attach again", attached, 20000);
+ await until("the stored theme", () => ev("document.documentElement.dataset.theme === 'light'"));
+ await until("the stored size", async () => (await fontPt()) === 14);
+ if (await ev("!!document.getElementById('settings')")) fail("the panel came back up on its own");
+ out.stored = await settings();
+ out.persist = "ok";
+
+ 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/settings.sh b/thinkterm-web/smoke/settings.sh
new file mode 100755
index 00000000..8ae4f62b
--- /dev/null
+++ b/thinkterm-web/smoke/settings.sh
@@ -0,0 +1,42 @@
+#!/bin/sh
+# The settings panel, end to end: a release server with an empty tree under
+# a throwaway HOME, the release bundle, headless Chrome, pinning the font,
+# following the desktop again, the light theme, and a reload that keeps
+# what was chosen.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/settings.sh [out.png]
+#
+# Prints the JSON settings-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18099
+OUT=${1:-/tmp/thinkterm-settings.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-settings.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"
+# Nothing is spawned here: the page makes its own tab when it attaches to
+# an empty server. There is no desktop to follow, so the size the page
+# lands on is what "Follow the desktop" has to come back to; the test reads
+# it rather than assuming one.
+URL=$($CLI web-token mint --label settings --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/settings-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/sidebar-drag-test.js b/thinkterm-web/smoke/sidebar-drag-test.js
new file mode 100644
index 00000000..c55c2d73
--- /dev/null
+++ b/thinkterm-web/smoke/sidebar-drag-test.js
@@ -0,0 +1,144 @@
+// The sidebar's page-side behaviours, which the end-to-end sidebar test
+// cannot see: the inline name field survives the re-listings that arrive
+// while it is being typed into, dragging the panel's edge does not resize
+// the terminal on every frame, and a put-away panel comes back on hover as
+// an overlay that resizes nothing.
+// node sidebar-drag-test.js <url> <out.png>
+const { spawn } = require("child_process");
+const http = require("http"); const fs = require("fs"); const os = require("os");
+const WebSocket = require("ws");
+const [url, 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-drag-`);
+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"); }
+(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 = 15000) => { 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())); };
+ 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 key = async (k, code, vk) => { await send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }, s); await send("Input.dispatchKeyEvent", { type: "keyUp", key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }, s); };
+ const type = async (text) => { for (const c of text) { await send("Input.dispatchKeyEvent", { type: "keyDown", text: c, key: c, code: "Key" + c.toUpperCase(), windowsVirtualKeyCode: c.toUpperCase().charCodeAt(0) }, s); await send("Input.dispatchKeyEvent", { type: "keyUp", key: c, code: "Key" + c.toUpperCase(), windowsVirtualKeyCode: c.toUpperCase().charCodeAt(0) }, s); await sleep(60); } };
+ const mouse = (type, x, y, extra = {}) => send("Input.dispatchMouseEvent", { type, x, y, button: "left", clickCount: 1, ...extra }, s);
+ 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);
+
+ // --- (a) the field being typed into survives the panel's re-listings.
+ await click("[data-action=new-thread]");
+ const thread = await until("landing thread on show", async () => (await threads()).find((t) => t.selected));
+ await dblclick(`[data-action=rename-thread][data-thread="${thread.id}"]`);
+ await until("rename field", () => ev("!!document.querySelector('#side input.rename')"));
+ // A mark on the element itself: a field that was thrown away and made
+ // again during the typing comes back without it.
+ await ev("document.querySelector('#side input.rename').dataset.probe = 'same'");
+ if (!(await ev("document.activeElement === document.querySelector('#side input.rename')"))) fail("the rename field did not take focus");
+ await type("abc");
+ out.typing = await ev(`(() => { const a = document.activeElement; const i = document.querySelector('#side input.rename');
+ return { same_element: a === i, kept_mark: a?.dataset?.probe === 'same', value: a?.value, listings: JSON.parse(document.getElementById('side').dataset.rows).length }; })()`);
+ // select() ran when the field appeared, so the first character replaced
+ // the whole name rather than being appended to it.
+ if (!out.typing.same_element || !out.typing.kept_mark) fail("the rename field was re-mounted while it was typed into: " + JSON.stringify(out.typing));
+ if (out.typing.value !== "abc") fail("what was typed did not survive: " + JSON.stringify(out.typing));
+ out.typing = "ok";
+
+ // Escape drops it: the name is the one the server has.
+ await key("Escape", "Escape", 27);
+ await until("field gone", () => ev("!document.querySelector('#side input.rename')"));
+ if ((await threads()).find((t) => t.id === thread.id)?.name !== thread.name) fail("Escape renamed the thread anyway");
+ out.escape = "ok";
+
+ // --- (b) the edge drags without resizing the terminal on every frame.
+ if ((await ev("getComputedStyle(document.documentElement).getPropertyValue('--side-w').trim()")) !== "220px") fail("the panel did not start at its default width");
+ // The panel clips what overflows it, so only the part of the 4px handle
+ // inside the panel's padding box can be pressed: at a width of 220 that
+ // is 217..219, the 1px border taking the last pixel. The press lands on
+ // the last column of what is left.
+ const grab = await ev(`(() => { const h = document.querySelector('#side .handle'); const side = document.getElementById('side');
+ const clip = side.getBoundingClientRect().left + side.clientWidth;
+ const x = Math.floor(Math.min(h.getBoundingClientRect().right, clip)) - 1;
+ const el = document.elementFromPoint(x, 400);
+ return { x, on: el ? (el.className || el.id || el.tagName) : null }; })()`);
+ if (grab.on !== "handle") fail(`${grab.x},400 is not the handle but ` + JSON.stringify(grab.on));
+ // Every change of the canvas's backing store, which is what one terminal
+ // resize costs; the count is read before the release and after it.
+ await ev(`(() => { const c = document.querySelector('canvas#term'); window.__resizes = 0; window.__last = c.width;
+ new MutationObserver(() => { if (c.width !== window.__last) { window.__last = c.width; window.__resizes++; } }).observe(c, { attributes: true, attributeFilter: ['width'] });
+ return c.width; })()`);
+ await mouse("mousePressed", grab.x, 400, { buttons: 1 });
+ for (let x = 215; x >= 180; x -= 5) { await mouse("mouseMoved", x, 400, { buttons: 1 }); await sleep(70); }
+ await sleep(300);
+ out.resizes_during_drag = await ev("window.__resizes");
+ const midWidth = await ev("getComputedStyle(document.documentElement).getPropertyValue('--side-w').trim()");
+ await mouse("mouseReleased", 180, 400, { buttons: 0 });
+ await sleep(900);
+ out.resizes_after_release = (await ev("window.__resizes")) - out.resizes_during_drag;
+ out.side_w = await ev("getComputedStyle(document.documentElement).getPropertyValue('--side-w').trim()");
+ out.stored = await ev("localStorage.getItem('thinkterm.sidebar')");
+ if (midWidth !== "180px") fail("the panel did not follow the pointer: " + midWidth);
+ if (out.resizes_during_drag !== 0) fail("the terminal was resized " + out.resizes_during_drag + " times during the drag");
+ if (out.resizes_after_release !== 1) fail("the release should resize the terminal exactly once, not " + out.resizes_after_release);
+ if (out.side_w !== "180px") fail("the width ended at " + out.side_w);
+ if (out.stored !== "180") fail("the width stored is " + JSON.stringify(out.stored));
+ out.drag = "ok";
+
+ // --- (c) the collapsed panel comes back on hover, over the canvas.
+ if (!(await click("#tabs [data-action=sidebar]"))) fail("no sidebar toggle in the tab row");
+ await until("the panel put away", () => ev("document.body.dataset.side === 'off'"));
+ await sleep(600);
+ const bare = await ev("document.querySelector('canvas#term').getBoundingClientRect().width");
+ const revealed = () => ev("!!document.querySelector('#side.revealed')");
+ const canvas = () => ev("document.querySelector('canvas#term').getBoundingClientRect().width");
+ const centre = await ev("Math.round(window.innerWidth / 2)");
+
+ // The window's left edge: 150 ms of the pointer resting there.
+ await mouse("mouseMoved", 2, 400, { button: "none", buttons: 0 });
+ await sleep(300);
+ if (!(await revealed())) fail("the left edge did not bring the panel back");
+ if (Math.abs((await canvas()) - bare) > 0.5) fail("the reveal resized the terminal: " + (await canvas()) + " vs " + bare);
+ // The layout's width is the one the body carries while the panel is put
+ // away; the root keeps the width the reveal paints at.
+ if ((await ev("getComputedStyle(document.body).getPropertyValue('--side-w').trim()")) !== "0px") fail("the reveal moved the layout's width");
+ out.reveal_width = await ev("document.getElementById('side').getBoundingClientRect().width");
+ if (out.reveal_width <= 0) fail("the revealed panel has no width");
+
+ // Away from it, and it retreats 250 ms later.
+ await mouse("mouseMoved", centre, 400, { button: "none", buttons: 0 });
+ await sleep(400);
+ if (await revealed()) fail("the panel stayed out after the pointer left it");
+
+ // The toggle itself is the other trigger.
+ const toggle = await ev(`(() => { const r = document.querySelector('#tabs [data-action=sidebar]').getBoundingClientRect();
+ return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) }; })()`);
+ await mouse("mouseMoved", toggle.x, toggle.y, { button: "none", buttons: 0 });
+ await sleep(300);
+ if (!(await revealed())) fail("hovering the toggle did not bring the panel back");
+
+ // Pressing it pins the panel open the ordinary way, and the reveal is over.
+ await click("#tabs [data-action=sidebar]");
+ await until("the panel pinned open", () => ev("document.body.dataset.side !== 'off'"));
+ if (await revealed()) fail("the reveal outlived the press that pinned the panel open");
+ out.hover = "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-drag.sh b/thinkterm-web/smoke/sidebar-drag.sh
new file mode 100755
index 00000000..e056e9c3
--- /dev/null
+++ b/thinkterm-web/smoke/sidebar-drag.sh
@@ -0,0 +1,38 @@
+#!/bin/sh
+# The sidebar's page-side behaviour, end to end: the inline name field
+# survives the panel's re-listings, and dragging its edge resizes the
+# terminal once, on release, instead of on every frame.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/sidebar-drag.sh [out.png]
+#
+# Prints the JSON sidebar-drag-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18093
+OUT=${1:-/tmp/thinkterm-sidebar-drag.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-drag.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-drag --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME node "$REPO/thinkterm-web/smoke/sidebar-drag-test.js" "$URL" "$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/sidebar-test.js b/thinkterm-web/smoke/sidebar-test.js
index 1a2a0871..4a0ab05d 100644
--- a/thinkterm-web/smoke/sidebar-test.js
+++ b/thinkterm-web/smoke/sidebar-test.js
@@ -1,7 +1,8 @@
// 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.
+// spawns there, archiving the last project is refused with a remark, and a
+// second Space is made, renamed and still on show after a reload.
// 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");
@@ -85,6 +86,48 @@ const sh = (cmd) => execSync(cmd, { encoding: "utf8" });
await until("refusal shown", () => ev("/last project/.test(document.getElementById('status').textContent) && !document.getElementById('status').hasAttribute('hidden')"), 10000);
out.archive = "ok";
+ // --- Spaces: the row's menu makes one, renames it, and the page opens
+ // on the one it was showing.
+ const menu = () => ev("Array.from(document.querySelectorAll('.menu .mi')).map((e) => e.dataset.id)");
+ const space = async () => (await rows())[0];
+ const openSpaceMenu = async () => {
+ if (!(await click("#side [data-action=space-menu]"))) fail("no Space menu button");
+ await until("the Space menu", () => ev("!!document.getElementById('menu')"));
+ return menu();
+ };
+ let ids = await openSpaceMenu();
+ out.space_menu = ids;
+ if (!ids.includes("new-space")) fail("the Space menu is " + JSON.stringify(ids));
+ if (ids.some((i) => /^delete-space:/.test(i))) fail("the last Space can be deleted: " + JSON.stringify(ids));
+ const landed = await space();
+ if (landed.kind !== "space") fail("the first row is " + JSON.stringify(landed));
+ if (!(await click('[data-id="new-space"]'))) fail("no New Space row");
+ const made = await until("a second Space on show", async () => {
+ const row = await space();
+ return row.kind === "space" && row.id !== landed.id ? row : null;
+ }, 15000);
+ if (made.name !== "Space 2") fail("the new Space is named " + JSON.stringify(made.name));
+ ids = await openSpaceMenu();
+ if (!ids.some((i) => /^delete-space:/.test(i))) fail("a Space of two cannot be deleted: " + JSON.stringify(ids));
+ if (!(await click('[data-id^="rename-space:"]'))) fail("no Rename row");
+ await until("the Space's rename field", () => ev("!!document.querySelector('#side .row.space input.rename')"));
+ await typeInto("Work");
+ await until("renamed", async () => (await space()).name === "Work");
+
+ // A real reload, not a jump to the same address with the token back in
+ // the fragment, which the browser would not reload for at all. The token
+ // is in this tab's session storage by now, so the address is enough.
+ await ev("window.__landed = 1");
+ await send("Page.reload", { ignoreCache: true }, s);
+ await until("a fresh document", () => ev("window.__landed === undefined"), 20000);
+ await until("attach again", async () => /this browser has|mirroring|following/.test(await ev("document.getElementById('status').dataset.summary || ''")), 20000);
+ const reopened = await until("the same Space on show", async () => {
+ const row = await space();
+ return row && row.kind === "space" && row.id === made.id ? row : null;
+ }, 20000);
+ if (reopened.name !== "Work") fail("the Space came back as " + JSON.stringify(reopened.name));
+ out.space = "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));