Skip to content

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

feat(web): add a Snippets tab to the right panel

RoversXa9adbb7db49c
diff --git a/thinkterm-web/Cargo.toml b/thinkterm-web/Cargo.toml
index 1911c9d4..f7fe4d02 100644
--- a/thinkterm-web/Cargo.toml
+++ b/thinkterm-web/Cargo.toml
@@ -28,9 +28,11 @@ termwiz = { workspace = true, features = ["use_serde"] }
thinkterm-font-core.workspace = true
thinkterm-font-web.workspace = true
thinkterm-i18n.workspace = true
+thinkterm-plugin-channel.workspace = true
thinkterm-proto.workspace = true
thinkterm-render = { workspace = true, features = ["wgpu"] }
thinkterm-session.workspace = true
+thinkterm-snippets.workspace = true
wezterm-color-types.workspace = true
wezterm-term = { workspace = true, features = ["use_serde"] }
wgpu.workspace = true
diff --git a/thinkterm-web/smoke/snippets-test.js b/thinkterm-web/smoke/snippets-test.js
new file mode 100644
index 00000000..8f089e9d
--- /dev/null
+++ b/thinkterm-web/smoke/snippets-test.js
@@ -0,0 +1,286 @@
+// The Snippets tab end to end, against a throwaway server whose plugin host
+// keeps one snippet already: the tab lists it, a snippet added in the
+// editor reaches the host's file, the search filters, Run types a snippet
+// into the terminal, another client's change arrives by itself, a delete
+// takes two presses, a Run lands in the pane focused at the press even when
+// focus moves before the host answers, and nowhere when the answer comes
+// too late; a killed host is replaced; and through a link with 50 ms each
+// way added, a search is timed and typing's requests are counted.
+// node snippets-test.js <url> <out.png>
+// Reads SNIPPETS_FILE (the host's file), TEST_HOME (the server's HOME) and
+// MUX_CLI (`thinkterm cli` pinned to the server) from the environment.
+const { spawn, execSync } = require("child_process");
+const http = require("http"); const fs = require("fs"); const os = require("os"); const net = require("net");
+const WebSocket = require("ws");
+const [url, outPng] = process.argv.slice(2);
+const { SNIPPETS_FILE, TEST_HOME, MUX_CLI, SLOW_PORT } = process.env;
+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); }, 240000).unref();
+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-snippets-`);
+const chrome = spawn(chromePath, ["--headless=new", "--no-first-run", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=1400,800", "--hide-scrollbars", "--enable-unsafe-webgpu", "about:blank"], { stdio: "ignore" });
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+async function browserWs() { for (let i = 0; i < 50; i++) { try { return await new Promise((res, rej) => http.get(`http://127.0.0.1:${port}/json/version`, (r) => { let b = ""; r.on("data", (d) => b += d); r.on("end", () => res(JSON.parse(b).webSocketDebuggerUrl)); }).on("error", rej)); } catch { await sleep(200); } } throw new Error("chrome did not come up"); }
+
+const socketPath = `${TEST_HOME}/.local/share/thinkterm/plugins-sock`;
+const hostPids = () => { try { return execSync(`pgrep -f ${JSON.stringify(socketPath)}`).toString().trim().split(/\s+/).filter(Boolean); } catch { return []; } };
+const onDisk = () => { try { return fs.readFileSync(SNIPPETS_FILE, "utf8"); } catch { return ""; } };
+// A pane's text, or every pane's.
+const paneText = (pane) => execSync(`${MUX_CLI} get-text --pane-id ${pane}`).toString();
+const allText = () => JSON.parse(execSync(`${MUX_CLI} list --format json`).toString())
+ .map((p) => paneText(p.pane_id)).join("\n");
+const printed = (text, marker) => text.split("\n").some((l) => l.trim() === marker);
+
+// A link to the server on `port` that holds every chunk back `delay` ms
+// each way, in order: a browser some way off.
+function slowLink(port, target, delay) {
+ return new Promise((resolve) => {
+ const server = net.createServer((client) => {
+ const upstream = net.connect(target, "127.0.0.1");
+ const relay = (from, to) => {
+ let last = 0;
+ // Everything, the end included, leaves in the order it came.
+ const later = (act) => {
+ const at = Math.max(Date.now() + delay, last);
+ last = at;
+ setTimeout(act, at - Date.now());
+ };
+ from.on("data", (chunk) => later(() => to.write(chunk)));
+ from.on("end", () => later(() => to.end()));
+ from.on("error", () => later(() => to.destroy()));
+ };
+ relay(client, upstream);
+ relay(upstream, client);
+ });
+ server.listen(port, "127.0.0.1", () => resolve(server));
+ });
+}
+
+// Another client of the host, as the desktop is: one frame out, the hello
+// and the answer back.
+function saveFromElsewhere(title, body) {
+ return new Promise((resolve, reject) => {
+ const sock = net.createConnection(socketPath);
+ let buf = Buffer.alloc(0); let frames = 0;
+ sock.on("data", (d) => {
+ buf = Buffer.concat([buf, d]);
+ while (buf.length >= 4 && buf.length >= 4 + buf.readUInt32LE(0)) {
+ const len = buf.readUInt32LE(0); const msg = JSON.parse(buf.subarray(4, 4 + len).toString()); buf = buf.subarray(4 + len);
+ frames++;
+ if (frames === 1) {
+ if (!msg.hello) return reject(new Error("no hello: " + JSON.stringify(msg)));
+ const payload = Buffer.from(JSON.stringify({ call: { id: 1, plugin: "snippets", body: { op: "save", title, body } } }));
+ const head = Buffer.alloc(4); head.writeUInt32LE(payload.length, 0);
+ sock.write(Buffer.concat([head, payload]));
+ } else if (msg.ok) { sock.end(); return resolve(); }
+ else if (msg.error) { sock.end(); return reject(new Error(msg.error.message)); }
+ }
+ });
+ sock.on("error", reject);
+ });
+}
+
+(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 type = (sel, text) => ev(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; el.value = ${JSON.stringify(text)}; el.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
+ const titles = () => ev("[...document.querySelectorAll('#agents .sn .sn-title')].map((e) => e.textContent)");
+ const card = (title) => `[...document.querySelectorAll('#agents .sn')].find((c) => c.querySelector('.sn-title').textContent === ${JSON.stringify(title)})`;
+ const cardButton = (title, n) => ev(`(() => { const c = ${card(title)}; if (!c) return false; c.querySelectorAll('.sn-btn')[${n}].click(); return true; })()`);
+ const fail = (what) => { throw new Error(what); };
+ const attached = async () => /this browser has/.test(await ev("document.getElementById('status').dataset.summary || ''"));
+ const out = {};
+
+ await send("Page.navigate", { url }, s);
+ await until("attach", attached, 20000);
+ await sleep(600);
+ if (hostPids().length) fail("a plugin host runs before anything asked for one");
+
+ // --- (a) the panel's Snippets tab lists what the host keeps.
+ if (!(await click("#tabs [data-action=agents]"))) fail("no right-panel button in the tab row");
+ await until("the panel", () => ev("!!document.getElementById('agents')"));
+ if (!(await click("#agents .mode[data-mode=snippets]"))) fail("no Snippets tab in the selector");
+ await until("the seeded snippet", async () => (await titles()).includes("List files"));
+ out.heading = await ev("document.querySelector('#agents .hd .ti').textContent");
+ if (out.heading !== "Snippets") fail("the heading is " + JSON.stringify(out.heading));
+ out.preview = await ev(`${card("List files")}.querySelector('.sn-preview').textContent`);
+ if (out.preview !== "ls -la") fail("the preview is " + JSON.stringify(out.preview));
+ out.hosts = hostPids().length;
+ if (out.hosts !== 1) fail(`${out.hosts} plugin hosts run`);
+ out.list = "ok";
+
+ // --- (b) one added in the editor reaches the host's file.
+ const marker = `snippet-ran-${process.pid}`;
+ if (!(await click("#agents .sbar .sb-icon"))) fail("no new-snippet button");
+ await until("the editor", () => ev("!!document.getElementById('snippet-body')"));
+ await type("#snippet-title", "Say hi");
+ await type("#snippet-body", `echo ${marker}`);
+ if (!(await click("#agents .sb-save"))) fail("no save button");
+ await until("the new card", async () => (await titles()).includes("Say hi"));
+ await until("the host to save it", () => onDisk().includes(marker));
+ out.order = await titles();
+ if (out.order[0] !== "Say hi") fail("the new snippet is not first: " + JSON.stringify(out.order));
+ out.add = "ok";
+
+ // --- (c) the search filters as the desktop's does.
+ await type("#agents .sb-search input", "SAY");
+ await until("the filter", async () => JSON.stringify(await titles()) === JSON.stringify(["Say hi"]));
+ await type("#agents .sb-search input", "nothing like it");
+ await until("the empty list", () => ev("document.querySelector('#agents .sn-empty-t')?.textContent === 'No matching snippets'"));
+ await type("#agents .sb-search input", "");
+ await until("the whole list", async () => (await titles()).length === 2);
+ out.search = "ok";
+
+ // --- (d) Run types it into the terminal and runs it.
+ if (!(await cardButton("Say hi", 0))) fail("no Run button");
+ await until("the command's output", () => printed(allText(), marker), 10000);
+ out.run = "ok";
+
+ // --- (e) another client's change arrives by itself.
+ await saveFromElsewhere("From elsewhere", "uptime");
+ await until("the other client's snippet", async () => (await titles()).includes("From elsewhere"));
+ out.pushed = "ok";
+
+ const shot = await send("Page.captureScreenshot", { format: "png" }, s); fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));
+
+ // --- (f) a delete takes two presses.
+ if (!(await cardButton("Say hi", 2))) fail("no delete button");
+ await sleep(200);
+ if (!(await titles()).includes("Say hi")) fail("one press deleted it");
+ out.armed = await ev(`${card("Say hi")}.querySelector('.sn-del').textContent`);
+ if (out.armed !== "delete?") fail("the armed button says " + JSON.stringify(out.armed));
+ await cardButton("Say hi", 2);
+ await until("the card to go", async () => !(await titles()).includes("Say hi"));
+ await until("the host to forget it", () => !onDisk().includes(`"body": "echo ${marker}"`));
+ out.delete = "ok";
+
+ // --- (h) a Run lands in the pane focused when it was pressed, though
+ // focus moves on while the host is held up; one whose answer comes too
+ // late is not sent at all.
+ const navs = async () => ev("[...document.querySelectorAll('#panes .nav')].map((n) => Number(n.dataset.nav))");
+ const focusedPane = async () => Number(await ev("document.querySelector('#panes .nav.focused')?.dataset.nav"));
+ const focusPane = async (pane) => {
+ await ev(`window.thinkterm.client.chrome_click('pane', ${pane}, undefined)`);
+ await until(`pane ${pane} to be focused`, async () => (await focusedPane()) === pane);
+ };
+ const [left, right] = await until("two panes on show", async () => { const n = await navs(); return n.length === 2 ? n : null; }).catch(async (e) => {
+ console.error("navs:", JSON.stringify(await navs()), "tabs:", await ev("window.thinkterm.client.tabs()"), "list:", execSync(`${MUX_CLI} list`).toString());
+ throw e;
+ });
+ const target = `snippet-target-${process.pid}`;
+ const late = `snippet-late-${process.pid}`;
+ for (const [title, body] of [["Target", `echo ${target}`], ["Late", `echo ${late}`]]) {
+ await saveFromElsewhere(title, body);
+ await until(`the ${title} card`, async () => (await titles()).includes(title));
+ }
+ await focusPane(left);
+ const [stalled] = hostPids();
+ process.kill(Number(stalled), "SIGSTOP");
+ await cardButton("Target", 0);
+ await sleep(150);
+ await focusPane(right);
+ await sleep(500);
+ process.kill(Number(stalled), "SIGCONT");
+ await until("the run in the pane it was pressed in", () => printed(paneText(left), target), 10000);
+ await sleep(500);
+ if (printed(paneText(right), target)) fail("the run landed in the pane focused afterwards");
+ out.run_target = "ok";
+
+ process.kill(Number(stalled), "SIGSTOP");
+ await cardButton("Late", 0);
+ await sleep(3500);
+ process.kill(Number(stalled), "SIGCONT");
+ await sleep(1500);
+ if (printed(allText(), late)) fail("a run whose text came 3.5 s late was sent");
+ out.run_late = "dropped";
+
+ // A save made while the host is held up waits for it, and lands once it
+ // resumes; the editor stays up meanwhile, with what was typed.
+ process.kill(Number(stalled), "SIGSTOP");
+ if (!(await click("#agents .sbar .sb-icon"))) fail("no new-snippet button");
+ await until("the editor", () => ev("!!document.getElementById('snippet-body')"));
+ await type("#snippet-body", "echo saved-while-held");
+ await click("#agents .sb-save");
+ await sleep(1500);
+ const held = await ev("!!document.getElementById('snippet-body') && document.querySelector('#agents .sb-save').disabled");
+ process.kill(Number(stalled), "SIGCONT");
+ if (!held) fail("the editor did not wait for the held-up host");
+ await until("the held save to land", () => onDisk().includes("saved-while-held"));
+ await until("the editor to close", () => ev("!document.getElementById('snippet-body')"));
+ out.save_held = "ok";
+
+ // --- (g) a killed host is replaced, and the list works on.
+ const [first] = hostPids();
+ process.kill(Number(first), "SIGKILL");
+ await until("a new host", () => { const now = hostPids(); return now.length === 1 && now[0] !== first; }, 20000);
+ await until("the list to be followed again", () => ev("JSON.parse(window.thinkterm.client.snippets()).state === 'ready'"));
+ if (!(await click("#agents .sbar .sb-icon"))) fail("no new-snippet button after the restart");
+ await until("the editor again", () => ev("!!document.getElementById('snippet-body')"));
+ await type("#snippet-body", "echo after-the-restart");
+ await click("#agents .sb-save");
+ await until("the new host to save it", () => onDisk().includes("after-the-restart"), 20000);
+ out.restart = "ok";
+
+ // --- (j) a search timed, and typing's requests counted: here, and in a
+ // second page whose link adds 50 ms each way. Timed in the page, from the
+ // keystroke to the rows answering it.
+ const measure = async (page) => {
+ const run = (body) => send("Runtime.evaluate", { expression: `(async () => { ${body} })()`, awaitPromise: true, returnByValue: true }, page.session).then((r) => r.result?.value);
+ const helpers = `
+ const view = () => JSON.parse(window.thinkterm.client.snippets());
+ const box = document.querySelector('#agents .sb-search input');
+ const type = (q) => { box.value = q; box.dispatchEvent(new Event('input', { bubbles: true })); };
+ const settle = async (q, t0) => { while (view().answers !== q) { if (performance.now() - t0 > 10000) return -1; await new Promise((r) => setTimeout(r, 2)); } return performance.now() - t0; };`;
+ const res = {};
+ res.search_ms = [];
+ for (const query of ["list", "", "up", "", "restart", ""]) {
+ res.search_ms.push(Math.round(await run(`${helpers} const t0 = performance.now(); type(${JSON.stringify(query)}); return await settle(${JSON.stringify(query)}, t0);`)));
+ }
+ // Typing "uptime" at 40 ms a key: the requests it made, and how long
+ // after the last key its rows came.
+ Object.assign(res, await run(`${helpers}
+ const before = view().asked;
+ for (let i = 1; i <= 6; i++) { type("uptime".slice(0, i)); await new Promise((r) => setTimeout(r, 40)); }
+ const t0 = performance.now() - 40;
+ const settled = await settle("uptime", t0);
+ return { typing_requests: view().asked - before, typing_settle_ms: Math.round(settled) };`));
+ await run(`${helpers} type(""); return await settle("", performance.now());`);
+ return res;
+ };
+ const page = (session) => ({ session, ev: async (expr) => (await send("Runtime.evaluate", { expression: expr, returnByValue: true }, session)).result?.value });
+ out.local = await measure(page(s));
+
+ const link = await slowLink(Number(SLOW_PORT), Number(new URL(url).port), 50);
+ const slowUrl = url.replace(/:\d+\//, `:${SLOW_PORT}/`);
+ const { targetId: slowTarget } = await send("Target.createTarget", { url: "about:blank" });
+ const s2 = (await send("Target.attachToTarget", { targetId: slowTarget, flatten: true })).sessionId;
+ await send("Runtime.enable", {}, s2); await send("Page.enable", {}, s2);
+ const ev2 = page(s2).ev;
+ await send("Page.navigate", { url: slowUrl }, s2);
+ await until("the slow page to attach", async () => (await ev2("document.getElementById('status')?.dataset.summary || ''")).length > 0, 40000).catch(async (e) => {
+ console.error("slow page:", await ev2("location.href + ' | ' + document.readyState + ' | ' + (document.body?.innerText || '').slice(0, 300)"), "\nlogs:", logs.slice(-12).join("\n"));
+ throw e;
+ });
+ await ev2(`(() => { document.querySelector('#tabs [data-action=agents]')?.click(); return true; })()`);
+ await until("the slow page's panel", () => ev2("!!document.getElementById('agents')"), 20000);
+ await ev2(`(() => { document.querySelector('#agents .mode[data-mode=snippets]')?.click(); return true; })()`);
+ const expected = (await titles()).length;
+ await until("the slow page's snippets", async () => JSON.parse(await ev2("window.thinkterm.client.snippets()")).rows.length === expected, 20000);
+ out.slow_50ms_each_way = await measure(page(s2));
+ link.close();
+
+ out.titles = await titles();
+ out.logs = logs.filter((l) => !/^\s*$/.test(l) && !/INFO/.test(l)).slice(-6);
+ console.log(JSON.stringify(out));
+ ws.close(); chrome.kill(); process.exit(0);
+})().catch((e) => { console.error(e); chrome.kill(); process.exit(1); });
diff --git a/thinkterm-web/smoke/snippets.sh b/thinkterm-web/smoke/snippets.sh
new file mode 100755
index 00000000..bf850ec3
--- /dev/null
+++ b/thinkterm-web/smoke/snippets.sh
@@ -0,0 +1,58 @@
+#!/bin/sh
+# The Snippets tab, end to end: a release server under a throwaway HOME,
+# its plugin host started through it, the release bundle and headless
+# Chrome. The page lists, adds, searches, runs and deletes snippets; a
+# change another client makes reaches it; a Run lands in the pane focused
+# when it was pressed, or nowhere once too late; the host is killed and
+# comes back; and through a link that adds latency, a search is timed and
+# the requests typing makes are counted.
+#
+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/snippets.sh [out.png]
+#
+# Prints the JSON snippets-test.js produces; exit status is the test's.
+set -eu
+cd "$(dirname "$0")/../.."
+REPO=$PWD
+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release
+PORT=18102
+OUT=${1:-/tmp/thinkterm-snippets.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/tts.XXXXXX)
+# SLOW is where the test's latency-adding link listens; the page it serves
+# is another origin, so it is allowed alongside the server's own.
+SLOW=18103
+if lsof -nP -t -i :$SLOW >/dev/null 2>&1; then echo "port $SLOW busy" >&2; exit 1; fi
+cat > "$T/web.lua" <<LUA
+return { web_servers = { {
+ bind_address = "127.0.0.1:$PORT",
+ allowed_origins = { "http://127.0.0.1:$PORT", "http://127.0.0.1:$SLOW" },
+} } }
+LUA
+export HOME="$T/home"; mkdir -p "$HOME"
+export THINKTERM_NO_PRIVACY_DISCLAIM=1
+export THINKTERM_WEB_STATIC_DIR="$REPO/thinkterm-web/www"
+# One snippet already there, as the desktop would have left it.
+DATA="$HOME/Library/Application Support/ThinkTerm"
+[ "$(uname)" = Darwin ] || DATA="$HOME/.local/share/ThinkTerm"
+mkdir -p "$DATA"
+cat > "$DATA/snippets.json" <<JSON
+{"version":1,"snippets":[{"id":"snippet-1-seeded","title":"List files","body":"ls -la","created_at_ms":1,"updated_at_ms":1}]}
+JSON
+"$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"
+# Two panes side by side in the tab on show: Run must land in the one that
+# was focused when it was pressed.
+FIRST=$($CLI list --format json | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["pane_id"])')
+$CLI split-pane --pane-id "$FIRST" --right >/dev/null
+URL=$($CLI web-token mint --label snippets --ttl 1h --url-only 2>/dev/null | head -1)
+status=0
+HOME=$REAL_HOME SNIPPETS_FILE="$DATA/snippets.json" TEST_HOME="$HOME" MUX_CLI="$CLI" SLOW_PORT=$SLOW \
+ node "$REPO/thinkterm-web/smoke/snippets-test.js" "$URL" "$OUT" || status=$?
+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
+exit $status
diff --git a/thinkterm-web/src/agents.rs b/thinkterm-web/src/agents.rs
index 826820f1..1e53f4f9 100644
--- a/thinkterm-web/src/agents.rs
+++ b/thinkterm-web/src/agents.rs
@@ -49,10 +49,13 @@ pub struct AgentsView {
}
/// 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,
-/// Notes and Code join here when they get a wire.
+/// can open: a button for a feature the browser lacks is noise. Files and
+/// Notes join here when they get a wire.
pub fn panel_tabs() -> Vec<PanelTab> {
- [("agents", "bot", "right-mode-agents")]
+ [
+ ("snippets", "code-xml", "right-mode-snippets"),
+ ("agents", "bot", "right-mode-agents"),
+ ]
.into_iter()
.map(|(id, icon, key)| {
let label = tr(key);
@@ -64,9 +67,9 @@ pub fn panel_tabs() -> Vec<PanelTab> {
#[cfg(test)]
mod panel_tests {
#[test]
- fn only_agents_is_available_in_a_browser() {
+ fn snippets_and_agents_are_available_in_a_browser() {
let tabs = super::panel_tabs();
- assert!(tabs.iter().map(|t| t.id).eq(["agents"]));
+ assert!(tabs.iter().map(|t| t.id).eq(["snippets", "agents"]));
assert!(tabs.iter().all(|t| t.available));
}
}
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index 20bff72d..2aae5f30 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -23,6 +23,7 @@ use thinkterm_render::pipeline::GpuTexture;
use thinkterm_render::quad::HeapQuadAllocator;
use thinkterm_render::vertex::Vertex;
use thinkterm_session::pane::PaneSession;
+use thinkterm_snippets::wire as snippets_wire;
use wezterm_term::color::ColorPalette;
use wezterm_term::input::{MouseButton, MouseEvent, MouseEventKind};
use wezterm_term::{KeyModifiers, StableRowIndex, TerminalSize};
@@ -164,6 +165,11 @@ impl Selection {
/// hammered.
const RECONNECT_MIN_MS: f64 = 500.0;
const RECONNECT_MAX_MS: f64 = 15_000.0;
+/// How long a call to the plugin host waits for its answer.
+const PLUGIN_CALL_TIMEOUT_MS: f64 = 10_000.0;
+/// How long a snippet's Run or Paste waits for its text: a command that
+/// arrives later than this is not the one the press was for.
+const SNIPPET_SEND_WAIT_MS: f64 = 3_000.0;
/// After this many failed attempts the status line stops saying
/// "reconnecting" and admits it may never work.
const RECONNECT_DOUBT_AFTER: u32 = 6;
@@ -409,6 +415,13 @@ pub struct Inner<P: Platform, L: Link> {
after_take_over: Option<AfterTakeOver>,
/// How the last ask for the terminal went, for the card to say.
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_shown: bool,
+ snippets: crate::snippets::SnippetsModel,
+ /// Calls to the plugin host waiting for their answers.
+ plugin_calls: crate::plugins::PluginCalls,
}
/// One pane's own font: its scale over the page's size, and what draws it.
@@ -631,6 +644,10 @@ impl<P: Platform, L: Link> App<P, L> {
closing_since: None,
after_take_over: None,
claim: Claim::Idle,
+ right_panel: "agents",
+ right_panel_shown: false,
+ snippets: Default::default(),
+ plugin_calls: Default::default(),
};
let app = Rc::new(Self {
platform: setup.platform,
@@ -1221,6 +1238,11 @@ impl<P: Platform, L: Link> App<P, L> {
self.refresh_status();
self.request_frame();
}
+ // The plugin host, through the server; see `plugin_frame`.
+ Pdu::PluginFrame(codec::PluginFrame { data }) => {
+ drop(inner);
+ self.plugin_frame(data);
+ }
Pdu::SetClipboard(clip) => {
// Every pane on the server pushes to every client. Only a
// pane this page shows may write the device's clipboard,
@@ -1243,6 +1265,9 @@ impl<P: Platform, L: Link> App<P, L> {
return;
}
inner.disconnected = Some(reason.clone());
+ // The server's connection to the plugin host went with it.
+ inner.snippets.connection_lost();
+ inner.plugin_calls.lost("the connection to the server closed");
// 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
@@ -1348,6 +1373,7 @@ impl<P: Platform, L: Link> App<P, L> {
match outcome {
Ok(list) => {
self.reconnected();
+ self.snippets_follow();
// The tab is laid out again from the fresh listing: panes
// that came or went while the socket was down are taken
// up or let go, and the ones that stayed keep their cells.
@@ -3853,7 +3879,246 @@ impl<P: Platform, L: Link> App<P, L> {
});
let summary = crate::agents::summary(&rows);
let tabs = crate::agents::panel_tabs();
- crate::agents::AgentsView { rows, summary, tabs, active: "agents" }
+ crate::agents::AgentsView { rows, summary, tabs, active: inner.right_panel }
+ }
+
+ /// 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 Some(tab) = crate::agents::panel_tabs().into_iter().find(|tab| tab.id == id && tab.available) else {
+ return false;
+ };
+ self.inner.borrow_mut().right_panel = tab.id;
+ self.snippets_follow();
+ true
+ }
+
+ /// The page put the right panel up, or took it down.
+ pub fn set_right_panel_shown(self: &Rc<Self>, shown: bool) {
+ self.inner.borrow_mut().right_panel_shown = shown;
+ self.snippets_follow();
+ }
+
+ /// Follow the snippets while their tab is on show, and let them and
+ /// the server's connection to the plugin host go when it is not.
+ fn snippets_follow(self: &Rc<Self>) {
+ let (ask, close) = {
+ let inner = &mut *self.inner.borrow_mut();
+ let wanted = inner.right_panel_shown && inner.right_panel == "snippets";
+ if !wanted {
+ (false, inner.snippets.close())
+ } else if inner.disconnected.is_some() {
+ // Asked for once the connection is back.
+ (false, false)
+ } else {
+ inner.snippets.open();
+ (true, false)
+ }
+ };
+ if ask {
+ self.snippets_list();
+ }
+ if close {
+ self.send_plugin_frame(Vec::new(), None);
+ }
+ Self::notify(&self.inner.borrow());
+ }
+
+ /// 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>) {
+ let answer = {
+ let inner = &mut *self.inner.borrow_mut();
+ if inner.disconnected.is_some() {
+ if let Some(call) = call {
+ inner.plugin_calls.fail(call, "not connected to the server");
+ }
+ return;
+ }
+ inner.link.request(Pdu::PluginFrame(codec::PluginFrame { data }))
+ };
+ let app = Rc::clone(self);
+ self.spawn(async move {
+ let refused = match answer.await {
+ Ok(Pdu::UnitResponse(_)) => return,
+ Ok(Pdu::ErrorResponse(err)) => err.reason,
+ Ok(other) => format!("unexpected answer {}", other.pdu_name()),
+ Err(err) => format!("{err:#}"),
+ };
+ log::warn!("plugin channel: {refused}");
+ if let Some(call) = call {
+ app.inner.borrow_mut().plugin_calls.fail(call, &refused);
+ }
+ });
+ }
+
+ /// 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.
+ async fn plugin_call(self: &Rc<Self>, plugin: &str, body: serde_json::Value) -> crate::plugins::Answer {
+ let (id, frame, answer) = self.inner.borrow_mut().plugin_calls.call(plugin, body);
+ self.send_plugin_frame(frame, Some(id));
+ let weak = Rc::downgrade(self);
+ self.platform.set_timeout(
+ PLUGIN_CALL_TIMEOUT_MS,
+ Box::new(move || {
+ if let Some(app) = weak.upgrade() {
+ app.inner.borrow_mut().plugin_calls.fail(id, "the plugin host did not answer in time");
+ }
+ }),
+ );
+ answer.await.unwrap_or_else(|_| Err("the call was dropped".into()))
+ }
+
+ /// A frame from the plugin host, through the server: an answer, an
+ /// event, or -- empty -- word that the server's connection to the host
+ /// closed. The snippets are then asked for again, after a pause that
+ /// grows while the host keeps going away.
+ fn plugin_frame(self: &Rc<Self>, data: Vec<u8>) {
+ if data.is_empty() {
+ let delay = {
+ let inner = &mut *self.inner.borrow_mut();
+ let again = inner.snippets.host_gone().then(|| inner.snippets.retry_delay_ms());
+ inner.plugin_calls.lost("the plugin host went away");
+ again
+ };
+ if let Some(delay) = delay {
+ let weak = Rc::downgrade(self);
+ self.platform.set_timeout(
+ delay,
+ Box::new(move || {
+ if let Some(app) = weak.upgrade() {
+ app.snippets_follow();
+ }
+ }),
+ );
+ }
+ Self::notify(&self.inner.borrow());
+ return;
+ }
+ let event = self.inner.borrow_mut().plugin_calls.heard(&data);
+ if let Some((plugin, body)) = event {
+ let changed = plugin == snippets_wire::PLUGIN
+ && matches!(serde_json::from_value(body), Ok(snippets_wire::Event::Changed));
+ if changed {
+ self.inner.borrow_mut().snippets.snippets_changed();
+ self.snippets_list();
+ }
+ }
+ }
+
+ /// Ask the plugin host for the rows the tab's search matches: one
+ /// request at a time, the newest search asked for once it lands.
+ fn snippets_list(self: &Rc<Self>) {
+ let Some(query) = self.inner.borrow_mut().snippets.next_list() else {
+ return;
+ };
+ let app = Rc::clone(self);
+ self.spawn(async move {
+ let answer = app.snippets_call(snippets_wire::Request::List { query: query.clone() }).await;
+ app.inner.borrow_mut().snippets.listed(query, answer);
+ // The search may have moved on while this was out.
+ app.snippets_list();
+ Self::notify(&app.inner.borrow());
+ });
+ }
+
+ async fn snippets_call(self: &Rc<Self>, request: snippets_wire::Request) -> crate::plugins::Answer {
+ let body = serde_json::to_value(request).expect("a snippets request always serialises");
+ self.plugin_call(snippets_wire::PLUGIN, body).await
+ }
+
+ /// The Snippets tab: JSON `SnippetsView`.
+ pub fn snippets_view(&self) -> crate::snippets::SnippetsView {
+ self.inner.borrow().snippets.view()
+ }
+
+ pub fn snippets_revision(&self) -> u64 {
+ self.inner.borrow().snippets.revision()
+ }
+
+ /// The search box: the plugin host is asked what it matches.
+ pub fn snippets_search(self: &Rc<Self>, query: &str) {
+ self.inner.borrow_mut().snippets.set_query(query);
+ self.snippets_list();
+ Self::notify(&self.inner.borrow());
+ }
+
+ /// A snippet whole, for the editor: JSON `Snippet`, or `null`.
+ pub async fn snippet(self: &Rc<Self>, id: String) -> String {
+ match self.snippets_call(snippets_wire::Request::Get { id }).await {
+ Ok(body) => body.to_string(),
+ Err(why) => {
+ log::warn!("snippets: {why}");
+ "null".to_string()
+ }
+ }
+ }
+
+ /// Save what the editor holds, as the plugin host decides: JSON
+ /// `Saved`, or an `error` outcome with its message.
+ pub async fn snippet_save(self: &Rc<Self>, id: Option<String>, title: String, body: String) -> String {
+ match self.snippets_call(snippets_wire::Request::Save { id, title, body }).await {
+ Ok(body) => body.to_string(),
+ Err(message) => serde_json::json!({ "outcome": "error", "message": message }).to_string(),
+ }
+ }
+
+ pub async fn snippet_delete(self: &Rc<Self>, id: String) -> bool {
+ match self.snippets_call(snippets_wire::Request::Delete { id }).await {
+ Ok(serde_json::Value::Bool(deleted)) => deleted,
+ Ok(_) => false,
+ Err(why) => {
+ log::warn!("snippets: {why}");
+ false
+ }
+ }
+ }
+
+ /// A snippet into the focused pane, as the plugin host says to send
+ /// it: pasted, or typed and run. Into the pane focused at the press,
+ /// never whichever is focused when the answer comes, and not at all
+ /// once that pane is off the page or the answer comes too late to still
+ /// be what was meant.
+ pub async fn snippet_paste(self: &Rc<Self>, id: String, run: bool) -> bool {
+ let (pane, pressed) = {
+ let inner = self.inner.borrow();
+ (inner.focused_pane, inner.platform.monotonic_ms())
+ };
+ let text = match self.snippets_call(snippets_wire::Request::Text { id, run }).await {
+ Ok(serde_json::Value::String(text)) => text,
+ Ok(_) => return false,
+ Err(why) => {
+ log::warn!("snippets: {why}");
+ return false;
+ }
+ };
+ if self.platform.monotonic_ms() - pressed > SNIPPET_SEND_WAIT_MS {
+ log::warn!("not sending a snippet: its text came too late");
+ return false;
+ }
+ self.send_snippet_to(pane, &text, !run)
+ }
+
+ /// `text` into `pane`, if it is still on the page and this page may type:
+ /// as a paste, or as typed keys.
+ fn send_snippet_to(&self, pane: PaneId, text: &str, paste: bool) -> bool {
+ let mut inner = self.inner.borrow_mut();
+ if inner.disconnected.is_some() || !Self::may_type(&inner) {
+ return false;
+ }
+ let platform = Rc::clone(&inner.platform);
+ let Some(cell) = inner.panes.get_mut(&pane) else {
+ return false;
+ };
+ cell.scroll_from_bottom = 0;
+ cell.scroll_px = 0.0;
+ let start = if paste { cell.session.paste(text) } else { cell.session.write_bytes(text.as_bytes()) };
+ Self::spawn_drain(&platform, &cell.session, start);
+ drop(inner);
+ self.request_frame();
+ true
}
/// Bring an agent's pane on show: switch to it here, or open the
diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rs
index 994467a3..3e16d49e 100644
--- a/thinkterm-web/src/bridge.rs
+++ b/thinkterm-web/src/bridge.rs
@@ -117,6 +117,63 @@ impl Client {
self.app.agent_reveal(pane as usize)
}
+ /// Show the right panel's tab `id` ("agents", "snippets"). False for
+ /// one the page does not offer.
+ pub fn set_right_panel(&self, id: String) -> bool {
+ self.app.set_right_panel(&id)
+ }
+
+ /// The page put the right panel up (`true`) or took it down.
+ pub fn set_right_panel_shown(&self, shown: bool) {
+ self.app.set_right_panel_shown(shown);
+ }
+
+ /// The Snippets tab: JSON `SnippetsView`.
+ pub fn snippets(&self) -> String {
+ json(&self.app.snippets_view())
+ }
+
+ /// Changes when `snippets()` would, so the page reads it only then.
+ pub fn snippets_revision(&self) -> u32 {
+ self.app.snippets_revision() as u32
+ }
+
+ pub fn snippets_search(&self, query: String) {
+ self.app.snippets_search(&query);
+ }
+
+ /// A snippet for the editor: a promise of JSON `{id, title, body}`, or
+ /// `null`.
+ pub fn snippet(&self, id: String) -> js_sys::Promise {
+ let app = Rc::clone(&self.app);
+ wasm_bindgen_futures::future_to_promise(async move { Ok(JsValue::from_str(&app.snippet(id).await)) })
+ }
+
+ /// Save what the editor holds, a new snippet when `id` is absent: a
+ /// promise of JSON `{outcome}` -- `saved` (with `id`), `empty`, `gone`,
+ /// or `error` (with `message`).
+ pub fn snippet_save(&self, id: Option<String>, title: String, body: String) -> js_sys::Promise {
+ let app = Rc::clone(&self.app);
+ wasm_bindgen_futures::future_to_promise(async move {
+ Ok(JsValue::from_str(&app.snippet_save(id, title, body).await))
+ })
+ }
+
+ /// A promise of whether there was such a snippet to delete.
+ pub fn snippet_delete(&self, id: String) -> js_sys::Promise {
+ let app = Rc::clone(&self.app);
+ wasm_bindgen_futures::future_to_promise(async move { Ok(JsValue::from_bool(app.snippet_delete(id).await)) })
+ }
+
+ /// Paste a snippet into the focused pane, or type it and run it: a
+ /// promise of whether anything was sent.
+ pub fn snippet_paste(&self, id: String, run: bool) -> js_sys::Promise {
+ let app = Rc::clone(&self.app);
+ wasm_bindgen_futures::future_to_promise(async move {
+ Ok(JsValue::from_bool(app.snippet_paste(id, run).await))
+ })
+ }
+
/// The languages the page can be set to: JSON `[{preference, label}]`,
/// "system" first, labelled in the active locale.
pub fn languages(&self) -> String {
diff --git a/thinkterm-web/src/lib.rs b/thinkterm-web/src/lib.rs
index ad7bcdd3..8ef437b6 100644
--- a/thinkterm-web/src/lib.rs
+++ b/thinkterm-web/src/lib.rs
@@ -25,9 +25,11 @@ pub mod menu;
pub mod navbar;
pub mod palette;
pub mod platform;
+pub mod plugins;
pub mod raster;
pub mod settings;
pub mod sidebar;
+pub mod snippets;
pub mod tree;
pub mod viewport;
pub mod views;
diff --git a/thinkterm-web/src/plugins.rs b/thinkterm-web/src/plugins.rs
new file mode 100644
index 00000000..36d882af
--- /dev/null
+++ b/thinkterm-web/src/plugins.rs
@@ -0,0 +1,106 @@
+//! The page's side of the plugin channel: calls to the plugin host on the
+//! server's machine, carried there and back by the server (`PluginFrame`).
+//! A call is answered by the frame naming its id; any other frame is an
+//! event, handed on; the host going away fails every call still waiting.
+
+use futures::channel::oneshot;
+use serde_json::Value;
+use std::collections::HashMap;
+use thinkterm_plugin_channel::wire::{FromHost, ToHost};
+
+/// A call's answer, or why there is none.
+pub type Answer = Result<Value, String>;
+
+#[derive(Debug, Default)]
+pub struct PluginCalls {
+ next_id: u64,
+ waiting: HashMap<u64, oneshot::Sender<Answer>>,
+}
+
+impl PluginCalls {
+ /// A call's frame to send, its id, and its answer to wait for.
+ pub fn call(&mut self, plugin: &str, body: Value) -> (u64, Vec<u8>, oneshot::Receiver<Answer>) {
+ self.next_id += 1;
+ let id = self.next_id;
+ let frame = ToHost::Call { id, plugin: plugin.to_string(), body }.encode();
+ let (tx, rx) = oneshot::channel();
+ self.waiting.insert(id, tx);
+ (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)> {
+ 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::Hello { .. }) => {}
+ Err(err) => log::warn!("a frame from the plugin host that does not read: {err}"),
+ }
+ None
+ }
+
+ fn answer(&mut self, id: u64, answer: Answer) {
+ if let Some(waiting) = self.waiting.remove(&id) {
+ let _ = waiting.send(answer);
+ }
+ }
+
+ /// The call `id` never reached the host.
+ pub fn fail(&mut self, id: u64, why: &str) {
+ self.answer(id, Err(why.to_string()));
+ }
+
+ /// The way to the host is gone: nothing still waiting will be answered.
+ pub fn lost(&mut self, why: &str) {
+ for (_, waiting) in self.waiting.drain() {
+ let _ = waiting.send(Err(why.to_string()));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn answered(rx: &mut oneshot::Receiver<Answer>) -> Option<Answer> {
+ rx.try_recv().expect("not cancelled")
+ }
+
+ #[test]
+ fn a_call_is_answered_by_its_id_and_an_event_is_handed_on() {
+ let mut calls = PluginCalls::default();
+ let (first, frame, mut first_rx) = calls.call("snippets", json!({"op": "list"}));
+ assert_eq!(
+ ToHost::decode(&frame).unwrap(),
+ ToHost::Call { id: first, plugin: "snippets".into(), body: json!({"op": "list"}) }
+ );
+ let (second, _, mut second_rx) = calls.call("snippets", json!({"op": "get"}));
+ assert_ne!(first, second);
+
+ let reply = FromHost::Error { id: second, message: "no".into() }.encode();
+ assert!(calls.heard(&reply).is_none());
+ assert_eq!(answered(&mut second_rx), Some(Err("no".into())));
+ 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"}))));
+
+ let reply = FromHost::Ok { id: first, body: json!([]) }.encode();
+ calls.heard(&reply);
+ assert_eq!(answered(&mut first_rx), Some(Ok(json!([]))));
+ }
+
+ #[test]
+ fn nothing_waits_for_a_host_that_went_away() {
+ let mut calls = PluginCalls::default();
+ let (_, _, mut a) = calls.call("snippets", json!(null));
+ let (b_id, _, mut b) = calls.call("snippets", json!(null));
+ calls.fail(b_id, "refused");
+ assert_eq!(answered(&mut b), Some(Err("refused".into())));
+ calls.lost("gone");
+ assert_eq!(answered(&mut a), Some(Err("gone".into())));
+ }
+}
diff --git a/thinkterm-web/src/snippets.rs b/thinkterm-web/src/snippets.rs
new file mode 100644
index 00000000..c178aee7
--- /dev/null
+++ b/thinkterm-web/src/snippets.rs
@@ -0,0 +1,307 @@
+//! The right panel's Snippets tab, as data. The snippets are the plugin
+//! host's, on the server's machine, reached through the server
+//! (`PluginFrame`): it searches, saves, deletes and says what a pane is sent
+//! (thinkterm-snippets `wire`). This holds only what the tab shows -- the
+//! search and the rows sent for it, asked for as every client asks
+//! (thinkterm-snippets `view`) -- and whether it is followed.
+
+use crate::plugins::Answer;
+use serde::Serialize;
+use thinkterm_snippets::view::Listing;
+use thinkterm_snippets::wire::Row;
+
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+enum Phase {
+ /// Not followed: the tab is not on show, or the connection went.
+ #[default]
+ Closed,
+ /// Asked for; the host has not answered.
+ Opening,
+ Open,
+ /// The host cannot be reached through this server; why.
+ Unavailable(String),
+}
+
+#[derive(Debug, Default)]
+pub struct SnippetsModel {
+ phase: Phase,
+ /// The tab is on show, so the snippets are wanted.
+ wanted: bool,
+ listing: Listing,
+ /// Counts changes to what [`view`](Self::view) shows, so the page
+ /// re-reads it only when it moved.
+ revision: u64,
+ /// Times in a row the host went away before it answered.
+ gone_in_a_row: u32,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct SnippetsView {
+ /// `loading`, `ready` or `unavailable`.
+ pub state: &'static str,
+ /// Why they are unavailable.
+ pub reason: Option<String>,
+ pub rows: Vec<Row>,
+ pub query: String,
+ /// What an empty list says.
+ pub empty: String,
+ /// The search the rows answer: `query`, once they have caught up.
+ pub answers: Option<String>,
+ /// How many times the rows were asked for, for probes.
+ pub asked: u64,
+ pub revision: u64,
+}
+
+impl SnippetsModel {
+ pub fn revision(&self) -> u64 {
+ self.revision
+ }
+
+ fn changed(&mut self) {
+ self.revision += 1;
+ }
+
+ /// Whether the rows follow the host, so a change there asks again.
+ pub fn followed(&self) -> bool {
+ matches!(self.phase, Phase::Opening | Phase::Open)
+ }
+
+ /// The tab is on show and the page connected: the rows are asked for
+ /// afresh, unless they are followed already.
+ pub fn open(&mut self) {
+ self.wanted = true;
+ if self.followed() {
+ return;
+ }
+ self.phase = Phase::Opening;
+ self.listing.changed();
+ self.changed();
+ }
+
+ /// The tab was put away, and the rows with it. True when the server's
+ /// connection to the host is to be closed.
+ pub fn close(&mut self) -> bool {
+ let followed = self.followed();
+ self.wanted = false;
+ self.phase = Phase::Closed;
+ self.listing.clear();
+ self.changed();
+ followed
+ }
+
+ pub fn set_query(&mut self, query: &str) {
+ if self.listing.query() != query {
+ self.listing.set_query(query);
+ self.changed();
+ }
+ }
+
+ /// The host said the snippets changed.
+ pub fn snippets_changed(&mut self) {
+ self.listing.changed();
+ }
+
+ /// The search to ask the host about now, if any: one request at a time,
+ /// and none while the tab is not followed.
+ pub fn next_list(&mut self) -> Option<String> {
+ if !self.followed() {
+ return None;
+ }
+ let next = self.listing.next();
+ if next.is_some() {
+ self.changed();
+ }
+ next
+ }
+
+ /// The host's answer to a list for `query`.
+ pub fn listed(&mut self, query: String, answer: Answer) {
+ let rows = answer.and_then(|body| {
+ serde_json::from_value::<Vec<Row>>(body).map_err(|err| err.to_string())
+ });
+ let answered = self.listing.answered(query, rows);
+ if !self.wanted {
+ return;
+ }
+ match answered {
+ Ok(()) => {
+ self.phase = Phase::Open;
+ self.gone_in_a_row = 0;
+ }
+ // Rows already on show stay; only an empty tab has news.
+ Err(why) if self.listing.rows().is_some() => log::warn!("snippets: {why}"),
+ Err(why) => self.phase = Phase::Unavailable(why),
+ }
+ self.changed();
+ }
+
+ /// The connection to the server went, and with it the one to the host:
+ /// the rows are asked for again once it is back, if still wanted.
+ pub fn connection_lost(&mut self) {
+ if self.followed() {
+ self.phase = Phase::Closed;
+ }
+ }
+
+ /// The server's connection to the host closed: the host went away, and
+ /// is asked again. True when it is still wanted.
+ pub fn host_gone(&mut self) -> bool {
+ if self.phase != Phase::Open {
+ self.gone_in_a_row += 1;
+ }
+ self.connection_lost();
+ self.wanted
+ }
+
+ /// How long to wait before asking again after the host went away: a
+ /// second, doubling while it keeps going before it answers, to half a
+ /// minute.
+ pub fn retry_delay_ms(&self) -> f64 {
+ 1000.0 * f64::from(1u32 << self.gone_in_a_row.min(5)).min(30.0)
+ }
+
+ pub fn view(&self) -> SnippetsView {
+ let rows = self.listing.rows();
+ let (state, reason) = match (&self.phase, rows) {
+ (_, Some(_)) => ("ready", None),
+ (Phase::Unavailable(reason), None) => ("unavailable", Some(reason.clone())),
+ _ => ("loading", None),
+ };
+ let query = self.listing.query();
+ let empty = match state {
+ "unavailable" => thinkterm_i18n::tr("right-snippets-unavailable"),
+ _ if query.trim().is_empty() => thinkterm_i18n::tr("right-no-snippets"),
+ _ => thinkterm_i18n::tr("right-no-matching-snippets"),
+ };
+ SnippetsView {
+ state,
+ reason,
+ rows: rows.map(<[_]>::to_vec).unwrap_or_default(),
+ query: query.to_string(),
+ empty,
+ answers: self.listing.answers().map(str::to_string),
+ asked: self.listing.asked(),
+ revision: self.revision,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn row(id: &str) -> serde_json::Value {
+ json!({"id": id, "title": id, "preview": "ls"})
+ }
+
+ fn ids(model: &SnippetsModel) -> Vec<String> {
+ model.view().rows.into_iter().map(|r| r.id).collect()
+ }
+
+ fn opened(model: &mut SnippetsModel, rows: serde_json::Value) {
+ model.open();
+ let query = model.next_list().expect("asked for");
+ model.listed(query, Ok(rows));
+ }
+
+ #[test]
+ fn opening_asks_once_and_shows_what_arrives() {
+ let mut model = SnippetsModel::default();
+ assert_eq!(model.view().state, "loading");
+ assert_eq!(model.next_list(), None, "not followed yet");
+ model.open();
+ assert_eq!(model.next_list().as_deref(), Some(""));
+ model.open();
+ assert_eq!(model.next_list(), None, "already asked");
+ model.listed(String::new(), Ok(json!([row("a")])));
+ assert_eq!(model.view().state, "ready");
+ assert_eq!(ids(&model), ["a"]);
+ }
+
+ #[test]
+ fn typing_has_one_request_out_and_the_newest_search_wins() {
+ let mut model = SnippetsModel::default();
+ opened(&mut model, json!([row("a"), row("b")]));
+ model.set_query("p");
+ assert_eq!(model.next_list().as_deref(), Some("p"));
+ for query in ["pu", "pul", "pull"] {
+ model.set_query(query);
+ assert_eq!(model.next_list(), None, "one request at a time");
+ }
+ model.listed("p".into(), Ok(json!([row("a")])));
+ assert_eq!(model.next_list().as_deref(), Some("pull"));
+ model.listed("pull".into(), Ok(json!([])));
+ assert!(ids(&model).is_empty());
+ assert_eq!(model.view().empty, "No matching snippets");
+ assert_eq!(model.view().asked, 3);
+ }
+
+ #[test]
+ fn a_change_asks_again() {
+ let mut model = SnippetsModel::default();
+ opened(&mut model, json!([row("a")]));
+ assert_eq!(model.next_list(), None);
+ model.snippets_changed();
+ assert_eq!(model.next_list().as_deref(), Some(""));
+ }
+
+ #[test]
+ fn an_unreachable_host_says_so_and_rows_on_show_stay() {
+ let mut model = SnippetsModel::default();
+ model.open();
+ let query = model.next_list().unwrap();
+ model.listed(query, Err("no plugin host here".into()));
+ let view = model.view();
+ assert_eq!((view.state, view.reason.as_deref()), ("unavailable", Some("no plugin host here")));
+ assert_eq!(view.empty, "Snippets are unavailable right now");
+ assert_eq!(model.next_list(), None, "not asked again in a loop");
+
+ let mut model = SnippetsModel::default();
+ opened(&mut model, json!([row("a")]));
+ model.snippets_changed();
+ let query = model.next_list().unwrap();
+ model.listed(query, Err("the plugin host went away".into()));
+ assert_eq!(ids(&model), ["a"]);
+ }
+
+ #[test]
+ fn closing_forgets_the_rows_and_ignores_what_comes_after() {
+ let mut model = SnippetsModel::default();
+ assert!(!model.close(), "nothing was followed");
+ opened(&mut model, json!([row("a")]));
+ assert!(model.close());
+ assert_eq!(model.view().state, "loading");
+ assert_eq!(model.next_list(), None);
+ assert!(!model.host_gone(), "not wanted, so not asked again");
+ }
+
+ #[test]
+ fn a_host_that_keeps_going_away_is_asked_less_often() {
+ let mut model = SnippetsModel::default();
+ model.open();
+ assert!(model.host_gone());
+ assert!(!model.followed());
+ assert_eq!(model.retry_delay_ms(), 2000.0);
+ for _ in 0..10 {
+ model.open();
+ model.host_gone();
+ }
+ assert_eq!(model.retry_delay_ms(), 30000.0);
+ model.open();
+ let query = model.next_list().unwrap();
+ model.listed(query, Ok(json!([])));
+ assert!(model.host_gone());
+ assert_eq!(model.retry_delay_ms(), 1000.0);
+ }
+
+ #[test]
+ fn a_lost_connection_asks_again_once_back() {
+ let mut model = SnippetsModel::default();
+ opened(&mut model, json!([row("a")]));
+ model.connection_lost();
+ model.open();
+ assert_eq!(model.next_list().as_deref(), Some(""));
+ assert_eq!(ids(&model), ["a"], "shown meanwhile");
+ }
+}
diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rs
index 19730a14..679cf95b 100644
--- a/thinkterm-web/src/views.rs
+++ b/thinkterm-web/src/views.rs
@@ -159,6 +159,18 @@ pub const STRING_KEYS: &[&str] = &[
"common-reset",
"web-tip-new-pane",
"command-palette-empty",
+ "right-new-snippet",
+ "right-edit-snippet",
+ "right-search",
+ "right-run",
+ "menu-paste",
+ "right-save",
+ "right-cancel",
+ "right-action-description",
+ "right-action-description-placeholder",
+ "right-script-required",
+ "right-script-placeholder",
+ "web-tip-delete-snippet",
];
pub fn strings() -> std::collections::BTreeMap<&'static str, String> {
diff --git a/thinkterm-web/ui/src/AgentsPanel.svelte b/thinkterm-web/ui/src/AgentsPanel.svelte
index d73de7a8..15b8863a 100644
--- a/thinkterm-web/ui/src/AgentsPanel.svelte
+++ b/thinkterm-web/ui/src/AgentsPanel.svelte
@@ -1,8 +1,11 @@
<script lang="ts">
- // The desktop's right-hand Agents panel: one row per pane a coding agent
- // runs in, with its live state. What `agent_panel.rs` paints, from the
- // rows the wasm publishes (thinkterm-web/src/agents.rs); a click on a row
- // brings that pane on show.
+ // 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).
+ import SnippetsBar from './SnippetsBar.svelte';
+ import SnippetsList from './SnippetsList.svelte';
import { handle } from './client';
import { refreshViews, s, views } from './client.svelte';
import { agentIcon, circleAlert, circleCheck, iconByName, loaderCircle } from './icons';
@@ -12,6 +15,7 @@
// (thinkterm-web/src/agents.rs `panel_tabs`); drawn here.
const tabs = $derived(views.agents.tabs);
const active = $derived(views.agents.active);
+ const heading = $derived(tabs.find((tab) => tab.id === active)?.label ?? s('web-agents-title'));
const rows = $derived(views.agents.rows);
const summary = $derived(views.agents.summary);
@@ -26,11 +30,23 @@
};
});
+ // What the panel shows is followed only while it is up: the snippets,
+ // and the server's connection to the plugin host for them, go with it.
+ $effect(() => {
+ handle.client?.set_right_panel_shown(true);
+ return () => handle.client?.set_right_panel_shown(false);
+ });
+
// A click anywhere in a row is that row's, as it is on the desktop: the
// whole row is the target, not a button inside it.
function onClick(ev: MouseEvent) {
const target = ev.target;
if (!(target instanceof Element)) return;
+ const mode = target.closest('.mode:not(.off)')?.getAttribute('data-mode');
+ if (mode) {
+ if (mode !== active && handle.client?.set_right_panel(mode)) refreshViews();
+ return;
+ }
const raw = target.closest('.ag')?.getAttribute('data-pane');
if (raw === null || raw === undefined) return;
const pane = Number(raw);
@@ -131,7 +147,7 @@
>
<div class="handle"></div>
<div class="hd">
- <span class="ti">{s('web-agents-title')}</span>
+ <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">
@@ -148,8 +164,15 @@
>{@html iconByName(tab.icon) ?? ''}{#if tab.id === active}<span class="ml">{tab.label}</span>{/if}</span>
{/each}
</div>
- <span class="sum">{summary}</span>
+ {#if active === 'snippets'}
+ <SnippetsBar />
+ {:else}
+ <span class="sum">{summary}</span>
+ {/if}
</div>
+ {#if active === 'snippets'}
+ <SnippetsList />
+ {:else}
<div class="list">
{#each rows as row (row.pane)}
<div class="ag" class:elsewhere={!row.here} data-pane={row.pane} title={row.place}>
@@ -168,4 +191,5 @@
</div>
{/each}
</div>
+ {/if}
</aside>
diff --git a/thinkterm-web/ui/src/SnippetsBar.svelte b/thinkterm-web/ui/src/SnippetsBar.svelte
new file mode 100644
index 00000000..4f66ebca
--- /dev/null
+++ b/thinkterm-web/ui/src/SnippetsBar.svelte
@@ -0,0 +1,40 @@
+<script lang="ts">
+ // The Snippets tab's toolbar line, where the Agents tab has its summary:
+ // the search and the new-snippet button over the list, and over the
+ // editor its way back, its title and Save -- the desktop's toolbar
+ // (`paint_snippets_toolbar`, `paint_snippet_editor`).
+ import { s, views } from './client.svelte';
+ import { arrowLeft, plus, search as searchIcon } from './icons';
+ import { closeEditor, editor, openNew, saveEditor, search } from './snippets.svelte';
+
+ const query = $derived(views.snippets.query);
+</script>
+
+{#if editor.open}
+ <div class="sbar">
+ <button class="sb-icon" type="button" title={s('right-cancel')} aria-label={s('right-cancel')} onclick={closeEditor}>{@html arrowLeft}</button>
+ <span class="sb-title">{editor.id === null ? s('right-new-snippet') : s('right-edit-snippet')}</span>
+ <button class="sb-save" type="button" disabled={editor.saving} onclick={saveEditor}>{s('right-save')}</button>
+ </div>
+{:else}
+ <div class="sbar">
+ <label class="sb-search">
+ <span class="sb-glass">{@html searchIcon}</span>
+ <input
+ type="search"
+ placeholder={s('right-search')}
+ value={query}
+ autocomplete="off"
+ spellcheck="false"
+ oninput={(ev) => search(ev.currentTarget.value)}
+ onkeydown={(ev) => {
+ if (ev.key === 'Escape' && ev.currentTarget.value !== '') {
+ ev.preventDefault();
+ search('');
+ }
+ }}
+ />
+ </label>
+ <button class="sb-icon" type="button" title={s('right-new-snippet')} aria-label={s('right-new-snippet')} onclick={openNew}>{@html plus}</button>
+ </div>
+{/if}
diff --git a/thinkterm-web/ui/src/SnippetsList.svelte b/thinkterm-web/ui/src/SnippetsList.svelte
new file mode 100644
index 00000000..5f243600
--- /dev/null
+++ b/thinkterm-web/ui/src/SnippetsList.svelte
@@ -0,0 +1,89 @@
+<script lang="ts">
+ // The Snippets tab below its toolbar: the cards, as the desktop draws
+ // them (`paint_snippets_list`), or the editor. A card's Run and Paste put
+ // it into the focused pane; a press anywhere else on it edits it.
+ import { s, views } from './client.svelte';
+ import { circleAlert, codeXml, trash2 } from './icons';
+ import { armed, closeEditor, editor, openExisting, paste, pressDelete, saveEditor } from './snippets.svelte';
+
+ const view = $derived(views.snippets);
+
+ function onCardClick(ev: MouseEvent, id: string) {
+ // The buttons on the card are their own.
+ if (ev.target instanceof Element && ev.target.closest('button')) return;
+ openExisting(id);
+ }
+
+ function onEditorKey(ev: KeyboardEvent) {
+ if (ev.key === 'Escape') {
+ ev.preventDefault();
+ closeEditor();
+ } else if (ev.key === 'Enter' && (ev.metaKey || ev.ctrlKey)) {
+ ev.preventDefault();
+ saveEditor();
+ }
+ }
+</script>
+
+{#if editor.open}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="list snippet-editor" onkeydown={onEditorKey}>
+ <label class="se-label" for="snippet-title">{s('right-action-description')}</label>
+ <input
+ id="snippet-title"
+ class="se-field"
+ type="text"
+ placeholder={s('right-action-description-placeholder')}
+ autocomplete="off"
+ bind:value={editor.title}
+ />
+ <label class="se-label" for="snippet-body">{s('right-script-required')}</label>
+ <textarea
+ id="snippet-body"
+ class="se-field se-body"
+ class:want={editor.wantBody}
+ placeholder={s('right-script-placeholder')}
+ autocapitalize="off"
+ autocomplete="off"
+ spellcheck="false"
+ bind:value={editor.body}
+ oninput={() => (editor.wantBody = false)}
+ ></textarea>
+ </div>
+{:else}
+ <div class="list snippets">
+ {#if view.rows.length === 0}
+ {#if view.state !== 'loading'}
+ <!-- Nothing yet while the host sends them: saying there are none
+ would be wrong for the moment it takes. -->
+ <div class="sn-empty" title={view.reason ?? ''}>
+ <span class="ic">{@html view.state === 'unavailable' ? circleAlert : codeXml}</span>
+ <span class="sn-empty-t">{view.empty}</span>
+ </div>
+ {/if}
+ {:else}
+ {#each view.rows as row (row.id)}
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="sn" data-snippet={row.id} onclick={(ev) => onCardClick(ev, row.id)}>
+ <div class="sn-top">
+ <span class="sn-title">{row.title}</span>
+ <span class="sn-actions">
+ <button type="button" class="sn-btn" onclick={() => paste(row.id, true)}>{s('right-run')}</button>
+ <button type="button" class="sn-btn" onclick={() => paste(row.id, false)}>{s('menu-paste')}</button>
+ <button
+ type="button"
+ class="sn-btn sn-del"
+ class:armed={armed.id === row.id}
+ title={s('web-tip-delete-snippet')}
+ aria-label={s('web-tip-delete-snippet')}
+ onclick={() => pressDelete(row.id)}
+ >{#if armed.id === row.id}{s('web-confirm-delete')}{:else}{@html trash2}{/if}</button>
+ </span>
+ </div>
+ <span class="sn-preview">{row.preview}</span>
+ </div>
+ {/each}
+ {/if}
+ </div>
+{/if}
diff --git a/thinkterm-web/ui/src/client.svelte.ts b/thinkterm-web/ui/src/client.svelte.ts
index 7768eb52..c79cca65 100644
--- a/thinkterm-web/ui/src/client.svelte.ts
+++ b/thinkterm-web/ui/src/client.svelte.ts
@@ -4,7 +4,7 @@
import { flushSync } from 'svelte';
import { handle, type Client } from './client';
-import type { AgentsView, NavsView, SidebarView, StatusView, Strings, TabsView, WebSettings } from './model';
+import type { AgentsView, NavsView, SidebarView, SnippetsView, StatusView, Strings, TabsView, WebSettings } from './model';
export const views = $state({
tabs: null as TabsView | null,
@@ -16,6 +16,8 @@ export const views = $state({
} as SidebarView,
/** The right-hand panel's rows, whether it is on show or not. */
agents: { rows: [], summary: '', tabs: [], active: 'agents' } 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 page's own preferences, as the wasm holds them (settings.rs). */
settings: {
language: 'system',
@@ -62,12 +64,16 @@ export function attach(client: Client) {
let lastStrings = '';
let lastSidebar = '';
let lastAgents = '';
+ // The snippets can be long; their view is read only when it moved.
+ let lastSnippets = -1;
let lastSettings = '';
const read = () => {
const strings = client.strings();
if (strings !== lastStrings) {
lastStrings = strings;
views.strings = JSON.parse(strings) as Strings;
+ // Its words are in the language too.
+ lastSnippets = -1;
}
const tabs = client.tabs();
if (tabs !== lastTabs) {
@@ -94,6 +100,11 @@ export function attach(client: Client) {
lastAgents = agents;
views.agents = JSON.parse(agents) as AgentsView;
}
+ const snippets = client.snippets_revision();
+ if (snippets !== lastSnippets) {
+ lastSnippets = snippets;
+ views.snippets = JSON.parse(client.snippets()) as SnippetsView;
+ }
const settings = client.settings();
if (settings !== lastSettings) {
lastSettings = settings;
diff --git a/thinkterm-web/ui/src/icons.ts b/thinkterm-web/ui/src/icons.ts
index 57ccb394..4280818f 100644
--- a/thinkterm-web/ui/src/icons.ts
+++ b/thinkterm-web/ui/src/icons.ts
@@ -3,6 +3,7 @@
// colour from CSS `color` and its size from CSS.
import archive from '../../../third_party/lucide/icons/archive.svg?raw';
+import arrowLeft from '../../../third_party/lucide/icons/arrow-left.svg?raw';
import archiveRestore from '../../../third_party/lucide/icons/archive-restore.svg?raw';
import bell from '../../../third_party/lucide/icons/bell.svg?raw';
import info from '../../../third_party/lucide/icons/info.svg?raw';
@@ -59,6 +60,7 @@ import brandCopilot from '../../../third_party/simple-icons/icons/githubcopilot.
export {
archive,
+ arrowLeft,
archiveRestore,
bell,
bot,
diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.ts
index bdae9e3f..ecc88637 100644
--- a/thinkterm-web/ui/src/model.ts
+++ b/thinkterm-web/ui/src/model.ts
@@ -203,6 +203,28 @@ export type PanelTab = {
export type AgentsView = { rows: AgentRow[]; summary: string; tabs: PanelTab[]; active: string };
+// The right panel's Snippets tab (thinkterm-web/src/snippets.rs
+// `SnippetsView`): the snippets the plugin host keeps, filtered by the
+// search, as the desktop's panel lists them.
+
+export type SnippetRow = { id: string; title: string; preview: string };
+
+export type SnippetsView = {
+ /** `loading` until the host has sent them; `unavailable` when this
+ server cannot reach a plugin host, with `reason`. */
+ state: 'loading' | 'ready' | 'unavailable';
+ reason: string | null;
+ rows: SnippetRow[];
+ query: string;
+ /** What an empty list says. */
+ empty: string;
+ /** The search the rows answer: `query`, once they have caught up. */
+ answers: string | null;
+ /** How many times the rows were asked for, for probes. */
+ asked: number;
+ revision: number;
+};
+
// The page's own preferences (thinkterm-web/src/settings.rs `WebSettings`),
// whose JSON names are kebab-case.
diff --git a/thinkterm-web/ui/src/snippets.svelte.ts b/thinkterm-web/ui/src/snippets.svelte.ts
new file mode 100644
index 00000000..20506244
--- /dev/null
+++ b/thinkterm-web/ui/src/snippets.svelte.ts
@@ -0,0 +1,130 @@
+// The Snippets tab's page-side state: the editor, and a delete pressed
+// once. The snippets are the plugin host's, which does everything with
+// them (thinkterm-snippets `wire`); the page asks through the wasm
+// (thinkterm-web/src/app.rs) and shows what comes back. This only holds
+// what is being typed until it is saved.
+
+import { tick } from 'svelte';
+import { handle } from './client';
+import { refreshViews } from './client.svelte';
+import { focusTerminal } from './mobile.svelte';
+
+export const editor = $state({
+ /** Whether the editor is up rather than the list. */
+ open: false,
+ /** The snippet being edited; null for a new one. */
+ id: null as string | null,
+ title: '',
+ body: '',
+ /** The host found nothing to save in the script: the field says so. */
+ wantBody: false,
+ /** A save is on its way: another press waits for its answer rather
+ than saving a new snippet twice. */
+ saving: false,
+});
+
+/** A delete pressed once, and when; the second press within the window
+ deletes, as the sidebar's thread delete does. */
+export const armed = $state({ id: null as string | null, at: 0 });
+const CONFIRM_MS = 3000;
+
+async function focusField(id: string) {
+ await tick();
+ document.getElementById(id)?.focus();
+}
+
+export function openNew() {
+ editor.open = true;
+ editor.id = null;
+ editor.title = '';
+ editor.body = '';
+ editor.wantBody = false;
+ focusField('snippet-title');
+}
+
+/** The editor, on a snippet the host sends whole. */
+export async function openExisting(id: string) {
+ const raw = await handle.client?.snippet(id);
+ if (typeof raw !== 'string' || raw === 'null') return;
+ const snippet = JSON.parse(raw) as { id: string; title: string; body: string };
+ editor.open = true;
+ editor.id = snippet.id;
+ editor.title = snippet.title;
+ editor.body = snippet.body;
+ editor.wantBody = false;
+ focusField('snippet-title');
+}
+
+export function closeEditor() {
+ editor.open = false;
+ editor.id = null;
+ editor.title = '';
+ editor.body = '';
+ editor.wantBody = false;
+}
+
+type SaveOutcome =
+ | { outcome: 'saved'; id: string }
+ | { outcome: 'empty' }
+ | { outcome: 'gone' }
+ | { outcome: 'error'; message: string };
+
+/** What the editor holds, to the host; the editor follows its answer, as
+ the desktop's does. */
+export async function saveEditor() {
+ const client = handle.client;
+ if (!client || editor.saving) return;
+ editor.saving = true;
+ try {
+ const raw = await client.snippet_save(editor.id ?? undefined, editor.title, editor.body);
+ const saved = JSON.parse(raw as string) as SaveOutcome;
+ switch (saved.outcome) {
+ case 'saved':
+ closeEditor();
+ break;
+ case 'empty':
+ editor.wantBody = true;
+ focusField('snippet-body');
+ break;
+ case 'gone':
+ // Deleted meanwhile: what was typed is kept, as a new one.
+ editor.id = null;
+ break;
+ case 'error':
+ console.warn(`snippets: ${saved.message}`);
+ break;
+ }
+ } finally {
+ editor.saving = false;
+ }
+ refreshViews();
+}
+
+/** The first press arms the button; the second, soon after, deletes. */
+export async function pressDelete(id: string) {
+ const now = performance.now();
+ if (armed.id === id && now - armed.at < CONFIRM_MS) {
+ armed.id = null;
+ await handle.client?.snippet_delete(id);
+ refreshViews();
+ return;
+ }
+ armed.id = id;
+ armed.at = now;
+ setTimeout(() => {
+ if (armed.id === id && performance.now() - armed.at >= CONFIRM_MS) armed.id = null;
+ }, CONFIRM_MS);
+}
+
+/** Into the focused pane, as the host says to send it, and the keyboard
+ back to the terminal, so a pasted command can be run with Enter --
+ where that is wanted: a phone keeps its soft keyboard down
+ (`focusTerminal`). */
+export async function paste(id: string, run: boolean) {
+ if (await handle.client?.snippet_paste(id, run)) focusTerminal();
+}
+
+export function search(query: string) {
+ handle.client?.snippets_search(query);
+ refreshViews();
+}
diff --git a/thinkterm-web/ui/src/tokens.css b/thinkterm-web/ui/src/tokens.css
index abeb1ac3..7fb131a8 100644
--- a/thinkterm-web/ui/src/tokens.css
+++ b/thinkterm-web/ui/src/tokens.css
@@ -232,6 +232,47 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }
#agents .st.spin { color: var(--open); }
#agents .st.alert { color: var(--warn); }
#agents .st.idle { color: var(--muted); }
+/* A tab of the selector that can be opened lifts under the pointer. */
+#agents .mode:not(.on):not(.off):hover { color: var(--text); }
+/* The Snippets tab (SnippetsBar, SnippetsList), as the desktop draws it:
+ a toolbar line of search and new-snippet button, then rounded cards of
+ a title and the first line of the script, whose Run, Paste and delete
+ come up under the pointer. */
+#agents .sbar { display: flex; align-items: center; gap: 6px; min-height: 32px; margin-top: 6px; }
+#agents .sb-search { display: flex; align-items: center; gap: 6px; flex: 1 1 auto; min-width: 0; height: 30px; box-sizing: border-box; padding: 0 9px; border-radius: 999px; background: var(--btn); border: 1px solid var(--btn-border); color: var(--muted); }
+#agents .sb-glass { display: inline-flex; flex: none; }
+#agents .sb-glass svg { width: 14px; height: 14px; }
+#agents .sb-search input { flex: 1 1 auto; min-width: 0; background: transparent; border: 0; outline: none; color: var(--text); font: 500 13px var(--ui); user-select: text; -webkit-user-select: text; }
+#agents .sb-search input::-webkit-search-cancel-button { display: none; }
+#agents .sb-icon { display: inline-flex; align-items: center; justify-content: center; flex: none; width: 30px; height: 30px; box-sizing: border-box; border-radius: 999px; background: var(--btn); border: 1px solid var(--btn-border); color: var(--text2); padding: 0; transition: var(--fade); }
+#agents .sb-icon:hover { background: var(--btn-hover); color: var(--text); }
+#agents .sb-icon svg { width: 15px; height: 15px; }
+#agents .sb-title { flex: 1 1 auto; min-width: 0; color: var(--text); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#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; }
+#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); }
+#agents .sn-top { display: flex; align-items: center; gap: 6px; min-height: 26px; }
+#agents .sn-title { flex: 1 1 auto; min-width: 0; color: var(--text); line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#agents .sn-actions { display: none; flex: none; gap: 5px; }
+#agents .sn:hover .sn-actions, #agents .sn:focus-within .sn-actions { display: inline-flex; }
+#agents .sn-btn { display: inline-flex; align-items: center; justify-content: center; height: 26px; min-width: 26px; box-sizing: border-box; padding: 0 9px; border-radius: 999px; background: var(--ctl); border: 1px solid var(--ctl-border); color: var(--text); font: 500 12px var(--ui); transition: var(--fade); }
+#agents .sn-btn:hover { background: var(--ctl-hover); }
+#agents .sn-del { padding: 0; width: 26px; color: var(--text2); }
+#agents .sn-del svg { width: 14px; height: 14px; }
+#agents .sn-del.armed { width: auto; padding: 0 9px; color: var(--danger); }
+#agents .sn-preview { color: var(--muted); font-size: 13px; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#agents .sn-empty { display: flex; align-items: center; gap: 10px; min-height: 56px; box-sizing: border-box; padding: 0 14px; border-radius: 14px; background: var(--btn); border: 1px solid var(--btn-border); color: var(--muted); }
+#agents .sn-empty .ic { color: var(--muted); }
+#agents .sn-empty-t { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#agents .snippet-editor { gap: 6px; }
+#agents .se-label { color: var(--muted); font-size: 12px; margin-top: 6px; }
+#agents .se-field { box-sizing: border-box; width: 100%; font: 400 14px var(--ui); color: var(--text); background: var(--ctl); border: 1px solid var(--ctl-border); border-radius: 9px; padding: 8px 10px; outline: none; user-select: text; -webkit-user-select: text; transition: var(--fade); }
+#agents .se-field:focus { border-color: var(--edge); }
+#agents .se-body { min-height: 180px; flex: none; resize: vertical; font: 400 13px ui-monospace, "SF Mono", Menlo, monospace; line-height: 1.45; white-space: pre; overflow: auto; }
+#agents .se-body.want { border-color: var(--danger); }
.nav { position: absolute; pointer-events: auto; box-sizing: border-box; display: flex; align-items: center; gap: 9px; padding: 0 5px; background: var(--bg); color: var(--text2); user-select: none; overflow: hidden; }
.nav.focused { color: var(--text); }
.nav .caps { display: flex; gap: 9px; flex: 1 1 auto; min-width: 0; overflow: hidden; }
@@ -485,6 +526,9 @@ body[data-mobile] #agents { padding-right: var(--safe-r); }
/* Their edges are dragged with a pointer, which a phone has not got. */
body[data-mobile] #side .handle,
body[data-mobile] #agents .handle { display: none; }
+/* No pointer to hover with: a snippet's buttons stay up. */
+body[data-mobile] #agents .sn-actions { display: inline-flex; }
+@media (hover: none) { #agents .sn-actions { display: inline-flex; } }
/* A row, a button and a footer icon a thumb can hit. The list's insets and
the panel's rhythm are the desktop's; only the heights grow. */
body[data-mobile] #side .row { min-height: 44px; }