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.

Compile the terminal core to wasm32

RoversX04ca04e8e381
diff --git a/.cargo/config.toml b/.cargo/config.toml
index b889045d..7e6294b8 100644
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,3 +1,9 @@
+# getrandom refuses to build for this target unless it is told where entropy
+# comes from, and it wants a cfg rather than a feature. The browser's
+# crypto.getRandomValues is the only source there is.
+[target.wasm32-unknown-unknown]
+rustflags = ['--cfg', 'getrandom_backend="wasm_js"']
+
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
ar = "x86_64-w64-mingw32-gcc-ar"
diff --git a/Cargo.toml b/Cargo.toml
index 280b990a..f943fdc9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
members = [
"bidi",
+ "wasm-probe",
"bidi/generate",
"strip-ansi-escapes",
"sync-color-schemes",
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index e4966b7d..a92eafff 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -9,6 +9,7 @@ use num_traits::ToPrimitive;
use std::collections::HashMap;
use std::io::{BufWriter, Write};
use std::num::NonZeroUsize;
+#[cfg(not(target_family = "wasm"))]
use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use terminfo::{Database, Value};
@@ -443,16 +444,33 @@ fn default_color_map() -> HashMap<u16, RgbColor> {
/// back-pressure when there is a lot of data to read,
/// and we're in control of the write side, which represents
/// input from the interactive user, or pastes.
+#[cfg(not(target_family = "wasm"))]
struct ThreadedWriter {
sender: Sender<WriterMessage>,
}
+#[cfg(target_family = "wasm")]
+struct ThreadedWriter {
+ writer: Box<dyn std::io::Write + Send>,
+}
+
+#[cfg(not(target_family = "wasm"))]
enum WriterMessage {
Data(Vec<u8>),
Flush,
}
impl ThreadedWriter {
+ /// wasm has no threads, and nothing to be freed from blocking on: there is
+ /// no pty behind the writer, only whatever the embedder passed in. Hand
+ /// writes straight through rather than queueing them for a worker that
+ /// cannot exist -- std::thread::spawn does not fail there, it panics.
+ #[cfg(target_family = "wasm")]
+ fn new(writer: Box<dyn std::io::Write + Send>) -> Self {
+ Self { writer }
+ }
+
+ #[cfg(not(target_family = "wasm"))]
fn new(mut writer: Box<dyn std::io::Write + Send>) -> Self {
let (sender, receiver) = channel::<WriterMessage>();
@@ -477,6 +495,18 @@ impl ThreadedWriter {
}
}
+#[cfg(target_family = "wasm")]
+impl std::io::Write for ThreadedWriter {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ self.writer.write(buf)
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ self.writer.flush()
+ }
+}
+
+#[cfg(not(target_family = "wasm"))]
impl std::io::Write for ThreadedWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.sender
diff --git a/termwiz/Cargo.toml b/termwiz/Cargo.toml
index f1199b7d..ce397f5b 100644
--- a/termwiz/Cargo.toml
+++ b/termwiz/Cargo.toml
@@ -15,7 +15,6 @@ anyhow.workspace = true
bitflags = "2.0"
cassowary = {workspace=true, optional=true}
fancy-regex.workspace = true
-filedescriptor.workspace = true
finl_unicode.workspace = true
fixedbitset.workspace = true
fnv = {workspace=true, optional=true}
@@ -61,6 +60,12 @@ criterion.workspace = true
env_logger.workspace = true
k9.workspace = true
+# Only the terminal:: implementations need this, and those are already gated on
+# unix/windows. Keeping it off other targets is what lets the escape parsing,
+# cell model and surface layers build for wasm32.
+[target."cfg(any(unix, windows))".dependencies]
+filedescriptor.workspace = true
+
[target."cfg(unix)".dependencies]
signal-hook.workspace = true
termios.workspace = true
diff --git a/termwiz/src/error.rs b/termwiz/src/error.rs
index b87d5b96..f5374cc4 100644
--- a/termwiz/src/error.rs
+++ b/termwiz/src/error.rs
@@ -66,6 +66,10 @@ pub enum InternalError {
#[error(transparent)]
Terminfo(#[from] terminfo::Error),
+ // Produced only by the terminal:: implementations, which exist on unix and
+ // windows alone; the crate otherwise builds for targets that have no such
+ // descriptors at all.
+ #[cfg(any(unix, windows))]
#[error(transparent)]
FileDescriptor(#[from] filedescriptor::Error),
diff --git a/termwiz/src/lib.rs b/termwiz/src/lib.rs
index f8bd962c..24f9622c 100644
--- a/termwiz/src/lib.rs
+++ b/termwiz/src/lib.rs
@@ -51,6 +51,9 @@ pub use wezterm_surface::hyperlink;
pub mod input;
pub mod istty;
pub mod keymap;
+// The line editor and the tty probe both drive a live terminal, so they
+// follow the Terminal trait in being unavailable where there is none.
+#[cfg(any(unix, windows))]
pub mod lineedit;
mod macros;
pub use wezterm_char_props::nerdfonts;
diff --git a/termwiz/src/terminal/mod.rs b/termwiz/src/terminal/mod.rs
index 7195198b..63ec474e 100644
--- a/termwiz/src/terminal/mod.rs
+++ b/termwiz/src/terminal/mod.rs
@@ -1,12 +1,18 @@
//! An abstraction over a terminal device
+#[cfg(any(unix, windows))]
use crate::caps::probed::ProbeCapabilities;
+#[cfg(any(unix, windows))]
use crate::caps::Capabilities;
+#[cfg(any(unix, windows))]
use crate::input::InputEvent;
+#[cfg(any(unix, windows))]
use crate::surface::Change;
+#[cfg(any(unix, windows))]
use crate::{format_err, Result};
use num_traits::NumCast;
use std::fmt::Display;
+#[cfg(any(unix, windows))]
use std::time::Duration;
#[cfg(feature = "use_serde")]
@@ -19,6 +25,11 @@ pub mod unix;
#[cfg(windows)]
pub mod windows;
+// Everything below that drives a live terminal -- the Terminal trait, its
+// buffered wrapper and new_terminal -- exists only where there is a terminal
+// to drive. ScreenSize and Blocking stay unconditional: they are plain data
+// that the surface and cell layers use on every target, wasm included.
+#[cfg(any(unix, windows))]
pub mod buffered;
#[cfg(unix)]
@@ -58,6 +69,7 @@ pub enum Blocking {
/// If the `set_raw_mode` or `set_cooked_mode` functions are used in
/// any combination, the implementation is required to restore the
/// terminal mode that was in effect when it was created.
+#[cfg(any(unix, windows))]
pub trait Terminal {
/// Raw mode disables input line buffering, allowing data to be
/// read as the user presses keys, disables local echo, so keys
@@ -126,6 +138,7 @@ pub type SystemTerminal = WindowsTerminal;
/// If you have a more advanced use case you will want to look to the
/// constructors for `UnixTerminal` and `WindowsTerminal` and call whichever
/// one is most suitable for your needs.
+#[cfg(any(unix, windows))]
pub fn new_terminal(caps: Capabilities) -> Result<impl Terminal> {
SystemTerminal::new(caps)
}
diff --git a/wasm-probe/Cargo.toml b/wasm-probe/Cargo.toml
new file mode 100644
index 00000000..592287b7
--- /dev/null
+++ b/wasm-probe/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "wasm-probe"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# Proves the terminal core links for wasm32, not merely that it compiles:
+# rlib output would never exercise the linker.
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+termwiz.workspace = true
+wezterm-term.workspace = true
diff --git a/wasm-probe/run-probe.js b/wasm-probe/run-probe.js
new file mode 100644
index 00000000..aaa2a5a5
--- /dev/null
+++ b/wasm-probe/run-probe.js
@@ -0,0 +1,59 @@
+// Runs the wasm-probe stages in Node with stub imports.
+// The __wbindgen_* imports come from getrandom's wasm_js backend; the probe
+// stages never draw randomness, so inert stubs are sufficient here. A real
+// browser build goes through wasm-bindgen CLI instead.
+const fs = require('fs');
+const path = process.argv[2];
+const buf = fs.readFileSync(path);
+
+let memory = null;
+const stubs = {
+ __wbindgen_placeholder__: {
+ __wbg_getRandomValues_38a1ff1ea09f6cc7: () => { throw new Error('getRandomValues stub called'); },
+ __wbindgen_object_drop_ref: () => {},
+ __wbindgen_describe: () => {},
+ },
+ __wbindgen_externref_xform__: {
+ __wbindgen_externref_table_set_null: () => {},
+ __wbindgen_externref_table_grow: (d) => 0,
+ },
+};
+
+function readPanic(inst) {
+ try {
+ const ptr = inst.exports.panic_msg_ptr();
+ const len = inst.exports.panic_msg_len();
+ if (len > 0) {
+ const bytes = new Uint8Array(inst.exports.memory.buffer, ptr, len);
+ return Buffer.from(bytes).toString('utf8');
+ }
+ } catch (e) {}
+ return '(no panic message)';
+}
+
+WebAssembly.instantiate(buf, stubs).then(({ instance }) => {
+ instance.exports.install_panic_hook();
+ const stages = [
+ ['stage1_alloc', 64],
+ ['stage2_parser', 13],
+ ['stage3_palette', 256],
+ ['stage4_terminal', 24],
+ ['stage5_advance', 0],
+ // "abcdef", cursor to col 3, ECH with u32::MAX: the clamp leaves "ab" (len 2).
+ // Unfixed 32-bit release would wrap and erase nothing, leaving len 6.
+ ['stage6_ech_overflow', 2],
+ ];
+ let failed = 0;
+ for (const [name, expect] of stages) {
+ try {
+ const got = instance.exports[name]();
+ const ok = got === expect;
+ if (!ok) failed++;
+ console.log(`${ok ? 'PASS' : 'FAIL'} ${name}: got ${got}, expect ${expect}`);
+ } catch (e) {
+ failed++;
+ console.log(`FAIL ${name}: trap ${e.message}; panic: ${readPanic(instance)}`);
+ }
+ }
+ process.exit(failed ? 1 : 0);
+}).catch(e => { console.error('instantiate failed:', e.message); process.exit(2); });
diff --git a/wasm-probe/src/lib.rs b/wasm-probe/src/lib.rs
new file mode 100644
index 00000000..55c4fe22
--- /dev/null
+++ b/wasm-probe/src/lib.rs
@@ -0,0 +1,118 @@
+//! Staged probes for the wasm build. Each entry point does strictly more than
+//! the last, so a failure identifies which layer is not portable rather than
+//! just reporting that something panicked.
+
+use std::sync::Arc;
+use std::sync::Mutex;
+
+// wasm32-unknown-unknown has nowhere to print a panic, and the trap that
+// follows tells you only "unreachable". Stash the message where JS can read it
+// out of linear memory after catching the trap.
+static PANIC: Mutex<String> = Mutex::new(String::new());
+static mut PANIC_BUF: [u8; 1024] = [0; 1024];
+
+#[no_mangle]
+pub extern "C" fn install_panic_hook() {
+ std::panic::set_hook(Box::new(|info| {
+ if let Ok(mut slot) = PANIC.lock() {
+ *slot = info.to_string();
+ }
+ }));
+}
+
+#[no_mangle]
+pub extern "C" fn panic_msg_ptr() -> *const u8 {
+ let msg = PANIC.lock().map(|m| m.clone()).unwrap_or_default();
+ let bytes = msg.as_bytes();
+ let n = bytes.len().min(1024);
+ unsafe {
+ let buf = (&raw mut PANIC_BUF) as *mut u8;
+ std::ptr::copy_nonoverlapping(bytes.as_ptr(), buf, n);
+ buf as *const u8
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn panic_msg_len() -> u32 {
+ PANIC.lock().map(|m| m.len().min(1024) as u32).unwrap_or(0)
+}
+use termwiz::escape::parser::Parser;
+use wezterm_term::{Terminal, TerminalConfiguration, TerminalSize};
+
+#[derive(Debug)]
+struct Config;
+
+impl TerminalConfiguration for Config {
+ fn color_palette(&self) -> wezterm_term::color::ColorPalette {
+ Default::default()
+ }
+}
+
+fn size() -> TerminalSize {
+ TerminalSize {
+ rows: 24,
+ cols: 80,
+ pixel_width: 800,
+ pixel_height: 480,
+ dpi: 96,
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn stage1_alloc() -> u32 {
+ let v: Vec<u8> = (0..64).collect();
+ v.len() as u32
+}
+
+#[no_mangle]
+pub extern "C" fn stage2_parser() -> u32 {
+ let mut p = Parser::new();
+ let mut n = 0u32;
+ p.parse(b"hello\x1b[1;31m wasm\x1b[0m", |_| n += 1);
+ n
+}
+
+#[no_mangle]
+pub extern "C" fn stage3_palette() -> u32 {
+ let pal = Config.color_palette();
+ pal.colors.0.len() as u32
+}
+
+#[no_mangle]
+pub extern "C" fn stage4_terminal() -> u32 {
+ let term = Terminal::new(size(), Arc::new(Config), "probe", "0.1", Box::new(Vec::new()));
+ term.screen().physical_rows as u32
+}
+
+#[no_mangle]
+pub extern "C" fn stage5_advance() -> u32 {
+ let mut term = Terminal::new(size(), Arc::new(Config), "probe", "0.1", Box::new(Vec::new()));
+ term.advance_bytes(b"hello\x1b[1;31m wasm\x1b[0m");
+ let mut out = String::new();
+ term.screen().for_each_phys_line(|idx, line| {
+ if idx == 0 {
+ out = line.as_str().trim_end().to_string();
+ }
+ });
+ if out == "hello wasm" {
+ 0
+ } else {
+ 1
+ }
+}
+
+/// A CSI parameter is a u32; on a 32-bit usize `cursor.x + n as usize` in the
+/// ECH handler overflows before .min() can clamp it. Any program writing to the
+/// pty can send this.
+#[no_mangle]
+pub extern "C" fn stage6_ech_overflow() -> u32 {
+ let mut term = Terminal::new(size(), Arc::new(Config), "probe", "0.1", Box::new(Vec::new()));
+ term.advance_bytes(b"abcdef\x1b[3G\x1b[4294967295X");
+ let mut out = String::new();
+ term.screen().for_each_phys_line(|idx, line| {
+ if idx == 0 {
+ out = line.as_str().trim_end().to_string();
+ }
+ });
+ out.len() as u32
+}
diff --git a/wezterm-blob-leases/Cargo.toml b/wezterm-blob-leases/Cargo.toml
index 0eb36f58..7e3c543d 100644
--- a/wezterm-blob-leases/Cargo.toml
+++ b/wezterm-blob-leases/Cargo.toml
@@ -16,6 +16,14 @@ tempfile = {workspace=true, optional=true}
thiserror.workspace = true
uuid = {workspace=true, features=["v4", "rng"]}
+# wasm32-unknown-unknown has no OS entropy of its own, so both crates that need
+# randomness have to be told to reach for the browser's crypto.getRandomValues.
+# getrandom additionally requires --cfg getrandom_backend="wasm_js" at build
+# time; see .cargo/config.toml.
+[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
+getrandom = {workspace=true, features=["wasm_js"]}
+uuid = {workspace=true, features=["v4", "rng", "js"]}
+
[features]
default = []
serde = ["dep:serde", "uuid/serde"]
diff --git a/wezterm-escape-parser/src/apc.rs b/wezterm-escape-parser/src/apc.rs
index 96cd96c3..943883fc 100644
--- a/wezterm-escape-parser/src/apc.rs
+++ b/wezterm-escape-parser/src/apc.rs
@@ -308,7 +308,15 @@ fn read_shared_memory_data(
Ok(data)
}
-#[cfg(all(feature = "kitty-shm", unix, target_os = "android"))]
+// Android has the API surface but not the permission to use it, and targets
+// like wasm32 have no shared memory at all. Both answer the same way, so the
+// parser keeps understanding the escape sequence and simply declines the
+// transfer rather than failing to build.
+#[cfg(all(
+ feature = "kitty-shm",
+ not(windows),
+ any(not(unix), target_os = "android")
+))]
fn read_shared_memory_data(
_name: &str,
_data_offset: Option<u32>,