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 the plugins with the panels in the browser's settings
RoversX06736101c57c
diff --git a/thinkterm-web/smoke/agents-test.js b/thinkterm-web/smoke/agents-test.jsindex babfa45c..052c32c7 100644--- a/thinkterm-web/smoke/agents-test.js+++ b/thinkterm-web/smoke/agents-test.js@@ -38,7 +38,7 @@ async function browserWs() { for (let i = 0; i < 50; i++) { try { return await nconst toggleFromSettings = async () => {if (!(await click("#side [data-action=settings]"))) fail("no gear in the sidebar footer");await until("the settings panel", () => ev("!!document.getElementById('settings')"));- await click("#settings [data-section=agents]");+ await click("#settings [data-section=sidebar]");if (!(await click("#settings input[data-setting=agents-panel]"))) fail("no agents-panel switch");if (!(await click("#settings .sc"))) fail("no close button");await until("the settings panel to close", () => ev("!document.getElementById('settings')"));diff --git a/thinkterm-web/smoke/plugins-test.js b/thinkterm-web/smoke/plugins-test.jsnew file mode 100644index 00000000..8e6605aa--- /dev/null+++ b/thinkterm-web/smoke/plugins-test.js@@ -0,0 +1,182 @@+// Plugins in a browser end to end, against a throwaway server with the+// example plugin installed beside a broken one and a second copy claiming+// the example's id: Settings › Sidebar & Plugins lists them all and the built-in+// 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.+// 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+// PLUGINS_DATA (the data directory the plugins are installed under).+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 { TEST_HOME, MUX_CLI, PLUGIN_CLI, PLUGINS_DATA, EXAMPLE_DIR, EXAMPLE_BIN } = 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); }, 180000).unref();+const profile = fs.mkdtempSync(`${os.tmpdir()}/tt-plugins-`);+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 pids = (pattern) => { try { return execSync(`pgrep -f ${JSON.stringify(pattern)}`).toString().trim().split(/\s+/).filter(Boolean); } catch { return []; } };+const allText = () => JSON.parse(execSync(`${MUX_CLI} list --format json`).toString())+ .map((p) => execSync(`${MUX_CLI} get-text --pane-id ${p.pane_id}`).toString()).join("\n");+const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/;+const switches = () => { try { return fs.readFileSync(`${PLUGINS_DATA}/plugins.json`, "utf8"); } catch { return ""; } };++(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 fail = (what) => { throw new Error(what); };+ const attached = async () => /this browser has/.test(await ev("document.getElementById('status').dataset.summary || ''"));+ const rows = () => ev("[...document.querySelectorAll('#settings [data-plugin]')].map((r) => ({ id: r.dataset.plugin, name: r.querySelector('.lab').textContent, detail: r.querySelector('.desc').textContent, on: r.querySelector('input')?.checked ?? null }))");+ // The row a plugin's id is used by: a copy claiming it is listed too, without a switch.+ const row = async (pluginId) => {+ const all = (await rows()).filter((r) => r.id === pluginId);+ return all.find((r) => r.on !== null) ?? all[0];+ };+ const paletteIds = () => ev("[...document.querySelectorAll('#palette .pe')].map((e) => e.dataset.id)");+ const cliList = () => execSync(`${PLUGIN_CLI} list`).toString();+ // The whole palette opens by its shortcut: Cmd+K on a Mac, Ctrl+K elsewhere.+ const openPalette = async (query) => {+ const press = (mods) => ev(`window.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', bubbles: true, ${mods} }))`);+ await press("metaKey: true");+ if (!(await ev("!!document.querySelector('#palette input')"))) await press("ctrlKey: true");+ await until("the palette", () => ev("!!document.querySelector('#palette input')"));+ await type("#palette input", query);+ };+ const closePalette = () => ev("document.querySelector('#palette input')?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))");+ const out = {};++ await send("Page.navigate", { url }, s);+ await until("attach", attached, 20000);+ await sleep(600);+ if (pids(socketPath).length) fail("a plugin host runs before anything asked for one");++ // --- (a) Settings › Sidebar & Plugins lists the built-in, the example and the broken one.+ if (!(await click("[data-action=settings]"))) fail("no settings button");+ await until("the settings panel", () => ev("!!document.querySelector('#settings .sec[data-section=sidebar]')"));+ await click("#settings .sec[data-section=sidebar]");+ await until("the plugin rows", async () => (await rows()).length === 4);+ const listed = await rows();+ out.rows = listed.map((r) => `${r.id}:${r.on}`);+ const snippets = listed.find((r) => r.id === "snippets");+ const tools = listed.find((r) => r.id === "text-tools" && r.on !== null);+ const twin = listed.find((r) => r.id === "text-tools" && r.on === null);+ const broken = listed.find((r) => r.id === "broken");+ if (!twin || !/text-tools has the same id/.test(twin.detail)) fail("the copy claiming the example's id: " + JSON.stringify(twin));+ if (!snippets || !/Built in · Provides the Snippets panel/.test(snippets.detail) || snippets.on !== null) fail("the built-in Snippets row: " + JSON.stringify(listed));+ if (!tools || tools.name !== "Text Tools" || !/0\.1\.0/.test(tools.detail) || tools.on !== true) fail("the example's row: " + JSON.stringify(tools));+ if (!broken || broken.on !== null || !/plugin\.toml, line 1/.test(broken.detail)) fail("the broken row: " + JSON.stringify(broken));+ if (pids(socketPath).length !== 1) fail(`${pids(socketPath).length} plugin hosts run`);+ if (pids("thinkterm-plugin-example").length) fail("the example runs before anything used it");+ out.settings = "ok";+ await click("#settings .sc");++ // --- (b) Nothing of a plugin outside the sidebar: the palette offers none+ // of it, and calls made from the command line leave nothing here.+ await openPalette("uuid");+ await sleep(800);+ const offered = (await paletteIds()).filter((id) => id.startsWith("plugin:"));+ if (offered.length) fail("plugin commands in the palette: " + offered.join(", "));+ await closePalette();+ const printed = execSync(`${PLUGIN_CLI} call text-tools '{"op":"uuid"}'`).toString();+ if (!UUID.test(printed)) fail("the command line got no UUID: " + printed);+ const decoded = execSync(`${PLUGIN_CLI} call text-tools '{"op":"decode","text":"aGk="}'`).toString();+ if (!/"text": "hi"/.test(decoded)) fail("the command line got no decoding: " + decoded);+ await sleep(800);+ if (await ev("!!document.getElementById('plugin-notice')")) fail("a plugin's notice is on the page");+ if (UUID.test(allText())) fail("a plugin's outcome went into a pane");+ out.outside_sidebar = "nothing";+ if (pids("thinkterm-plugin-example").length !== 1) fail("the example is not running after its command");+ // It is running now, and the settings say so.+ await click("[data-action=settings]");+ await click("#settings .sec[data-section=sidebar]");+ await until("Running", async () => /Running/.test((await row("text-tools"))?.detail || ""));+ await click("#settings .sc");++ // --- (b2) A plugin installed now is found when the settings open again.+ const more = `${PLUGINS_DATA}/plugins/more-tools`;+ fs.mkdirSync(more, { recursive: true });+ fs.writeFileSync(`${more}/plugin.toml`, fs.readFileSync(`${EXAMPLE_DIR}/plugin.toml`, "utf8").replace('id = "text-tools"', 'id = "more-tools"').replace('name = "Text Tools"', 'name = "More Tools"'));+ fs.copyFileSync(EXAMPLE_BIN, `${more}/thinkterm-plugin-example`);+ fs.chmodSync(`${more}/thinkterm-plugin-example`, 0o755);+ await click("[data-action=settings]");+ await click("#settings .sec[data-section=about]");+ await click("#settings .sec[data-section=sidebar]");+ await until("the new plugin in the settings", async () => !!(await row("more-tools")));+ await click("#settings .sc");+ fs.rmSync(more, { recursive: true, force: true });+ out.installed_meanwhile = "ok";++ // --- (c) Turned off, its program stops, and the switch is on disk.+ await click("[data-action=settings]");+ await click("#settings .sec[data-section=sidebar]");+ await until("the rows", async () => (await rows()).length >= 4);+ await click('#settings [data-plugin-switch="text-tools"]');+ await until("the example off", async () => (await row("text-tools"))?.on === false && /text-tools/.test(switches()));+ await until("its program to stop", () => pids("thinkterm-plugin-example").length === 0, 5000);+ if (!/text-tools\s+off/.test(cliList())) fail("the command line does not see it off:\n" + cliList());+ await click('#settings [data-plugin-switch="text-tools"]');+ await until("the example on", async () => (await row("text-tools"))?.on === true);+ out.switch = "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");+ await until("the Snippets tab", () => ev("!!document.querySelector('#agents .mode[data-mode=snippets]')"));+ await click("[data-action=settings]");+ await click("#settings .sec[data-section=sidebar]");+ await until("the rows", async () => (await rows()).length >= 4);+ // Snippets is a built-in plugin: its switch is its panel's, among the+ // panels, and its row in the list has none.+ if (await ev("!!document.querySelector('#settings [data-plugin=snippets] input')")) fail("the built-in row has a switch");+ await click('#settings [data-panel-switch="snippets"]');+ await until("Snippets off", () => ev("document.querySelector('#settings [data-panel-switch=snippets]')?.checked === false"));+ await until("the Snippets tab to go", () => ev("!document.querySelector('#agents .mode[data-mode=snippets]')"));+ await click('#settings [data-panel-switch="snippets"]');+ await until("the Snippets tab back", () => ev("!!document.querySelector('#agents .mode[data-mode=snippets]')"));+ out.snippetsTab = "ok";++ // --- (e) Reload stops the running plugin; a missing program is a failure its row explains.+ await click("#settings .sc");+ execSync(`${PLUGIN_CLI} call text-tools '{"op":"uuid"}'`);+ await until("the example running", () => pids("thinkterm-plugin-example").length === 1, 8000);+ await click("[data-action=settings]");+ await click("#settings .sec[data-section=sidebar]");+ await click('#settings [data-action="reload-plugins"]');+ await until("it stopped", () => pids("thinkterm-plugin-example").length === 0, 5000);+ await until("the row back to idle", async () => !/Running/.test((await row("text-tools"))?.detail || "Running"));+ fs.rmSync(`${PLUGINS_DATA}/plugins/text-tools/thinkterm-plugin-example`);+ let why = "";+ try { execSync(`${PLUGIN_CLI} call text-tools '{"op":"uuid"}'`, { stdio: "pipe" }); } catch (err) { why = String(err.stderr); }+ if (!/cannot find its program/.test(why)) fail("the command line was not told why: " + why);+ const failed = await until("the failure in its row", async () => { const r = await row("text-tools"); return r && /cannot find its program/.test(r.detail) && r.detail; });+ out.failed = failed;+ if (await ev("!!document.getElementById('plugin-notice')")) fail("a plugin's failure is on the page outside the sidebar");++ const shot = await send("Page.captureScreenshot", { format: "png" }, s);+ if (shot.data) fs.writeFileSync(outPng, Buffer.from(shot.data, "base64"));+ out.exceptions = logs.filter((l) => l.startsWith("EXCEPTION"));+ if (out.exceptions.length) fail("the page threw: " + out.exceptions.join("; "));+ console.log(JSON.stringify(out, null, 1));+ chrome.kill(); process.exit(0);+})().catch((err) => { console.error("FAIL", err.message); try { chrome.kill(); } catch {} process.exit(1); });diff --git a/thinkterm-web/smoke/plugins.sh b/thinkterm-web/smoke/plugins.shnew file mode 100755index 00000000..e4fbae3a--- /dev/null+++ b/thinkterm-web/smoke/plugins.sh@@ -0,0 +1,52 @@+#!/bin/sh+# Plugins in a browser, end to end: a release server under a throwaway+# HOME with the example plugin installed beside a broken one, its plugin+# host started through it, the release bundle and headless Chrome. The page+# lists the plugins in Settings › Sidebar & Plugins and shows nothing of them outside+# the sidebar, turns them off and on -- Snippets' tab going with its switch+# -- reloads them, and says in a row why a plugin failed.+#+# cargo build --release -p wezterm-mux-server -p wezterm \+# -p thinkterm-plugin-server -p thinkterm-plugin-example+# NODE_PATH=<dir with node_modules/ws> thinkterm-web/smoke/plugins.sh [out.png]+#+# Prints the JSON plugins-test.js produces; exit status is the test's.+set -eu+cd "$(dirname "$0")/../.."+REPO=$PWD+BIN=${CARGO_TARGET_DIR:-$REPO/target}/release+PORT=18104+OUT=${1:-/tmp/thinkterm-plugins.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/ttp.XXXXXX)+cat > "$T/web.lua" <<LUA+return { web_servers = { { bind_address = "127.0.0.1:$PORT" } } }+LUA+export HOME="$T/home"; mkdir -p "$HOME"+export THINKTERM_NO_PRIVACY_DISCLAIM=1+export THINKTERM_WEB_STATIC_DIR="$REPO/thinkterm-web/www"+DATA="$HOME/Library/Application Support/ThinkTerm"+[ "$(uname)" = Darwin ] || DATA="$HOME/.local/share/ThinkTerm"+# The example, installed as its docs say; a plugin whose manifest does not+# read; and a second copy of the example under another directory, which+# claims its id and so is listed as not used.+mkdir -p "$DATA/plugins/text-tools" "$DATA/plugins/broken" "$DATA/plugins/twin"+cp "$REPO/thinkterm-plugin-example/plugin.toml" "$BIN/thinkterm-plugin-example" "$DATA/plugins/text-tools/"+cp "$REPO/thinkterm-plugin-example/plugin.toml" "$DATA/plugins/twin/"+echo 'id = ' > "$DATA/plugins/broken/plugin.toml"+"$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"+PLUGIN_CLI="env HOME=$HOME THINKTERM_NO_PRIVACY_DISCLAIM=1 $BIN/thinkterm plugin"+URL=$($CLI web-token mint --label plugins --ttl 1h --url-only 2>/dev/null | head -1)+status=0+HOME=$REAL_HOME TEST_HOME="$HOME" MUX_CLI="$CLI" PLUGIN_CLI="$PLUGIN_CLI" PLUGINS_DATA="$DATA" \+ EXAMPLE_DIR="$REPO/thinkterm-plugin-example" EXAMPLE_BIN="$BIN/thinkterm-plugin-example" \+ node "$REPO/thinkterm-web/smoke/plugins-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 $statusdiff --git a/thinkterm-web/src/agents.rs b/thinkterm-web/src/agents.rsindex 1e53f4f9..705a5be2 100644--- a/thinkterm-web/src/agents.rs+++ b/thinkterm-web/src/agents.rs@@ -50,13 +50,15 @@ 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 and-/// Notes join here when they get a wire.-pub fn panel_tabs() -> Vec<PanelTab> {+/// 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> {[("snippets", "code-xml", "right-mode-snippets"),("agents", "bot", "right-mode-agents"),].into_iter()+ .filter(|(id, _, _)| snippets || *id != "snippets").map(|(id, icon, key)| {let label = tr(key);PanelTab { id, icon, label: label.clone(), available: true, tip: label }@@ -68,9 +70,11 @@ pub fn panel_tabs() -> Vec<PanelTab> {mod panel_tests {#[test]fn snippets_and_agents_are_available_in_a_browser() {- let tabs = super::panel_tabs();+ let tabs = super::panel_tabs(true);assert!(tabs.iter().map(|t| t.id).eq(["snippets", "agents"]));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");}}diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 2aae5f30..1e6ef411 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_plugin_channel::registry as plugins_api;use thinkterm_snippets::wire as snippets_wire;use wezterm_term::color::ColorPalette;use wezterm_term::input::{MouseButton, MouseEvent, MouseEventKind};@@ -167,6 +168,10 @@ 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 the server's way to the plugin host is kept once nothing needs+/// it: Settings › Sidebar & Plugins opened again soon after, or a panel+/// switched back to, finds it there.+const PLUGIN_PIPE_LINGER_MS: f64 = 30_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;@@ -420,8 +425,16 @@ pub struct Inner<P: Platform, L: Link> {right_panel: &'static str,right_panel_shown: bool,snippets: crate::snippets::SnippetsModel,+ /// The plugins as last heard, and what wants them.+ plugin_list: crate::plugin_list::PluginsModel,/// Calls to the plugin host waiting for their answers.plugin_calls: crate::plugins::PluginCalls,+ /// The server holds a way to the plugin host for this page: frames were+ /// sent since it was last closed.+ plugin_pipe: bool,+ /// Counts the lingers after the last need, so only the latest lets the+ /// way to the host go.+ plugin_pipe_linger: u64,}/// One pane's own font: its scale over the page's size, and what draws it.@@ -647,7 +660,10 @@ impl<P: Platform, L: Link> App<P, L> {right_panel: "agents",right_panel_shown: false,snippets: Default::default(),+ plugin_list: Default::default(),plugin_calls: Default::default(),+ plugin_pipe: false,+ plugin_pipe_linger: 0,};let app = Rc::new(Self {platform: setup.platform,@@ -1267,6 +1283,8 @@ impl<P: Platform, L: Link> App<P, L> {inner.disconnected = Some(reason.clone());// The server's connection to the plugin host went with it.inner.snippets.connection_lost();+ inner.plugin_list.connection_lost();+ inner.plugin_pipe = false;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@@ -1373,7 +1391,7 @@ impl<P: Platform, L: Link> App<P, L> {match outcome {Ok(list) => {self.reconnected();- self.snippets_follow();+ self.plugins_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.@@ -3878,50 +3896,195 @@ 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();+ let tabs = crate::agents::panel_tabs(Self::snippets_offered(&inner));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 {+ 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 {return false;};self.inner.borrow_mut().right_panel = tab.id;- self.snippets_follow();+ self.plugins_follow();true}- /// The page put the right panel up, or took it down.+ /// The page put the right panel up, or took it down. While it is up+ /// the plugin list is followed: its Snippets tab is there only while+ /// the Snippets plugin is on.pub fn set_right_panel_shown(self: &Rc<Self>, shown: bool) {- self.inner.borrow_mut().right_panel_shown = shown;- self.snippets_follow();+ {+ let inner = &mut *self.inner.borrow_mut();+ inner.right_panel_shown = shown;+ inner.plugin_list.want("panel", shown);+ }+ self.plugins_follow();+ }++ /// Whether the right panel offers Snippets: unless the plugin list, as+ /// last heard, has its plugin off or broken.+ fn snippets_offered(inner: &Inner<P, L>) -> bool {+ inner.plugin_list.usable(snippets_wire::PLUGIN) != Some(false)+ }++ /// Something on the page needs the plugin list, or no longer does:+ /// `who` is `settings` or `panel`.+ pub fn plugins_want(self: &Rc<Self>, who: &str, on: bool) {+ let who = match who {+ "settings" => "settings",+ "panel" => "panel",+ _ => return,+ };+ self.inner.borrow_mut().plugin_list.want(who, on);+ self.plugins_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) = {+ /// Whether the Snippets tab is on show, and so the snippets followed.+ fn snippets_wanted(inner: &Inner<P, L>) -> bool {+ inner.right_panel_shown && inner.right_panel == "snippets"+ }++ /// 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()+ }++ /// Follow what the page shows of the plugins: the snippets while their+ /// tab is on show, the plugin list while something needs it. The+ /// 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 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 {+ if !Self::snippets_offered(inner) && inner.right_panel == "snippets" {+ inner.right_panel = "agents";+ }+ let snippets_wanted = Self::snippets_wanted(inner);+ let mut ask_snippets = false;+ if !snippets_wanted {+ inner.snippets.close();+ } else if inner.disconnected.is_none() {+ // Asked for once the connection is back, otherwise.inner.snippets.open();- (true, false)+ ask_snippets = true;}+ ask_snippets};- if ask {+ if ask_snippets {self.snippets_list();}+ self.plugins_list();+ self.linger_plugin_pipe();+ Self::notify(&self.inner.borrow());+ }++ /// 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.+ fn linger_plugin_pipe(self: &Rc<Self>) {+ let linger = {+ let inner = &mut *self.inner.borrow_mut();+ if Self::plugin_pipe_needed(inner) || !inner.plugin_pipe {+ return;+ }+ inner.plugin_pipe_linger += 1;+ inner.plugin_pipe_linger+ };+ let weak = Rc::downgrade(self);+ self.platform.set_timeout(+ PLUGIN_PIPE_LINGER_MS,+ Box::new(move || {+ if let Some(app) = weak.upgrade() {+ app.plugin_pipe_let_go(linger);+ }+ }),+ );+ }++ /// The linger after the last need is over: the way to the host is let+ /// go, unless something needed it meanwhile or a later linger runs.+ fn plugin_pipe_let_go(self: &Rc<Self>, linger: u64) {+ let close = {+ let inner = &mut *self.inner.borrow_mut();+ let close = inner.plugin_pipe_linger == linger+ && inner.plugin_pipe+ && inner.disconnected.is_none()+ && !Self::plugin_pipe_needed(inner);+ if close {+ inner.plugin_pipe = false;+ inner.plugin_list.connection_lost();+ }+ close+ };if close {self.send_plugin_frame(Vec::new(), None);}+ }++ /// Ask the plugin host for the plugin list, if something needs it and it+ /// is out of date: one request at a time.+ fn plugins_list(self: &Rc<Self>) {+ let locale = {+ let inner = &mut *self.inner.borrow_mut();+ if inner.disconnected.is_some() {+ return;+ }+ let Some(locale) = inner.plugin_list.next_list(thinkterm_i18n::current_locale()) else {+ return;+ };+ locale+ };+ let app = Rc::clone(self);+ self.spawn(async move {+ let request = plugins_api::Request::List { locale };+ let body = serde_json::to_value(request).expect("a plugin request always serialises");+ let answer = app.plugin_call(plugins_api::PLUGIN, body).await;+ app.inner.borrow_mut().plugin_list.listed(answer);+ // A change may have come meanwhile, and the Snippets tab+ // follows its plugin's switch.+ app.plugins_follow();+ });+ }++ /// The plugin list in Settings › Sidebar & Plugins: JSON `PluginsView`.+ pub fn plugins_view(&self) -> crate::plugin_list::PluginsView {+ self.inner.borrow().plugin_list.view()+ }++ pub fn plugins_revision(&self) -> u64 {+ self.inner.borrow().plugin_list.revision()+ }++ /// Turn a plugin on or off. The switch shows the change until the+ /// host answers; false when it refused.+ pub async fn plugin_set_enabled(self: &Rc<Self>, id: String, enabled: bool) -> bool {+ self.inner.borrow_mut().plugin_list.switching(&id, enabled);Self::notify(&self.inner.borrow());+ let request = plugins_api::Request::SetEnabled { id: id.clone(), enabled };+ 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.switched(&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 {+ let request = plugins_api::Request::Reload { id: None };+ let body = serde_json::to_value(request).expect("a plugin request always serialises");+ let answer = self.plugin_call(plugins_api::PLUGIN, body).await;+ let done = answer.is_ok();+ if let Err(why) = answer {+ self.inner.borrow_mut().plugin_list.refused(why);+ }+ self.plugins_follow();+ done}/// One frame for the plugin host, through the server, on the wire now@@ -3936,6 +4099,9 @@ impl<P: Platform, L: Link> App<P, L> {}return;}+ // A frame opens the server's way to the host; an empty one+ // closes it.+ inner.plugin_pipe = !data.is_empty();inner.link.request(Pdu::PluginFrame(codec::PluginFrame { data }))};let app = Rc::clone(self);@@ -3956,19 +4122,41 @@ impl<P: Platform, L: Link> App<P, L> {/// 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 {+ fn plugin_call(self: &Rc<Self>, plugin: &str, body: serde_json::Value) -> impl Future<Output = crate::plugins::Answer> {+ self.plugin_call_within(plugin, body, PLUGIN_CALL_TIMEOUT_MS)+ }++ /// [`plugin_call`](Self::plugin_call), waiting `wait_ms` for the answer.+ /// The call is on its way when this returns, before its answer is+ /// awaited: whatever the page does next finds it waiting, and keeps the+ /// way to the host for it.+ fn plugin_call_within(+ self: &Rc<Self>,+ plugin: &str,+ body: serde_json::Value,+ 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));let weak = Rc::downgrade(self);+ let timeout = weak.clone();self.platform.set_timeout(- PLUGIN_CALL_TIMEOUT_MS,+ wait_ms,Box::new(move || {- if let Some(app) = weak.upgrade() {+ if let Some(app) = timeout.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()))+ async move {+ let answer = answer.await.unwrap_or_else(|_| Err("the call was dropped".into()));+ // The way to the host was kept for this call; it may be the last+ // thing that needed it.+ if let Some(app) = weak.upgrade() {+ app.linger_plugin_pipe();+ }+ answer+ }}/// A frame from the plugin host, through the server: an answer, an@@ -3979,7 +4167,11 @@ impl<P: Platform, L: Link> App<P, L> {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_pipe = false;+ 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);inner.plugin_calls.lost("the plugin host went away");again};@@ -3989,7 +4181,8 @@ impl<P: Platform, L: Link> App<P, L> {delay,Box::new(move || {if let Some(app) = weak.upgrade() {- app.snippets_follow();+ app.inner.borrow_mut().plugin_list.retry();+ app.plugins_follow();}}),);@@ -3998,13 +4191,24 @@ impl<P: Platform, L: Link> App<P, L> {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();+ let Some((plugin, body)) = event else {+ return;+ };+ if plugin == plugins_api::PLUGIN {+ match serde_json::from_value(body) {+ Ok(plugins_api::Event::Changed) => {+ self.inner.borrow_mut().plugin_list.list_changed();+ self.plugins_list();+ }+ Err(err) => log::warn!("a plugin list event that does not read: {err}"),}+ return;+ }+ 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();}}@@ -4098,12 +4302,12 @@ impl<P: Platform, L: Link> App<P, L> {log::warn!("not sending a snippet: its text came too late");return false;}- self.send_snippet_to(pane, &text, !run)+ self.send_text_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 {+ fn send_text_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;diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rsindex 3e16d49e..91979875 100644--- a/thinkterm-web/src/bridge.rs+++ b/thinkterm-web/src/bridge.rs@@ -174,6 +174,38 @@ impl Client {})}+ /// Something on the page needs the plugin list, or no longer does:+ /// `settings` or `panel`.+ pub fn plugins_want(&self, who: String, on: bool) {+ self.app.plugins_want(&who, on);+ }++ /// The plugin list in Settings › Sidebar & Plugins: JSON `PluginsView`.+ pub fn plugins(&self) -> String {+ json(&self.app.plugins_view())+ }++ /// Changes when `plugins()` would, so the page reads it only then.+ pub fn plugins_revision(&self) -> u32 {+ self.app.plugins_revision() as u32+ }++ /// Turn a plugin on or off: a promise of whether the plugin host took+ /// the change.+ pub fn plugin_set_enabled(&self, id: String, enabled: bool) -> js_sys::Promise {+ let app = Rc::clone(&self.app);+ wasm_bindgen_futures::future_to_promise(async move {+ Ok(JsValue::from_bool(app.plugin_set_enabled(id, enabled).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 {+ let app = Rc::clone(&self.app);+ wasm_bindgen_futures::future_to_promise(async move { Ok(JsValue::from_bool(app.plugins_reload().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.rsindex 8ef437b6..42fbe835 100644--- a/thinkterm-web/src/lib.rs+++ b/thinkterm-web/src/lib.rs@@ -25,6 +25,7 @@ pub mod menu;pub mod navbar;pub mod palette;pub mod platform;+pub mod plugin_list;pub mod plugins;pub mod raster;pub mod settings;diff --git a/thinkterm-web/src/plugin_list.rs b/thinkterm-web/src/plugin_list.rsnew file mode 100644index 00000000..a31b60c7--- /dev/null+++ b/thinkterm-web/src/plugin_list.rs@@ -0,0 +1,496 @@+//! The plugins as the page shows them: the list in Settings › Sidebar &+//! Plugins, and whether the right panel offers Snippets. Nothing of a+//! plugin shows outside the sidebar. Like the snippets, the list is the+//! plugin host's, on+//! the server's machine, reached through the server (`PluginFrame`): it is+//! asked for while something on show needs it, and its changes are+//! followed while they are. What was last heard stays on show, but is never+//! taken for current once the way to the host went: it is asked for afresh.++use crate::plugins::Answer;+use serde::Serialize;+use thinkterm_i18n::{tr, tr_args};+use thinkterm_plugin_channel::registry::{Info, State};++/// What wants the list: Settings › Sidebar & Plugins, the right panel.+pub type Want = &'static str;++#[derive(Debug, Default)]+pub struct PluginsModel {+ wanted: Vec<Want>,+ plugins: Option<Vec<Info>>,+ /// The list was asked for over the way to the host that is open now,+ /// so its changes come here.+ followed: bool,+ asking: bool,+ /// What was last heard is out of date.+ stale: bool,+ /// The way to the host went while the list was on its way: it is asked+ /// for again after the pause that follows, or when something new wants+ /// it -- not at once, over and over.+ resting: bool,+ /// The language the list was last asked for in.+ locale: String,+ /// Why the host cannot be reached through the server, while it cannot.+ trouble: Option<String>,+ /// Switches flipped here whose change is on its way, and to what.+ switching: Vec<(String, bool)>,+ /// 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+ /// next try.+ failures: u32,+ /// Counts changes to what the views show, so the page re-reads them+ /// only when they moved.+ revision: u64,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct PluginsView {+ /// `loading`, `ready` or `unavailable`.+ pub state: &'static str,+ /// What the section says besides its list: loading, before there is+ /// one, or why the host cannot be reached -- which makes a list on show+ /// only what was last heard.+ pub status: String,+ pub rows: Vec<PluginRow>,+ /// Why the host refused the last change asked of it here, as a sentence.+ pub refused: Option<String>,+ pub revision: u64,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct PluginRow {+ /// Tells rows apart: two installed plugins can claim one id, and the+ /// one not used is listed too, with why.+ pub key: String,+ pub id: String,+ pub name: String,+ /// Where it came from, its state when that is worth saying, and what it+ /// does, in one line.+ pub detail: String,+ /// The switch as it is to be shown: the change on its way, if one is.+ pub enabled: bool,+ /// Whether a switch could do anything for it.+ pub switchable: bool,+ /// Built into ThinkTerm: its switch is its panel's, among the panels,+ /// not in the list.+ pub builtin: bool,+}++fn with_reason(key: &str, reason: &str) -> String {+ let mut args = thinkterm_i18n::FluentArgs::new();+ args.set("reason", reason.to_string());+ tr_args(key, &args)+}++/// The line under a plugin's name, as the desktop's settings write it: a+/// built-in plugin says which panel it provides.+fn detail(plugin: &Info) -> String {+ if plugin.builtin && plugin.id == thinkterm_snippets::wire::PLUGIN {+ let mut args = thinkterm_i18n::FluentArgs::new();+ args.set("panel", tr("right-mode-snippets"));+ return tr_args("settings-plugins-builtin-panel", &args);+ }+ let origin = if plugin.builtin {+ tr("settings-plugins-builtin")+ } else {+ plugin.version.clone()+ };+ let state = match &plugin.state {+ State::Off | State::Idle => None,+ State::Starting => Some(tr("settings-plugins-starting")),+ State::Running => Some(tr("settings-plugins-running")),+ State::Crashed { reason } => Some(with_reason("settings-plugins-crashed", reason)),+ State::Failed { reason } => Some(with_reason("settings-plugins-failed", reason)),+ State::Invalid { reason } => Some(with_reason("settings-plugins-invalid", reason)),+ State::Unsupported { .. } => Some(tr("settings-plugins-unsupported")),+ };+ [Some(origin), state, Some(plugin.description.clone())]+ .into_iter()+ .flatten()+ .filter(|part| !part.is_empty())+ .collect::<Vec<_>>()+ .join(" · ")+}++impl PluginsModel {+ pub fn revision(&self) -> u64 {+ self.revision+ }++ fn changed(&mut self) {+ self.revision += 1;+ }++ /// `who` needs the list, or no longer does. Something coming on show+ /// asks for it afresh, and with it the host looks at its plugins+ /// directory again. True when that makes it wanted where it was not.+ pub fn want(&mut self, who: Want, on: bool) -> bool {+ let before = self.wanted();+ let had = self.wanted.contains(&who);+ self.wanted.retain(|wanting| *wanting != who);+ if on {+ self.wanted.push(who);+ if !had {+ self.stale = true;+ self.resting = false;+ }+ }+ !before && self.wanted()+ }++ pub fn wanted(&self) -> bool {+ !self.wanted.is_empty()+ }++ /// The language to ask for the list in now, if it is to be asked for:+ /// one request at a time, while it is wanted, when what was heard is+ /// out of date, or was heard over a way to the host that is gone, or in+ /// another language.+ pub fn next_list(&mut self, locale: &str) -> Option<String> {+ if !self.wanted() || self.asking || self.resting {+ return None;+ }+ if !self.stale && self.followed && self.locale == locale {+ return None;+ }+ self.asking = true;+ self.stale = false;+ self.followed = true;+ self.locale = locale.to_string();+ Some(self.locale.clone())+ }++ /// The host's answer to a list asked for in `locale`. An error is not+ /// asked about again until something changes -- the way to the host+ /// going and coming back, say: an unreachable host is not asked in a+ /// loop.+ pub fn listed(&mut self, answer: Answer) {+ self.asking = false;+ let plugins = answer.and_then(|body| {+ serde_json::from_value::<Vec<Info>>(body).map_err(|err| err.to_string())+ });+ match plugins {+ Ok(plugins) => {+ self.plugins = Some(plugins);+ self.trouble = None;+ self.failures = 0;+ }+ Err(why) => {+ log::warn!("plugins: {why}");+ self.trouble = Some(why);+ self.failures = self.failures.saturating_add(1);+ // Failed because the way went meanwhile: the pause decides+ // when to try again.+ if !self.followed {+ self.resting = true;+ }+ }+ }+ self.changed();+ }++ /// How long to wait before asking again after the way to the host+ /// went: a second, doubling while the list cannot be had, to half a+ /// minute.+ pub fn retry_delay_ms(&self) -> f64 {+ 1000.0 * f64::from(1u32 << self.failures.min(5)).min(30.0)+ }++ /// The host said the list changed.+ pub fn list_changed(&mut self) {+ self.stale = true;+ }++ /// The pause after the way to the host went is over.+ pub fn retry(&mut self) {+ self.resting = false;+ }++ /// The way to the host went: whatever was heard is kept on show, and+ /// asked for afresh on the next need.+ pub fn connection_lost(&mut self) {+ self.followed = false;+ self.asking = false;+ self.switching.clear();+ self.changed();+ }++ /// A switch flipped here, on its way to the host.+ pub fn switching(&mut self, id: &str, enabled: bool) {+ self.refused = None;+ self.switching.retain(|(switching, _)| switching != id);+ self.switching.push((id.to_string(), enabled));+ self.changed();+ }++ /// The host's answer to a switch flipped here: the list is out of date+ /// whichever way it went.+ pub fn switched(&mut self, id: &str, answer: Result<(), String>) {+ self.switching.retain(|(switching, _)| switching != id);+ if let Err(why) = answer {+ self.refused = Some(why);+ }+ self.stale = true;+ self.changed();+ }++ /// The host refused something asked of it here.+ pub fn refused(&mut self, why: String) {+ self.refused = Some(why);+ self.changed();+ }++ /// Whether plugin `id` is on and working, as last heard; `None` before+ /// anything was.+ pub fn usable(&self, id: &str) -> Option<bool> {+ let plugins = self.plugins.as_ref()?;+ Some(+ plugins+ .iter()+ .any(|plugin| plugin.id == id && plugin.usable()),+ )+ }++ pub fn view(&self) -> PluginsView {+ let (state, status) = match (&self.plugins, &self.trouble) {+ (Some(_), None) => ("ready", String::new()),+ (Some(_), Some(why)) => ("ready", with_reason("settings-plugins-unavailable", why)),+ (None, Some(why)) => (+ "unavailable",+ with_reason("settings-plugins-unavailable", why),+ ),+ (None, None) => ("loading", tr("settings-plugins-loading")),+ };+ let rows = self+ .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+ .switching+ .iter()+ .find(|(id, _)| *id == plugin.id)+ .map_or(plugin.enabled, |(_, enabled)| *enabled),+ switchable: !matches!(+ plugin.state,+ State::Invalid { .. } | State::Unsupported { .. }+ ),+ builtin: plugin.builtin,+ })+ .collect();+ PluginsView {+ state,+ status,+ rows,+ refused: self+ .refused+ .as_deref()+ .map(|why| with_reason("settings-plugins-refused", why)),+ revision: self.revision,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn listed(model: &mut PluginsModel, plugins: serde_json::Value) {+ model.next_list("en-US").expect("asked");+ model.listed(Ok(plugins));+ }++ fn plugin(id: &str, enabled: bool, state: serde_json::Value) -> serde_json::Value {+ json!({+ "id": id, "name": id.to_uppercase(), "version": "1.0", "enabled": enabled,+ "state": state, "description": "Does things."+ })+ }++ #[test]+ fn the_list_is_asked_for_while_wanted_and_again_when_it_changed() {+ let mut model = PluginsModel::default();+ assert_eq!(model.next_list("en-US"), None, "nothing wants it");+ assert!(model.want("settings", true));+ assert!(!model.want("panel", true), "wanted already");+ assert_eq!(model.next_list("en-US").as_deref(), Some("en-US"));+ assert_eq!(model.next_list("en-US"), None, "one at a time");+ model.listed(Ok(json!([plugin("a", true, json!({"kind": "idle"}))])));+ assert_eq!(model.next_list("en-US"), None, "heard, and nothing changed");+ model.list_changed();+ assert!(model.next_list("en-US").is_some());+ model.listed(Ok(json!([])));+ assert!(model.next_list("zh-CN").is_some(), "another language");+ model.listed(Ok(json!([])));+ model.connection_lost();+ assert!(+ model.next_list("zh-CN").is_some(),+ "the way to the host went"+ );+ }++ #[test]+ fn a_list_that_cannot_be_had_is_not_asked_for_in_a_loop() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ model.next_list("en-US").unwrap();+ model.listed(Err("no plugin host".into()));+ assert_eq!(model.next_list("en-US"), None, "not again at once");+ assert_eq!(model.view().state, "unavailable");+ assert!(model.view().status.contains("no plugin host"));+ let first = model.retry_delay_ms();+ model.connection_lost();+ model+ .next_list("en-US")+ .expect("asked again once the way went");+ model.listed(Err("no plugin host".into()));+ assert!(model.retry_delay_ms() > first, "and less and less often");+ }++ #[test]+ fn a_list_heard_before_the_host_went_says_it_is_only_that() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ listed(+ &mut model,+ json!([plugin("a", true, json!({"kind": "idle"}))]),+ );+ assert_eq!(model.view().status, "");+ model.connection_lost();+ model.next_list("en-US").expect("asked again");+ model.listed(Err("no plugin host".into()));+ let view = model.view();+ assert_eq!(view.state, "ready");+ assert_eq!(view.rows.len(), 1, "what was heard stays on show");+ assert!(view.status.contains("no plugin host"), "{}", view.status);+ }++ #[test]+ fn a_list_lost_with_the_way_to_the_host_waits_for_the_pause() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ model.next_list("en-US").unwrap();+ // The way goes with the list on its way, which then fails.+ model.connection_lost();+ model.listed(Err("the plugin host went away".into()));+ assert_eq!(model.next_list("en-US"), None, "asked again at once");+ model.retry();+ assert!(model.next_list("en-US").is_some(), "asked after the pause");+ model.listed(Err("the plugin host went away".into()));++ model.connection_lost();+ model.listed(Err("the plugin host went away".into()));+ model.want("panel", true);+ assert!(+ model.next_list("en-US").is_some(),+ "the panel coming on show asks"+ );+ }++ #[test]+ fn coming_on_show_again_asks_for_the_list_afresh() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ listed(&mut model, json!([]));+ model.want("panel", true);+ assert!(model.next_list("en-US").is_some(), "the panel came on show");+ model.listed(Ok(json!([])));+ model.want("panel", true);+ assert_eq!(model.next_list("en-US"), None, "still open: nothing new");+ model.want("panel", false);+ model.want("panel", true);+ assert!(model.next_list("en-US").is_some(), "opened again");+ }++ #[test]+ fn two_plugins_claiming_one_id_are_two_rows() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ let mut used = plugin("a", true, json!({"kind": "idle"}));+ used["dir"] = json!("/plugins/a");+ let mut unused = plugin(+ "a",+ true,+ json!({"kind": "invalid", "reason": "a has the same id"}),+ );+ unused["dir"] = json!("/plugins/b");+ listed(+ &mut model,+ json!([+ plugin("snippets", true, json!({"kind": "idle"})),+ used,+ unused+ ]),+ );+ let keys: Vec<String> = model.view().rows.into_iter().map(|row| row.key).collect();+ assert_eq!(keys, ["snippets", "/plugins/a", "/plugins/b"]);+ }++ #[test]+ fn a_switch_shows_its_change_until_the_host_answers() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ listed(+ &mut model,+ json!([plugin("a", true, json!({"kind": "running"}))]),+ );+ assert!(model.view().rows[0].enabled);+ model.switching("a", false);+ assert!(!model.view().rows[0].enabled);+ model.switched("a", Err("cannot save".into()));+ let view = model.view();+ assert!(view.rows[0].enabled, "went back");+ assert!(view.refused.unwrap().contains("cannot save"));+ assert!(model.next_list("en-US").is_some(), "asked again either way");+ }++ #[test]+ fn a_built_in_plugin_says_which_panel_it_provides() {+ let mut model = PluginsModel::default();+ model.want("settings", true);+ listed(+ &mut model,+ json!([{+ "id": "snippets", "name": "Snippets", "version": "", "builtin": true,+ "enabled": true, "state": {"kind": "idle"}, "description": "Saved commands."+ }]),+ );+ let row = &model.view().rows[0];+ assert!(row.builtin);+ assert!(row.detail.contains("Snippets"), "{}", row.detail);+ assert!(!row.detail.contains("Saved commands."), "{}", row.detail);+ }++ #[test]+ fn rows_say_what_state_a_plugin_is_in_and_what_it_offers() {+ let mut model = PluginsModel::default();+ model.want("panel", true);+ listed(+ &mut model,+ json!([+ plugin("a", true, json!({"kind": "running"})),+ plugin("b", false, json!({"kind": "off"})),+ plugin(+ "c",+ true,+ json!({"kind": "invalid", "reason": "no plugin.toml"})+ ),+ ]),+ );+ let view = model.view();+ assert_eq!(view.state, "ready");+ assert_eq!(view.rows[0].detail, "1.0 · Running · Does things.");+ assert!(!view.rows[2].switchable);+ assert!(view.rows[2].detail.contains("no plugin.toml"));+ assert_eq!(model.usable("a"), Some(true));+ assert_eq!(model.usable("b"), Some(false));+ assert_eq!(PluginsModel::default().usable("b"), None);+ }+}diff --git a/thinkterm-web/src/plugins.rs b/thinkterm-web/src/plugins.rsindex 36d882af..7ebc14ab 100644--- a/thinkterm-web/src/plugins.rs+++ b/thinkterm-web/src/plugins.rs@@ -52,6 +52,12 @@ impl PluginCalls {self.answer(id, Err(why.to_string()));}+ /// Whether any call is waiting for its answer: the way to the host is+ /// kept open until none is.+ pub fn waiting(&self) -> bool {+ !self.waiting.is_empty()+ }+/// 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() {diff --git a/thinkterm-web/src/views.rs b/thinkterm-web/src/views.rsindex 679cf95b..1824563e 100644--- a/thinkterm-web/src/views.rs+++ b/thinkterm-web/src/views.rs@@ -171,6 +171,15 @@ pub const STRING_KEYS: &[&str] = &["right-script-required","right-script-placeholder","web-tip-delete-snippet",+ "settings-sidebar-description",+ "right-mode-snippets",+ "settings-sidebar-snippets-description",+ "settings-section-plugins",+ "settings-plugins-description",+ "settings-plugins-reload",+ "settings-plugins-reload-description",+ "settings-plugins-reload-button",+ "settings-plugins-unusable",];pub fn strings() -> std::collections::BTreeMap<&'static str, String> {diff --git a/thinkterm-web/ui/src/SettingsPanel.svelte b/thinkterm-web/ui/src/SettingsPanel.svelteindex c39145cd..27089fb7 100644--- a/thinkterm-web/ui/src/SettingsPanel.svelte+++ b/thinkterm-web/ui/src/SettingsPanel.svelte@@ -3,8 +3,9 @@// holds them (thinkterm-web/src/settings.rs) and applies the language and// the font itself; the theme is painted here, and the rest is read by// whatever it concerns.+ import { handle } from './client';import { s, views } from './client.svelte';- import { bot, info, minus, palette, panelLeft, plus, rotateCcw, search, slidersHorizontal, x } from './icons';+ import { info, minus, palette, panelLeft, plus, rotateCcw, search, slidersHorizontal, x } from './icons';import { applyTheme, closeSettings, FOLLOW_DESKTOP, loadSchemes, panel, pickScheme, previewScheme, schemes, setSetting, storedScheme } from './settings.svelte';import type { Hotkey, Scheme, ScrollMode, Theme } from './model';import { POP, WINDOW, ms } from './motion';@@ -26,12 +27,13 @@// The window's sections, as the desktop's settings window lists them// on the left; the page has fewer rows, so fewer sections.- type Section = 'general' | 'appearance' | 'sidebar' | 'agents' | 'about';+ // The panels and the plugins are both under Sidebar: whatever a plugin+ // shows, it shows in a panel.+ type Section = 'general' | 'appearance' | 'sidebar' | 'about';const SECTIONS: [Section, string, string][] = [['general', 'settings-section-general', slidersHorizontal],['appearance', 'settings-section-appearance', palette],['sidebar', 'settings-section-sidebar', panelLeft],- ['agents', 'settings-section-agents', bot],['about', 'settings-section-about', info],];let section = $state<Section>('general');@@ -72,6 +74,42 @@// The theme is the page's to paint, whether the panel is open or not.$effect(() => applyTheme(settings.theme));+ // The plugins the plugin host on the server's machine runs, under the+ // panels: asked for while Sidebar is on show, or a search could find one+ // there. Told only when that changes: a want let go and taken again would+ // close the server's way to the host in between.+ const plugins = $derived(views.plugins);+ let pluginsWanted = false;+ $effect(() => {+ const wanted = panel.open && (section === 'sidebar' || query.trim() !== '');+ if (wanted === pluginsWanted) return;+ pluginsWanted = wanted;+ handle.client?.plugins_want('settings', wanted);+ });+ /** The plugins a search finds, or every one on the section's own page. */+ const pluginRows = $derived(+ query.trim() === '' || shows('sidebar', s('settings-section-plugins'))+ ? plugins.rows+ : plugins.rows.filter((row) => shows('sidebar', row.name)),+ );+ /** Snippets, a built-in plugin: its switch is its panel's. */+ const snippetsRow = $derived(plugins.rows.find((row) => row.builtin && row.id === 'snippets'));+ let reloading = $state(false);++ function onPlugin(id: string, ev: Event) {+ const field = ev.currentTarget;+ if (field instanceof HTMLInputElement) void handle.client?.plugin_set_enabled(id, field.checked);+ }++ async function reloadPlugins() {+ reloading = true;+ try {+ await handle.client?.plugins_reload();+ } finally {+ reloading = false;+ }+ }+// The size the "Fixed size" field offers: the pinned one, else the size// the terminal is drawn at now, so choosing "Fixed size" pins what is// already on screen rather than a number out of nowhere.@@ -339,13 +377,52 @@</div>{/if}- {#if shows('agents', s('web-settings-agents-panel'))}+ <!-- The right panel's panels, a switch each. Snippets is a built-in+ plugin, and its switch is the plugin's. -->+ {#if shows('sidebar', s('web-settings-agents-panel')) || shows('sidebar', s('right-mode-snippets'))}+ {#if query.trim() === ''}<div class="sdesc">{d('settings-sidebar-description')}</div>{/if}+ <div class="card">+ {#if shows('sidebar', s('web-settings-agents-panel'))}+ <div class="srow">+ <div class="tx"><div class="lab">{s('web-settings-agents-panel')}</div><div class="desc">{d('web-settings-agents-panel-description')}</div></div>+ <label class="switch"><input type="checkbox" data-setting="agents-panel" checked={settings['agents-panel']} onchange={(ev) => onFlag('agents-panel', ev)} /><span class="knob"></span></label>+ </div>+ {/if}+ {#if shows('sidebar', s('right-mode-snippets'))}+ <div class="srow">+ <div class="tx"><div class="lab">{s('right-mode-snippets')}</div><div class="desc">{d('settings-sidebar-snippets-description')}</div></div>+ <label class="switch"><input type="checkbox" data-panel-switch="snippets" checked={snippetsRow?.enabled ?? false} disabled={!snippetsRow?.switchable} onchange={(ev) => onPlugin('snippets', ev)} /><span class="knob"></span></label>+ </div>+ {/if}+ </div>+ {/if}++ {#if shows('sidebar', s('settings-section-plugins')) || (query.trim() !== '' && pluginRows.length > 0)}+ {#if query.trim() === ''}<div class="sdesc">{d('settings-plugins-description')}</div>{/if}<div class="card"><div class="srow">- <div class="tx"><div class="lab">{s('web-settings-agents-panel')}</div><div class="desc">{d('web-settings-agents-panel-description')}</div></div>- <label class="switch"><input type="checkbox" data-setting="agents-panel" checked={settings['agents-panel']} onchange={(ev) => onFlag('agents-panel', ev)} /><span class="knob"></span></label>+ <div class="tx"><div class="lab">{s('settings-plugins-reload')}</div><div class="desc">{d('settings-plugins-reload-description')}</div></div>+ <button class="pillbtn" type="button" data-action="reload-plugins" disabled={reloading} onclick={reloadPlugins}>{s('settings-plugins-reload-button')}</button></div></div>+ {#if plugins.state === 'ready' && plugins.status !== ''}<div class="err">{plugins.status}</div>{/if}+ <div class="card" data-plugins={plugins.state}>+ {#each pluginRows as row (row.key)}+ <div class="srow" data-plugin={row.id}>+ <div class="tx"><div class="lab">{row.name}</div><div class="desc">{row.detail}</div></div>+ {#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>+ {:else}+ <span class="pilltag">{s('settings-plugins-unusable')}</span>+ {/if}+ </div>+ {:else}+ <div class="srow"><div class="tx"><div class="desc">{plugins.status}</div></div></div>+ {/each}+ </div>+ {#if plugins.refused}<div class="err">{plugins.refused}</div>{/if}{/if}{#if shows('about', s('settings-section-about'))}diff --git a/thinkterm-web/ui/src/client.svelte.ts b/thinkterm-web/ui/src/client.svelte.tsindex c79cca65..c3851198 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, SnippetsView, StatusView, Strings, TabsView, WebSettings } from './model';+import type { AgentsView, NavsView, PluginsView, SidebarView, SnippetsView, StatusView, Strings, TabsView, WebSettings } from './model';export const views = $state({tabs: null as TabsView | null,@@ -18,6 +18,8 @@ export const views = $state({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 plugin list in Settings › Sidebar & Plugins. */+ plugins: { state: 'loading', status: '', rows: [], refused: null, revision: 0 } as PluginsView,/** The page's own preferences, as the wasm holds them (settings.rs). */settings: {language: 'system',@@ -66,6 +68,7 @@ export function attach(client: Client) {let lastAgents = '';// The snippets can be long; their view is read only when it moved.let lastSnippets = -1;+ let lastPlugins = -1;let lastSettings = '';const read = () => {const strings = client.strings();@@ -74,6 +77,7 @@ export function attach(client: Client) {views.strings = JSON.parse(strings) as Strings;// Its words are in the language too.lastSnippets = -1;+ lastPlugins = -1;}const tabs = client.tabs();if (tabs !== lastTabs) {@@ -105,6 +109,11 @@ export function attach(client: Client) {lastSnippets = snippets;views.snippets = JSON.parse(client.snippets()) as SnippetsView;}+ const plugins = client.plugins_revision();+ if (plugins !== lastPlugins) {+ lastPlugins = plugins;+ views.plugins = JSON.parse(client.plugins()) as PluginsView;+ }const settings = client.settings();if (settings !== lastSettings) {lastSettings = settings;diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.tsindex ecc88637..39e42afb 100644--- a/thinkterm-web/ui/src/model.ts+++ b/thinkterm-web/ui/src/model.ts@@ -225,6 +225,36 @@ export type SnippetsView = {revision: number;};+// The plugin list in Settings › Sidebar & Plugins+// (thinkterm-web/src/plugin_list.rs `PluginsView`): the plugins the plugin+// host on the server's machine runs, as the desktop's lists them.++export type PluginRow = {+ /** Tells rows apart: two installed plugins can claim one id. */+ key: string;+ id: string;+ name: string;+ /** Where it came from, its state, what it does: one line. */+ detail: string;+ /** The switch as it is to be shown, a change on its way included. */+ enabled: boolean;+ /** Whether a switch could do anything for it. */+ switchable: boolean;+ /** Built into ThinkTerm: its switch is its panel's, not in the list. */+ builtin: boolean;+};++export type PluginsView = {+ state: 'loading' | 'ready' | 'unavailable';+ /** What the section says besides its list: loading, or why the host+ cannot be reached (then the list is only what was last heard). */+ status: string;+ rows: PluginRow[];+ /** Why the last change asked here was refused. */+ refused: string | null;+ 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/tokens.css b/thinkterm-web/ui/src/tokens.cssindex 7fb131a8..4fe16cd1 100644--- a/thinkterm-web/ui/src/tokens.css+++ b/thinkterm-web/ui/src/tokens.css@@ -414,6 +414,10 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }#settings .switch input:checked + .knob { background: var(--accent); }#settings .switch input:checked + .knob::after { transform: translateX(16px); }#settings .err { padding: 0 2px 8px 2px; color: var(--danger); font-size: 12px; }+/* A section's own sentence above its cards, and a row's state where it+ has no control. */+#settings .sdesc { padding: 0 2px 12px 2px; color: var(--muted); font-size: 13px; font-weight: 500; }+#settings .pilltag { flex: none; color: var(--muted); font: 500 12px var(--ui); }/* Focus lives here so the IME composes into a real text field; thefield itself stays out of sight. */#kbd { position: fixed; left: 0; top: 0; width: 1px; height: 1px; opacity: 0; border: 0; padding: 0; margin: 0; resize: none; overflow: hidden; pointer-events: none; }