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(plugins): give the example plugin a panel
RoversX29eced300375
diff --git a/docs/thinkterm/plugins.md b/docs/thinkterm/plugins.mdindex bf4b17a6..ec6765bb 100644--- a/docs/thinkterm/plugins.md+++ b/docs/thinkterm/plugins.md@@ -656,7 +656,9 @@ fn main() -> std::io::Result<()> {The server's tests use that to exercise the protocol end to end.`thinkterm-plugin-example`, in `plugins/example`, is a complete plugin: a-manifest and two calls. To install it and try it:+manifest, two calls, and a panel that decodes what is typed in it or the+lowest line that decodes on the terminal beside it. To install it and try+it:```shcargo build --release -p thinkterm-plugin-examplediff --git a/plugins/example/plugin.toml b/plugins/example/plugin.tomlindex bc487c6d..15f6eeb3 100644--- a/plugins/example/plugin.toml+++ b/plugins/example/plugin.toml@@ -4,7 +4,7 @@ id = "text-tools"name = "Text Tools"version = "0.1.0"description = "Decodes text, and makes UUIDs."-api = 1+api = 2[run]program = "thinkterm-plugin-example"@@ -12,6 +12,9 @@ program = "thinkterm-plugin-example"[run.windows]program = "thinkterm-plugin-example.exe"+[panel]+icon = "puzzle"+[locales.zh-CN]name = "文本工具"description = "解码文字,生成 UUID。"diff --git a/plugins/example/src/main.rs b/plugins/example/src/main.rsindex c90e8d39..c1ab2bec 100644--- a/plugins/example/src/main.rs+++ b/plugins/example/src/main.rs@@ -1,12 +1,15 @@-//! An example ThinkTerm plugin: two calls, in one small program. To make-//! one of your own, copy this directory, change the id in plugin.toml and-//! the name in Cargo.toml, and change what the calls do.+//! An example ThinkTerm plugin: two calls and a panel, in one small+//! program. To make one of your own, copy this directory, change the id in+//! plugin.toml and the name in Cargo.toml, and change what the calls do.//! docs/thinkterm/plugins.md says how to install it.//!//! - `{"op": "decode", "text": "…"}` answers with what the text decodes//! to, or `null`://! `thinkterm plugin call text-tools '{"op":"decode","text":"aGk="}'`.//! - `{"op": "uuid"}` answers with a new UUID.+//! - The panel decodes what is typed in it, or the lowest line that decodes+//! on the screen of the terminal beside it (`View::cli`), and shows what+//! that decodes to in as many lines as it has room for (`Text::wrap`).use anyhow::{bail, Context as _};use base64::alphabet;@@ -14,9 +17,32 @@ use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig};use base64::engine::DecodePaddingMode;use base64::Engine as _;use serde_json::{json, Value};-use thinkterm_plugin_sdk::{Cx, Plugin};+use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use thinkterm_plugin_sdk::panel::{+ feature, Align, Click, FieldText, Frame, Hit, Input, Rect, Size, Text, Token,+};+use thinkterm_plugin_sdk::{Cx, Emitter, Plugin, View};-struct TextTools;+const PAD: f32 = 12.0;+/// The panel's field, and its button that reads the terminal.+const TYPED: &str = "typed";+const READ: &str = "read";++struct TextTools {+ /// What each panel decodes: typed in its field, or put there from the+ /// terminal beside it.+ typed: HashMap<u64, FieldText>,+ /// Lines read off a panel's terminal, on their way to its field, with+ /// the turn of the panel's they answer.+ read: Arc<Mutex<Vec<(u64, u64, String)>>>,+ /// Each panel's turn: it moves on with each read asked for and each+ /// thing typed, and a line read for an earlier one is dropped -- what+ /// the user typed since, or a later read, stands.+ turns: HashMap<u64, u64>,+ /// Draws the panels again once a line is read; none in the tests.+ emitter: Option<Emitter>,+}impl Plugin for TextTools {fn call(&mut self, body: Value, _cx: &mut Cx) -> anyhow::Result<Value> {@@ -34,10 +60,144 @@ impl Plugin for TextTools {_ => bail!("unknown op; this plugin knows \"decode\" and \"uuid\""),}}++ fn draw(&mut self, view: &View, frame: &mut Frame) {+ let turn = self.turns.get(&view.id).copied().unwrap_or_default();+ let typed = self.typed.entry(view.id).or_default();+ let mut read = self+ .read+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ read.retain(|(of, answers, line)| {+ if *of == view.id && *answers == turn {+ typed.set(line.as_str());+ }+ *of != view.id+ });+ drop(read);+ draw(typed, view, frame);+ }++ fn input(&mut self, view: &View, input: Input, _cx: &mut Cx) {+ match input {+ Input::Text(text) | Input::Submit(text) if text.id == TYPED => {+ *self.turns.entry(view.id).or_default() += 1;+ self.typed.entry(view.id).or_default().heard(&text);+ }+ Input::Click(Click { id, .. }) if id == READ => {+ let Some(cli) = view.cli() else {+ return;+ };+ let turn = self.turns.entry(view.id).or_default();+ *turn += 1;+ // Off the plugin's thread: drawing does not wait for it.+ let (read, emitter, of, turn) =+ (Arc::clone(&self.read), self.emitter.clone(), view.id, *turn);+ std::thread::spawn(move || {+ if let Some(line) = lowest_decodable_line(cli) {+ read.lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .push((of, turn, line));+ if let Some(emitter) = emitter {+ emitter.redraw();+ }+ }+ });+ }+ _ => {}+ }+ }++ fn closed(&mut self, view: &View) {+ self.typed.remove(&view.id);+ self.turns.remove(&view.id);+ // A line read for it may be on its way still: it is dropped when it+ // comes. One that came already goes now.+ self.read+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .retain(|(of, ..)| *of != view.id);+ }+}++/// The panel: a field to type in, where the client has fields; a button+/// that reads the terminal beside it, where there is one; and what the+/// text decodes to.+fn draw(typed: &FieldText, view: &View, frame: &mut Frame) {+ let env = &view.env;+ let width = env.width - PAD * 2.0;+ let mut y = PAD;+ if env.has(feature::FIELDS) {+ let tall = env.body.line + 12.0;+ frame.push(+ typed+ .field(TYPED, PAD, y, width, tall)+ .placeholder("Text to decode")+ .clear(),+ );+ y += tall + 8.0;+ }+ if env.terminal.is_some() {+ let tall = env.body.line + 10.0;+ frame.push(+ Rect::new(PAD, y, width, tall)+ .fill(Token::BgRaised)+ .radius(6.0),+ );+ frame.push(+ Hit::new(READ, PAD, y, width, tall)+ .hover(Token::BgHover)+ .radius(6.0),+ );+ let label = Text::new(PAD, y, width, tall, "Decode from the terminal");+ frame.push(label.align(Align::Center));+ y += tall + 12.0;+ }+ let text = typed.text().trim();+ if text.is_empty() {+ return;+ }+ let Some(decoded) = decode(text) else {+ let none = Text::new(PAD, y, width, env.body.line, "Nothing here decodes");+ frame.push(none.color(Token::TextMuted));+ return;+ };+ let kind = Text::new(PAD, y, width, env.small.line, decoded.kind);+ frame.push(kind.size(Size::Small).color(Token::TextMuted));+ y += env.small.line + 4.0;+ // As many lines as the panel has room for, where the client breaks+ // them with the font it shows them in; one line where it cannot.+ if env.has(feature::WRAP) {+ let rows = ((env.height - y - PAD) / env.body.line).floor().max(1.0);+ frame.push(Text::new(PAD, y, width, rows * env.body.line, decoded.text).wrap());+ } else {+ frame.push(Text::new(PAD, y, width, env.body.line, decoded.text));+ }+}++/// The lowest line on the screen of the terminal `cli` reaches that+/// decodes: what a command just printed, under the line it was typed on.+fn lowest_decodable_line(mut cli: std::process::Command) -> Option<String> {+ let out = cli.args(["get-text", "--trim", "--unwrap"]).output().ok()?;+ if !out.status.success() {+ eprintln!("get-text: {}", String::from_utf8_lossy(&out.stderr).trim());+ return None;+ }+ String::from_utf8_lossy(&out.stdout)+ .lines()+ .rev()+ .map(str::trim)+ .find(|line| decode(line).is_some())+ .map(str::to_string)}fn main() -> std::io::Result<()> {- thinkterm_plugin_sdk::run(TextTools)+ thinkterm_plugin_sdk::run_with(|emitter| TextTools {+ typed: HashMap::new(),+ read: Arc::default(),+ turns: HashMap::new(),+ emitter: Some(emitter),+ })}#[derive(Debug, PartialEq)]@@ -226,9 +386,51 @@ mod tests {}}+ fn tools() -> TextTools {+ TextTools {+ typed: HashMap::new(),+ read: Arc::default(),+ turns: HashMap::new(),+ emitter: None,+ }+ }++ #[test]+ fn a_line_read_for_an_earlier_turn_is_dropped() {+ let env = serde_json::from_value(json!({+ "width": 320.0, "height": 640.0, "scale": 2.0, "dark": true,+ "small": {"size": 11.0, "line": 15.0},+ "body": {"size": 13.0, "line": 17.0},+ "title": {"size": 15.0, "line": 20.0},+ "mono": {"size": 12.0, "line": 16.0, "advance": 7.2},+ "features": ["fields", "wrap"]+ }))+ .unwrap();+ let view = View::new(3, env);+ let mut plugin = tools();+ // A read asked for, its turn 1; then the user typed, turn 2.+ plugin.turns.insert(view.id, 2);+ plugin+ .read+ .lock()+ .unwrap()+ .push((view.id, 1, "aGk=".into()));+ plugin.draw(&view, &mut Frame::default());+ assert_eq!(plugin.typed[&view.id].text(), "");+ assert!(plugin.read.lock().unwrap().is_empty(), "let go of");+ // One read for the turn it is now is taken.+ plugin+ .read+ .lock()+ .unwrap()+ .push((view.id, 2, "aGk=".into()));+ plugin.draw(&view, &mut Frame::default());+ assert_eq!(plugin.typed[&view.id].text(), "aGk=");+ }+#[test]fn the_calls() {- let mut plugin = TextTools;+ let mut plugin = tools();let mut cx = Cx::new();assert_eq!(plugin