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
//! The handle the page holds: what the chrome shows, as JSON (`views`),
//! and the few things it can ask for. The display layer is not told what
//! changed, only that something did; it reads the views it draws.
use crate::page::WebApp;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct Client {
app: Rc<WebApp>,
}
impl Client {
pub(crate) fn new(app: Rc<WebApp>) -> Self {
Self { app }
}
}
fn json<T: serde::Serialize>(value: &T) -> String {
serde_json::to_string(value).unwrap_or_else(|err| format!("{{\"error\":{:?}}}", err.to_string()))
}
#[wasm_bindgen]
impl Client {
/// Called once right away, then once per task in which any view
/// changed.
pub fn on_change(&self, callback: js_sys::Function) {
self.app.set_on_change(Rc::new(move || {
if let Err(err) = callback.call0(&JsValue::NULL) {
log::warn!("the page's change handler failed: {err:?}");
}
}));
}
pub fn sidebar(&self) -> String {
json(&self.app.sidebar_view())
}
pub fn tabs(&self) -> String {
json(&self.app.tabs_view())
}
pub fn navs(&self) -> String {
json(&self.app.navs_view())
}
pub fn status(&self) -> String {
json(&self.app.status_view())
}
pub fn layout(&self) -> String {
self.app.layout_view()
}
/// The page's own labels in the active locale, keyed by catalogue id.
pub fn strings(&self) -> String {
json(&crate::views::strings())
}
/// Switch the language: a preference (`"system"` or a tag) and the
/// browser's own list. Returns the locale it resolved to.
pub fn set_locale(&self, preference: String, languages: Vec<String>) -> String {
let code = thinkterm_i18n::activate_preference(&preference, &languages);
self.app.locale_changed();
code.to_string()
}
/// A panel's edge is being dragged (`on`) or was let go: while it is,
/// the canvas follows but the tab is not reshaped on the server; the
/// one reshape comes at the end.
pub fn panel_drag(&self, on: bool) {
self.app.set_panel_drag(on);
}
/// Refit the canvas to its box now, in the same task as the layout
/// change that moved it, so no frame shows the old bitmap stretched.
pub fn resize(&self) {
self.app.resize();
}
/// The page put this machine's terminal on show (`true`) or behind
/// another machine's. Hidden, it keeps its sessions but does not paint.
pub fn set_shown(&self, shown: bool) {
self.app.platform.set_shown(shown);
if shown {
self.app.mark_focused_program_status_seen();
self.app.resize();
self.app.request_frame();
// Listed again now, so a tab it shows is claimed as on any
// showing rather than at the next poll.
self.app.refresh_layout();
}
}
/// Let this client go: its connection closes, and nothing it set going
/// does anything more. The page frees it after.
pub fn close(&self) {
self.app.retire();
self.app.platform.release();
}
/// Whether the connection is up; a change comes with a view change.
pub fn connected(&self) -> bool {
self.app.connected()
}
/// This server's Spaces: JSON `[{id, name, current, default}]`.
pub fn spaces(&self) -> String {
json(&self.app.spaces())
}
/// A new tab in the named domain of this server (a plain ssh one).
pub fn new_tab_in(&self, domain: String) {
self.app.new_tab_in(Some(domain));
}
/// The card's button, or a press on the card: ask for the terminal
/// another device holds. What comes of it is the card's next state.
pub fn take_over(&self) {
self.app.take_over();
}
/// A click in the sidebar: `kind` names the row or button, `id` the
/// thread, project or window it is about, `flag` the pin state.
/// Returns false for a kind the model does not know.
pub fn side_click(&self, kind: String, id: Option<String>, flag: Option<bool>) -> bool {
let Some(click) = crate::commands::side_click(&kind, id, flag) else {
return false;
};
self.app.on_side_click(click);
true
}
/// The context menu for `kind` ("pane", "tab", "thread", "project",
/// "archived-project", "sidebar-options") and `id`: JSON `MenuItem[]`.
pub fn context_menu(&self, kind: String, id: String) -> String {
json(&self.app.context_menu(&kind, &id))
}
/// Perform a menu row's action by its id: JSON `MenuOutcome`.
pub fn menu_action(&self, id: String) -> String {
json(&self.app.menu_action(&id))
}
/// The Agents panel: JSON `AgentsView`.
pub fn agents(&self) -> String {
json(&self.app.agents_view())
}
/// Bring an agent's pane on show.
pub fn agent_reveal(&self, pane: u32) -> bool {
self.app.agent_reveal(pane as usize)
}
/// Open or fold an agent's sub-task list.
pub fn agent_toggle_subtasks(&self, pane: u32) -> bool {
self.app.agent_toggle_subtasks(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);
}
/// How much room the page gives a plugin's panel -- or, `extended`, its
/// extended view -- in CSS pixels, how its text measures, and whether
/// there is room for an extended view: JSON `Env`. Returns an error
/// text or "".
pub fn plugin_panel_env(&self, extended: bool, env: String) -> String {
match serde_json::from_str(&env) {
Ok(env) => {
self.app.plugin_panel_env(extended, env);
String::new()
}
Err(err) => format!("{err}"),
}
}
/// The plugin panel on show, or its extended view: JSON `PanelView`, or
/// `null` when none is.
pub fn plugin_panel(&self, extended: bool) -> String {
json(&self.app.plugin_panel_view(extended))
}
/// Changes when `plugin_panel(extended)` would, so the page paints only
/// then.
pub fn plugin_panel_revision(&self, extended: bool) -> f64 {
self.app.plugin_panel_revision(extended) as f64
}
/// Whether the plugin panel on show asks for its extended view: the
/// page gives it room beside the right panel while it does.
pub fn plugin_panel_extended(&self) -> bool {
self.app.plugin_panel_extended()
}
/// The extended view's close button, pressed.
pub fn plugin_extended_close(&self) {
self.app.plugin_extended_close();
}
/// The page took the room it gave the extended view away.
pub fn plugin_extended_gone(&self) {
self.app.plugin_extended_gone();
}
/// The pointer over the plugin panel, or its extended view, in CSS
/// pixels from its corner. True when it is to be painted again.
pub fn plugin_panel_pointer(&self, extended: bool, x: f32, y: f32) -> bool {
self.app.plugin_panel_pointer(extended, x, y)
}
pub fn plugin_panel_leave(&self, extended: bool) -> bool {
self.app.plugin_panel_leave(extended)
}
/// A press in the plugin panel, or its extended view: `button` 0, 1 or
/// 2 as the DOM numbers them, `count` 2 for a double click. True when
/// the plugin hears of it.
#[allow(clippy::too_many_arguments)]
pub fn plugin_panel_click(
&self,
extended: bool,
x: f32,
y: f32,
button: u8,
count: u32,
shift: bool,
ctrl: bool,
alt: bool,
meta: bool,
) -> bool {
use thinkterm_plugin_panel::{Button, Mods};
let button = match button {
1 => Button::Middle,
2 => Button::Right,
_ => Button::Left,
};
let mods = Mods { shift, ctrl, alt, cmd: meta };
self.app.plugin_panel_click(extended, x, y, button, count.max(1), mods)
}
/// The wheel over the plugin panel, or its extended view, `dy` CSS
/// pixels down. True when something in it scrolled.
pub fn plugin_panel_wheel(&self, extended: bool, x: f32, y: f32, dx: f32, dy: f32) -> bool {
self.app.plugin_panel_wheel(extended, x, y, dx, dy)
}
/// Whether the plugin panel, or its extended view, has the keyboard.
pub fn plugin_panel_has_keyboard(&self, extended: bool) -> bool {
self.app.plugin_panel_has_keyboard(extended)
}
/// The page's field over the panel's field `id` got the keyboard.
pub fn plugin_panel_field_focus(&self, extended: bool, id: String) {
self.app.plugin_panel_field_focus(extended, &id);
}
/// What the page's field over the panel's field `id` holds now: what
/// it is to hold instead, when the panel's takes less.
pub fn plugin_panel_field_text(&self, extended: bool, id: String, text: String) -> Option<String> {
self.app.plugin_panel_field_text(extended, &id, &text)
}
/// Return in the page's field over the panel's field `id`.
pub fn plugin_panel_field_submit(&self, extended: bool, id: String) {
self.app.plugin_panel_field_submit(extended, &id);
}
/// The keyboard went from the panel's fields to elsewhere on the page.
pub fn plugin_panel_blur(&self, extended: bool) {
self.app.plugin_panel_blur(extended);
}
/// A key the page's field with the keyboard does not use, as
/// `KeyboardEvent.key` names it: true when it was the panel's, and the
/// page is to keep it to itself.
#[allow(clippy::too_many_arguments)]
pub fn plugin_panel_key(
&self,
extended: bool,
key: String,
shift: bool,
ctrl: bool,
alt: bool,
meta: bool,
) -> bool {
let mods = thinkterm_plugin_panel::Mods { shift, ctrl, alt, cmd: meta };
self.app.plugin_panel_key(extended, &key, mods)
}
/// 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))
})
}
/// 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))
})
}
/// How long a plugin runs unused -- `always`, `briefly` or `never`: a
/// promise of whether the plugin host took the choice.
pub fn plugin_set_background(&self, id: String, background: String) -> js_sys::Promise {
let app = Rc::clone(&self.app);
wasm_bindgen_futures::future_to_promise(async move {
Ok(JsValue::from_bool(app.plugin_set_background(id, background).await))
})
}
/// Look for new and removed plugins, and restart the running ones: a
/// promise of whether the plugin host did.
pub fn plugins_reload(&self) -> js_sys::Promise {
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 {
let list: Vec<serde_json::Value> = thinkterm_i18n::LANGUAGE_OPTIONS
.iter()
.map(|o| serde_json::json!({ "preference": o.preference, "label": thinkterm_i18n::language_option_label(*o) }))
.collect();
json(&list)
}
/// The page's preferences as the model holds them: JSON `WebSettings`.
pub fn settings(&self) -> String {
json(&self.app.settings_view())
}
/// The version of the ThinkTerm at the other end, as it answered when
/// the page attached: what Settings › About shows.
pub fn server_version(&self) -> String {
self.app.server_version()
}
/// The stored preferences, whole, at boot. Returns an error text or "".
pub fn apply_settings(&self, json: String) -> String {
self.app.apply_settings(&json).err().unwrap_or_default()
}
/// One preference (`key` as in the JSON, `value` as JSON). Returns an
/// error text or "".
pub fn set_setting(&self, key: String, value: String) -> String {
self.app.set_setting(&key, &value).err().unwrap_or_default()
}
/// A finger came down at a point: whether that starts dragging a
/// divider near it (`App::touch_divider`).
pub fn touch_divider(&self, x: f64, y: f64) -> bool {
self.app.touch_divider(x, y)
}
/// The tab icon cards the page's server sent over the relay (a
/// `WireCatalog`, as JSON). Returns an error text or "".
pub fn set_tab_icons(&self, json: String) -> String {
self.app.set_tab_icons(&json).err().unwrap_or_default()
}
/// The colours of the scheme named by `terminal-scheme`, as the page
/// read them out of `schemes.json`; `None` follows the server's
/// configuration. Returns an error text or "".
pub fn set_terminal_palette(&self, json: Option<String>) -> String {
let palette = match json.as_deref() {
None => None,
Some(text) => match crate::settings::SchemeColors::parse(text)
.and_then(|colors| colors.to_palette())
{
Ok(palette) => Some(palette),
Err(err) => return err,
},
};
self.app.set_terminal_palette(palette);
String::new()
}
/// The search palette's entries for `query`, ranked: JSON `Results`.
pub fn palette(&self, query: String) -> String {
json(&self.app.palette(&query))
}
/// Perform a palette pick by its entry id: JSON `PaletteOutcome`.
pub fn palette_run(&self, id: String) -> String {
json(&self.app.palette_run(&id))
}
/// The page's remembered picks (most recent first), at boot.
pub fn set_recent(&self, ids: Vec<String>) {
self.app.set_recent(ids);
}
/// Show a Space in the sidebar (the page remembers the last one).
pub fn set_space(&self, id: String) -> bool {
self.app.set_space(&id)
}
/// A key the page pressed for the user (its key bar on a phone), by
/// its DOM name ("Escape", "ArrowUp", "c"), with modifiers. Returns
/// whether the terminal took it.
pub fn key(&self, name: String, ctrl: bool, alt: bool, shift: bool) -> bool {
let dom = crate::keymap::DomKey { key: &name, code: "", ctrl, alt, shift, meta: false, composing: false };
match crate::keymap::map_key(&dom) {
Some((key, mods)) => self.app.key_down(key, mods, shift),
None => false,
}
}
/// Text from the page's clipboard, typed into the focused pane.
pub fn paste(&self, text: String) {
self.app.paste(&text);
}
/// Enter or Escape in the sidebar's inline input, with its value.
pub fn side_key(&self, key: String, value: String) {
self.app.on_side_key(&key, value);
}
/// A click on the tab row or a pane's bar. Returns false for an
/// action the model does not know.
/// A drop, decided here: `kind` is "tab" (id = tab id, `at` = the
/// index it lands on), "pane" (id = pane id, `target` = the pane it
/// was dropped on, `edge` = "left"|"right"|"top"|"bottom"), "thread"
/// or "project" (`target` = the row it lands before, None for last).
/// False when the model refuses; the listing or tree that follows
/// redraws the page.
pub fn drop(&self, kind: String, id: String, target: Option<String>, edge: Option<String>, at: Option<u32>) -> bool {
match kind.as_str() {
"tab" => match (id.parse(), at) {
(Ok(tab), Some(at)) => self.app.move_tab(tab, at as usize),
_ => false,
},
"pane" => {
let (Ok(pane), Some(Ok(target))) = (id.parse(), target.map(|t| t.parse())) else {
return false;
};
let Some((direction, second)) = edge.as_deref().and_then(crate::commands::drop_edge) else {
return false;
};
self.app.move_pane(pane, target, direction, second)
}
"thread" => self.app.move_thread(&id, target.as_deref()),
"project" => self.app.move_project(&id, target.as_deref()),
_ => false,
}
}
pub fn chrome_click(&self, action: String, pane: Option<u32>, tab: Option<u32>) -> bool {
let pane = pane.map(|p| p as usize);
let Some(click) = crate::commands::chrome_click(&action, pane, tab.map(|t| t as usize)) else {
return false;
};
self.app.on_chrome_click(click);
true
}
}