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.

web access: the small things the audits confirmed

RoversXd81980ce5f18
diff --git a/docs/thinkterm/web-access.md b/docs/thinkterm/web-access.md
index 44d4f22f..ba2a8463 100644
--- a/docs/thinkterm/web-access.md
+++ b/docs/thinkterm/web-access.md
@@ -12,7 +12,11 @@ moment you type into it.
`config.web_servers` is a list of `WebServer` objects, read when
`thinkterm-mux-server` starts, like `tls_servers`; reloading the configuration
-does not open or close web ports.
+does not open or close web ports. While the server runs, the port is opened
+and closed from the desktop's Settings → Web, or with
+`thinkterm cli web-server on|off|status`; an address that is in
+`web_servers` brings its TLS, origins and bundle directory with it, and one
+that is not gets the loopback, plain-HTTP defaults.
```lua
config.web_servers = {
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index ea06be9a..81122b70 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -1886,13 +1886,20 @@ impl Mux {
return None;
}
let lease = self.frontend_lease.lock();
- Some(match lease.access_mode {
- FrontendAccessMode::Handoff => lease.handoff_owner.as_ref() == Some(client_id),
+ let owner = match lease.access_mode {
+ FrontendAccessMode::Handoff => lease.handoff_owner.as_ref(),
FrontendAccessMode::TmuxLatest => match lease.tabs.get(&tab_id) {
- None => true,
- Some(state) => state.owner.as_ref() == Some(client_id),
+ None => return Some(true),
+ Some(state) => state.owner.as_ref(),
},
- })
+ };
+ let may = owner == Some(client_id);
+ if !may {
+ // Both ids in full: a client that believes it owns the viewport
+ // and is refused here is comparing them differently from us.
+ log::warn!("resize of tab {tab_id} refused: owner {owner:?}, asked by {client_id:?}");
+ }
+ Some(may)
}
fn publish_frontend_access_state(&self) {
diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rs
index fa72b98e..dc1be9ab 100644
--- a/thinkterm-web/src/app.rs
+++ b/thinkterm-web/src/app.rs
@@ -12,6 +12,7 @@ use codec::Pdu;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
+use thinkterm_session::host::SessionEvents as _;
use termwiz::input::{KeyCode, Modifiers};
use thinkterm_font_web::FontSet;
use thinkterm_proto::{PaneId, TabId};
@@ -915,6 +916,8 @@ impl App {
let (tab_id, pane_id) = (inner.tab_id, inner.pane_id);
if owner {
inner.session.apply_local_resize(size);
+ let session = Arc::clone(&inner.session);
+ let host = Arc::clone(&inner.host);
wasm_bindgen_futures::spawn_local(async move {
let pdu = Pdu::Resize(codec::Resize {
containing_tab_id: tab_id,
@@ -927,7 +930,15 @@ impl App {
})
.await
{
+ // The reflow above was optimistic. Refused, it would
+ // show a grid the server does not have, for ever:
+ // back to the canonical one, and repaint.
log::warn!("resize refused: {err:#}");
+ if let Some(canonical) = link.lease().canonical_size {
+ session.apply_local_resize(canonical);
+ session.make_all_stale();
+ host.events.pane_output(0);
+ }
}
});
} else {
diff --git a/thinkterm-web/src/glyphs.rs b/thinkterm-web/src/glyphs.rs
index 5b88dd44..86601fb6 100644
--- a/thinkterm-web/src/glyphs.rs
+++ b/thinkterm-web/src/glyphs.rs
@@ -147,6 +147,11 @@ pub struct GlyphCache {
/// and this table goes with it. So is presentation -- one font string,
/// one drawing procedure, no difference in the pixels.
fallback: HashMap<u8, HashMap<String, Option<Rc<CachedGlyph>>>>,
+ /// Gaps whose drawing threw, with when to try again and how long the
+ /// next wait is. Neither a fact about this machine (so not `fallback`)
+ /// nor something to redo every frame: a canvas that keeps throwing
+ /// would otherwise cost a draw and a warning per gap per frame.
+ failed: HashMap<(u8, String), (f64, f64)>,
scratch: Renderer,
/// The CSS font stack the fallback draws with.
pub families: Rc<str>,
@@ -223,6 +228,7 @@ impl GlyphCache {
blocks: HashMap::new(),
shapes: HashMap::new(),
fallback: HashMap::new(),
+ failed: HashMap::new(),
scratch: Renderer::Untried,
families,
blank: Rc::new(blank_glyph()),
@@ -427,6 +433,12 @@ impl GlyphCache {
self.declined += 1;
return Ok(None);
}
+ let now = crate::app::monotonic_ms();
+ if let Some((retry_at, _)) = self.failed.get(&(cells, gap.text.clone())) {
+ if now < *retry_at {
+ return Ok(None);
+ }
+ }
// The canvas is checked before the budget. Spending budget on a
// browser that will not give us a 2D context produced `deferred`,
// `deferred` asked for another frame, and the next frame was
@@ -454,14 +466,27 @@ impl GlyphCache {
// retrying every frame would redraw the same nothing for ever.
Ok(None) => return Ok(self.remember(gap, cells, None)),
Err(err) => {
- // Not remembered. `Ok(None)` above is a fact about this
- // machine -- no font has the glyph -- and is worth caching
- // for ever. A thrown exception is not: `getImageData` can
- // fail for reasons that pass, and writing "undrawable" here
- // left the grapheme a box for the life of the cache. The
- // budget already stops this from being redrawn more than a
- // few times a frame.
- log::warn!("the canvas could not draw {:?}: {err:#}", gap.text);
+ // Not a fact about this machine the way `Ok(None)` is:
+ // `getImageData` can fail for reasons that pass, and writing
+ // "undrawable" here left the grapheme a box for the life of
+ // the cache. Not forgotten either: retried every frame, a
+ // canvas that keeps throwing costs a draw and a warning per
+ // gap per frame. So: a box now, another try after a wait
+ // that doubles up to the atlas's own cap.
+ if self.failed.len() > MAX_FALLBACK_ENTRIES {
+ self.failed.clear();
+ }
+ let backoff = self
+ .failed
+ .get(&(cells, gap.text.clone()))
+ .map(|(_, backoff)| (backoff * 2.0).min(crate::fallback::MAX_RETRY_MS))
+ .unwrap_or(crate::fallback::MIN_RETRY_MS);
+ self.failed
+ .insert((cells, gap.text.clone()), (now + backoff, backoff));
+ log::warn!(
+ "the canvas could not draw {:?}, retrying in {backoff:.0} ms: {err:#}",
+ gap.text
+ );
return Ok(None);
}
};
diff --git a/wezterm-gui/src/web_settings.rs b/wezterm-gui/src/web_settings.rs
index d0603a0c..0b52b6a3 100644
--- a/wezterm-gui/src/web_settings.rs
+++ b/wezterm-gui/src/web_settings.rs
@@ -72,24 +72,48 @@ pub fn reset() {
*STATE.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
-/// The mux client, if this GUI has one. A GUI with only local panes and no
-/// mux server has nothing to ask, and the section says so.
+/// The mux client the switch is about, if this GUI has one. A GUI with
+/// only local panes and no mux server has nothing to ask, and the section
+/// says so.
+///
+/// The server that owns this machine's sessions is the one the page means
+/// -- the local session host, when local sessions run in one, the same
+/// rule `local_sessions` applies to spawning. Only without a host does it
+/// fall back to a remote domain, and it says so when it had to pick among
+/// several, because "Web" then reads as that server's port.
fn client() -> Option<Client> {
+ let mut clients = Vec::new();
for domain in Mux::get().iter_domains() {
- let is_client = domain.downcast_ref::<ClientDomain>().is_some();
- log::debug!(
- "web settings: domain {} ({}) client={is_client}",
- domain.domain_id(),
- domain.domain_name()
- );
- if is_client {
- match ClientDomain::get_client_inner_for_domain(domain.domain_id()) {
- Ok(inner) => return Some(inner.client.clone()),
- Err(err) => log::debug!("web settings: domain has no live client: {err:#}"),
- }
+ if domain.downcast_ref::<ClientDomain>().is_none() {
+ continue;
+ }
+ match ClientDomain::get_client_inner_for_domain(domain.domain_id()) {
+ Ok(inner) => clients.push((
+ domain.domain_id(),
+ domain.domain_name().to_string(),
+ inner.client.clone(),
+ )),
+ Err(err) => log::debug!("web settings: domain has no live client: {err:#}"),
}
}
- None
+ if let Some((_, _, client)) = clients
+ .iter()
+ .find(|(id, _, _)| crate::local_sessions::is_host_domain_id(*id))
+ {
+ return Some(client.clone());
+ }
+ if clients.len() > 1 {
+ log::warn!(
+ "web settings: no local session host; the Web section is about {} (attached: {})",
+ clients[0].1,
+ clients
+ .iter()
+ .map(|(_, name, _)| name.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ );
+ }
+ clients.into_iter().next().map(|(_, _, client)| client)
}
/// Which gate an answer releases. They are separate on purpose: a poll
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index b4006f64..8c13b191 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -1749,9 +1749,13 @@ impl SessionHandler {
containing_tab_id,
) {
None => anyhow::bail!("client connection was superseded"),
- Some(false) => {
- return Ok(Pdu::UnitResponse(UnitResponse {}));
- }
+ // An error, not a silent success: the
+ // client reflowed itself before asking,
+ // and "ok" would leave it showing a grid
+ // the server does not have, for ever.
+ Some(false) => anyhow::bail!(
+ "resize refused: this client does not own the viewport of tab {containing_tab_id}"
+ ),
Some(true) => {}
}
}
diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rs
index b4dc7757..d52f26ab 100644
--- a/wezterm/src/cli/mod.rs
+++ b/wezterm/src/cli/mod.rs
@@ -185,11 +185,20 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>
let mut ui = mux::connui::ConnectionUI::new_headless();
let initial = true;
+ // The browser port and its tokens belong to the mux server; a GUI's
+ // in-process mux has neither. Asking the GUI (the default, for every
+ // other command) answered "not accepting browser clients" while the
+ // server was.
+ let prefer_mux = cli.prefer_mux
+ || matches!(
+ cli.sub,
+ CliSubCommand::WebServer(_) | CliSubCommand::WebToken(_)
+ );
let client = Client::new_default_unix_domain(
initial,
&mut ui,
cli.no_auto_start,
- cli.prefer_mux,
+ prefer_mux,
cli.class
.as_deref()
.unwrap_or(wezterm_gui_subcommands::DEFAULT_WINDOW_CLASS),
diff --git a/wezterm/src/cli/web_server.rs b/wezterm/src/cli/web_server.rs
index 84e370dc..8408fe62 100644
--- a/wezterm/src/cli/web_server.rs
+++ b/wezterm/src/cli/web_server.rs
@@ -1,9 +1,10 @@
//! `thinkterm cli web-server …`: turn the browser listener on and off, and
//! see where it is accepting.
//!
-//! The port is bound by the mux server, so this is the only way to change
-//! it without restarting one: `web_servers` in the configuration is read at
-//! startup and nothing re-reads it.
+//! The port is bound by the mux server, and `web_servers` in the
+//! configuration is read only when one starts; this and the Web section of
+//! the desktop's Settings are the two ways to change it while it runs.
+//! Both talk to the mux server, never to a GUI's in-process mux.
use anyhow::bail;
use clap::Parser;