Skip to content

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

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).

websocket.ts
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.

Set socket.binaryType = 'arraybuffer' before listening for messages:

  • Incoming binary frames go straight into terminal.write(new Uint8Array(data)). libghostty-vt decodes 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 through TextDecoder.
  • Text frames stay free for small JSON control messages such as { type: 'resize', columns, rows }.

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.

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.bufferedAmount before 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 of terminal.write(bytes) to coalesce writes across animation frames under a configurable byte budget (writeQueue option).
  • Direct worker ports: On ghostty-webgpu/worker, transfer a producer’s MessagePort directly to the terminal worker via attachOutputPort(port) and coordinate draining with fenceOutput(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.

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 SIGWINCH redraw) into the existing terminal.

Recap

  • Set socket.binaryType = ‘arraybuffer’ and pass Uint8Array slices directly between the WebSocket and Terminal.

  • Send initial size on socket open and keep it updated through terminal.onResize.

  • Pace heavy output on the server with bufferedAmount, or use writeBatched() and worker attachOutputPort() for high-volume streams.