Wire a PTY
Connecting ghostty-webgpu to a remote shell takes one binary WebSocket and a tiny resize message. Keeping terminal traffic in raw Uint8Array bytes avoids UTF-16 conversion overhead and prevents corrupted multi-byte sequences when packets split mid-character.
You will learn
How to stream binary PTY frames in and out of a mounted
Terminal- How initial and live viewport resize messages stay in sync with the PTY
How to apply backpressure, client-side write batching, and worker output ports under heavy streaming
- How to handle reconnects without leaving stale screen contents behind
Mount the terminal and socket
Section titled “Mount the terminal and socket”Pair this browser client with a server that exchanges raw terminal bytes over binary frames and accepts JSON resize control messages (see Connect a real shell for a ready-to-run Bun server).
import { Terminal } from 'ghostty-webgpu'import { attachTerminalHotkeys } from 'ghostty-webgpu/hotkeys'
export async function connectShell(host: HTMLElement, url: string) { const terminal = await Terminal.create() attachTerminalHotkeys(terminal) await terminal.open(host) const socket = new WebSocket(url) socket.binaryType = 'arraybuffer' const sendSize = () => { if (socket.readyState !== WebSocket.OPEN) return const { columns, rows } = terminal.geometry() socket.send(JSON.stringify({ type: 'resize', columns, rows })) } socket.addEventListener('open', sendSize) terminal.onResize(sendSize) terminal.onData(({ bytes }) => { if (socket.readyState === WebSocket.OPEN) socket.send(new Uint8Array(bytes)) }) socket.addEventListener('message', ({ data }) => { if (data instanceof ArrayBuffer) terminal.write(new Uint8Array(data)) }) terminal.focus() return () => { socket.close() terminal.dispose() }}Hold onto the returned disposer and call it when unmounting the view so both the WebSocket and the WebAssembly terminal release their resources together.
Why binary frames matter
Section titled “Why binary frames matter”Set socket.binaryType = 'arraybuffer' before listening for messages:
- Incoming binary frames go straight into
terminal.write(new Uint8Array(data)).libghostty-vtdecodes UTF-8 incrementally, even when a 4-byte emoji or escape sequence arrives split across two WebSocket frames. - Outgoing keystrokes and pastes from
terminal.onData(({ bytes }) => ...)go back to the socket as binary frames without ever passing throughTextDecoder. - Text frames stay free for small JSON control messages such as
{ type: 'resize', columns, rows }.
Keeping PTY dimensions synchronized
Section titled “Keeping PTY dimensions synchronized”Because await terminal.open(host) fits the grid synchronously before resolving, terminal.geometry() already matches the host container’s true columns and rows when the socket’s open handler fires sendSize(). After that, terminal.onResize pushes updated { type: 'resize', columns, rows } messages whenever the layout, DPR, or font size changes.
Handling heavy streaming output
Section titled “Handling heavy streaming output”A fast compiler or cat on a multi-megabyte log can outpace the browser if your server writes unbounded chunks. Combine three controls when throughput matters:
- Server-side backpressure: Check
socket.bufferedAmountbefore pushing more PTY bytes. Pause PTY reads once queued bytes cross your high-water mark and resume when the socket drains. - Client-side batching: For bursty streams on the main thread, call
terminal.writeBatched(bytes)instead ofterminal.write(bytes)to coalesce writes across animation frames under a configurable byte budget (writeQueueoption). - Direct worker ports: On
ghostty-webgpu/worker, transfer a producer’sMessagePortdirectly to the terminal worker viaattachOutputPort(port)and coordinate draining withfenceOutput(sequence)so bulk PTY bytes bypass the main thread altogether.
Parse timing vs. paint timing
Calling terminal.write() parses bytes into libghostty-vt
immediately, while rendering coalesces onto the scheduler’s next animation frame. Subscribe to
terminal.onFrame only when you need to observe painted rows, and keep network
flow-control acknowledgements independent of visual paint notifications so background tabs do
not stall a PTY.
Handling reconnects cleanly
Section titled “Handling reconnects cleanly”Opening a fresh WebSocket needs an explicit session policy on the server:
- New shell: spawn a fresh PTY and call
terminal.reset()on the client before streaming output so stale screen state from the previous session is cleared. - Reattaching to a persistent PTY: replay the server’s buffered history (or send a
SIGWINCHredraw) into the existing terminal.
Recap
Set
socket.binaryType = ‘arraybuffer’and passUint8Arrayslices directly between the WebSocket andTerminal.Send initial size on socket
openand keep it updated throughterminal.onResize.Pace heavy output on the server with
bufferedAmount, or usewriteBatched()and workerattachOutputPort()for high-volume streams.