A web-based terminal emulator that integrates Ghostty's VT100 parser via WebAssembly.
npm install ghostty-webOr install directly from GitHub (includes pre-built dist files):
# Latest from main branch
npm install github:junaid33/ghostty-web
# Specific commit or branch (recommended for production)
npm install github:junaid33/ghostty-web#commit-shaNote: GitHub installs work without requiring Zig because the repository includes pre-built
dist/files andghostty-vt.wasm.
This fork carries the VibeGhost fixes in source and in the checked-in distribution:
- correct Kitty image movement through historical viewports
- one active viewport decode per terminal mutation and a bounded 256-row scrollback cache
- empty public writes that do not force the viewport to the live bottom
- selection invalidation wired to the event-driven render scheduler through public
requestRender() - public render/response hooks for integrations that write through
wasmTerm - lifecycle-owned full canvas restoration after page foregrounding,
pageshow, renderer context restoration, and terminal resume
import { Terminal } from 'ghostty-web';
const term = new Terminal({ cols: 80, rows: 24 });
term.open(document.getElementById('terminal')!);
term.write('Hello, World!\r\n');Canvas2D remains the default renderer. WebGL is explicit opt-in:
const term = new Terminal({
cols: 80,
rows: 24,
renderer: 'webgl',
});When renderer: 'webgl' is requested, ghostty-web checks for webgl2 support on a throwaway probe canvas before constructing the renderer. If WebGL2 is unavailable, or if WebGL initialization fails after binding a context, initialization safely falls back to the default Canvas2D renderer on a fresh canvas. The WebGL path is currently experimental: it uses a vendored adapter from 0xBigBoss/ghostty-webgl and preserves the same terminal-facing renderer contract, but Canvas2D remains the production default.
The WebGL adapter mirrors the Canvas renderer contract for selection, hyperlinks, decorations/search highlights, cursor blink, IME preedit overlays, scrollback viewports, theme colors (including common CSS color forms), font changes, DPR changes, transparency, and scrollbar width. Both renderers are hardened for iframe/embedded browsing contexts by deriving DOM, timer, animation-frame, link-opening, clipboard fallback, and device-pixel-ratio state from the terminal canvas' owner document/window instead of assuming globals. WebGL uses conservative full-row uploads for correctness and an RGBA glyph atlas for better WebKit/WKWebView compatibility. Kitty graphics and geometric box/block rendering remain Canvas-only for now; choose Canvas when those features are required.
The sections below cover the main integration and development workflows.
- ✅ Full xterm.js-compatible API
- ✅ Production-tested VT100 parser (via Ghostty)
- ✅ Upstream Ghostty C ABI / render-state integration (no local WASM patch required)
- ✅ ANSI colors (16, 256, RGB true color)
- ✅ CJK and wide-emoji cell width handling
- ✅ Styled scrollback and row-iterator based viewport rendering
- ✅ CSI
14/16/18 tsize responses and callback-based terminal query handling - ✅ Event-driven Canvas rendering with dirty-row redraws
- ✅ Experimental opt-in WebGL renderer with Canvas fallback
- ✅ Scrollback buffer
- ✅ Text selection & clipboard
- ✅ FitAddon for responsive sizing
- ✅ TypeScript declarations included
Version 0.9.2 adds the experimental WebGL renderer path and hardens the shared renderer lifecycle on top of the upstream Ghostty ABI/render-state migration:
- Canvas remains the default renderer; WebGL2 is explicit opt-in via
new Terminal({ renderer: 'webgl' })with safe Canvas fallback - terminal/rendering code is event-driven rather than a perpetual frame loop, with explicit wakeups for writes, scrolls, cursor blink, selections, hover underlines, theme changes, clear/reset, and runtime option changes
- Canvas, Terminal, SelectionManager, and WebGL paths use the terminal canvas' owner browsing context for DOM nodes, timers, animation frames, font measurement, clipboard fallbacks, link opening, and DPR rather than assuming global
window/document - WebGL now tracks DPR changes, owner-document font measurement, runtime scrollbar width, transparency, decorations/search highlights, cursor blink, IME preedit, and scrollback viewport parity
- CSS theme color parsing is shared in spirit between renderer and WASM color config paths, including hex alpha forms,
rgb(...)/rgba(...), percentage channels, and browser-normalized named colors - link activation supports
onLinkClick, uses owner-window default opening, and guards async hover/click lookups against stale results after mouse movement or disposal - custom key handlers expose the full three-way behavior already implemented by
InputHandler:trueconsumes,falsebubbles, andundefinedcontinues default terminal processing - public scroll/selection/decoration inputs and renderer/WebGL internals guard non-finite or invalid dimensions before feeding canvas, GL, or buffer math
- resize handling keeps the active renderer as the sole canvas backing-store owner and only updates public dimensions after WASM resize succeeds
- Ghostty WASM wrapper scratch allocations now check allocation failure and free temporary buffers through
finallyblocks across key encoding, writes, colors, modes, kitty graphics, and render-state getters - lifecycle cleanup is symmetric for document/canvas listeners, context-loss listeners, timers, animation frames, and renderer resources
- Canvas-only features remain documented: kitty graphics and geometric box/block rendering are still not implemented in the WebGL path
Requires server
# Builds/serves the package demo with PTY WebSocket support
bun run demo
# Development mode uses the repo sources and Vite-compatible assets
bun run demo:dev
# Open the printed local URL, typically http://localhost:8080/This provides a real persistent shell session! You can:
- Use
cdand it persists between commands - Run interactive programs like
vim,nano,top,htop - Use tab completion and command history (↑/↓)
- Use pipes, redirects, and background jobs
- Access all your shell aliases and environment
Renderer selection: The demo uses the default Canvas renderer. The experimental WebGL renderer is available to library consumers with new Terminal({ renderer: 'webgl' }); Canvas remains recommended for kitty graphics and box/block geometry coverage. WebGL is safe to request in browsers without WebGL2 because initialization probes a throwaway canvas and falls back to Canvas on failure.
Remote Access: The demo serves HTTP and WebSocket traffic from the same origin, so reverse proxies only need to forward the demo HTTP port and preserve WebSocket upgrade headers.
The terminal will automatically connect to the WebSocket using the same hostname you're accessing the page from.
Colors Demo (no server needed)
bun run dev
# Open: http://localhost:8000/demo/colors-demo.htmlSee all ANSI colors (16, 256, RGB) and text styles in action.
import { Terminal } from './lib/index.ts';
import { FitAddon } from './lib/addons/fit.ts';
// Create terminal
const term = new Terminal({
cols: 80,
rows: 24,
cursorBlink: true,
// Set false when the host wants selection without automatic clipboard writes.
// Explicit Cmd+C / copySelection() still copy the active selection.
copyOnSelect: true,
// Use 'native' when the host owns a synchronous browser copy listener.
copyMode: 'clipboard',
theme: {
background: '#1e1e1e',
foreground: '#d4d4d4',
},
});
// Add FitAddon for responsive sizing
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
// Open in container
await term.open(document.getElementById('terminal'));
fitAddon.fit();
// Write output (supports ANSI colors)
term.write('Hello, World!\r\n');
term.write('\x1b[1;32mGreen bold text\x1b[0m\r\n');
// Handle user input
term.onData((data) => {
console.log('User typed:', data);
// Send to backend, echo, etc.
});const ws = new WebSocket('ws://localhost:3001/ws');
// Send user input to backend
term.onData((data) => {
ws.send(JSON.stringify({ type: 'input', data }));
});
// Display backend output
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
term.write(msg.data);
};Ghostty-web automatically detects and makes clickable:
- OSC 8 hyperlinks - Explicit terminal escape sequences (e.g., from
ls --hyperlink) - Plain text URLs - Common protocols detected via regex (https, http, mailto, ssh, git, ftp, tel, magnet)
URLs are detected on hover and can be opened with Ctrl/Cmd+Click. Default link activation uses the click event's owning window, which is safer for iframes and embedded webviews than assuming the global window.
// URL detection works automatically after opening terminal
await term.open(container);
// URLs in output become clickable automatically
term.write('Visit https://github.com for code\r\n');
term.write('Contact mailto:[email protected]\r\n');Override default activation with onLinkClick. Return true to prevent the built-in open behavior:
const term = new Terminal({
onLinkClick(url, event) {
event.preventDefault();
showInAppLinkPreview(url);
return true;
},
});Async hover and click lookups are guarded so stale results cannot overwrite newer hover state or activate after disposal.
Custom Link Providers
Register custom providers to detect additional link types:
import { UrlRegexProvider } from 'ghostty-web';
// Create custom provider
const myProvider = {
provideLinks(y, callback) {
// Your detection logic here
const links = detectCustomLinks(y);
callback(links);
},
};
// Register after opening terminal
term.registerLinkProvider(myProvider);See AGENTS.md for development guide and code patterns.
Themes accept common CSS color forms for renderer colors and Ghostty/WASM color config, including #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(...), rgba(...), percentage channels, and browser-normalized named colors. Alpha is used by renderers where applicable; the WASM config receives RGB values.
const term = new Terminal({
allowTransparency: true,
theme: {
background: 'rgba(30, 30, 30, 0.65)',
foreground: 'hsl(0 0% 90%)',
},
});allowTransparency can also be changed at runtime; the active renderer is updated and repainted.
import { SearchAddon } from 'ghostty-web';
const search = new SearchAddon();
term.loadAddon(search);
search.onDidChangeResults(({ resultIndex, resultCount }) => {
console.log(resultIndex, resultCount);
});
search.findNext('error'); // Older output; wraps at the end
search.findPrevious('error'); // Newer output
search.clearDecorations();Search covers the active screen and retained history and highlights the selected
match without replacing caller decorations. Literal searches use the core with
ASCII case folding. Pass { caseSensitive: true }, { wholeWord: true } or
{ regex: true } to use the bounded text-search path. Regex uses RE2JS's linear-time
engine; unsupported syntax such as backreferences is reported through the result
error field. Advanced snapshots are built cooperatively and cancelled if output
changes. Result events expose pending, truncated and error where relevant.
Limits are 1024 query characters, 500,000 cells/1 MiB of snapshot text and 10,000
matches; truncated results are explicitly marked. Soft wraps and complete
combining graphemes retain cell positions.
Prompt marks emitted with OSC 133 can be navigated with term.scrollToPrompt()
(older) and term.scrollToPrompt(false) (newer). Navigation returns false when
no retained prompt is available or an alternate-screen application is active.
For an authoritative remote VT service, use emitTerminalResponses: false:
keyboard input still emits normally, while local parser-generated replies are
discarded so the server can answer each query once.
Large writes are parsed in bounded chunks with time-limited work between browser
tasks. A write(data, callback) callback runs after that write has been parsed,
not after it has painted. Use completion callbacks when maintaining transport
resume offsets. An empty write with a callback is an ordered parser barrier.
Reset and disposal discard unparsed work. A terminal rejects a parser backlog
over 8 MiB; onWriteError reports parser failures.
The bridge reads compound layouts and packed style flags from the loaded WASM's ABI manifest, caches them per instance, and rejects incompatible selectors or unsupported ABI shapes before creating native handles.
Selections are anchored and copied by the terminal core. Normal drags retain
linear selection; Alt-drag selects a rectangle. Shift/Alt selection gestures
do not send application mouse clicks. Programmatic rectangular selection is
available as term.selectRectangle(startCol, startRow, endCol, endRow) in visible
cell coordinates. Selected pins follow output scrolling/pruning, and copy uses
the core formatter with a 1 MiB limit. Canvas and WebGL highlights preserve the
rectangle's bounded columns on every row.
Canvas and WebGL cell pitch and baseline are resolved on an integral physical pixel grid, including fractional device-pixel ratios. Owning-window resize/DPR changes remeasure metrics and request a full redraw. This avoids repeated canvas resize churn caused by comparing integer backing dimensions with fractional computed sizes.
Kitty images use the core's resolved viewport rectangles, layers, offsets and content generations. Pixel snapshots are owned and bounded, so retransmission, memory growth and animation cannot reuse stale borrowed views. The terminal owns animation deadlines, pauses them during suspension/synchronized output, and cancels them on reset/disposal. Canvas rendering interleaves image layers with row backgrounds and text, clipping to rows being repainted.
Mobile browsers may discard a canvas bitmap while an app is backgrounded even
though the terminal's WASM state remains intact. Ghostty Web listens to the
owning page lifecycle and restores the full viewport automatically. Calling
resume() after a host-controlled suspension also performs a full repaint.
Integrations can request the same operation explicitly through the public API:
term.refresh();The renderers keep an opaque CSS background behind the bitmap when transparency is disabled, preventing a white flash before the restored frame is painted.
Ghostty-web supports custom font families. Font families with spaces are automatically quoted for proper CSS handling.
const term = new Terminal({
fontFamily: 'Fira Code, Consolas, monospace',
fontSize: 14,
});
await term.open(container);Loading Web Fonts
When using web fonts (e.g., Google Fonts, local .woff2 files), you must wait for the font to load before the terminal can measure it correctly:
// Option 1: Wait for specific font
await document.fonts.load('14px "Fira Code"');
term.loadFonts();
// Option 2: Wait for all fonts to be ready
await document.fonts.ready;
term.loadFonts();
// Option 3: Use FontFace API
const font = new FontFace('Fira Code', 'url(/fonts/FiraCode.woff2)');
await font.load();
document.fonts.add(font);
term.loadFonts();Changing Fonts at Runtime
// Change font family
term.options.fontFamily = 'JetBrains Mono, monospace';
// Change font size
term.options.fontSize = 16;
// If using a web font, wait for it to load
await document.fonts.load('16px "JetBrains Mono"');
term.loadFonts();The Terminal supports a snapshot API for playback mode, enabling direct terminal state injection without re-parsing VT100 sequences. This is useful for terminal recordings and time-travel debugging.
import { Terminal, GhosttyCell } from 'ghostty-web';
// Create cells array (flat row-major order: rows * cols cells)
const cells: GhosttyCell[] = recordedFrame.cells;
const cursor = { x: 10, y: 5 };
// Set snapshot - renderer will use this instead of WASM terminal
terminal.setSnapshot(cells, cursor);
// Check if in snapshot mode
if (terminal.hasSnapshot()) {
console.log('Playback mode active');
}
// Clear snapshot and return to normal rendering
terminal.clearSnapshot();Each GhosttyCell contains:
codepoint: Unicode codepoint (number)fg_r,fg_g,fg_b: Foreground RGB (0-255)bg_r,bg_g,bg_b: Background RGB (0-255)flags: Style flags (bold, italic, etc.)width: Character width (1 or 2 for wide chars)
DON'T re-implement VT100 parsing from scratch (years of work, thousands of edge cases).
DO use Ghostty's proven parser:
- ✅ Battle-tested by thousands of users
- ✅ Handles all VT100/ANSI quirks correctly
- ✅ Modern features (RGB colors, Kitty keyboard protocol)
- ✅ Get bug fixes and updates for free
You build: Screen buffer, rendering, UI (the "easy" parts in TypeScript)
Ghostty handles: VT100 parsing (the hard part via WASM)
┌─────────────────────────────────────────┐
│ Terminal (lib/terminal.ts) │
│ - Public xterm.js-compatible API │
│ - Event handling (onData, onResize) │
└───────────┬─────────────────────────────┘
│
├─► GhosttyTerminal (lib/ghostty.ts)
│ - Upstream Ghostty C ABI, render-state rows, scrollback
│ - Kitty graphics, callbacks, terminal size/query responses
│
├─► ITerminalRenderer (lib/renderer-contract.ts)
│ ├─► CanvasRenderer (lib/renderer.ts)
│ │ - Default renderer, kitty graphics, box/block geometry
│ └─► WebGLRenderer (lib/webgl-renderer.ts)
│ - Experimental opt-in WebGL2 adapter with Canvas fallback
│
├─► SelectionManager (lib/selection-manager.ts)
│ - Text selection, clipboard, renderer decoration ranges
│
└─► InputHandler (lib/input-handler.ts)
- Keyboard/IME/mouse events → Ghostty-compatible input
Demo server (demo/bin/demo.js)
└─► Starts the Vite demo and WebSocket control/PTY plumbing
├── lib/
│ ├── terminal.ts - Main Terminal class (xterm.js-compatible)
│ ├── ghostty.ts - Ghostty WASM/C ABI wrapper
│ ├── renderer-contract.ts - Shared Terminal-facing renderer contract
│ ├── renderer.ts - Default Canvas renderer
│ ├── webgl-renderer.ts - Experimental opt-in WebGL renderer adapter
│ ├── wasm-png-decoder.ts - Vendored WASM PNG decoder wrapper for kitty graphics
│ ├── input-handler.ts - Keyboard, IME, mouse input handling
│ ├── selection-manager.ts - Selection, clipboard, decorations
│ ├── types.ts - TypeScript type definitions
│ ├── interfaces.ts - xterm.js-compatible interfaces
│ ├── vendor/ - Vendored PNG/WebGL support code
│ └── addons/
│ └── fit.ts - FitAddon for responsive sizing
│
├── demo/
│ ├── index.html - Browser terminal demo
│ ├── colors-demo.html - ANSI colors showcase
│ ├── render-test.html - Browser render regression harness
│ └── bin/
│ ├── demo.js - Demo server launcher
│ └── render-test.ts - Screenshot regression runner
│
├── scripts/
│ ├── ensure-zig.sh - Deterministic Zig bootstrap
│ └── build-wasm.sh - Ghostty WASM build script
│
└── ghostty-vt.wasm - Built Ghostty terminal WASM artifact
The WASM binary is built from source, not committed to the repo.
Requirements:
- Zig 0.17.0+
- Git submodules initialized
Build:
# Initialize submodule (first time only)
git submodule update --init --recursive
# Build WASM
./scripts/build-wasm.sh
# or
bun run build:wasmWhat it does:
- Initializes
ghostty/submodule (ghostty-org/ghostty) - Applies
patches/ghostty-wasm-api.patchif it contains local patch content - Builds WASM with the deterministic Zig bootstrap from
scripts/ensure-zig.sh - Outputs
ghostty-vt.wasm - Keeps Zig cache/tooling outside linted source paths
The WASM bundle tracks official Ghostty c6174c88f42b48adb14857c9233b16f6947ab732
(1.4.1-dev). Build it with Zig 0.17.0. Local patches enable browser-supplied
Kitty graphics decoding and reject filesystem/shared-memory image transmission.
The JavaScript bridge uses that revision's public C API and compact style layout.
Scrollback is configured in lines; Ghostty reclaims whole pages, so the retained
line count varies when pruning occurs.
Updating Ghostty:
cd ghostty
git fetch origin
git checkout <commit-or-tag>
cd ..
./scripts/build-wasm.sh
# Test, then commit the updated submodule pointerCI: The WASM is built as part of the test and build jobs.
Canvas remains the default. To request WebGPU, await initialization:
const term = new Terminal({ renderer: 'webgpu', bidi: true });
await term.openAsync(document.getElementById('terminal')!);WebGPU requires a supported browser in a secure context (HTTPS or localhost).
Unavailable adapters, initialization errors, device loss and excessive texture
sizes fall back to Canvas. The VT, selection and input survive device loss.
Synchronous open() remains supported and uses Canvas when WebGPU has not
been initialized.
This backend uses Canvas for glyph rasterization and WebGPU for composition and presentation; it is not GPU-side text layout or an instanced glyph renderer. Additional GPU texture storage is capped at 64 MiB per pane. GPU display behaviour has not been validated in the development environment; keep the option off if your browser has display problems.
bidi: true enables row-local bidirectional ordering with an LTR paragraph
base. Cursor, IME placement, search highlights, hyperlinks, mouse reports and
linear copy use coherent visual/logical coordinates. Rectangles select visual
columns and copy the selected cells in logical order per row. Core storage,
exports and programmatic linear selection remain logical.
BiDi uses bidi-js 1.0.3's Unicode 13 tables, independently of the VT core's Unicode tables. It does not provide Arabic joining/shaping or paragraph layout across wrapped rows. Rows containing Kitty Unicode image placeholders retain logical order to preserve image placement. BiDi selects Canvas instead of WebGL; WebGPU shares the Canvas text path. Use the default mode for cursor-addressed programs that do their own BiDi layout.
The row mapper is adapted from NimbleMarkets/ghostty-web. Retained notices are in licenses/.
Run the test suite:
bun test # Run all tests
bun test --watch # Watch mode
bun run typecheck # Type checking
bun run build # Build distributionTest Coverage:
The current suite covers terminal integration, Ghostty ABI behavior, input handling, selection, renderer behavior, WebGL adapter/vendor pieces, FitAddon, kitty graphics, scrollback regressions, viewport corruption/merge regressions, and PNG decoding. The suite includes WebGPU resource/fallback and BiDi mapping/copy tests. The current run reports 532 passing tests and two existing historical scrollback skips.
- AGENTS.md - Development guide for AI agents and developers
MIT. Third-party code retains its own notices, including bidi-js and the adapted BiDi mapper.