Skip to content

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

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.

pty-server.ts
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:

Terminal window
bun pty-server.ts

It logs Shell WebSocket listening at ws://127.0.0.1:8080/pty.

In your app, mount the terminal and wire the socket to ws://127.0.0.1:8080/pty:

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()
}
}

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 from terminal.onData(({ bytes }) => ...) go straight back to the PTY.
  • Text frames carry JSON resize messages ({ type: 'resize', columns, rows }). Because await terminal.open(host) fits the grid before resolving, terminal.geometry() already holds the true dimensions the instant the socket opens.
  1. Click the terminal, type printf 'Hello from Bash\n', and press Enter to confirm round-trip byte delivery.
  2. Resize the browser window and run stty size. The printed rows and columns should match terminal.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.

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 Origin allowlist.
  • 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 after await terminal.open(host) to send the initial PTY size.

  • Keep terminal.onResize wired to the socket so interactive TUIs reflow cleanly when the viewport changes.

  • Never expose a shell WebSocket beyond 127.0.0.1 without authentication, origin checks, and OS/container isolation.