Connect a real shell
A browser terminal becomes a real shell the moment you pair ghostty-webgpu with a server-side pseudoterminal (PTY). This tutorial builds a complete local setup using Bun’s built-in PTY support on Linux or macOS and connects it to the browser over a single WebSocket.
You will learn
- How to spawn a Bash PTY per WebSocket connection in Bun
- Why PTY traffic uses binary frames while resize messages use JSON text frames
- How to connect the browser client and verify end-to-end resize sync
- What security boundaries to add before exposing a PTY over a network
Start the local PTY server
Section titled “Start the local PTY server”You need Bun 1.4.2 or newer on Linux or macOS with bash on your PATH. Save the server below as pty-server.ts. Each incoming WebSocket spawns an isolated bash --noprofile --norc child attached to a PTY.
interface ShellConnection { process?: ReturnType<typeof Bun.spawn>}
export function serveShell(port = 8080) { return Bun.serve<ShellConnection>({ hostname: '127.0.0.1', port, fetch(request, server) { if (new URL(request.url).pathname !== '/pty') return new Response('Missing route', { status: 404 }) const origin = URL.parse(request.headers.get('origin') ?? '') if (origin?.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(origin.hostname)) return new Response('Loopback browser origin required', { status: 403 }) if (server.upgrade(request, { data: {} })) return return new Response('WebSocket required', { status: 400 }) }, websocket: { open(socket) { socket.data.process = Bun.spawn(['bash', '--noprofile', '--norc'], { env: { ...process.env, TERM: 'xterm-256color' }, terminal: { cols: 80, rows: 24, data(_terminal, bytes) { socket.send(bytes) }, }, onExit() { socket.close() }, }) }, message(socket, message) { const terminal = socket.data.process?.terminal if (!terminal) return if (typeof message !== 'string') { terminal.write(message) return } let size: unknown try { size = JSON.parse(message) } catch { socket.close(1003, 'Resize message must be JSON') return } if (!size || typeof size !== 'object' || !('type' in size) || size.type !== 'resize') return if (!('columns' in size) || !('rows' in size)) return const { columns, rows } = size if (typeof columns !== 'number' || typeof rows !== 'number') return if (!Number.isInteger(columns) || !Number.isInteger(rows)) return if (columns < 1 || columns > 500 || rows < 1 || rows > 200) return terminal.resize(columns, rows) }, close(socket) { socket.data.process?.kill() socket.data.process?.terminal?.close() }, }, })}
if (import.meta.main) { serveShell() console.log('Shell WebSocket listening at ws://127.0.0.1:8080/pty')}Run it from your terminal:
bun pty-server.tsIt logs Shell WebSocket listening at ws://127.0.0.1:8080/pty.
Connect the browser client
Section titled “Connect the browser client”In your app, mount the terminal and wire the socket to ws://127.0.0.1:8080/pty:
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() }}Notice how the protocol splits data and control across WebSocket frame types:
- Binary frames carry raw terminal bytes in both directions: PTY output goes directly into
terminal.write(new Uint8Array(data)), and browser keystrokes fromterminal.onData(({ bytes }) => ...)go straight back to the PTY. - Text frames carry JSON resize messages (
{ type: 'resize', columns, rows }). Becauseawait terminal.open(host)fits the grid before resolving,terminal.geometry()already holds the true dimensions the instant the socket opens.
Verify bytes and resize sync
Section titled “Verify bytes and resize sync”- Click the terminal, type
printf 'Hello from Bash\n', and press Enter to confirm round-trip byte delivery. - Resize the browser window and run
stty size. The printed rows and columns should matchterminal.geometry().
Why bytes never pass through TextDecoder
A PTY can split a multi-byte UTF-8 character or an escape sequence across two separate OS
reads and two separate WebSocket frames. Decoding each chunk independently to a JavaScript
string corrupts split sequences with replacement characters (U+FFFD) and burns
extra UTF-16 allocation overhead.
Feeding raw Uint8Array chunks directly to terminal.write() lets
libghostty-vt’s stateful UTF-8 and VT parser stitch split sequences natively.
Security checklist before deploying
Section titled “Security checklist before deploying”The example server above is scoped for localhost development: it binds only to 127.0.0.1, rejects non-loopback Origin headers, validates integer grid bounds (1..500 columns and 1..200 rows), and closes sockets on malformed JSON.
Because a PTY spawns a shell with the host user’s permissions, put these controls in place before exposing any PTY endpoint on a network:
- Require authentication on the WebSocket upgrade request and enforce an explicit
Originallowlist. - Isolate each user’s shell inside a container, sandbox, or dedicated OS account.
- Cap concurrent connections per user and bound outbound buffers when a client stops reading (see Wire a PTY for backpressure patterns).
Recap
Use binary WebSocket frames (
socket.binaryType = 'arraybuffer') for raw PTY bytes and text frames for JSON resize control messages.Read
terminal.geometry()immediately afterawait terminal.open(host)to send the initial PTY size.Keep
terminal.onResizewired to the socket so interactive TUIs reflow cleanly when the viewport changes.Never expose a shell WebSocket beyond
127.0.0.1without authentication, origin checks, and OS/container isolation.