A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(web): show plugin panels in the browser
RoversXf855fcdf5adb
diff --git a/Cargo.lock b/Cargo.lockindex 70b27cc6..fe9a3975 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8815,6 +8815,7 @@ dependencies = ["js-sys","log","nucleo-matcher",+ "percent-encoding","serde","serde_json","termwiz 0.24.0",@@ -8822,6 +8823,7 @@ dependencies = ["thinkterm-font-web","thinkterm-i18n","thinkterm-plugin-channel",+ "thinkterm-plugin-panel","thinkterm-proto","thinkterm-render","thinkterm-session",diff --git a/thinkterm-web/Cargo.toml b/thinkterm-web/Cargo.tomlindex f7fe4d02..c4bf2c88 100644--- a/thinkterm-web/Cargo.toml+++ b/thinkterm-web/Cargo.toml@@ -22,6 +22,7 @@ euclid.workspace = truefutures.workspace = truelog.workspace = truenucleo-matcher.workspace = true+percent-encoding.workspace = trueserde.workspace = trueserde_json.workspace = truetermwiz = { workspace = true, features = ["use_serde"] }@@ -29,6 +30,7 @@ thinkterm-font-core.workspace = truethinkterm-font-web.workspace = truethinkterm-i18n.workspace = truethinkterm-plugin-channel.workspace = true+thinkterm-plugin-panel.workspace = truethinkterm-proto.workspace = truethinkterm-render = { workspace = true, features = ["wgpu"] }thinkterm-session.workspace = truediff --git a/thinkterm-web/smoke/panels-test.js b/thinkterm-web/smoke/panels-test.jsnew file mode 100644index 00000000..4a807b9c--- /dev/null+++ b/thinkterm-web/smoke/panels-test.js@@ -0,0 +1,280 @@+// A plugin's panel in a browser, against a throwaway server with the diff+// plugin installed and its terminal in a repository made for the test: the+// right panel's selector offers the plugin's panel; the page paints the+// repository's changed files; the pointer tints a file's row, rounded; a+// click on a file reaches the plugin, which asks for its extended view,+// and the page opens it left of the panel, the terminal making room, and+// paints the file's lines there; the wheel scrolls its ten thousand+// changed lines at once and the rows that come into view are asked for and+// painted, and a finger drags them too; a wide line scrolls sideways under+// still line numbers; the extended view's edge sizes it, kept for the+// plugin; ThinkTerm's close button at its top left closes it, and the+// plugin puts the file down; the panel goes with its tab, the plugin told;+// and on a phone, the panel a drawer with no room beside it, a tap picks a+// file whose lines the panel shows itself, and a finger scrolls them.+// node panels-test.js <url> <out.png> (and <out>-phone.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, 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-panels-`);+const chrome = spawn(chromePath, ["--headless=new", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=1400,900", "--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 pids = (pattern) => { try { return execSync(`pgrep -f ${JSON.stringify(pattern)}`).toString().trim().split(/\s+/).filter(Boolean); } catch { return []; } };+// This server's copy of the plugin, not any other running on the machine.+const plugin = `${process.env.PLUGINS_DATA}/plugins/diff/thinkterm-plugin-diff`;++(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: "none", ...extra }, s);+ const fail = (what) => { throw new Error(what); };+ const attached = async () => /this browser has/.test(await ev("document.getElementById('status').dataset.summary || ''"));+ // What the panel, or its extended view, paints, as the wasm hands it to+ // the canvas.+ const panel = async (extended = false) => JSON.parse((await ev(`window.thinkterm.client.plugin_panel(${extended})`)) || "null");+ const beside = () => panel(true);+ const texts = (view) => (view?.painting?.ops ?? []).filter((op) => op.op === "text").map((op) => op.text);+ const textOp = (view, match) => (view?.painting?.ops ?? []).find((op) => op.op === "text" && match(op.text));+ const canvasOf = (extended) => extended ? "#extended .plugin canvas" : "#agents .plugin canvas";+ const box = (sel) => ev(`(() => { const e = document.querySelector(${JSON.stringify(sel)}); if (!e) return null; const r = e.getBoundingClientRect(); return { x: r.left, y: r.top, w: r.width, h: r.height }; })()`);+ // Where a text op is on the screen, from the canvas's corner.+ const where = async (text, extended = false) => {+ const op = textOp(await panel(extended), (t) => t === text);+ if (!op) return null;+ const at = await box(canvasOf(extended));+ return { x: at.x + op.x + 4, y: at.y + op.y + op.h / 2 };+ };+ const press = async (at) => {+ await mouse("mousePressed", at.x, at.y, { button: "left", clickCount: 1 });+ await mouse("mouseReleased", at.x, at.y, { button: "left", clickCount: 1 });+ };+ const out = {};++ await send("Page.navigate", { url }, s);+ await until("attach", attached, 20000);+ await sleep(600);++ // --- (a) The right panel, up, offers the plugin's panel under its name.+ 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=sidebar]");+ if (!(await click("#settings input[data-setting=agents-panel]"))) fail("no agents-panel switch");+ await click("#settings .sc");+ await until("the right panel", () => ev("!!document.getElementById('agents')"));+ await until("the plugin's tab", () => ev("!!document.querySelector('#agents .mode[data-mode=\"plugin:diff\"]')"));+ out.tab = await ev("document.querySelector('#agents .mode[data-mode=\"plugin:diff\"]').getAttribute('title')");+ if (out.tab !== "Diff") fail("the tab is not under the plugin's name: " + out.tab);+ if (pids(plugin).length) fail("the plugin runs before its panel is on show");++ // --- (b) Its tab paints the repository's changes, from the terminal's+ // directory: the page told the plugin where that is.+ await click("#agents .mode[data-mode=\"plugin:diff\"]");+ try {+ await until("the changes", async () => texts(await panel()).includes("README.md"), 20000);+ } catch (e) {+ fail(e.message + ": the panel says " + JSON.stringify(texts(await panel())));+ }+ const first = await panel();+ out.first = { state: first.state, ops: first.painting.ops.length, files: texts(first).filter((t) => /\.(md|txt)$/.test(t)) };+ for (const name of ["repo", "README.md", "big.txt", "wide.txt", "new.txt"]) {+ if (!texts(first).includes(name)) fail(`${name} is not shown: ` + texts(first).slice(0, 30));+ }+ if (!texts(first).some((t) => /^main · 4 changed files$/.test(t))) fail("no branch and count: " + texts(first).slice(0, 10));+ // With room beside it, the panel lists the files alone: nothing is+ // picked, and nothing is extended.+ if (texts(first).some((t) => /^\d+$/.test(t))) fail("lines in the panel before a file is picked");+ if (await ev("!!document.getElementById('extended')")) fail("an extended view before a file is picked");+ const pixels = await ev("(() => { const c = document.querySelector('#agents .plugin canvas'); const d = c.getContext('2d').getImageData(0, 0, c.width, c.height).data; let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i]) n++; return n; })()");+ if (!(pixels > 1000)) fail("the canvas is blank: " + pixels);+ out.painted_pixels = pixels;++ // --- (c) The pointer over a file tints its row at once, rounded like the+ // pick.+ const big = await where("big.txt");+ if (!big) fail("the rewritten file is not listed");+ await mouse("mouseMoved", big.x, big.y);+ const tint = await until("the hover", async () => (await panel()).painting.ops.find((op) => op.op === "rect" && op.fill === "bg-hover"));+ if (!(tint.radius > 0)) fail("the hover is square: " + JSON.stringify(tint));+ out.hover = { radius: tint.radius };++ // --- (d) A click reaches the plugin, which asks for its extended view:+ // the page opens it left of the panel, the terminal making room, and the+ // plugin shows the picked file there, its name large and its folder+ // below.+ const termBefore = (await box("#term")).w;+ await press(big);+ await until("the extended view", () => ev("!!document.getElementById('extended')"));+ await until("the picked file beside the panel", async () => {+ const shown = texts(await beside());+ return shown.includes("big.txt") && shown.includes("src");+ });+ const room = await box("#extended");+ const termAfter = (await box("#term")).w;+ if (Math.abs(room.w - 560) > 1) fail("the extended view is not as wide as it starts: " + room.w);+ if (Math.abs(termBefore - termAfter - room.w) > 2) fail(`the terminal made no room: ${termBefore} -> ${termAfter}`);+ if (texts(await panel()).some((t) => /^\d+$/.test(t))) fail("the lines are in the panel too");+ out.picked = { file: "src/big.txt", extended: room.w, terminal: [termBefore, termAfter] };++ // --- (e) The wheel scrolls its ten thousand changed lines at once, and+ // the rows that come into view are asked for and painted.+ const numbers = (view) => texts(view).filter((t) => /^\d+$/.test(t)).map(Number);+ await until("the first rows", async () => numbers(await beside()).length > 5);+ const before = Math.max(...numbers(await beside()));+ const diffArea = { x: room.x + room.w / 2, y: room.y + room.h - 60 };+ const started = Date.now();+ for (let i = 0; i < 20; i++) await send("Input.dispatchMouseEvent", { type: "mouseWheel", x: diffArea.x, y: diffArea.y, deltaX: 0, deltaY: 4000 }, s);+ await until("rows far down", async () => Math.max(...numbers(await beside()), 0) > before + 2000);+ out.scrolled = { before, after: Math.max(...numbers(await beside())), ms: Date.now() - started };++ // --- (e2) A finger drags the lines as the wheel does: up the glass is+ // down the file. Its pointer events are handed to the canvas from the+ // page: a browser with touch turned on is a phone to the page, which+ // shows no extended view.+ // The first line number on show, once there are lines on show.+ const topNumber = async () => {+ const shown = numbers(await beside());+ return shown.length > 0 ? Math.min(...shown) : null;+ };+ const beforeDrag = await until("lines on show", topNumber);+ await ev(`(() => {+ const canvas = document.querySelector('#extended .plugin canvas');+ const finger = (type, y) => canvas.dispatchEvent(new PointerEvent(type, {+ pointerId: 7, pointerType: 'touch', isPrimary: true, bubbles: true, clientX: ${diffArea.x}, clientY: y,+ }));+ finger('pointerdown', ${diffArea.y});+ for (let i = 1; i <= 10; i++) finger('pointermove', ${diffArea.y} - i * 30);+ finger('pointerup', ${diffArea.y} - 300);+ return true;+ })()`);+ await until("the finger to scroll the lines", async () => {+ const top = await topNumber();+ return top !== null && top > beforeDrag + 10;+ });+ out.touched = { from: beforeDrag, to: await topNumber() };++ // --- (f) A line wider than the extended view scrolls sideways; its+ // numbers stay.+ await press(await where("wide.txt"));+ const wideOp = (view) => textOp(view, (t) => t.startsWith("wide000"));+ await until("the wide line", async () => wideOp(await beside()));+ const numberOp = (view) => textOp(view, (t) => t === "2");+ const at = { wide: wideOp(await beside()).x, number: numberOp(await beside()).x };+ for (let i = 0; i < 4; i++) await send("Input.dispatchMouseEvent", { type: "mouseWheel", x: diffArea.x, y: diffArea.y, deltaX: 100, deltaY: 0 }, s);+ await until("the line to move", async () => (wideOp(await beside())?.x ?? at.wide) < at.wide - 300);+ const moved = await beside();+ if (numberOp(moved).x !== at.number) fail("the line numbers moved sideways too");+ const thumbAcross = moved.painting.ops.find((op) => op.op === "thumb" && op.w > op.h);+ if (!thumbAcross) fail("no thumb shows how far across");+ out.sideways = { line: [at.wide, wideOp(moved).x], number: at.number };++ await send("Page.captureScreenshot", { format: "png" }, s).then((r) => fs.writeFileSync(outPng, Buffer.from(r.data, "base64")));++ // --- (g) Its edge sizes it, within what the terminal leaves -- a fifth+ // of the window is the terminal's -- and the width is kept for the+ // plugin.+ const edge = { x: room.x + 1, y: room.y + room.h / 2 };+ await mouse("mousePressed", edge.x, edge.y, { button: "left", clickCount: 1 });+ for (let dx = 10; dx <= 30; dx += 10) await mouse("mouseMoved", edge.x - dx, edge.y, { button: "left", buttons: 1 });+ await mouse("mouseReleased", edge.x - 30, edge.y, { button: "left", clickCount: 1 });+ const wider = (await box("#extended")).w;+ if (Math.abs(wider - room.w - 30) > 2) fail("the edge did not size it: " + wider);+ await mouse("mousePressed", edge.x - 30, edge.y, { button: "left", clickCount: 1 });+ await mouse("mouseMoved", 0, edge.y, { button: "left", buttons: 1 });+ await mouse("mouseReleased", 0, edge.y, { button: "left", clickCount: 1 });+ const widest = (await box("#extended")).w;+ const terminal = (await box("#term")).w;+ if (terminal < 1400 / 5 - 2) fail(`the terminal was left ${terminal}`);+ // Back to the width it was.+ await mouse("mousePressed", room.x + room.w - widest + 1, edge.y, { button: "left", clickCount: 1 });+ await mouse("mouseMoved", edge.x - 30, edge.y, { button: "left", buttons: 1 });+ await mouse("mouseReleased", edge.x - 30, edge.y, { button: "left", clickCount: 1 });+ if (Math.abs((await box("#extended")).w - wider) > 2) fail("it did not come back: " + (await box("#extended")).w);+ const kept = JSON.parse((await ev("localStorage.getItem('thinkterm.plugin-extended-widths')")) || "{}");+ if (Math.abs((kept.diff ?? 0) - wider) > 1) fail("the width is not kept for the plugin: " + JSON.stringify(kept));+ await until("the view told its new width", async () => (await beside())?.painting?.clips?.some((c) => c[2] > room.w + 20));+ out.sized = { from: room.w, to: wider, widest, terminal, kept };++ // --- (h) ThinkTerm's close button, at its top left whatever the plugin+ // draws: the plugin keeps its header clear of it; pressed, the view goes,+ // the terminal taking its room back, and the plugin puts the file down.+ const button = await box("#extended .close");+ const canvas = await box(canvasOf(true));+ if (!button || button.x - room.x > 20 || button.y - room.y > 20) fail("no close button at the top left: " + JSON.stringify(button));+ const title = ((await beside())?.painting?.ops ?? []).find((op) => op.op === "text" && op.size === "title");+ if (!title || canvas.x + title.x < button.x + button.w) fail("the header is under the close button: " + JSON.stringify(title));+ if (texts(await beside()).includes("\u00d7")) fail("the plugin draws a close button of its own");+ await press({ x: button.x + button.w / 2, y: button.y + button.h / 2 });+ await until("the extended view to go", async () => !(await ev("!!document.getElementById('extended')")));+ await until("the terminal to take its room back", async () => Math.abs((await box("#term")).w - termBefore) < 2);+ if ((await beside()) !== null) fail("the extended view is still open");+ await until("the plugin to put the file down", async () => !(await ev("window.thinkterm.client.plugin_panel_extended()")));+ // Picked again, it comes back as wide as it was left.+ await press(await where("README.md"));+ await until("the extended view again", () => ev("!!document.getElementById('extended')"));+ const again = (await box("#extended")).w;+ if (Math.abs(again - wider) > 1) fail("not as wide as it was left: " + again);+ out.closed = { again };++ // --- (i) The panel goes with its tab, and its extended view with it:+ // the plugin is told.+ if (pids(plugin).length !== 1) fail("the plugin does not run while its panel is on show");+ await click("#agents .mode[data-mode=agents]");+ await until("the panel to go", async () => (await panel()) === null && (await beside()) === null);+ if (await ev("!!document.getElementById('extended')")) fail("the extended view stayed");+ out.gone = "ok";++ // --- (j) On a phone the right panel is a drawer with no room beside it,+ // and a finger is all there is: a tap picks a file, whose lines the panel+ // shows below the files, and a drag up the glass scrolls them.+ await send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 3, mobile: true }, s);+ await send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 1 }, s);+ await until("the phone shape", () => ev("document.body.dataset.mobile !== undefined"));+ await until("the drawer", () => ev("!!document.querySelector('#agents .mode[data-mode=\"plugin:diff\"]')"));+ await click("#agents .mode[data-mode=\"plugin:diff\"]");+ await until("the files in the drawer", async () => texts(await panel()).includes("big.txt"), 20000);+ const finger = (type, at) => send("Input.dispatchTouchEvent", { type, touchPoints: type === "touchEnd" ? [] : [{ x: at.x, y: at.y }] }, s);+ const tapAt = await where("big.txt");+ await finger("touchStart", tapAt);+ await finger("touchEnd", tapAt);+ await until("the picked file in the panel", async () => {+ const view = await panel();+ return texts(view).includes("src/big.txt") && numbers(view).length > 5;+ });+ if (await ev("!!document.getElementById('extended')")) fail("an extended view on a phone");+ const drawer = await box(canvasOf(false));+ const low = { x: drawer.x + drawer.w / 2, y: drawer.y + drawer.h - 80 };+ const topInPanel = async () => {+ const shown = numbers(await panel());+ return shown.length > 0 ? Math.min(...shown) : null;+ };+ const fromTop = await topInPanel();+ await finger("touchStart", low);+ for (let i = 1; i <= 10; i++) await finger("touchMove", { x: low.x, y: low.y - i * 30 });+ await finger("touchEnd", { x: low.x, y: low.y - 300 });+ await until("the finger to scroll the drawer's lines", async () => {+ const top = await topInPanel();+ return top !== null && top > fromTop + 10;+ });+ out.phone = { drawer: drawer.w, from: fromTop, to: await topInPanel() };+ await send("Page.captureScreenshot", { format: "png" }, s).then((r) => fs.writeFileSync(outPng.replace(/(\.png)?$/, "-phone.png"), Buffer.from(r.data, "base64")));++ const exceptions = logs.filter((l) => l.startsWith("EXCEPTION"));+ if (exceptions.length) fail("the page threw: " + exceptions.join("; "));+ console.log(JSON.stringify(out, null, 1));+ ws.close(); chrome.kill(); process.exit(0);+})().catch((e) => { console.error("FAIL", e.message); try { chrome.kill(); } catch {} process.exit(1); });diff --git a/thinkterm-web/smoke/panels.sh b/thinkterm-web/smoke/panels.shnew file mode 100755index 00000000..a346d88b--- /dev/null+++ b/thinkterm-web/smoke/panels.sh@@ -0,0 +1,80 @@+#!/bin/sh+# A plugin's panel in a browser, end to end: a release server under a+# throwaway HOME with the diff plugin installed, a terminal in a git+# repository made for the test, the release bundle and headless Chrome. The+# page offers the plugin's panel in the right panel's selector, paints the+# repository's changes, tints what the pointer is over with rounded+# corners, sends a click on a file to the plugin and opens the extended+# view it asks for, showing the file there, scrolls ten thousand changed+# lines by the wheel and by a finger, asking for the rows that come into+# view, scrolls a wide line sideways under its line numbers, sizes the+# extended view by its edge and closes it by its button, and lets the panel+# go with its tab; then, shaped as a phone, a tap picks a file in the+# drawer and a finger scrolls its lines there.+#+# cargo build --release -p wezterm-mux-server -p wezterm \+# -p thinkterm-plugin-server -p thinkterm-plugin-diff+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/panels.sh [out.png]+#+# Prints the JSON panels-test.js produces; exit status is the test's.+set -eu+cd "$(dirname "$0")/../.."+REPO=$PWD+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release+PORT=18105+OUT=${1:-/tmp/thinkterm-panels.png}+if lsof -nP -t -i :$PORT >/dev/null 2>&1; then echo "port $PORT busy" >&2; exit 1; fi+REAL_HOME=$HOME+# Short, under /tmp: the host's socket goes under this HOME, and a unix+# socket path is limited to 104 bytes.+T=$(mktemp -d /tmp/ttq.XXXXXX)+# However it ends, what runs under the throwaway HOME is stopped and the+# HOME removed: a server left behind holds the port for the next run.+cleanup() {+ for p in $(pgrep -f "$T/" || true); do kill "$p" 2>/dev/null || true; done+ sleep 0.5+ rm -rf "$T" 2>/dev/null || true+}+trap cleanup EXIT+trap 'exit 1' INT TERM+export HOME="$T/home"; mkdir -p "$HOME"+export THINKTERM_NO_PRIVACY_DISCLAIM=1+export THINKTERM_WEB_STATIC_DIR="$REPO/thinkterm-web/www"+DATA="$HOME/Library/Application Support/ThinkTerm"+[ "$(uname)" = Darwin ] || DATA="$HOME/.local/share/ThinkTerm"+mkdir -p "$DATA/plugins/diff"+cp "$REPO/plugins/diff/plugin.toml" "$BIN/thinkterm-plugin-diff" "$DATA/plugins/diff/"+# A repository with a commit and changes since: a file edited in two places,+# one of five thousand lines all rewritten -- ten thousand changed lines --+# one with a line far wider than the panel, and a new one.+FIX="$T/repo"+mkdir -p "$FIX/src"+g() {+ git -C "$FIX" -c user.name=example -c [email protected] \+ -c commit.gpgsign=false -c core.hooksPath=/dev/null "$@"+}+g init -q -b main+printf 'one\ntwo\nthree\nfour\nfive\n' > "$FIX/README.md"+seq 1 5000 | sed 's/^/line /' > "$FIX/src/big.txt"+printf 'short\n' > "$FIX/wide.txt"+g add .+g commit -q -m first+printf 'one\n2\nthree\nfour\nfive\nsix\n' > "$FIX/README.md"+seq 1 5000 | sed 's/^/row /' > "$FIX/src/big.txt"+{ printf 'short\n'; awk 'BEGIN { for (i = 0; i < 300; i++) printf "wide%03d ", i; print "" }'; } > "$FIX/wide.txt"+printf 'hello\n' > "$FIX/new.txt"+# The terminals start in it: the page shows the server's first.+cat > "$T/web.lua" <<LUA+return {+ web_servers = { { bind_address = "127.0.0.1:$PORT" } },+ default_cwd = "$FIX",+}+LUA+"$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+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 panels --ttl 1h --url-only 2>/dev/null | head -1)+status=0+HOME=$REAL_HOME PLUGINS_DATA="$DATA" node "$REPO/thinkterm-web/smoke/panels-test.js" "$URL" "$OUT" || status=$?+exit $statusdiff --git a/thinkterm-web/smoke/plugins-test.js b/thinkterm-web/smoke/plugins-test.jsindex 8e6605aa..01f07d17 100644--- a/thinkterm-web/smoke/plugins-test.js+++ b/thinkterm-web/smoke/plugins-test.js@@ -4,9 +4,10 @@// Snippets; nothing of a plugin shows outside the sidebar -- the palette// offers none of it, and calls made from the command line leave nothing on// the page; a plugin installed while the page is open is found-// when the settings open again; a plugin turned off stops, and Snippets-// turned off leaves the right panel; a reload stops the running plugin; and-// a plugin whose program is gone says why in its row.+// when the settings open again; a plugin turned off stops, one chosen to run+// always starts by itself, and Snippets turned off leaves the right panel; a+// reload stops the running plugin; and a plugin whose program is gone says+// why in its row.// node plugins-test.js <url> <out.png>// Reads TEST_HOME (the server's HOME), MUX_CLI (`thinkterm cli` pinned to// the server), PLUGIN_CLI (`thinkterm plugin` under that HOME) and@@ -139,6 +140,23 @@ const switches = () => { try { return fs.readFileSync(`${PLUGINS_DATA}/plugins.jawait until("the example on", async () => (await row("text-tools"))?.on === true);out.switch = "ok";+ // --- (c2) How long it runs unused: chosen here, kept on disk beside its+ // switch, and "always" has the server's machine keep it running -- the+ // mux, ThinkTerm there, keeps the plugin host up for it and it starts by+ // itself. The manifest's own choice again is no choice at all.+ const picker = '#settings select[data-plugin-background="text-tools"]';+ const choose = (value) => ev(`(() => { const select = document.querySelector('${picker}'); select.value = '${value}'; select.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`);+ const chosen = () => ev(`document.querySelector('${picker}')?.value ?? null`);+ await until("the background beside the switch", async () => (await chosen()) === "briefly");+ const always = () => { try { return fs.readFileSync(`${PLUGINS_DATA}/plugins-always`, "utf8"); } catch { return ""; } };+ if (always()) fail("a plugin runs always before any was chosen to: " + always());+ await choose("always");+ await until("always, on disk", async () => (await chosen()) === "always" && /"background": "always"/.test(switches()) && /text-tools/.test(always()));+ await until("it to start by itself", () => pids("thinkterm-plugin-example").length === 1, 30000);+ await choose("briefly");+ await until("the manifest's own again", async () => (await chosen()) === "briefly" && !/background/.test(switches()) && !always());+ out.background = "ok";+// --- (d) Snippets off takes its tab out of the right panel.await click("#settings .sc");if (!(await click("#tabs [data-action=agents]"))) fail("no right-panel button");diff --git a/thinkterm-web/src/agents.rs b/thinkterm-web/src/agents.rsindex 705a5be2..44ab7443 100644--- a/thinkterm-web/src/agents.rs+++ b/thinkterm-web/src/agents.rs@@ -25,13 +25,15 @@ pub struct AgentRow {}/// One tab of the right panel's selector, as the desktop lists them-/// (`RightSidebarMode::ALL`: Files, Notes, Code, Agents). Which exist and-/// which the browser can open is decided here, not in the display layer.+/// (`RightSidebarMode::ALL`: Files, Notes, Code, Agents, then the plugins'+/// panels). Which exist and which the browser can open is decided here,+/// not in the display layer.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct PanelTab {- pub id: &'static str,+ /// `snippets`, `agents`, or `plugin:` and the plugin's id.+ pub id: String,/// A lucide name, as the menus name theirs.- pub icon: &'static str,+ pub icon: String,pub label: String,/// Off for the panels whose APIs the browser has not got; the tip/// says so, and a press does nothing.@@ -45,15 +47,43 @@ pub struct AgentsView {pub summary: String,/// The selector above the panel, and which of its tabs is showing.pub tabs: Vec<PanelTab>,- pub active: &'static str,+ pub active: String,+ /// Whether the active tab carries its label ([`labeled`]).+ pub labeled: bool,+}++/// The most tabs the selector names the active one of: past this its label+/// has no room, and every tab is its icon alone, the active one told by its+/// pill -- as the desktop's selector does (`right_sidebar.rs`,+/// RIGHT_SIDEBAR_LABELED_MODES).+pub const LABELED_TABS: usize = 5;++/// Whether the selector over `tabs` names the active one.+pub fn labeled(tabs: &[PanelTab]) -> bool {+ tabs.len() <= LABELED_TABS+}++/// A panel a plugin adds, as the plugin list names it.+#[derive(Debug, Clone, PartialEq)]+pub struct PluginPanel {+ pub id: String,+ pub name: String,+ /// A Lucide icon's name, one of `thinkterm_plugin_panel::ICONS`.+ pub icon: String,+}++/// The tab id of plugin `id`'s panel.+pub fn plugin_tab(id: &str) -> String {+ format!("plugin:{id}")}/// The panel's sections, in the desktop's order, but only those the page/// can open: a button for a feature the browser lacks is noise. Files and/// Notes join here when they get a wire. Snippets is there while its-/// plugin is on, as on the desktop.-pub fn panel_tabs(snippets: bool) -> Vec<PanelTab> {- [+/// plugin is on, as on the desktop, and the plugins' panels after the+/// rest.+pub fn panel_tabs(snippets: bool, plugins: &[PluginPanel]) -> Vec<PanelTab> {+ let own = [("snippets", "code-xml", "right-mode-snippets"),("agents", "bot", "right-mode-agents"),]@@ -61,20 +91,40 @@ pub fn panel_tabs(snippets: bool) -> Vec<PanelTab> {.filter(|(id, _, _)| snippets || *id != "snippets").map(|(id, icon, key)| {let label = tr(key);- PanelTab { id, icon, label: label.clone(), available: true, tip: label }- })- .collect()+ PanelTab { id: id.to_string(), icon: icon.to_string(), label: label.clone(), available: true, tip: label }+ });+ let plugins = plugins.iter().map(|panel| PanelTab {+ id: plugin_tab(&panel.id),+ icon: panel.icon.clone(),+ label: panel.name.clone(),+ available: true,+ tip: panel.name.clone(),+ });+ own.chain(plugins).collect()}#[cfg(test)]mod panel_tests {+ use super::*;+#[test]- fn snippets_and_agents_are_available_in_a_browser() {- let tabs = super::panel_tabs(true);- assert!(tabs.iter().map(|t| t.id).eq(["snippets", "agents"]));+ fn snippets_agents_and_the_plugins_panels_are_available_in_a_browser() {+ let stocks = PluginPanel { id: "stocks".into(), name: "Stocks".into(), icon: "chart-line".into() };+ let tabs = panel_tabs(true, std::slice::from_ref(&stocks));+ assert!(tabs.iter().map(|t| t.id.as_str()).eq(["snippets", "agents", "plugin:stocks"]));assert!(tabs.iter().all(|t| t.available));- let tabs = super::panel_tabs(false);- assert!(tabs.iter().map(|t| t.id).eq(["agents"]), "the plugin is off");+ assert_eq!((tabs[2].label.as_str(), tabs[2].icon.as_str()), ("Stocks", "chart-line"));+ let tabs = panel_tabs(false, &[]);+ assert!(tabs.iter().map(|t| t.id.as_str()).eq(["agents"]), "the plugin is off");+ }++ #[test]+ fn past_five_tabs_the_active_one_is_its_icon_alone() {+ let panel = |id: &str| PluginPanel { id: id.into(), name: id.into(), icon: "chart-line".into() };+ let three: Vec<PluginPanel> = ["a", "b", "c"].into_iter().map(panel).collect();+ assert!(labeled(&panel_tabs(true, &three)), "five: named");+ let four: Vec<PluginPanel> = ["a", "b", "c", "d"].into_iter().map(panel).collect();+ assert!(!labeled(&panel_tabs(true, &four)), "six: no room");}}diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 1e6ef411..bdd0271b 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -422,8 +422,20 @@ pub struct Inner<P: Platform, L: Link> {claim: Claim,/// The right panel's tab on show (`agents.rs` `panel_tabs`), and/// whether the page has the panel up at all.- right_panel: &'static str,+ right_panel: String,right_panel_shown: bool,+ /// The plugin panel on show in the right panel, while one is.+ plugin_panel: Option<crate::plugin_panel::PanelModel>,+ /// What the page last said of the room a plugin panel has: its size,+ /// fonts and theme. A panel opens once there is this.+ plugin_panel_env: Option<thinkterm_plugin_panel::Env>,+ /// The panel's extended view, beside the right panel, while its frames+ /// ask for one, and what the page said of its room, which it opens+ /// once it has: the page gives it room while it is asked for.+ plugin_extended: Option<crate::plugin_panel::PanelModel>,+ plugin_extended_env: Option<thinkterm_plugin_panel::Env>,+ /// Numbers the page's openings of plugin panels.+ plugin_panel_views: u64,snippets: crate::snippets::SnippetsModel,/// The plugins as last heard, and what wants them.plugin_list: crate::plugin_list::PluginsModel,@@ -463,6 +475,17 @@ enum AfterTakeOver {Key(KeyCode, Modifiers, bool),}+/// Who hears of it when a frame for the plugin host does not reach it.+#[derive(Debug, Clone, Copy)]+enum FrameFor {+ Nobody,+ /// The call with this number, which fails.+ Call(u64),+ /// The page's plugin panel, or its extended view, opened under this+ /// number.+ Panel(u64),+}+pub struct App<P: Platform, L: Link> {pub platform: Rc<P>,inner: RefCell<Inner<P, L>>,@@ -473,6 +496,9 @@ pub struct App<P: Platform, L: Link> {retry_pending: Cell<bool>,/// When the pending timer is due, so a nearer one can replace it.retry_due: Cell<f64>,+ /// When a timer set to come back to the plugin panel is due, while+ /// one is: to tell its plugin a size, or to open it again.+ panel_wake: Cell<Option<f64>>,/// Set once the App is let go: a tick that still finds it (an/// interval cannot be cancelled) does nothing more.retired: Cell<bool>,@@ -657,8 +683,13 @@ impl<P: Platform, L: Link> App<P, L> {closing_since: None,after_take_over: None,claim: Claim::Idle,- right_panel: "agents",+ right_panel: "agents".to_string(),right_panel_shown: false,+ plugin_panel: None,+ plugin_panel_env: None,+ plugin_extended: None,+ plugin_extended_env: None,+ plugin_panel_views: 0,snippets: Default::default(),plugin_list: Default::default(),plugin_calls: Default::default(),@@ -671,6 +702,7 @@ impl<P: Platform, L: Link> App<P, L> {frame_requested: Cell::new(false),retry_pending: Cell::new(false),retry_due: Cell::new(0.0),+ panel_wake: Cell::new(None),retired: Cell::new(false),});let weak = Rc::downgrade(&app);@@ -1286,6 +1318,14 @@ impl<P: Platform, L: Link> App<P, L> {inner.plugin_list.connection_lost();inner.plugin_pipe = false;inner.plugin_calls.lost("the connection to the server closed");+ // Opened again as soon as the connection is back.+ let now = inner.platform.monotonic_ms();+ if let Some(panel) = inner.plugin_panel.as_mut() {+ panel.lost(now);+ }+ if let Some(extended) = inner.plugin_extended.as_mut() {+ extended.lost(now);+ }// The connection that just died settles its own backoff here:// one that held for a while earns the short delay back, one// that did not keeps the long one. Left set, a frame drawn@@ -3896,15 +3936,20 @@ impl<P: Platform, L: Link> App<P, L> {inner.panes.get(&pane).map(|c| crate::navbar::display_title(&c.title).0)});let summary = crate::agents::summary(&rows);- let tabs = crate::agents::panel_tabs(Self::snippets_offered(&inner));- crate::agents::AgentsView { rows, summary, tabs, active: inner.right_panel }+ let tabs = Self::panel_tabs(&inner);+ let labeled = crate::agents::labeled(&tabs);+ crate::agents::AgentsView { rows, summary, tabs, active: inner.right_panel.clone(), labeled }+ }++ fn panel_tabs(inner: &Inner<P, L>) -> Vec<crate::agents::PanelTab> {+ crate::agents::panel_tabs(Self::snippets_offered(inner), &inner.plugin_list.panels())}/// Show a tab of the right panel by its id. False for one the page/// does not offer.pub fn set_right_panel(self: &Rc<Self>, id: &str) -> bool {- let offered = Self::snippets_offered(&self.inner.borrow());- let Some(tab) = crate::agents::panel_tabs(offered).into_iter().find(|tab| tab.id == id && tab.available) else {+ let tabs = Self::panel_tabs(&self.inner.borrow());+ let Some(tab) = tabs.into_iter().find(|tab| tab.id == id && tab.available) else {return false;};self.inner.borrow_mut().right_panel = tab.id;@@ -3950,7 +3995,10 @@ impl<P: Platform, L: Link> App<P, L> {/// Whether anything needs the server's way to the plugin host: a tab or/// section on show, or a call waiting for its answer.fn plugin_pipe_needed(inner: &Inner<P, L>) -> bool {- Self::snippets_wanted(inner) || inner.plugin_list.wanted() || inner.plugin_calls.waiting()+ Self::snippets_wanted(inner)+ || inner.plugin_panel.is_some()+ || inner.plugin_list.wanted()+ || inner.plugin_calls.waiting()}/// Follow what the page shows of the plugins: the snippets while their@@ -3958,11 +4006,21 @@ impl<P: Platform, L: Link> App<P, L> {/// server's way to the plugin host is let go a while after nothing needs/// it any more.fn plugins_follow(self: &Rc<Self>) {- let ask_snippets = {+ let (ask_snippets, closing, sends, extended_sends, panel_later) = {let inner = &mut *self.inner.borrow_mut();if !Self::snippets_offered(inner) && inner.right_panel == "snippets" {- inner.right_panel = "agents";- }+ inner.right_panel = "agents".to_string();+ }+ // A plugin's panel goes from the selector with its plugin, once+ // the list says so.+ let offered = !inner.plugin_list.known()+ || Self::panel_tabs(inner).iter().any(|tab| tab.id == inner.right_panel);+ if !offered {+ inner.right_panel = "agents".to_string();+ }+ let (closing, sends, panel_later) = Self::follow_plugin_panel(inner);+ let (closing_extended, extended_sends) = Self::follow_plugin_extended(inner);+ let closing: Vec<Vec<u8>> = closing.into_iter().chain(closing_extended).collect();let snippets_wanted = Self::snippets_wanted(inner);let mut ask_snippets = false;if !snippets_wanted {@@ -3972,8 +4030,16 @@ impl<P: Platform, L: Link> App<P, L> {inner.snippets.open();ask_snippets = true;}- ask_snippets+ (ask_snippets, closing, sends, extended_sends, panel_later)};+ for frame in closing {+ self.send_plugin_frame(frame, FrameFor::Nobody);+ }+ self.send_panel_frames(sends, false);+ self.send_panel_frames(extended_sends, true);+ if let Some(delay) = panel_later {+ self.wake_plugin_panel(delay);+ }if ask_snippets {self.snippets_list();}@@ -3982,6 +4048,378 @@ impl<P: Platform, L: Link> App<P, L> {Self::notify(&self.inner.borrow());}+ /// Opens the plugin panel the right panel shows, closes one it no+ /// longer does, and opens again one whose time to be has come: the+ /// frame that closes the last, those for the one on show, and how long+ /// until that time when it has not come yet. A panel opens once the+ /// page has said how much room it has; one waiting for the way to the+ /// host keeps what it shows.+ fn follow_plugin_panel(inner: &mut Inner<P, L>) -> (Option<Vec<u8>>, Vec<Vec<u8>>, Option<f64>) {+ let wanted = inner+ .right_panel_shown+ .then(|| inner.right_panel.strip_prefix("plugin:"))+ .flatten()+ .map(str::to_string);+ let mut sends = Vec::new();+ let mut closing = None;+ let other = inner+ .plugin_panel+ .as_ref()+ .is_some_and(|panel| Some(panel.plugin()) != wanted.as_deref());+ if other {+ let panel = inner.plugin_panel.take().expect("checked above");+ if !panel.waiting() && inner.disconnected.is_none() {+ closing = Some(panel.close());+ }+ }+ if inner.disconnected.is_some() {+ return (closing, sends, None);+ }+ let now = inner.platform.monotonic_ms();+ let mut later = None;+ match (&mut inner.plugin_panel, wanted, &inner.plugin_panel_env) {+ (Some(panel), _, _) => match panel.again_in(now) {+ Some(wait) if wait > 0.0 => later = Some(wait),+ Some(_) => {+ inner.plugin_panel_views += 1;+ sends.extend(panel.reopen(inner.plugin_panel_views, None, now));+ }+ None => {}+ },+ (None, Some(plugin), Some(env)) => {+ inner.plugin_panel_views += 1;+ let views = inner.plugin_panel_views;+ let (panel, open) = crate::plugin_panel::PanelModel::open(&plugin, views, None, env.clone(), now);+ inner.plugin_panel = Some(panel);+ sends.extend(open);+ }+ _ => {}+ }+ (closing, sends, later)+ }++ /// Opens the extended view of the plugin panel on show while the+ /// panel's frames ask for one and the page gave it room -- as that of+ /// the panel's opening, once the panel is drawn on it; one of an earlier+ /// opening shows what it had until then -- and closes it once they stop+ /// asking: the frame that closes it, and those for it. One the host+ /// stopped serving waits for the panel's next opening.+ fn follow_plugin_extended(inner: &mut Inner<P, L>) -> (Option<Vec<u8>>, Vec<Vec<u8>>) {+ let Some(panel) = inner.plugin_panel.as_ref().filter(|panel| panel.wants_extended()) else {+ // What the page said of its room stands until the page takes+ // the room away (`plugin_extended_gone`): asked for again before+ // the page has looked, it opens in the room still there.+ let closing = inner+ .plugin_extended+ .take()+ .filter(|extended| !extended.waiting() && inner.disconnected.is_none())+ .map(|extended| extended.close());+ return (closing, Vec::new());+ };+ let (plugin, opening) = (panel.plugin().to_string(), panel.view());+ if !panel.drawn() || inner.disconnected.is_some() {+ return (None, Vec::new());+ }+ let Some(env) = inner.plugin_extended_env.clone() else {+ return (None, Vec::new());+ };+ let now = inner.platform.monotonic_ms();+ match inner.plugin_extended.as_mut() {+ Some(extended) if extended.extends() == Some(opening) => (None, Vec::new()),+ Some(extended) => {+ inner.plugin_panel_views += 1;+ (None, extended.reopen(inner.plugin_panel_views, Some(opening), now))+ }+ None => {+ inner.plugin_panel_views += 1;+ let views = inner.plugin_panel_views;+ let (extended, open) = crate::plugin_panel::PanelModel::open(&plugin, views, Some(opening), env, now);+ inner.plugin_extended = Some(extended);+ (None, open)+ }+ }+ }++ /// Comes back to the plugin panel after `delay_ms`, to tell its plugin a+ /// size or to open it again. A timer already set for sooner will do.+ fn wake_plugin_panel(self: &Rc<Self>, delay_ms: f64) {+ let due = self.platform.monotonic_ms() + delay_ms;+ if self.panel_wake.get().is_some_and(|at| at <= due) {+ return;+ }+ self.panel_wake.set(Some(due));+ let weak = Rc::downgrade(self);+ self.platform.set_timeout(+ delay_ms.max(0.0),+ Box::new(move || {+ if let Some(app) = weak.upgrade() {+ if app.panel_wake.get() == Some(due) {+ app.panel_wake.set(None);+ }+ app.plugin_panel_tell_env();+ app.plugins_follow();+ }+ }),+ );+ }++ /// What the host said about the page's panel `view`, or its extended+ /// view.+ fn plugin_panel_heard(self: &Rc<Self>, view: u64, event: thinkterm_plugin_channel::wire::PanelEvent) {+ let (sends, closing, extended_sends, again) = {+ let inner = &mut *self.inner.borrow_mut();+ let now = inner.platform.monotonic_ms();+ if let Some(panel) = inner.plugin_panel.as_mut().filter(|panel| panel.view() == view) {+ let sends = panel.heard(event, now);+ let again = panel.again_in(now);+ // Its extended view follows what it drew.+ let (closing, extended_sends) = Self::follow_plugin_extended(inner);+ (sends, closing, extended_sends, again)+ } else if let Some(extended) = inner.plugin_extended.as_mut().filter(|extended| extended.view() == view) {+ (Vec::new(), None, extended.heard(event, now), None)+ } else {+ // An opening the page has let go of since.+ return;+ }+ };+ if let Some(frame) = closing {+ self.send_plugin_frame(frame, FrameFor::Nobody);+ }+ self.send_panel_frames(sends, false);+ self.send_panel_frames(extended_sends, true);+ if let Some(delay) = again {+ self.wake_plugin_panel(delay);+ }+ Self::notify(&self.inner.borrow());+ }++ /// How much room the page gives a plugin panel, or its extended view,+ /// its fonts and theme: an `Env`, which says whether the page has room+ /// for an extended view. The first opens the view on show.+ pub fn plugin_panel_env(self: &Rc<Self>, extended: bool, mut env: thinkterm_plugin_panel::Env) {+ {+ let inner = &mut *self.inner.borrow_mut();+ env.locale = thinkterm_i18n::current_locale().to_string();+ env.cwd = Self::focused_cwd(inner);+ if extended {+ env.can_extend = false;+ inner.plugin_extended_env = Some(env.clone());+ if let Some(extended) = inner.plugin_extended.as_mut() {+ extended.set_env(env);+ }+ } else {+ inner.plugin_panel_env = Some(env.clone());+ if let Some(panel) = inner.plugin_panel.as_mut() {+ panel.set_env(env);+ }+ }+ }+ self.plugin_panel_tell_env();+ self.plugins_follow();+ }++ /// Tells the panel's plugin where the pane in focus is, and the page's+ /// language, when either moved since it was told.+ fn plugin_panel_follow_place(self: &Rc<Self>) {+ let moved = {+ let inner = &mut *self.inner.borrow_mut();+ let cwd = Self::focused_cwd(inner);+ let locale = thinkterm_i18n::current_locale();+ let mut moved = false;+ let views = [+ (&mut inner.plugin_panel_env, &mut inner.plugin_panel),+ (&mut inner.plugin_extended_env, &mut inner.plugin_extended),+ ];+ for (env, model) in views {+ match env.as_mut() {+ Some(env) if env.cwd != cwd || env.locale != locale => {+ env.cwd = cwd.clone();+ env.locale = locale.to_string();+ if let Some(model) = model.as_mut() {+ model.set_env(env.clone());+ }+ moved = true;+ }+ _ => {}+ }+ }+ moved+ };+ if moved {+ self.plugin_panel_tell_env();+ }+ }++ /// The directory of the pane in focus, as a path on the server's+ /// machine: where the plugins the page reaches run, and the terminal.+ fn focused_cwd(inner: &Inner<P, L>) -> Option<String> {+ let url = inner.panes.get(&inner.focused_pane)?.session.working_dir()?;+ if url.scheme() != "file" {+ return None;+ }+ let path = percent_encoding::percent_decode_str(url.path())+ .decode_utf8()+ .ok()?;+ // `/C:/Users/...` from a Windows server.+ let path = match path.strip_prefix('/') {+ Some(rest) if rest.as_bytes().get(1) == Some(&b':') => rest,+ _ => &path,+ };+ (!path.is_empty()).then(|| path.to_string())+ }++ /// Tells the panel's plugin the size the page gave it last, if it is+ /// still to be told and the last was told long enough ago; comes back+ /// when that is, if it is not.+ fn plugin_panel_tell_env(self: &Rc<Self>) {+ let (sends, extended_sends, later) = {+ let inner = &mut *self.inner.borrow_mut();+ let now = inner.platform.monotonic_ms();+ if inner.disconnected.is_some() {+ return;+ }+ let (sends, later) = inner.plugin_panel.as_mut().map_or((Vec::new(), None), |panel| panel.tell_env(now));+ let (extended_sends, extended_later) =+ inner.plugin_extended.as_mut().map_or((Vec::new(), None), |extended| extended.tell_env(now));+ let later = match (later, extended_later) {+ (Some(a), Some(b)) => Some(a.min(b)),+ (a, b) => a.or(b),+ };+ (sends, extended_sends, later)+ };+ self.send_panel_frames(sends, false);+ self.send_panel_frames(extended_sends, true);+ if let Some(delay) = later {+ self.wake_plugin_panel(delay);+ }+ }++ /// The plugin panel on show, or its extended view: JSON `PanelView`, or+ /// `null`.+ pub fn plugin_panel_view(&self, extended: bool) -> Option<crate::plugin_panel::PanelView> {+ let inner = self.inner.borrow();+ Self::plugin_view(&inner, extended).map(|panel| panel.view_json())+ }++ /// Changes when `plugin_panel_view` would.+ pub fn plugin_panel_revision(&self, extended: bool) -> u64 {+ let inner = self.inner.borrow();+ Self::plugin_view(&inner, extended).map_or(0, |panel| (panel.view() << 32) | (panel.revision() & 0xffff_ffff))+ }++ /// Whether the page is to give the plugin panel on show room beside+ /// the right panel for its extended view: its frames ask for one.+ pub fn plugin_panel_extended(&self) -> bool {+ self.inner.borrow().plugin_panel.as_ref().is_some_and(|panel| panel.wants_extended())+ }++ /// The extended view's close button pressed: the view goes at once, its+ /// plugin is told the user closed it, and the panel gets none until its+ /// frames have stopped asking for one.+ pub fn plugin_extended_close(self: &Rc<Self>) {+ let frames = {+ let inner = &mut *self.inner.borrow_mut();+ if let Some(panel) = inner.plugin_panel.as_mut() {+ panel.dismiss();+ }+ match inner.plugin_extended.take() {+ Some(extended) if !extended.waiting() && inner.disconnected.is_none() => {+ vec![extended.closed_by_user(), extended.close()]+ }+ _ => Vec::new(),+ }+ };+ // For a view that is gone: nothing is to hear of them.+ for frame in frames {+ self.send_plugin_frame(frame, FrameFor::Nobody);+ }+ Self::notify(&self.inner.borrow());+ }++ /// The page took the extended view's room away -- nothing asks for it,+ /// or the window grew too narrow for it: it is closed, and opened again+ /// once the page gives it room.+ pub fn plugin_extended_gone(self: &Rc<Self>) {+ let closing = {+ let inner = &mut *self.inner.borrow_mut();+ inner.plugin_extended_env = None;+ inner+ .plugin_extended+ .take()+ .filter(|extended| !extended.waiting() && inner.disconnected.is_none())+ .map(|extended| extended.close())+ };+ if let Some(frame) = closing {+ self.send_plugin_frame(frame, FrameFor::Nobody);+ }+ Self::notify(&self.inner.borrow());+ }++ /// The pointer over the plugin panel, or its extended view, in its+ /// units. True when the page is to paint it again.+ pub fn plugin_panel_pointer(&self, extended: bool, x: f32, y: f32) -> bool {+ let mut inner = self.inner.borrow_mut();+ Self::plugin_view_mut(&mut inner, extended).is_some_and(|panel| panel.pointer(x, y))+ }++ pub fn plugin_panel_leave(&self, extended: bool) -> bool {+ let mut inner = self.inner.borrow_mut();+ Self::plugin_view_mut(&mut inner, extended).is_some_and(|panel| panel.leave())+ }++ /// A press in the plugin panel, or its extended view. True when it went+ /// to the plugin.+ #[allow(clippy::too_many_arguments)]+ pub fn plugin_panel_click(+ self: &Rc<Self>,+ extended: bool,+ x: f32,+ y: f32,+ button: thinkterm_plugin_panel::Button,+ count: u32,+ mods: thinkterm_plugin_panel::Mods,+ ) -> bool {+ let sends = {+ let mut inner = self.inner.borrow_mut();+ match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) => panel.click(x, y, button, count, mods),+ None => return false,+ }+ };+ let sent = !sends.is_empty();+ self.send_panel_frames(sends, extended);+ sent+ }++ /// The wheel over the plugin panel, or its extended view, `dy` of its+ /// units down. True when something in it scrolled, and the page is to+ /// paint it again.+ pub fn plugin_panel_wheel(self: &Rc<Self>, extended: bool, x: f32, y: f32, dx: f32, dy: f32) -> bool {+ let (moved, sends) = {+ let mut inner = self.inner.borrow_mut();+ match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) => panel.wheel(x, y, dx, dy),+ None => return false,+ }+ };+ self.send_panel_frames(sends, extended);+ moved+ }++ fn plugin_view(inner: &Inner<P, L>, extended: bool) -> Option<&crate::plugin_panel::PanelModel> {+ match extended {+ true => inner.plugin_extended.as_ref(),+ false => inner.plugin_panel.as_ref(),+ }+ }++ fn plugin_view_mut(inner: &mut Inner<P, L>, extended: bool) -> Option<&mut crate::plugin_panel::PanelModel> {+ match extended {+ true => inner.plugin_extended.as_mut(),+ false => inner.plugin_panel.as_mut(),+ }+ }+/// Once nothing needs the server's way to the plugin host, it is let go/// after a while: looked at whenever a need may have ended -- something/// went off show, or a call was answered.@@ -4021,7 +4459,7 @@ impl<P: Platform, L: Link> App<P, L> {close};if close {- self.send_plugin_frame(Vec::new(), None);+ self.send_plugin_frame(Vec::new(), FrameFor::Nobody);}}@@ -4073,6 +4511,31 @@ impl<P: Platform, L: Link> App<P, L> {done}+ /// Let plugin `id` run unused as `background` says -- `always`,+ /// `briefly` or `never` -- its manifest's own being kept as no choice at+ /// all.+ pub async fn plugin_set_background(self: &Rc<Self>, id: String, background: String) -> bool {+ let Some(background) = crate::plugin_list::background_named(&background) else {+ return false;+ };+ let default = {+ let inner = &mut *self.inner.borrow_mut();+ inner.plugin_list.choosing(&id, background);+ inner.plugin_list.background_default(&id)+ };+ Self::notify(&self.inner.borrow());+ let request = plugins_api::Request::SetBackground {+ id: id.clone(),+ background: (Some(background) != default).then_some(background),+ };+ let body = serde_json::to_value(request).expect("a plugin request always serialises");+ let answer = self.plugin_call(plugins_api::PLUGIN, body).await.map(drop);+ let done = answer.is_ok();+ self.inner.borrow_mut().plugin_list.chose(&id, answer);+ self.plugins_follow();+ done+ }+/// Look for new and removed plugins on the server's machine, and/// restart the running ones.pub async fn plugins_reload(self: &Rc<Self>) -> bool {@@ -4090,11 +4553,12 @@ impl<P: Platform, L: Link> App<P, L> {/// One frame for the plugin host, through the server, on the wire now/// and so behind every frame sent before it. The call it carries, if/// any, fails when the server cannot pass it on.- fn send_plugin_frame(self: &Rc<Self>, data: Vec<u8>, call: Option<u64>) {+ fn send_plugin_frame(self: &Rc<Self>, data: Vec<u8>, sender: FrameFor) {let answer = {let inner = &mut *self.inner.borrow_mut();if inner.disconnected.is_some() {- if let Some(call) = call {+ // A panel hears of it from `on_close`.+ if let FrameFor::Call(call) = sender {inner.plugin_calls.fail(call, "not connected to the server");}return;@@ -4113,12 +4577,48 @@ impl<P: Platform, L: Link> App<P, L> {Err(err) => format!("{err:#}"),};log::warn!("plugin channel: {refused}");- if let Some(call) = call {- app.inner.borrow_mut().plugin_calls.fail(call, &refused);+ match sender {+ FrameFor::Nobody => {}+ FrameFor::Call(call) => app.inner.borrow_mut().plugin_calls.fail(call, &refused),+ FrameFor::Panel(view) => app.plugin_panel_unsent(view, &refused),}});}+ /// Sends frames for the page's plugin panel, or its extended view: one+ /// that does not reach the host has the view say why, and a panel open+ /// again in a while.+ fn send_panel_frames(self: &Rc<Self>, frames: Vec<Vec<u8>>, extended: bool) {+ if frames.is_empty() {+ return;+ }+ let view = Self::plugin_view(&self.inner.borrow(), extended).map(|panel| panel.view());+ for frame in frames {+ self.send_plugin_frame(frame, view.map_or(FrameFor::Nobody, FrameFor::Panel));+ }+ }++ /// A frame for the page's panel `view` did not reach the host -- the+ /// server could not reach it, say, and closes no way to it, having+ /// opened none: the panel says why, and is opened again in a while.+ fn plugin_panel_unsent(self: &Rc<Self>, view: u64, why: &str) {+ let later = {+ let inner = &mut *self.inner.borrow_mut();+ let now = inner.platform.monotonic_ms();+ // An extended view says why, and waits for its panel's next+ // opening.+ if let Some(extended) = inner.plugin_extended.as_mut().filter(|extended| extended.view() == view) {+ extended.unsent(why, now);+ }+ let panel = inner.plugin_panel.as_mut().filter(|panel| panel.view() == view);+ panel.and_then(|panel| panel.unsent(why, now))+ };+ if let Some(delay) = later {+ self.wake_plugin_panel(delay);+ }+ Self::notify(&self.inner.borrow());+ }+/// Ask a plugin on the server's machine: its answer, or why there is/// none. A host that does not answer in time is given up on, so a save/// or a list never waits for good.@@ -4137,7 +4637,7 @@ impl<P: Platform, L: Link> App<P, L> {wait_ms: f64,) -> impl Future<Output = crate::plugins::Answer> {let (id, frame, answer) = self.inner.borrow_mut().plugin_calls.call(plugin, body);- self.send_plugin_frame(frame, Some(id));+ self.send_plugin_frame(frame, FrameFor::Call(id));let weak = Rc::downgrade(self);let timeout = weak.clone();self.platform.set_timeout(@@ -4171,7 +4671,19 @@ impl<P: Platform, L: Link> App<P, L> {let snippets_again = inner.snippets.host_gone();inner.plugin_list.connection_lost();let delay = inner.snippets.retry_delay_ms().max(inner.plugin_list.retry_delay_ms());- let again = (snippets_again || inner.plugin_list.wanted()).then_some(delay);+ // Opened again when the rest is asked for again.+ let at = inner.platform.monotonic_ms() + delay;+ let panel_again = match inner.plugin_panel.as_mut() {+ Some(panel) => {+ panel.lost(at);+ panel.waiting()+ }+ None => false,+ };+ if let Some(extended) = inner.plugin_extended.as_mut() {+ extended.lost(at);+ }+ let again = (snippets_again || panel_again || inner.plugin_list.wanted()).then_some(delay);inner.plugin_calls.lost("the plugin host went away");again};@@ -4190,9 +4702,11 @@ impl<P: Platform, L: Link> App<P, L> {Self::notify(&self.inner.borrow());return;}- let event = self.inner.borrow_mut().plugin_calls.heard(&data);- let Some((plugin, body)) = event else {- return;+ let heard = self.inner.borrow_mut().plugin_calls.heard(&data);+ let (plugin, body) = match heard {+ Some(crate::plugins::Heard::Event(plugin, body)) => (plugin, body),+ Some(crate::plugins::Heard::Panel(view, event)) => return self.plugin_panel_heard(view, event),+ None => return,};if plugin == plugins_api::PLUGIN {match serde_json::from_value(body) {@@ -5387,6 +5901,13 @@ impl<P: Platform, L: Link> App<P, L> {self.refresh_status();inner = self.inner.borrow_mut();}+ // A plugin's panel is told where the pane in focus is as it moves:+ // a `cd`, another pane.+ if inner.plugin_panel.is_some() {+ drop(inner);+ self.plugin_panel_follow_place();+ inner = self.inner.borrow_mut();+ }// One budget for the whole frame, not one per attempt. The loop// below calls `paint` more than once, so a fresh budget each time// would let a single browser callback draw several times the cap --diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rsindex 91979875..5e7f146e 100644--- a/thinkterm-web/src/bridge.rs+++ b/thinkterm-web/src/bridge.rs@@ -128,6 +128,90 @@ impl Client {self.app.set_right_panel_shown(shown);}+ /// How much room the page gives a plugin's panel -- or, `extended`, its+ /// extended view -- in CSS pixels, how its text measures, and whether+ /// there is room for an extended view: JSON `Env`. Returns an error+ /// text or "".+ pub fn plugin_panel_env(&self, extended: bool, env: String) -> String {+ match serde_json::from_str(&env) {+ Ok(env) => {+ self.app.plugin_panel_env(extended, env);+ String::new()+ }+ Err(err) => format!("{err}"),+ }+ }++ /// The plugin panel on show, or its extended view: JSON `PanelView`, or+ /// `null` when none is.+ pub fn plugin_panel(&self, extended: bool) -> String {+ json(&self.app.plugin_panel_view(extended))+ }++ /// Changes when `plugin_panel(extended)` would, so the page paints only+ /// then.+ pub fn plugin_panel_revision(&self, extended: bool) -> f64 {+ self.app.plugin_panel_revision(extended) as f64+ }++ /// Whether the plugin panel on show asks for its extended view: the+ /// page gives it room beside the right panel while it does.+ pub fn plugin_panel_extended(&self) -> bool {+ self.app.plugin_panel_extended()+ }++ /// The extended view's close button, pressed.+ pub fn plugin_extended_close(&self) {+ self.app.plugin_extended_close();+ }++ /// The page took the room it gave the extended view away.+ pub fn plugin_extended_gone(&self) {+ self.app.plugin_extended_gone();+ }++ /// The pointer over the plugin panel, or its extended view, in CSS+ /// pixels from its corner. True when it is to be painted again.+ pub fn plugin_panel_pointer(&self, extended: bool, x: f32, y: f32) -> bool {+ self.app.plugin_panel_pointer(extended, x, y)+ }++ pub fn plugin_panel_leave(&self, extended: bool) -> bool {+ self.app.plugin_panel_leave(extended)+ }++ /// A press in the plugin panel, or its extended view: `button` 0, 1 or+ /// 2 as the DOM numbers them, `count` 2 for a double click. True when+ /// the plugin hears of it.+ #[allow(clippy::too_many_arguments)]+ pub fn plugin_panel_click(+ &self,+ extended: bool,+ x: f32,+ y: f32,+ button: u8,+ count: u32,+ shift: bool,+ ctrl: bool,+ alt: bool,+ meta: bool,+ ) -> bool {+ use thinkterm_plugin_panel::{Button, Mods};+ let button = match button {+ 1 => Button::Middle,+ 2 => Button::Right,+ _ => Button::Left,+ };+ let mods = Mods { shift, ctrl, alt, cmd: meta };+ self.app.plugin_panel_click(extended, x, y, button, count.max(1), mods)+ }++ /// The wheel over the plugin panel, or its extended view, `dy` CSS+ /// pixels down. True when something in it scrolled.+ pub fn plugin_panel_wheel(&self, extended: bool, x: f32, y: f32, dx: f32, dy: f32) -> bool {+ self.app.plugin_panel_wheel(extended, x, y, dx, dy)+ }+/// The Snippets tab: JSON `SnippetsView`.pub fn snippets(&self) -> String {json(&self.app.snippets_view())@@ -199,6 +283,15 @@ impl Client {})}+ /// How long a plugin runs unused -- `always`, `briefly` or `never`: a+ /// promise of whether the plugin host took the choice.+ pub fn plugin_set_background(&self, id: String, background: String) -> js_sys::Promise {+ let app = Rc::clone(&self.app);+ wasm_bindgen_futures::future_to_promise(async move {+ Ok(JsValue::from_bool(app.plugin_set_background(id, background).await))+ })+ }+/// Look for new and removed plugins, and restart the running ones: a/// promise of whether the plugin host did.pub fn plugins_reload(&self) -> js_sys::Promise {diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rsindex 42fbe835..38260179 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -26,6 +26,7 @@ pub mod navbar;pub mod palette;pub mod platform;pub mod plugin_list;+pub mod plugin_panel;pub mod plugins;pub mod raster;pub mod settings;diff --git a/thinkterm-web/src/plugin_list.rs b/thinkterm-web/src/plugin_list.rsindex a31b60c7..74e7e487 100644--- a/thinkterm-web/src/plugin_list.rs+++ b/thinkterm-web/src/plugin_list.rs@@ -10,7 +10,7 @@use crate::plugins::Answer;use serde::Serialize;use thinkterm_i18n::{tr, tr_args};-use thinkterm_plugin_channel::registry::{Info, State};+use thinkterm_plugin_channel::registry::{Background, Info, State};/// What wants the list: Settings › Sidebar & Plugins, the right panel.pub type Want = &'static str;@@ -35,6 +35,8 @@ pub struct PluginsModel {trouble: Option<String>,/// Switches flipped here whose change is on its way, and to what.switching: Vec<(String, bool)>,+ /// How long plugins run unused, chosen here, on its way.+ choosing: Vec<(String, Background)>,/// Why the host refused the last change asked of it here.refused: Option<String>,/// Times in a row the list could not be had, for the pause before the@@ -76,6 +78,45 @@ pub struct PluginRow {/// Built into ThinkTerm: its switch is its panel's, among the panels,/// not in the list.pub builtin: bool,+ /// How long it runs unused -- `always`, `briefly` or `never`, a choice on+ /// its way included -- for an installed plugin that is on; none for any+ /// other, which offers no choice.+ pub background: Option<&'static str>,+ /// What that choice means, and whether it is the plugin's own.+ pub background_detail: String,+}++fn background_name(background: Background) -> &'static str {+ match background {+ Background::Always => "always",+ Background::Briefly => "briefly",+ Background::Never => "never",+ }+}++/// What running `background` means, as the desktop's settings say it, and+/// that it is the plugin's own when it is `default`.+fn background_detail(background: Background, default: Background) -> String {+ let meaning = tr(match background {+ Background::Always => "settings-plugins-background-always-description",+ Background::Briefly => "settings-plugins-background-briefly-description",+ Background::Never => "settings-plugins-background-never-description",+ });+ if background == default {+ format!("{meaning} · {}", tr("settings-plugins-background-default"))+ } else {+ meaning+ }+}++/// The choice a page names, `always`, `briefly` or `never`.+pub fn background_named(name: &str) -> Option<Background> {+ match name {+ "always" => Some(Background::Always),+ "briefly" => Some(Background::Briefly),+ "never" => Some(Background::Never),+ _ => None,+ }}fn with_reason(key: &str, reason: &str) -> String {@@ -214,6 +255,7 @@ impl PluginsModel {self.followed = false;self.asking = false;self.switching.clear();+ self.choosing.clear();self.changed();}@@ -236,12 +278,64 @@ impl PluginsModel {self.changed();}+ /// How long plugin `id` runs unused, chosen here, on its way to the+ /// host.+ pub fn choosing(&mut self, id: &str, background: Background) {+ self.refused = None;+ self.choosing.retain(|(choosing, _)| choosing != id);+ self.choosing.push((id.to_string(), background));+ self.changed();+ }++ /// The host's answer to a choice made here, as to a switch.+ pub fn chose(&mut self, id: &str, answer: Result<(), String>) {+ self.choosing.retain(|(choosing, _)| choosing != id);+ if let Err(why) = answer {+ self.refused = Some(why);+ }+ self.stale = true;+ self.changed();+ }++ /// The manifest's choice for plugin `id`, as last heard.+ pub fn background_default(&self, id: &str) -> Option<Background> {+ self.plugins+ .iter()+ .flatten()+ .find(|plugin| plugin.id == id && !plugin.builtin)+ .map(|plugin| plugin.background_default)+ }+/// The host refused something asked of it here.pub fn refused(&mut self, why: String) {self.refused = Some(why);self.changed();}+ /// The panels plugins add to the right panel, as last heard: those of+ /// the plugins that are on and not broken, in the list's order.+ pub fn panels(&self) -> Vec<crate::agents::PluginPanel> {+ let Some(plugins) = &self.plugins else {+ return Vec::new();+ };+ plugins+ .iter()+ .filter(|plugin| plugin.usable())+ .filter_map(|plugin| {+ Some(crate::agents::PluginPanel {+ id: plugin.id.clone(),+ name: plugin.name.clone(),+ icon: plugin.panel.as_ref()?.icon.clone(),+ })+ })+ .collect()+ }++ /// Whether the list has been heard at all.+ pub fn known(&self) -> bool {+ self.plugins.is_some()+ }+/// Whether plugin `id` is on and working, as last heard; `None` before/// anything was.pub fn usable(&self, id: &str) -> Option<bool> {@@ -267,21 +361,37 @@ impl PluginsModel {.plugins.iter().flatten()- .map(|plugin| PluginRow {- key: plugin.dir.clone().unwrap_or_else(|| plugin.id.clone()),- id: plugin.id.clone(),- name: plugin.name.clone(),- detail: detail(plugin),- enabled: self+ .map(|plugin| {+ let enabled = self.switching.iter().find(|(id, _)| *id == plugin.id)- .map_or(plugin.enabled, |(_, enabled)| *enabled),- switchable: !matches!(+ .map_or(plugin.enabled, |(_, enabled)| *enabled);+ let switchable = !matches!(plugin.state,State::Invalid { .. } | State::Unsupported { .. }- ),- builtin: plugin.builtin,+ );+ let background = self+ .choosing+ .iter()+ .find(|(id, _)| *id == plugin.id)+ .map_or(plugin.background, |(_, background)| *background);+ let offered = !plugin.builtin && switchable && enabled;+ PluginRow {+ key: plugin.dir.clone().unwrap_or_else(|| plugin.id.clone()),+ id: plugin.id.clone(),+ name: plugin.name.clone(),+ detail: detail(plugin),+ enabled,+ switchable,+ builtin: plugin.builtin,+ background: offered.then(|| background_name(background)),+ background_detail: if offered {+ background_detail(background, plugin.background_default)+ } else {+ String::new()+ },+ }}).collect();PluginsView {@@ -451,6 +561,36 @@ mod tests {assert!(model.next_list("en-US").is_some(), "asked again either way");}+ #[test]+ fn a_plugin_that_is_on_offers_how_long_it_runs_unused() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ let mut kept = plugin("a", true, json!({"kind": "running"}));+ kept["background"] = json!("always");+ kept["background_default"] = json!("always");+ listed(+ &mut model,+ json!([+ plugin("snippets", true, json!({"kind": "idle"})),+ kept,+ plugin("b", false, json!({"kind": "off"})),+ ]),+ );+ let view = model.view();+ assert_eq!(view.rows[1].background, Some("always"));+ assert!(view.rows[1].background_detail.contains("The plugin's default"));+ assert_eq!(view.rows[2].background, None, "off: nothing to choose");+ model.choosing("a", Background::Never);+ let row = &model.view().rows[1];+ assert_eq!(row.background, Some("never"), "the choice on its way");+ assert!(!row.background_detail.contains("default"), "{}", row.background_detail);+ model.chose("a", Err("cannot save".into()));+ assert_eq!(model.view().rows[1].background, Some("always"), "went back");+ assert_eq!(model.background_default("a"), Some(Background::Always));+ assert_eq!(background_named("briefly"), Some(Background::Briefly));+ assert_eq!(background_named("sometimes"), None);+ }+#[test]fn a_built_in_plugin_says_which_panel_it_provides() {let mut model = PluginsModel::default();diff --git a/thinkterm-web/src/plugin_panel.rs b/thinkterm-web/src/plugin_panel.rsnew file mode 100644index 00000000..b220e3b8--- /dev/null+++ b/thinkterm-web/src/plugin_panel.rs@@ -0,0 +1,538 @@+//! A plugin's panel in the right panel, as the page shows it: the view the+//! plugin host on the server's machine serves the page, through the server+//! (`PluginFrame`), and the player that shows it (thinkterm-plugin-panel).+//! The page paints the player's painting on a canvas of its own and hands+//! the pointer and the wheel back here; everything else is decided here.+//!+//! What is to go to the host comes back from each change as frames, for+//! the app to send on the way to the host it keeps. Times are the+//! platform's monotonic milliseconds.+//!+//! A panel's extended view, beside the right panel, is a model of its own,+//! opened as the extended view of the panel's opening: the app opens it+//! while the panel's frames ask for one.++use serde::Serialize;+use thinkterm_plugin_channel::wire::{PanelEvent, PanelRequest, Raw, ToHost};+use thinkterm_plugin_panel::{Button, Env, Frame, Mods, Painting, Player, Rows};++/// How long a panel the host closed, but may serve again, waits before it+/// is opened anew: the plugin is being started again.+pub const REOPEN_MS: f64 = 400.0;+/// The least time between two sizes told to the plugin: a panel being+/// resized changes its size each frame, and each is drawn anew.+pub const ENV_EVERY_MS: f64 = 100.0;++/// Frames for the host, in order.+pub type Sends = Vec<Vec<u8>>;++/// What the page shows of the panel.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct PanelView {+ /// `starting`, `open` or `stopped`.+ pub state: &'static str,+ /// What the panel says instead of a painting: starting, or why it+ /// stopped.+ pub message: Option<String>,+ /// What to paint; none before the plugin first drew.+ pub painting: Option<Painting>,+}++#[derive(Debug, Clone, PartialEq)]+enum Status {+ /// Opened, and not drawn on this opening yet.+ Opening,+ Open,+ /// Closed by the host or with the way to it; to be opened again from+ /// this time on.+ Again(f64),+ Stopped(String),+}++pub struct PanelModel {+ plugin: String,+ /// The page's number for this opening of it.+ view: u64,+ /// For an extended view, the page's number for the opening of the+ /// panel it extends.+ extends: Option<u64>,+ player: Player,+ status: Status,+ revision: u64,+ /// When the plugin was last told the panel's size, and whether the+ /// player has one since that it is still to be told: rows asked for+ /// meanwhile, which are drawn for it, wait until it is.+ env_told: f64,+ env_due: bool,+ /// Why what was sent for it did not reach the host, until the host is+ /// heard from again, and how many openings in a row that happened to:+ /// each waits twice as long before the next.+ trouble: Option<String>,+ failures: u32,+ /// The user closed its extended view with the close button: it is not+ /// opened again until its frames have stopped asking for one.+ dismissed: bool,+}++impl PanelModel {+ /// Plugin `plugin`'s panel, the size `env` says, opened as the page's+ /// panel number `view` at `now` -- the extended view of panel+ /// `extends`, with one: with the frame that opens it.+ pub fn open(plugin: &str, view: u64, extends: Option<u64>, env: Env, now: f64) -> (Self, Sends) {+ let model = Self {+ plugin: plugin.to_string(),+ view,+ extends,+ player: Player::new(env),+ status: Status::Opening,+ revision: 0,+ env_told: now,+ env_due: false,+ trouble: None,+ failures: 0,+ dismissed: false,+ };+ let open = model.open_frame();+ (model, vec![open])+ }++ pub fn plugin(&self) -> &str {+ &self.plugin+ }++ pub fn view(&self) -> u64 {+ self.view+ }++ pub fn revision(&self) -> u64 {+ self.revision+ }++ pub fn extends(&self) -> Option<u64> {+ self.extends+ }++ /// Whether the plugin has drawn it on this opening.+ pub fn drawn(&self) -> bool {+ self.status == Status::Open+ }++ /// Whether its frames ask for its extended view, and it is to have one:+ /// not once it cannot be served.+ pub fn wants_extended(&self) -> bool {+ self.player.shown() && self.player.extend() && !self.dismissed && !matches!(self.status, Status::Stopped(_))+ }++ /// Its extended view was closed with the close button.+ pub fn dismiss(&mut self) {+ self.dismissed = true;+ self.changed();+ }++ /// Tells the plugin the user closed this extended view with its close+ /// button: the frame, for the view is closed at once.+ pub fn closed_by_user(&self) -> Vec<u8> {+ self.frame(PanelRequest::Input { input: Raw::new(&thinkterm_plugin_panel::Input::Close) })+ }++ /// Whether it is waiting to be opened again.+ pub fn waiting(&self) -> bool {+ matches!(self.status, Status::Again(_))+ }++ /// How long until it is to be opened again, if it waits to be.+ pub fn again_in(&self, now: f64) -> Option<f64> {+ match self.status {+ Status::Again(at) => Some((at - now).max(0.0)),+ _ => None,+ }+ }++ pub fn view_json(&self) -> PanelView {+ let stopped = |reason: &str| {+ let mut args = thinkterm_i18n::FluentArgs::new();+ args.set("reason", reason.to_string());+ ("stopped", Some(thinkterm_i18n::tr_args("right-plugin-stopped", &args)))+ };+ let (state, message) = match (&self.status, &self.trouble) {+ (Status::Open, _) => ("open", None),+ (Status::Stopped(reason), _) => stopped(reason),+ // Opened again and again while the host cannot be reached: why.+ (Status::Opening | Status::Again(_), Some(why)) => stopped(why),+ (Status::Opening | Status::Again(_), None) if self.player.shown() => ("open", None),+ (Status::Opening | Status::Again(_), None) => {+ ("starting", Some(thinkterm_i18n::tr("right-plugin-starting")))+ }+ };+ PanelView {+ state,+ message,+ painting: (state != "stopped" && self.player.shown()).then(|| self.player.painting()),+ }+ }++ /// The panel's size, fonts or theme changed on the page: the plugin is+ /// told by [`tell_env`](Self::tell_env).+ pub fn set_env(&mut self, env: Env) {+ if self.player.set_env(env) {+ self.env_due = true;+ self.changed();+ }+ }++ /// Tells the plugin a size it is still to be told, and asks for the+ /// rows drawn for it, once the last was told long enough ago: the+ /// frames, and how long until then when it is not yet. One waiting to+ /// be opened again is told with the opening.+ pub fn tell_env(&mut self, now: f64) -> (Sends, Option<f64>) {+ if !self.env_due || self.waiting() {+ return (Vec::new(), None);+ }+ let due = self.env_told + ENV_EVERY_MS;+ if now < due {+ return (Vec::new(), Some(due - now));+ }+ self.env_told = now;+ self.env_due = false;+ let env = Raw::new(self.player.env());+ let mut sends = vec![self.frame(PanelRequest::Env { env })];+ sends.extend(self.wanted());+ (sends, None)+ }++ /// What the host said about the panel, at `now`.+ pub fn heard(&mut self, event: PanelEvent, now: f64) -> Sends {+ let mut sends = Vec::new();+ // Heard, so the host is reached.+ self.trouble = None;+ self.failures = 0;+ match event {+ PanelEvent::Frame { frame } => {+ // Taken in either way, so the next one can come.+ sends.push(self.frame(PanelRequest::Shown));+ match frame.read::<Frame>() {+ Ok(frame) => {+ // Once its frames stop asking, the next that asks+ // opens it.+ if !frame.extend {+ self.dismissed = false;+ }+ self.player.frame(frame);+ self.status = Status::Open;+ }+ Err(err) => log::warn!("plugin panel {}: a frame that does not read: {err}", self.plugin),+ }+ }+ PanelEvent::Rows { rows } => match rows.read::<Rows>() {+ Ok(rows) => self.player.rows(rows),+ Err(err) => log::warn!("plugin panel {}: rows that do not read: {err}", self.plugin),+ },+ PanelEvent::Closed { reason, again } => {+ self.status = if again {+ Status::Again(now + REOPEN_MS)+ } else {+ log::info!("plugin panel {}: {reason}", self.plugin);+ Status::Stopped(reason)+ };+ }+ // The page never says its terminal runs on another machine: a+ // plugin asking of one anyway is told so.+ PanelEvent::Remote { id, .. } => {+ let answer = thinkterm_plugin_panel::Answer::failed(+ "the terminal beside this panel runs where the plugin does",+ );+ let answer = Raw::new(&answer);+ sends.push(self.frame(PanelRequest::Answer { id, answer }));+ }+ }+ sends.extend(self.wanted());+ self.changed();+ sends+ }++ /// The way to the host went, with the panel: it is opened again once+ /// there is one, from `at` on.+ pub fn lost(&mut self, at: f64) {+ if !matches!(self.status, Status::Stopped(_)) {+ self.status = Status::Again(at);+ self.changed();+ }+ }++ /// Something sent for it did not reach the host, for `why` -- one that+ /// cannot be started, say: it is to be opened again, in two seconds,+ /// then twice as long each time again to half a minute, and says why+ /// meanwhile. How long until then; `None` when it is not to be.+ pub fn unsent(&mut self, why: &str, now: f64) -> Option<f64> {+ match self.status {+ Status::Stopped(_) => return None,+ // What else was sent with it went the same way.+ Status::Again(at) => return Some((at - now).max(0.0)),+ Status::Opening | Status::Open => {}+ }+ self.failures = self.failures.saturating_add(1);+ let delay = 1000.0 * f64::from(1u32 << self.failures.min(5)).min(30.0);+ self.status = Status::Again(now + delay);+ self.trouble = Some(why.to_string());+ self.changed();+ Some(delay)+ }++ /// Opens it again at `now`, under a new number -- an extended view as+ /// that of the panel's opening `extends`: what the last opening asked+ /// will not be answered.+ pub fn reopen(&mut self, view: u64, extends: Option<u64>, now: f64) -> Sends {+ self.view = view;+ self.extends = extends;+ self.status = Status::Opening;+ self.env_told = now;+ self.env_due = false;+ self.player.restarted();+ // What was asked of the last opening is asked again on this one,+ // once the plugin has drawn on it: asked before, a plugin that+ // makes what it keeps for a view as it draws it has no rows yet.+ self.changed();+ vec![self.open_frame()]+ }++ /// The frame that lets it go.+ pub fn close(&self) -> Vec<u8> {+ self.frame(PanelRequest::Close)+ }++ /// The pointer moved to `x`, `y`. True when the panel is to be painted+ /// again.+ pub fn pointer(&mut self, x: f32, y: f32) -> bool {+ let moved = self.player.pointer_moved(x, y);+ if moved {+ self.changed();+ }+ moved+ }++ pub fn leave(&mut self) -> bool {+ let moved = self.player.pointer_left();+ if moved {+ self.changed();+ }+ moved+ }++ /// A press: what the plugin is to hear of it.+ pub fn click(&mut self, x: f32, y: f32, button: Button, count: u32, mods: Mods) -> Sends {+ let Some(input) = self.player.click(x, y, button, count, mods) else {+ return Vec::new();+ };+ self.changed();+ vec![self.frame(PanelRequest::Input { input: Raw::new(&input) })]+ }++ /// The wheel turned: what scrolled is painted again, and the rows it+ /// brings near are asked for.+ pub fn wheel(&mut self, x: f32, y: f32, dx: f32, dy: f32) -> (bool, Sends) {+ if !self.player.wheel(x, y, dx, dy) {+ return (false, Vec::new());+ }+ self.changed();+ (true, self.wanted())+ }++ /// Asks for what the lists need next, once the plugin is told the size+ /// it is drawn for.+ fn wanted(&mut self) -> Sends {+ if self.env_due {+ return Vec::new();+ }+ self.player+ .wanted()+ .into_iter()+ .map(|wanted| self.frame(PanelRequest::Rows { wanted: Raw::new(&wanted) }))+ .collect()+ }++ fn open_frame(&self) -> Vec<u8> {+ let env = Raw::new(self.player.env());+ self.frame(PanelRequest::Open { plugin: self.plugin.clone(), env, extends: self.extends })+ }++ fn frame(&self, request: PanelRequest) -> Vec<u8> {+ ToHost::Panel { view: self.view, request }.encode()+ }++ fn changed(&mut self) {+ self.revision += 1;+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ use thinkterm_plugin_panel::{MonoMetrics, TextMetrics};++ fn env() -> Env {+ let text = TextMetrics { size: 13.0, line: 18.0 };+ Env {+ width: 300.0,+ height: 400.0,+ scale: 2.0,+ dark: true,+ small: text,+ body: text,+ title: text,+ mono: MonoMetrics { size: 12.0, line: 17.0, advance: 7.0 },+ locale: String::new(),+ cwd: None,+ remote: None,+ can_extend: false,+ close: None,+ }+ }++ fn requests(sends: &Sends) -> Vec<serde_json::Value> {+ sends+ .iter()+ .map(|frame| match ToHost::decode(frame).unwrap() {+ ToHost::Panel { request, .. } => serde_json::to_value(request).unwrap(),+ other => panic!("{other:?}"),+ })+ .collect()+ }++ #[test]+ fn a_frame_is_taken_in_asked_after_and_painted() {+ let (mut panel, sends) = PanelModel::open("stocks", 1, None, env(), 0.0);+ assert_eq!(requests(&sends)[0]["open"]["plugin"], "stocks");+ assert_eq!(panel.view_json().state, "starting");++ let frame = json!({"items": [+ {"hit": {"id": "a", "x": 0, "y": 0, "w": 300, "h": 20, "hover": "bg-hover"}},+ {"list": {"id": "l", "x": 0, "y": 20, "w": 300, "h": 100, "count": 50, "row": 20, "key": "k"}}+ ]});+ let sends = panel.heard(PanelEvent::Frame { frame: Raw::new(&frame) }, 0.0);+ let asked = requests(&sends);+ assert_eq!(asked[0], json!("shown"), "taken in first");+ assert_eq!(asked[1]["rows"]["wanted"]["from"], 0);+ let view = panel.view_json();+ assert_eq!(view.state, "open");+ assert!(view.painting.is_some());++ let before = panel.revision();+ assert!(panel.pointer(10.0, 5.0));+ assert!(panel.revision() > before);+ let clicked = panel.click(10.0, 5.0, Button::Left, 1, Mods::default());+ assert_eq!(requests(&clicked)[0]["input"]["input"]["click"]["id"], "a");++ // Opened again: its rows are asked for once the plugin draws on this+ // opening, not with the open.+ let sends = panel.reopen(2, None, 0.0);+ assert_eq!(requests(&sends).len(), 1, "the open alone");+ let sends = panel.heard(PanelEvent::Frame { frame: Raw::new(&frame) }, 0.0);+ assert!(requests(&sends).iter().any(|asked| asked["rows"]["wanted"]["layout"] == 1), "{:?}", requests(&sends));+ }++ #[test]+ fn a_panel_asks_for_its_extended_view_which_opens_as_that_of_its_opening() {+ let (mut panel, _) = PanelModel::open("diff", 1, None, env(), 0.0);+ assert!(!panel.wants_extended(), "nothing drawn asks nothing");+ let asking = json!({"items": [], "extend": true});+ panel.heard(PanelEvent::Frame { frame: Raw::new(&asking) }, 0.0);+ assert!(panel.drawn() && panel.wants_extended());++ let (mut extended, sends) = PanelModel::open("diff", 2, Some(1), env(), 0.0);+ assert_eq!(requests(&sends)[0]["open"]["extends"], 1);+ assert_eq!(extended.extends(), Some(1));+ // The panel opened again as 3: so is the view that extends it.+ let sends = extended.reopen(4, Some(3), 0.0);+ assert_eq!(requests(&sends)[0]["open"]["extends"], 3);++ panel.dismiss();+ assert!(!panel.wants_extended(), "closed with its button");+ panel.heard(PanelEvent::Frame { frame: Raw::new(&asking) }, 0.0);+ assert!(!panel.wants_extended(), "not while the frames go on asking");+ assert_eq!(requests(&vec![extended.closed_by_user()])[0], json!({"input": {"input": "close"}}));+ panel.heard(PanelEvent::Frame { frame: Raw::new(&json!({"items": []})) }, 0.0);+ assert!(!panel.wants_extended(), "a frame that does not ask lets it go");+ panel.heard(PanelEvent::Frame { frame: Raw::new(&asking) }, 0.0);+ assert!(panel.wants_extended(), "and the next that asks opens it");+ panel.heard(PanelEvent::Frame { frame: Raw::new(&asking) }, 0.0);+ panel.heard(PanelEvent::Closed { reason: "turned off".into(), again: false }, 0.0);+ assert!(!panel.wants_extended(), "nor does a panel that stopped");+ }++ #[test]+ fn a_panel_the_host_closed_is_opened_again_in_a_while_or_stays_stopped() {+ let (mut panel, _) = PanelModel::open("stocks", 1, None, env(), 0.0);+ panel.heard(PanelEvent::Closed { reason: "restarting".into(), again: true }, 1_000.0);+ assert!(panel.waiting());+ assert_eq!(panel.again_in(1_000.0), Some(REOPEN_MS));+ assert_eq!(panel.again_in(1_000.0 + REOPEN_MS), Some(0.0));+ let sends = panel.reopen(2, None, 1_000.0 + REOPEN_MS);+ assert_eq!(panel.view(), 2);+ assert_eq!(requests(&sends)[0]["open"]["plugin"], "stocks");+ panel.lost(5_000.0);+ assert_eq!(panel.again_in(2_000.0), Some(3_000.0), "after the host's retry delay");+ panel.reopen(3, None, 5_000.0);+ panel.heard(PanelEvent::Closed { reason: "turned off".into(), again: false }, 5_000.0);+ assert!(!panel.waiting());+ let view = panel.view_json();+ assert_eq!(view.state, "stopped");+ assert!(view.message.unwrap().contains("turned off"));+ panel.lost(0.0);+ assert!(!panel.waiting(), "stopped stays stopped");+ }++ #[test]+ fn a_panel_whose_frames_do_not_reach_the_host_says_why_and_opens_again_later() {+ let (mut panel, _) = PanelModel::open("stocks", 1, None, env(), 0.0);+ let why = "no plugin host here: it cannot be started";+ assert_eq!(panel.unsent(why, 0.0), Some(2_000.0));+ assert_eq!(panel.unsent(why, 500.0), Some(1_500.0), "the rest of what was sent with it");+ let view = panel.view_json();+ assert_eq!(view.state, "stopped");+ assert!(view.message.unwrap().contains("cannot be started"));+ // Still out of reach: each wait twice as long, to half a minute.+ panel.reopen(2, None, 2_000.0);+ assert_eq!(panel.view_json().state, "stopped", "says why while it tries");+ assert_eq!(panel.unsent(why, 2_000.0), Some(4_000.0));+ for n in 3..10 {+ panel.reopen(n, None, 0.0);+ panel.unsent(why, 0.0);+ }+ panel.reopen(10, None, 0.0);+ assert_eq!(panel.unsent(why, 0.0), Some(30_000.0));+ // Reached at last.+ panel.reopen(11, None, 0.0);+ let frame = json!({"items": []});+ panel.heard(PanelEvent::Frame { frame: Raw::new(&frame) }, 0.0);+ assert_eq!(panel.view_json().state, "open");+ assert_eq!(panel.unsent(why, 0.0), Some(2_000.0), "counted afresh");+ panel.heard(PanelEvent::Closed { reason: "turned off".into(), again: false }, 0.0);+ assert_eq!(panel.unsent(why, 0.0), None, "stopped stays stopped");+ }++ #[test]+ fn sizes_are_told_at_most_every_little_while_and_rows_wait_for_them() {+ let (mut panel, _) = PanelModel::open("stocks", 1, None, env(), 0.0);+ let frame = json!({"items": [+ {"list": {"id": "l", "x": 0, "y": 0, "w": 300, "h": 100, "count": 500, "row": 20, "key": "k"}}+ ]});+ panel.heard(PanelEvent::Frame { frame: Raw::new(&frame) }, 0.0);+ let sized = |width: f32| Env { width, ..env() };+ panel.set_env(sized(310.0));+ let (sends, later) = panel.tell_env(50.0);+ assert!(sends.is_empty());+ assert_eq!(later, Some(ENV_EVERY_MS - 50.0));+ // Rows asked for meanwhile wait for the size they are drawn for.+ let (moved, asked) = panel.wheel(10.0, 10.0, 0.0, 2_000.0);+ assert!(moved && asked.is_empty());+ panel.set_env(sized(320.0));+ let (sends, later) = panel.tell_env(ENV_EVERY_MS);+ assert_eq!(later, None);+ let told = requests(&sends);+ assert_eq!(told[0]["env"]["env"]["width"], 320.0, "the last size only");+ assert!(told[1..].iter().all(|asked| asked["rows"]["wanted"]["layout"] == 2), "{told:?}");+ assert!(told.len() > 1, "the rows for it follow");+ assert_eq!(panel.tell_env(ENV_EVERY_MS * 3.0), (Vec::new(), None), "told already");+ }+}diff --git a/thinkterm-web/src/plugins.rs b/thinkterm-web/src/plugins.rsindex 7ebc14ab..3abc0a56 100644--- a/thinkterm-web/src/plugins.rs+++ b/thinkterm-web/src/plugins.rs@@ -6,11 +6,20 @@use futures::channel::oneshot;use serde_json::Value;use std::collections::HashMap;-use thinkterm_plugin_channel::wire::{FromHost, ToHost};+use thinkterm_plugin_channel::wire::{FromHost, PanelEvent, ToHost};/// A call's answer, or why there is none.pub type Answer = Result<Value, String>;+/// A frame from the host that is not an answer.+#[derive(Debug, PartialEq)]+pub enum Heard {+ /// A plugin's event: its name, and what it said.+ Event(String, Value),+ /// About the page's panel `.0`.+ Panel(u64, PanelEvent),+}+#[derive(Debug, Default)]pub struct PluginCalls {next_id: u64,@@ -28,13 +37,14 @@ impl PluginCalls {(id, frame, rx)}- /// A frame from the host: the answer to a call, delivered, or an event,- /// handed back as the plugin's name and what it said.- pub fn heard(&mut self, frame: &[u8]) -> Option<(String, Value)> {+ /// A frame from the host: the answer to a call, delivered, or what+ /// else it is, handed back.+ pub fn heard(&mut self, frame: &[u8]) -> Option<Heard> {match FromHost::decode(frame) {Ok(FromHost::Ok { id, body }) => self.answer(id, Ok(body)),Ok(FromHost::Error { id, message }) => self.answer(id, Err(message)),- Ok(FromHost::Event { plugin, body }) => return Some((plugin, body)),+ Ok(FromHost::Event { plugin, body }) => return Some(Heard::Event(plugin, body)),+ Ok(FromHost::Panel { view, event }) => return Some(Heard::Panel(view, event)),Ok(FromHost::Hello { .. }) => {}Err(err) => log::warn!("a frame from the plugin host that does not read: {err}"),}@@ -92,7 +102,7 @@ mod tests {assert_eq!(answered(&mut first_rx), None, "still waiting");let event = FromHost::Event { plugin: "snippets".into(), body: json!({"event": "changed"}) }.encode();- assert_eq!(calls.heard(&event), Some(("snippets".into(), json!({"event": "changed"}))));+ assert_eq!(calls.heard(&event), Some(Heard::Event("snippets".into(), json!({"event": "changed"}))));let reply = FromHost::Ok { id: first, body: json!([]) }.encode();calls.heard(&reply);diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rsindex 1824563e..e74218e5 100644--- a/thinkterm-web/src/views.rs+++ b/thinkterm-web/src/views.rs@@ -173,6 +173,7 @@ pub const STRING_KEYS: &[&str] = &["web-tip-delete-snippet","settings-sidebar-description","right-mode-snippets",+ "right-plugin-starting","settings-sidebar-snippets-description","settings-section-plugins","settings-plugins-description",@@ -180,6 +181,9 @@ pub const STRING_KEYS: &[&str] = &["settings-plugins-reload-description","settings-plugins-reload-button","settings-plugins-unusable",+ "settings-plugins-background-always",+ "settings-plugins-background-briefly",+ "settings-plugins-background-never",];pub fn strings() -> std::collections::BTreeMap<&'static str, String> {@@ -246,6 +250,44 @@ mod tests {assert_eq!(strings()["web-tip-sidebar"].is_empty(), false);}+ /// A key the page's sources name in quotes -- in a call, or in a list+ /// of choices -- reaches the page, which shows the key itself otherwise.+ #[test]+ fn every_string_the_page_names_is_sent_to_it() {+ let ui = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("ui/src");+ let mut missing = Vec::new();+ for entry in std::fs::read_dir(&ui).unwrap() {+ let path = entry.unwrap().path();+ let name = path.file_name().unwrap().to_string_lossy().into_owned();+ if !(name.ends_with(".svelte") || name.ends_with(".ts")) {+ continue;+ }+ let text = std::fs::read_to_string(&path).unwrap();+ let bytes = text.as_bytes();+ let mut at = 0;+ while at < bytes.len() {+ let quote = bytes[at];+ at += 1;+ if !matches!(quote, b'\'' | b'"' | b'`') {+ continue;+ }+ let Some(len) = bytes[at..].iter().position(|&b| b == quote) else {+ continue;+ };+ let quoted = &text[at..at + len];+ let key_like = quoted.starts_with(|c: char| c.is_ascii_lowercase())+ && quoted.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');+ if key_like && thinkterm_i18n::has_key(quoted) {+ if !STRING_KEYS.contains("ed) {+ missing.push(format!("{name}: {quoted}"));+ }+ at += len + 1;+ }+ }+ }+ assert!(missing.is_empty(), "named by the page and not sent to it: {missing:?}");+ }+#[test]fn tabs_and_status_shapes() {let v = to_value(TabsView {diff --git a/thinkterm-web/ui/src/AgentsPanel.svelte b/thinkterm-web/ui/src/AgentsPanel.svelteindex 15b8863a..b86d4f66 100644--- a/thinkterm-web/ui/src/AgentsPanel.svelte+++ b/thinkterm-web/ui/src/AgentsPanel.svelte@@ -2,8 +2,12 @@// The desktop's right-hand panel: its Agents tab, one row per pane a// coding agent runs in with its live state, as `agent_panel.rs` paints// it from the rows the wasm publishes (thinkterm-web/src/agents.rs), a- // click on a row bringing that pane on show; and its Snippets tab- // (SnippetsBar, SnippetsList).+ // click on a row bringing that pane on show; its Snippets tab+ // (SnippetsBar, SnippetsList); and the panels plugins draw+ // (PluginPanel), with the extended view one asks for left of it+ // (PluginExtended).+ import PluginExtended from './PluginExtended.svelte';+ import PluginPanel from './PluginPanel.svelte';import SnippetsBar from './SnippetsBar.svelte';import SnippetsList from './SnippetsList.svelte';import { handle } from './client';@@ -15,6 +19,7 @@// (thinkterm-web/src/agents.rs `panel_tabs`); drawn here.const tabs = $derived(views.agents.tabs);const active = $derived(views.agents.active);+ const plugin = $derived(active.startsWith('plugin:'));const heading = $derived(tabs.find((tab) => tab.id === active)?.label ?? s('web-agents-title'));const rows = $derived(views.agents.rows);@@ -148,9 +153,10 @@<div class="handle"></div><div class="hd"><span class="ti">{heading}</span>- <!-- The desktop's selector: four segments, the active one a filled pill- carrying its label, the rest icon-only. -->- <div class="modes" role="tablist">+ <!-- The desktop's selector: a segment a tab, the active one a filled+ pill carrying its label, the rest icon-only; past five tabs the+ label has no room, and the active one is its icon too. -->+ <div class="modes" class:icons={!views.agents.labeled} role="tablist">{#each tabs as tab (tab.id)}<spanclass="mode"@@ -161,17 +167,21 @@aria-disabled={!tab.available}data-mode={tab.id}title={tab.tip}- >{@html iconByName(tab.icon) ?? ''}{#if tab.id === active}<span class="ml">{tab.label}</span>{/if}</span>+ >{@html iconByName(tab.icon) ?? ''}{#if tab.id === active && views.agents.labeled}<span class="ml">{tab.label}</span>{/if}</span>{/each}</div>{#if active === 'snippets'}<SnippetsBar />- {:else}+ {:else if !plugin}<span class="sum">{summary}</span>{/if}</div>{#if active === 'snippets'}<SnippetsList />+ {:else if plugin}+ {#key active}+ <PluginPanel />+ {/key}{:else}<div class="list">{#each rows as row (row.pane)}@@ -193,3 +203,8 @@</div>{/if}</aside>+{#if plugin && views.panelExtended}+ {#key active}+ <PluginExtended plugin={active.slice('plugin:'.length)} />+ {/key}+{/if}diff --git a/thinkterm-web/ui/src/PluginExtended.svelte b/thinkterm-web/ui/src/PluginExtended.sveltenew file mode 100644index 00000000..5815219f--- /dev/null+++ b/thinkterm-web/ui/src/PluginExtended.svelte@@ -0,0 +1,115 @@+<script lang="ts">+ // A plugin panel's extended view: the wide area left of the right panel,+ // as the desktop's is left of its sidebar, while the panel's frames ask+ // for one (thinkterm-web/src/app.rs `plugin_panel_extended`). What it+ // shows is PluginPanel's; this is its room -- as wide as it was last+ // dragged for the plugin in this browser, within what the window has --+ // and the handle on its edge that sizes it.+ import PluginPanel from './PluginPanel.svelte';+ import { handle } from './client';+ import { views } from './client.svelte';+ import { EXTENDED_MIN, canExtend, extendedRoom, storeWidth, storedWidth } from './extended';++ let { plugin }: { plugin: string } = $props();++ /** Whether the window has room for it: none, and it is not shown. */+ let room = $state(canExtend());+ /** The width asked for, and the one it has in the room there is. The+ plugin is this one's for good: it is shown anew for another. */+ let wanted = 0;+ let width = 0;++ function setWidth(px: number): number {+ const w = Math.round(Math.min(extendedRoom(), Math.max(EXTENDED_MIN, px)));+ document.documentElement.style.setProperty('--ext-w', `${w}px`);+ handle.client?.resize();+ return w;+ }++ // A window made narrower, or a panel beside it made wider, leaves it what+ // room there is, or none. Its own width is not what it fits to, so+ // fitting it comes to rest.+ $effect(() => {+ const fit = () => {+ room = canExtend();+ if (room && wanted) width = setWidth(wanted);+ };+ window.addEventListener('resize', fit);+ const term = document.getElementById('term');+ const others = new ResizeObserver(fit);+ if (term) others.observe(term);+ return () => {+ window.removeEventListener('resize', fit);+ others.disconnect();+ };+ });++ // The mark on the body is what makes the tab row and the terminal leave+ // room for it, as the right panel's does for the panel.+ $effect(() => {+ if (!room) return;+ wanted ||= storedWidth(plugin);+ document.body.dataset.extended = '';+ width = setWidth(wanted);+ return () => {+ delete document.body.dataset.extended;+ handle.client?.resize();+ handle.client?.plugin_extended_gone();+ };+ });++ let dragging = false;++ function onPointerDown(ev: PointerEvent) {+ const target = ev.target;+ if (!(target instanceof HTMLElement) || !target.classList.contains('handle')) return;+ ev.preventDefault();+ dragging = true;+ handle.client?.panel_drag(true);+ try {+ target.setPointerCapture(ev.pointerId);+ } catch {+ // Without capture the drag still follows the pointer over the area.+ }+ }++ // Its right edge is the right panel's left: its width is what lies+ // between that and the pointer.+ function onPointerMove(ev: PointerEvent) {+ if (!dragging) return;+ // A release the page never saw ends the drag on the next move with no+ // button down.+ if (ev.buttons === 0) {+ onPointerUp();+ return;+ }+ const edge = document.getElementById('agents')?.getBoundingClientRect().left ?? window.innerWidth;+ wanted = edge - ev.clientX;+ width = setWidth(wanted);+ }++ function onPointerUp() {+ if (!dragging) return;+ dragging = false;+ handle.client?.panel_drag(false);+ wanted = width;+ const plugins = views.plugins.state === 'ready' ? views.plugins.rows.map((row) => row.id) : null;+ storeWidth(plugin, width, plugins);+ }+</script>++{#if room}+ <!-- The handle's drag, captured: its moves come to the area. -->+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <section+ id="extended"+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ onpointercancel={onPointerUp}+ onlostpointercapture={onPointerUp}+ >+ <div class="handle"></div>+ <PluginPanel extended />+ </section>+{/if}diff --git a/thinkterm-web/ui/src/PluginPanel.svelte b/thinkterm-web/ui/src/PluginPanel.sveltenew file mode 100644index 00000000..c47fb740--- /dev/null+++ b/thinkterm-web/ui/src/PluginPanel.svelte@@ -0,0 +1,511 @@+<script lang="ts">+ // A plugin's panel in the right panel, or -- `extended` -- its extended+ // view beside it (PluginExtended): what its player gives to paint+ // (thinkterm-plugin-panel `Painting`, through thinkterm-web/src/+ // plugin_panel.rs), painted on a canvas with the page's own fonts and+ // colours, as the desktop paints it with its own. The pointer and the+ // wheel go back to the wasm, which says whether to paint again; what the+ // plugin draws anew arrives as a new revision.+ import { handle } from './client';+ import { refreshViews, s, views } from './client.svelte';+ import { canExtend } from './extended';+ import { x as closeIcon } from './icons';+ import type { PanelOp, PanelView, Painting } from './model';++ let { extended = false }: { extended?: boolean } = $props();++ // An extended view's close button: ThinkTerm's, at its top left, where+ // the desktop has the file preview's, whatever the plugin draws. The+ // plugin is told where it is, in the canvas's units, to keep clear of it.+ const CLOSE = { x: 8, y: 4, size: 28 };++ // The page's type scale for a panel, in CSS pixels: the sizes the right+ // panel's own rows use, and a line a little over each.+ const TEXT = {+ small: { size: 12, line: 16 },+ body: { size: 14, line: 20 },+ title: { size: 16, line: 22 },+ } as const;+ const MONO = { size: 13, line: 18 };+ // The terminal's face, which the page fetched for its glyphs; registered+ // for the canvas under a name of its own, with the system's to fall back+ // on until it is.+ const MONO_FACE = 'ThinkTerm Panel Mono';+ const MONO_FAMILY = `"${MONO_FACE}", ui-monospace, Menlo, monospace`;+ const ELLIPSIS = '...';++ let host: HTMLDivElement;+ let canvas: HTMLCanvasElement;+ let view = $state<PanelView | null>(null);+ let width = 0;+ let height = 0;+ /** The revision on show, so what is on show already is not painted+ again: a hover repaints here, and its revision comes round after. */+ let painted = -1;++ type Rgba = [number, number, number, number];+ let palette: Record<string, Rgba> | null = null;+ let dark = document.documentElement.dataset.theme !== 'light';++ // ThinkTerm's colours by the names a panel uses (thinkterm-plugin-panel+ // `Token`), from the page's own tokens. The grounds are laid on the+ // panel's ground here, as the desktop lays them: a see-through green+ // reads stronger than the same green mixed.+ const SOURCES: Record<string, string> = {+ text: '--text',+ 'text-muted': '--text2',+ 'text-faint': '--muted',+ bg: '--side-bg',+ 'bg-raised': '--btn',+ 'bg-hover': '--row-hover',+ 'bg-selected': '--row-sel',+ border: '--sep',+ accent: '--accent',+ positive: '--plus',+ negative: '--minus',+ warning: '--caution',+ thumb: '--muted',+ };++ function parse(css: string): Rgba {+ const m = css.match(/rgba?\(([^)]+)\)/);+ if (!m) return [0, 0, 0, 1];+ const parts = m[1].split(/[\s,/]+/).filter((p) => p !== '').map(Number);+ return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0, parts[3] ?? 1];+ }++ function resolvePalette(): Record<string, Rgba> {+ const probe = document.createElement('span');+ probe.style.display = 'none';+ host.appendChild(probe);+ const out: Record<string, Rgba> = {};+ for (const [name, variable] of Object.entries(SOURCES)) {+ probe.style.color = `var(${variable})`;+ out[name] = parse(getComputedStyle(probe).color);+ }+ probe.remove();+ out['on-accent'] = [255, 255, 255, 1];+ const ground = out.bg;+ const [faint, strong] = dark ? [0.16, 0.34] : [0.12, 0.26];+ const mix = (over: Rgba, amount: number): Rgba => [+ Math.round(ground[0] + (over[0] - ground[0]) * amount),+ Math.round(ground[1] + (over[1] - ground[1]) * amount),+ Math.round(ground[2] + (over[2] - ground[2]) * amount),+ 1,+ ];+ out['positive-bg'] = mix(out.positive, faint);+ out['negative-bg'] = mix(out.negative, faint);+ out['positive-bg-strong'] = mix(out.positive, strong);+ out['negative-bg-strong'] = mix(out.negative, strong);+ out.thumb = [out.thumb[0], out.thumb[1], out.thumb[2], 0.55];+ return out;+ }++ /** A panel's colour: one of ThinkTerm's by name, or `#rrggbb[aa]`. A+ name the page does not know draws as text, as on the desktop. */+ function rgba(color: string): Rgba {+ if (color.startsWith('#')) {+ const hex = color.slice(1);+ if (/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(hex)) {+ const byte = (at: number) => parseInt(hex.slice(at, at + 2), 16);+ return [byte(0), byte(2), byte(4), hex.length === 8 ? byte(6) / 255 : 1];+ }+ }+ const pal = palette ?? (palette = resolvePalette());+ return pal[color] ?? pal.text;+ }++ function css([r, g, b, a]: Rgba, alpha = 1): string {+ return `rgba(${r}, ${g}, ${b}, ${a * alpha})`;+ }++ /** The interface font's family, read once a painting: reading a style+ makes the page work its styles out. */+ function uiFamily(): string {+ return getComputedStyle(document.documentElement).getPropertyValue('--ui').trim() || 'system-ui';+ }++ function font(op: Extract<PanelOp, { op: 'text' }>, family: string): string {+ if (op.font === 'mono') return `400 ${MONO.size}px ${MONO_FAMILY}`;+ return `${op.bold ? 600 : 400} ${TEXT[op.size].size}px ${family}`;+ }++ // Text as shown and how wide, remembered by font, text and -- when it is+ // ellipsized -- room: measuring is the costly part of painting a list,+ // and the same rows come back scroll after scroll. Let go of whole once+ // it grows past its bound.+ type Cut = { shown: string; wide: number };+ const cuts = new Map<string, Cut>();+ const CUTS = 4000;++ function cut(ctx: CanvasRenderingContext2D, text: string, room: number, ellipsize: boolean): Cut {+ const key = `${ctx.font}\u0000${ellipsize ? room : -1}\u0000${text}`;+ const known = cuts.get(key);+ if (known !== undefined) return known;+ let shown = text;+ let wide = ctx.measureText(text).width;+ if (ellipsize && wide > room) {+ const chars = Array.from(text);+ const budget = room - ctx.measureText(ELLIPSIS).width;+ let low = 0;+ let high = chars.length;+ while (low < high) {+ const mid = Math.ceil((low + high) / 2);+ if (ctx.measureText(chars.slice(0, mid).join('')).width <= budget) low = mid;+ else high = mid - 1;+ }+ shown = budget > 0 ? chars.slice(0, low).join('') + ELLIPSIS : '';+ wide = ctx.measureText(shown).width;+ }+ if (cuts.size >= CUTS) cuts.clear();+ const result = { shown, wide };+ cuts.set(key, result);+ return result;+ }++ function paint(painting: Painting | null) {+ const ctx = canvas?.getContext('2d');+ if (!ctx) return;+ const scale = devicePixelRatio || 1;+ ctx.setTransform(scale, 0, 0, scale, 0, 0);+ ctx.clearRect(0, 0, width, height);+ canvas.style.cursor = painting?.cursor === 'pointer' ? 'pointer' : 'default';+ if (!painting) return;+ const family = uiFamily();+ let region = -1;+ for (const op of painting.ops) {+ if (op.clip !== region) {+ if (region !== -1) ctx.restore();+ ctx.save();+ const [l, t, r, b] = painting.clips[op.clip] ?? [0, 0, width, height];+ ctx.beginPath();+ ctx.rect(l, t, r - l, b - t);+ ctx.clip();+ region = op.clip;+ }+ paintOp(ctx, op, family);+ }+ if (region !== -1) ctx.restore();+ }++ function paintOp(ctx: CanvasRenderingContext2D, op: PanelOp, family: string) {+ switch (op.op) {+ case 'rect': {+ if (op.w <= 0 || op.h <= 0) return;+ const radius = Math.max(0, Math.min(op.radius, op.w / 2, op.h / 2));+ if (op.fill !== undefined) {+ ctx.fillStyle = css(rgba(op.fill));+ ctx.beginPath();+ ctx.roundRect(op.x, op.y, op.w, op.h, radius);+ ctx.fill();+ }+ if (op.border !== undefined) {+ ctx.strokeStyle = css(rgba(op.border));+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.roundRect(op.x + 0.5, op.y + 0.5, op.w - 1, op.h - 1, Math.max(0, radius - 0.5));+ ctx.stroke();+ }+ return;+ }+ case 'text': {+ if (op.text === '' || op.w < 1) return;+ ctx.font = font(op, family);+ ctx.fillStyle = css(rgba(op.color));+ ctx.textBaseline = 'middle';+ const { shown, wide } = cut(ctx, op.text, op.w, op.font === 'ui');+ const left = Math.max(+ op.x,+ op.align === 'center' ? op.x + (op.w - wide) / 2 : op.align === 'right' ? op.x + op.w - wide : op.x,+ );+ const middle = op.y + op.h / 2;+ // The monospaced font is cut at its box's edge, not ellipsized: a+ // plugin lines its columns up itself.+ if (op.font === 'mono' && wide > op.w) {+ ctx.save();+ ctx.beginPath();+ ctx.rect(op.x, op.y, op.w, op.h);+ ctx.clip();+ ctx.fillText(shown, left, middle);+ ctx.restore();+ } else {+ ctx.fillText(shown, left, middle);+ }+ return;+ }+ case 'line': {+ if (op.points.length < 4) return;+ ctx.strokeStyle = css(rgba(op.color));+ ctx.lineWidth = op.width;+ ctx.lineJoin = 'round';+ ctx.lineCap = 'round';+ ctx.beginPath();+ ctx.moveTo(op.points[0], op.points[1]);+ for (let i = 2; i + 1 < op.points.length; i += 2) ctx.lineTo(op.points[i], op.points[i + 1]);+ ctx.stroke();+ return;+ }+ case 'area': {+ if (op.points.length < 4) return;+ const color = rgba(op.color);+ let top = op.base;+ ctx.beginPath();+ ctx.moveTo(op.points[0], op.base);+ for (let i = 0; i + 1 < op.points.length; i += 2) {+ ctx.lineTo(op.points[i], op.points[i + 1]);+ top = Math.min(top, op.points[i + 1]);+ }+ ctx.lineTo(op.points[op.points.length - 2], op.base);+ ctx.closePath();+ if (op.fade && op.base > top) {+ const fade = ctx.createLinearGradient(0, top, 0, op.base);+ fade.addColorStop(0, css(color));+ fade.addColorStop(1, css(color, 0));+ ctx.fillStyle = fade;+ } else {+ ctx.fillStyle = css(color);+ }+ ctx.fill();+ return;+ }+ case 'thumb': {+ ctx.fillStyle = css(rgba('thumb'));+ ctx.beginPath();+ ctx.roundRect(op.x, op.y, op.w, op.h, Math.min(op.w, op.h) / 2);+ ctx.fill();+ return;+ }+ }+ }++ /** Reads the panel as the wasm has it, and paints it: when it changed+ since it was last painted, or `anew`, when the canvas was cleared or+ what it is painted with changed. */+ function refresh(anew = false) {+ const revision = handle.client?.plugin_panel_revision(extended) ?? -1;+ if (!anew && revision === painted) return;+ painted = revision;+ const json = handle.client?.plugin_panel(extended);+ const next = json ? (JSON.parse(json) as PanelView | null) : null;+ view = next;+ paint(next?.painting ?? null);+ }++ /** Tells the wasm how much room there is and how text measures in it,+ and, for the panel, whether there is room beside it for its extended+ view. */+ function sendEnv() {+ const ctx = canvas?.getContext('2d');+ if (!ctx || width <= 0 || height <= 0) return;+ ctx.font = `400 ${MONO.size}px ${MONO_FAMILY}`;+ const advance = ctx.measureText('0'.repeat(20)).width / 20;+ const env = {+ width,+ height,+ scale: devicePixelRatio || 1,+ dark,+ small: TEXT.small,+ body: TEXT.body,+ title: TEXT.title,+ mono: { ...MONO, advance },+ can_extend: !extended && canExtend(),+ close: extended ? CLOSE : undefined,+ };+ const refused = handle.client?.plugin_panel_env(extended, JSON.stringify(env));+ if (refused) console.warn('plugin panel size: ' + refused);+ }++ function fit() {+ const box = host.getBoundingClientRect();+ width = Math.max(0, Math.floor(box.width));+ height = Math.max(0, Math.floor(box.height));+ const scale = devicePixelRatio || 1;+ canvas.width = Math.round(width * scale);+ canvas.height = Math.round(height * scale);+ canvas.style.width = `${width}px`;+ canvas.style.height = `${height}px`;+ sendEnv();+ refresh(true);+ }++ $effect(() => {+ const observer = new ResizeObserver(() => fit());+ observer.observe(host);+ // The theme comes and goes with a mark on the root.+ const theme = new MutationObserver(() => {+ dark = document.documentElement.dataset.theme !== 'light';+ palette = null;+ sendEnv();+ refresh(true);+ });+ theme.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });+ // The terminal's face, once: measured again when it is in.+ if (![...document.fonts].some((face) => face.family === MONO_FACE)) {+ const face = new FontFace(MONO_FACE, 'url(./fonts/JetBrainsMono-Regular.ttf)');+ document.fonts.add(face);+ face.load().then(() => {+ cuts.clear();+ sendEnv();+ refresh(true);+ }, () => {});+ }+ // The wheel scrolls the panel and nothing else: a listener that can+ // say so, which Svelte's own is not.+ const onWheel = (ev: WheelEvent) => {+ ev.preventDefault();+ const line = ev.deltaMode === 1 ? 16 : 1;+ let dx = ev.deltaX * (ev.deltaMode === 2 ? width : line);+ let dy = ev.deltaY * (ev.deltaMode === 2 ? height : line);+ // A mouse's wheel turns one way: with Shift, it goes across.+ if (ev.shiftKey && dx === 0) [dx, dy] = [dy, 0];+ const { x, y } = local(ev);+ if (handle.client?.plugin_panel_wheel(extended, x, y, dx, dy)) refresh();+ };+ canvas.addEventListener('wheel', onWheel, { passive: false });+ // The room beside the panel changes with the terminal's width: with+ // the window's, and with either panel's.+ const room = new ResizeObserver(() => sendEnv());+ const term = document.getElementById('term');+ if (!extended && term) room.observe(term);+ fit();+ return () => {+ stopFling();+ observer.disconnect();+ room.disconnect();+ theme.disconnect();+ canvas.removeEventListener('wheel', onWheel);+ };+ });++ // What the plugin drew anew.+ $effect(() => {+ void (extended ? views.extendedRevision : views.panelRevision);+ refresh();+ });++ function local(ev: MouseEvent): { x: number; y: number } {+ const box = canvas.getBoundingClientRect();+ return { x: ev.clientX - box.left, y: ev.clientY - box.top };+ }++ // A finger drags the panel's lists and scroll areas as a wheel turns+ // them, and a flick carries on a little after it lifts, as the terminal's+ // scrollback does (touch.ts). A tap is left alone: the browser sends it+ // as a click. The canvas takes no touch of the browser's own+ // (`touch-action`), so a drag never scrolls the page instead.+ const SLOP = 8;+ const FLING_DECAY = 0.94;+ const FLING_MIN = 0.04;+ type Drag = { id: number; x0: number; y0: number; x: number; y: number; at: number; vx: number; vy: number; moving: boolean };+ let drag: Drag | null = null;+ let fling: number | null = null;++ function stopFling() {+ if (fling === null) return;+ cancelAnimationFrame(fling);+ fling = null;+ }++ /** Scrolls what is under `at` (client pixels) by `dx`, `dy` of its units. */+ function scrollAt(at: { x: number; y: number }, dx: number, dy: number) {+ const box = canvas.getBoundingClientRect();+ if (handle.client?.plugin_panel_wheel(extended, at.x - box.left, at.y - box.top, dx, dy)) refresh();+ }++ function onPointerDown(ev: PointerEvent) {+ if (ev.pointerType !== 'touch') return;+ // A finger on the glass stops what a flick was still scrolling.+ stopFling();+ if (drag) return;+ drag = { id: ev.pointerId, x0: ev.clientX, y0: ev.clientY, x: ev.clientX, y: ev.clientY, at: ev.timeStamp, vx: 0, vy: 0, moving: false };+ }++ function onPointerMove(ev: PointerEvent) {+ if (ev.pointerType === 'touch') {+ if (!drag || ev.pointerId !== drag.id) return;+ if (!drag.moving && Math.hypot(ev.clientX - drag.x0, ev.clientY - drag.y0) < SLOP) return;+ drag.moving = true;+ // Up the glass is down the list, as a wheel turned toward you is.+ const dx = drag.x - ev.clientX;+ const dy = drag.y - ev.clientY;+ const dt = Math.max(1, ev.timeStamp - drag.at);+ drag.vx = 0.8 * (dx / dt) + 0.2 * drag.vx;+ drag.vy = 0.8 * (dy / dt) + 0.2 * drag.vy;+ drag.x = ev.clientX;+ drag.y = ev.clientY;+ drag.at = ev.timeStamp;+ scrollAt(drag, dx, dy);+ return;+ }+ const { x, y } = local(ev);+ if (handle.client?.plugin_panel_pointer(extended, x, y)) refresh();+ }++ function onPointerUp(ev: PointerEvent) {+ if (!drag || ev.pointerId !== drag.id) return;+ const { moving, at, x, y } = drag;+ let { vx, vy } = drag;+ drag = null;+ // A flick carries on; a finger that stopped before lifting does not.+ if (!moving || ev.type === 'pointercancel' || ev.timeStamp - at > 80) return;+ if (Math.hypot(vx, vy) < FLING_MIN) return;+ let last = performance.now();+ const tick = (now: number) => {+ const dt = Math.min(now - last, 64);+ last = now;+ scrollAt({ x, y }, vx * dt, vy * dt);+ const keep = Math.pow(FLING_DECAY, dt / 16);+ vx *= keep;+ vy *= keep;+ fling = Math.hypot(vx, vy) < FLING_MIN ? null : requestAnimationFrame(tick);+ };+ fling = requestAnimationFrame(tick);+ }++ function onPointerLeave(ev: PointerEvent) {+ if (ev.pointerType === 'touch') return;+ if (handle.client?.plugin_panel_leave(extended)) refresh();+ }++ /** The close button: the view goes at once, and its plugin hears so. */+ function onClose(ev: MouseEvent) {+ ev.preventDefault();+ handle.client?.plugin_extended_close();+ refreshViews();+ }++ function onMouseDown(ev: MouseEvent) {+ const { x, y } = local(ev);+ const heard = handle.client?.plugin_panel_click(+ extended, x, y, ev.button, Math.max(1, ev.detail), ev.shiftKey, ev.ctrlKey, ev.altKey, ev.metaKey,+ );+ if (heard) {+ ev.preventDefault();+ refresh();+ }+ }+</script>++<div class="plugin" class:extended bind:this={host}>+ <canvas+ bind:this={canvas}+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ onpointercancel={onPointerUp}+ onpointerleave={onPointerLeave}+ onmousedown={onMouseDown}+ ></canvas>+ {#if view?.message}+ <div class="msg">{view.message}</div>+ {/if}+ {#if extended}+ <button+ class="close"+ type="button"+ title={s('web-settings-close')}+ style="left: {CLOSE.x}px; top: {CLOSE.y}px; width: {CLOSE.size}px; height: {CLOSE.size}px"+ onclick={onClose}+ >{@html closeIcon}</button>+ {/if}+</div>diff --git a/thinkterm-web/ui/src/SettingsPanel.svelte b/thinkterm-web/ui/src/SettingsPanel.svelteindex 27089fb7..d758314a 100644--- a/thinkterm-web/ui/src/SettingsPanel.svelte+++ b/thinkterm-web/ui/src/SettingsPanel.svelte@@ -101,6 +101,13 @@if (field instanceof HTMLInputElement) void handle.client?.plugin_set_enabled(id, field.checked);}+ /** How long a plugin runs unused, as the desktop's settings offer it. */+ const BACKGROUNDS = [+ ['always', 'settings-plugins-background-always'],+ ['briefly', 'settings-plugins-background-briefly'],+ ['never', 'settings-plugins-background-never'],+ ] as const;+async function reloadPlugins() {reloading = true;try {@@ -413,7 +420,15 @@{#if row.builtin}<!-- Its switch is its panel's, above. -->{:else if row.switchable}- <label class="switch"><input type="checkbox" data-plugin-switch={row.id} checked={row.enabled} onchange={(ev) => onPlugin(row.id, ev)} /><span class="knob"></span></label>+ <div class="ctl">+ {#if row.background}+ <!-- How long it runs unused, beside its switch. -->+ <select class="pillsel" data-plugin-background={row.id} title={row.background_detail} value={row.background} onchange={(ev) => void handle.client?.plugin_set_background(row.id, (ev.currentTarget as HTMLSelectElement).value)}>+ {#each BACKGROUNDS as [value, label] (value)}<option {value}>{s(label)}</option>{/each}+ </select>+ {/if}+ <label class="switch"><input type="checkbox" data-plugin-switch={row.id} checked={row.enabled} onchange={(ev) => onPlugin(row.id, ev)} /><span class="knob"></span></label>+ </div>{:else}<span class="pilltag">{s('settings-plugins-unusable')}</span>{/if}diff --git a/thinkterm-web/ui/src/client.svelte.ts b/thinkterm-web/ui/src/client.svelte.tsindex c3851198..691c296e 100644--- a/thinkterm-web/ui/src/client.svelte.ts+++ b/thinkterm-web/ui/src/client.svelte.ts@@ -15,11 +15,18 @@ export const views = $state({reveal: { edge: 6, dwell_ms: 150, retreat_ms: 250 }, footer: [], footer_label_min_width: 168,} as SidebarView,/** The right-hand panel's rows, whether it is on show or not. */- agents: { rows: [], summary: '', tabs: [], active: 'agents' } as AgentsView,+ agents: { rows: [], summary: '', tabs: [], active: 'agents', labeled: true } as AgentsView,/** The right panel's Snippets tab; loading until it is first on show. */snippets: { state: 'loading', reason: null, rows: [], query: '', empty: '', answers: null, asked: 0, revision: 0 } as SnippetsView,/** The plugin list in Settings › Sidebar & Plugins. */plugins: { state: 'loading', status: '', rows: [], refused: null, revision: 0 } as PluginsView,+ /** Changes when a plugin's panel is to be painted anew (PluginPanel). */+ panelRevision: 0,+ /** The same, for the panel's extended view. */+ extendedRevision: 0,+ /** The panel on show asks for room beside the right panel for its+ extended view (PluginExtended). */+ panelExtended: false,/** The page's own preferences, as the wasm holds them (settings.rs). */settings: {language: 'system',@@ -69,6 +76,8 @@ export function attach(client: Client) {// The snippets can be long; their view is read only when it moved.let lastSnippets = -1;let lastPlugins = -1;+ let lastPanel = -1;+ let lastExtended = -1;let lastSettings = '';const read = () => {const strings = client.strings();@@ -114,6 +123,17 @@ export function attach(client: Client) {lastPlugins = plugins;views.plugins = JSON.parse(client.plugins()) as PluginsView;}+ const panel = client.plugin_panel_revision(false);+ if (panel !== lastPanel) {+ lastPanel = panel;+ views.panelRevision = panel;+ }+ const extended = client.plugin_panel_revision(true);+ if (extended !== lastExtended) {+ lastExtended = extended;+ views.extendedRevision = extended;+ }+ views.panelExtended = client.plugin_panel_extended();const settings = client.settings();if (settings !== lastSettings) {lastSettings = settings;diff --git a/thinkterm-web/ui/src/extended.ts b/thinkterm-web/ui/src/extended.tsnew file mode 100644index 00000000..3fced41c--- /dev/null+++ b/thinkterm-web/ui/src/extended.ts@@ -0,0 +1,56 @@+// The room a plugin panel's extended view has, left of the right panel:+// sized as the desktop sizes it (`right_sidebar.rs`, the file preview's+// widths), and kept per plugin in this browser.++export const EXTENDED_MIN = 360;+export const EXTENDED_DEFAULT = 560;++/** The most the extended view can have: what is left of the window beside+ the two panels, less the fifth the terminal keeps. None on a phone,+ whose panels are drawers over the terminal. */+export function extendedRoom(): number {+ if (document.body.dataset.mobile !== undefined) return 0;+ const style = getComputedStyle(document.body);+ const px = (name: string) => parseFloat(style.getPropertyValue(name)) || 0;+ return window.innerWidth - px('--side-w') - px('--agents-w') - window.innerWidth / 5;+}++/** Whether there is room for an extended view at all. */+export function canExtend(): boolean {+ return extendedRoom() >= EXTENDED_MIN;+}++const STORE = 'thinkterm.plugin-extended-widths';++function stored(): Record<string, number> {+ try {+ const raw = localStorage.getItem(STORE);+ const widths = raw ? (JSON.parse(raw) as unknown) : null;+ if (widths && typeof widths === 'object') return widths as Record<string, number>;+ } catch {+ // A browser that blocks storage starts every plugin at the default.+ }+ return {};+}++/** How wide plugin `plugin`'s extended view was last made here. */+export function storedWidth(plugin: string): number {+ const width = stored()[plugin];+ return typeof width === 'number' && Number.isFinite(width) ? width : EXTENDED_DEFAULT;+}++/** Keeps `width` for plugin `plugin`, and forgets the plugins no longer+ among `plugins` -- every one the host lists, on or off, as the desktop+ keeps them; `null` while the list is not known, when none is forgotten. */+export function storeWidth(plugin: string, width: number, plugins: string[] | null) {+ const widths: Record<string, number> = {};+ for (const [id, kept] of Object.entries(stored())) {+ if (plugins === null || plugins.includes(id)) widths[id] = kept;+ }+ widths[plugin] = Math.round(width);+ try {+ localStorage.setItem(STORE, JSON.stringify(widths));+ } catch {+ // As above: the width is then this page load's only.+ }+}diff --git a/thinkterm-web/ui/src/icons.ts b/thinkterm-web/ui/src/icons.tsindex 4280818f..7b5bc411 100644--- a/thinkterm-web/ui/src/icons.ts+++ b/thinkterm-web/ui/src/icons.ts@@ -52,6 +52,20 @@ import trash2 from '../../../third_party/lucide/icons/trash-2.svg?raw';import x from '../../../third_party/lucide/icons/x.svg?raw';import zoomIn from '../../../third_party/lucide/icons/zoom-in.svg?raw';import zoomOut from '../../../third_party/lucide/icons/zoom-out.svg?raw';+// What a plugin's panel is shown by in the selector (thinkterm-plugin-panel+// ICONS), the puzzle piece for any other.+import activity from '../../../third_party/lucide/icons/activity.svg?raw';+import bug from '../../../third_party/lucide/icons/bug.svg?raw';+import calendar from '../../../third_party/lucide/icons/calendar.svg?raw';+import chartCandlestick from '../../../third_party/lucide/icons/chart-candlestick.svg?raw';+import chartLine from '../../../third_party/lucide/icons/chart-line.svg?raw';+import cpu from '../../../third_party/lucide/icons/cpu.svg?raw';+import database from '../../../third_party/lucide/icons/database.svg?raw';+import gauge from '../../../third_party/lucide/icons/gauge.svg?raw';+import gitBranch from '../../../third_party/lucide/icons/git-branch.svg?raw';+import gitCompare from '../../../third_party/lucide/icons/git-compare.svg?raw';+import listTodo from '../../../third_party/lucide/icons/list-todo.svg?raw';+import puzzle from '../../../third_party/lucide/icons/puzzle.svg?raw';// The two brand marks the Agents panel draws (simple-icons): a single// fill-less path, so they take their colour from CSS `fill: currentColor`// rather than from `stroke` as the lucide icons above do.@@ -169,9 +183,24 @@ const BY_NAME: Record<string, string> = {/** A lucide icon by its name; nothing for a name the page has not inlined. */export function iconByName(name: string): string | undefined {- return BY_NAME[name];+ return BY_NAME[name] ?? PANEL_ICONS[name];}+const PANEL_ICONS: Record<string, string> = {+ activity,+ bug,+ calendar,+ 'chart-candlestick': chartCandlestick,+ 'chart-line': chartLine,+ cpu,+ database,+ gauge,+ 'git-branch': gitBranch,+ 'git-compare': gitCompare,+ 'list-todo': listTodo,+ puzzle,+};+// An agent row names its mark the way `agents.rs` does: a brand when the// page has one, `bot` otherwise. Kept apart from `BY_NAME` above, which is// lucide's names and nothing else.diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.tsindex 39e42afb..29fe9027 100644--- a/thinkterm-web/ui/src/model.ts+++ b/thinkterm-web/ui/src/model.ts@@ -201,7 +201,9 @@ export type PanelTab = {tip: string;};-export type AgentsView = { rows: AgentRow[]; summary: string; tabs: PanelTab[]; active: string };+/** `labeled`: the active tab carries its label; past five tabs, none+ does (`agents.rs` `LABELED_TABS`). */+export type AgentsView = { rows: AgentRow[]; summary: string; tabs: PanelTab[]; active: string; labeled: boolean };// The right panel's Snippets tab (thinkterm-web/src/snippets.rs// `SnippetsView`): the snippets the plugin host keeps, filtered by the@@ -242,6 +244,10 @@ export type PluginRow = {switchable: boolean;/** Built into ThinkTerm: its switch is its panel's, not in the list. */builtin: boolean;+ /** How long an installed plugin that is on runs unused; none for others. */+ background: 'always' | 'briefly' | 'never' | null;+ /** What that choice means, and whether it is the plugin's own. */+ background_detail: string;};export type PluginsView = {@@ -255,6 +261,46 @@ export type PluginsView = {revision: number;};+// A plugin's panel in the right panel (thinkterm-web/src/plugin_panel.rs+// `PanelView`; its painting is thinkterm-plugin-panel's `Painting`): what to+// paint, in CSS pixels from the panel's corner, each op cut to a region.+// Colours are ThinkTerm's by name (`text`, `bg-hover`, `positive-bg`...),+// or `#rrggbb[aa]`.++export type PanelOp =+ | { op: 'rect'; clip: number; x: number; y: number; w: number; h: number; fill?: string; border?: string; radius: number }+ | {+ op: 'text';+ clip: number;+ x: number;+ y: number;+ w: number;+ h: number;+ text: string;+ color: string;+ font: 'ui' | 'mono';+ size: 'small' | 'body' | 'title';+ bold: boolean;+ align: 'left' | 'center' | 'right';+ }+ | { op: 'line'; clip: number; points: number[]; width: number; color: string }+ | { op: 'area'; clip: number; points: number[]; base: number; color: string; fade: boolean }+ | { op: 'thumb'; clip: number; x: number; y: number; w: number; h: number };++export type Painting = {+ /** Left, top, right, bottom. */+ clips: [number, number, number, number][];+ ops: PanelOp[];+ cursor: 'pointer' | 'arrow' | null;+};++export type PanelView = {+ state: 'starting' | 'open' | 'stopped';+ /** Said instead of a painting: starting, or why it stopped. */+ message: string | null;+ painting: Painting | null;+};+// The page's own preferences (thinkterm-web/src/settings.rs `WebSettings`),// whose JSON names are kebab-case.diff --git a/thinkterm-web/ui/src/tokens.css b/thinkterm-web/ui/src/tokens.cssindex 4fe16cd1..1b03ec5d 100644--- a/thinkterm-web/ui/src/tokens.css+++ b/thinkterm-web/ui/src/tokens.css@@ -8,8 +8,11 @@--text: #F2F2F7; --text2: #C7C7CC; --muted: #8E8E93; --accent: #0A84FF; --danger: #FF453A;--wash: rgba(242,242,247,.025); --ring: rgba(242,242,247,.12); --edge: rgba(242,242,247,.38); --shadow: 0 .5px 0 1px rgba(0,0,0,.12);--ui: -apple-system, "SF Pro Text", "Helvetica Neue", Roboto, system-ui, sans-serif;- --tabs: 40px; --side-w: 220px; --side-px: 220px; --agents-w: 0px; --keybar: 0px;+ --tabs: 40px; --side-w: 220px; --side-px: 220px; --agents-w: 0px; --ext-w: 0px; --keybar: 0px;--done: #7CE5A2; --open: #61B8FF; --warn: #DB7320;+ /* A plugin panel's added, removed and caution colours (plugin_panel.rs+ on the desktop), which the chrome has no use for elsewhere. */+ --plus: #3FB950; --minus: #F85149; --caution: #D29922;/* Measured off the desktop's own frames: its round buttons and pills(#262628), its selected row (#3E3E41), its settings card (#1D1D1F). */--btn: #262628; --btn-hover: #313134; --btn-border: rgba(118,118,128,.35);@@ -22,12 +25,15 @@ body[data-side=off] { --side-w: 0px; }the mark on the body -- which the panel itself puts there -- nothingleaves room for it. */body:not([data-agents]) { --agents-w: 0px; }+/* So is a plugin panel's extended view's, left of the panel. */+body:not([data-agents]), body:not([data-extended]) { --ext-w: 0px; }[data-theme=light] {--bg: #EEEEF2; --side-bg: #E2E2E8; --sep: rgba(60,60,67,.18);--ctl: rgba(255,255,255,.94); --ctl-hover: rgba(247,247,250,.98); --ctl-pressed: rgba(232,242,255,.98); --ctl-border: rgba(60,60,67,.20);--text: #1C1C1E; --text2: #48484A; --muted: #8E8E93; --accent: #007AFF; --danger: #D7263D;--wash: rgba(28,28,30,.025); --ring: rgba(28,28,30,.12); --edge: rgba(28,28,30,.38); --shadow: 0 .5px 0 1px rgba(0,0,0,.04);--warn: #C05F14;+ --plus: #1A7F37; --minus: #CF222E; --caution: #9A6700;--btn: rgba(255,255,255,.86); --btn-hover: #FFFFFF; --btn-border: rgba(60,60,67,.24);--row-hover: rgba(28,28,30,.06); --row-sel: rgba(255,255,255,.94);--card: rgba(255,255,255,.72); --card-border: rgba(60,60,67,.16); --card-line: rgba(60,60,67,.14);@@ -40,7 +46,7 @@ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text2)#app { display: contents; }svg { width: 16px; height: 16px; flex: none; }/* The window's tab row. Capsules never shrink; the row scrolls. */-#tabs { position: absolute; left: var(--side-w); right: var(--agents-w); top: 0; height: var(--tabs); box-sizing: border-box; display: flex; align-items: center; gap: 9px; padding: 2px 8px 0 8px; background: var(--bg); overflow-x: auto; overflow-y: hidden; white-space: nowrap; user-select: none; scrollbar-width: none; }+#tabs { position: absolute; left: var(--side-w); right: calc(var(--agents-w) + var(--ext-w)); top: 0; height: var(--tabs); box-sizing: border-box; display: flex; align-items: center; gap: 9px; padding: 2px 8px 0 8px; background: var(--bg); overflow-x: auto; overflow-y: hidden; white-space: nowrap; user-select: none; scrollbar-width: none; }#tabs::-webkit-scrollbar { display: none; }#tabs .tab { display: inline-flex; align-items: center; flex: 0 0 auto; width: 128px; height: 30px; box-sizing: border-box; padding: 0 9px; border-radius: 999px; border: 1px solid transparent; color: var(--text2); cursor: default; transition: var(--fade); }#tabs .tab:hover { background: var(--ctl-hover); }@@ -57,12 +63,12 @@ svg { width: 16px; height: 16px; flex: none; }#tabs .follow { color: var(--muted); font-size: 12px; padding: 0 8px; height: 24px; line-height: 24px; border-radius: 999px; cursor: default; }#tabs .follow.on { color: var(--accent); }#tabs .follow:hover { background: var(--ctl-hover); }-#term { position: absolute; inset: var(--tabs) var(--agents-w) 0 var(--side-w); width: calc(100% - var(--side-w) - var(--agents-w)); height: calc(100% - var(--tabs)); display: block; outline: none; }+#term { position: absolute; inset: var(--tabs) calc(var(--agents-w) + var(--ext-w)) 0 var(--side-w); width: calc(100% - var(--side-w) - var(--agents-w) - var(--ext-w)); height: calc(100% - var(--tabs)); display: block; outline: none; }/* Its own layer: the sidebar's edge moves the canvas on every drag frame,and a promoted layer moves instead of being laid out again. */canvas#term { will-change: transform; }/* One bar over each pane, laid out from the canvas's cells. */-#panes { position: absolute; inset: var(--tabs) var(--agents-w) 0 var(--side-w); pointer-events: none; overflow: hidden; }+#panes { position: absolute; inset: var(--tabs) calc(var(--agents-w) + var(--ext-w)) 0 var(--side-w); pointer-events: none; overflow: hidden; }/* The desktop's left sidebar: Spaces, Projects, Threads. Every row's boxspans the panel's 10px insets, so a trailing control's centre lands 25pxfrom the right edge, round button or hover action alike. */@@ -208,6 +214,13 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#agents .mode { display: inline-flex; align-items: center; justify-content: center; gap: 6px; flex: 1 1 0; min-width: 0; box-sizing: border-box; border-radius: 999px; border: 1px solid transparent; color: var(--text2); font-size: 13px; cursor: default; transition: var(--fade); }#agents .mode svg { width: 15px; height: 15px; }#agents .mode.on { flex: 0 1 auto; padding: 0 11px; background: var(--ctl); border-color: var(--ctl-border); box-shadow: var(--shadow); color: var(--text); }+/* Past five tabs, the active one is its icon alone, a share like the rest,+ its pill a circle round the icon: 28px, the height the pill has with its+ label (the selector's 34px less its padding and border), and no wider+ than its share. */+#agents .modes.icons .mode.on { flex: 1 1 0; padding: 0; position: relative; background: none; border-color: transparent; box-shadow: none; }+#agents .modes.icons .mode.on::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 28px; max-width: 100%; aspect-ratio: 1; box-sizing: border-box; border-radius: 50%; background: var(--ctl); border: 1px solid var(--ctl-border); box-shadow: var(--shadow); }+#agents .modes.icons .mode.on svg { position: relative; }#agents .mode .ml { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }/* Nothing to press: the tooltip is the whole answer, so no hover lift. */#agents .mode.off { color: var(--muted); opacity: .55; }@@ -251,6 +264,20 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#agents .sb-save { flex: none; height: 30px; padding: 0 14px; border-radius: 999px; background: var(--accent); border: 0; color: #fff; font: 600 13px var(--ui); }/* The toolbar line sits 6px lower than the summary it replaces. */#agents .list.snippets, #agents .list.snippet-editor { top: 122px; }+/* A plugin's panel: its canvas under the selector, to the panel's edges;+ the plugin draws its own margins. */+#agents .plugin { position: absolute; inset: 86px 0 0 0; }+#agents .plugin canvas, #extended .plugin canvas { display: block; touch-action: none; }+#agents .plugin .msg, #extended .plugin .msg { position: absolute; left: 12px; right: 12px; top: 8px; color: var(--muted); font-size: 13px; }+/* A plugin panel's extended view (PluginExtended): the wide area left of+ the panel, the plugin's from its top, as the desktop's is. */+#extended { position: absolute; right: var(--agents-w); top: 0; bottom: 0; width: var(--ext-w); box-sizing: border-box; background: var(--side-bg); border-left: 1px solid var(--sep); user-select: none; overflow: hidden; }+#extended .handle { position: absolute; left: -2px; top: 0; bottom: 0; width: 4px; cursor: col-resize; z-index: 1; }+#extended .plugin { position: absolute; inset: 8px 0 0 0; }+#extended .plugin .msg { left: 44px; }+#extended .close { position: absolute; display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; padding: 0; border: 0; border-radius: 8px; background: transparent; color: var(--text2); cursor: pointer; transition: var(--fade); }+#extended .close svg { width: 16px; height: 16px; }+#extended .close:hover { background: var(--row-hover); color: var(--text); }#agents .list.snippets { gap: 8px; }#agents .sn { display: flex; flex-direction: column; gap: 6px; flex: none; box-sizing: border-box; padding: 10px 12px; border-radius: 14px; background: var(--btn); border: 1px solid var(--btn-border); transition: var(--fade); }#agents .sn:hover { background: var(--btn-hover); border-color: var(--ctl-border); }@@ -291,7 +318,7 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#card:not([hidden]) { animation: card-in .16s cubic-bezier(0,0,.2,1); }/* The desktop's opaque surface: the terminal area, nothing of the paneshowing through, the text a little above centre as the desktop's is. */-#card { position: absolute; inset: var(--tabs) var(--agents-w) 0 var(--side-w); z-index: 12; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 24px; box-sizing: border-box; text-align: center; background: var(--bg); user-select: none; cursor: default; }+#card { position: absolute; inset: var(--tabs) calc(var(--agents-w) + var(--ext-w)) 0 var(--side-w); z-index: 12; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 24px; box-sizing: border-box; text-align: center; background: var(--bg); user-select: none; cursor: default; }#card[hidden] { display: none; }#card .eyes { font: 20px var(--ui); color: var(--text); letter-spacing: 2px; margin-bottom: 18px; }#card .title { font: 500 17px var(--ui); color: var(--text); }@@ -429,7 +456,7 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }takes the width, the two panels become drawers over it, and a key barsupplies the keys a soft keyboard has not got. */body[data-mobile] {- --side-w: 0px; --agents-w: 0px; --tabs: 46px;+ --side-w: 0px; --agents-w: 0px; --ext-w: 0px; --tabs: 46px;/* What the notch, the rounded corners and the home indicator take. Zeroeverywhere the browser reports nothing, which is every desktop. */--safe-t: env(safe-area-inset-top, 0px);