Skip to content
lostintangentPublic

About

🪶 A GPU-accelerated terminal emulator for your web, macOS, and iOS apps

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

1,048 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

The Thrush mark, an amber-chested bird with a terminal chevron in its blue-gray wing

Thrush

Thrush is an embeddable terminal emulator for macOS, iOS and web apps. All you need to do is import a single view and connect it to a PTY, and you get a terminal that's fast, feature-rich and feels native to each platform.

Thrush is a single emulator core, written in Swift with zero dependencies, that runs natively and as WebAssembly. It has renderers for Metal on macOS and iOS and WebGL on the web, so the terminal looks and behaves exactly the same wherever you use it.

Thrush running GitHub Copilot in a Mac window, btop in Chrome, and Vim on an iPhone with the software keyboard and its Esc, Ctrl, Tab and arrow key row

Thrush was originally built for Toy Box, where it powers the web, macOS and iOS apps, as well as the server-side replay for all three clients.

Features

  • One view for Mac, iPhone and the web: TerminalView handles typing, selection, copy, find and links, and follows the system's light and dark appearance, in SwiftUI and in the browser. On Mac and iPhone, VoiceOver reads it too.
  • Made for phones: A key row puts Esc, Ctrl, Tab and the arrows above the keyboard, and the terminal fits the rows above the keyboard, so Vim, Codex and other full-screen programs show their whole page while you type. The browser view floats the same row on a touch screen.
  • Scrolling that follows your finger: Swipes, trackpads and mouse wheels move through history smoothly, and full-screen programs like Vim and less scroll too.
  • Sessions that ride out the network: A dropped connection reconnects on its own to the same shell, and a closed session keeps its last screen readable.
  • Correct: Recorded Bash, Vim and Codex sessions, and a case for each control sequence it handles, must match an independent reference emulator on every push.
  • Fast: The emulator outruns the other emulator cores it's measured against on most workloads, and built for WebAssembly it beats xterm.js in the same JavaScript engine on every one. The view draws nothing while idle.
  • Any shell: Connect a session over WebSocket, bring your own transport in Swift for SSH or a local PTY, or write any program's output to the browser view.
  • The same emulator on your server: A JavaScript server keeps each shell for Thrush's sessions with a WebAssembly build of the same emulator, so a client that attaches later sees the screen it missed.

Add a terminal to a Mac or iPhone app

Thrush needs macOS 27 or iOS 27.2 and Swift 6.4, and a Mac app can build it with only Command Line Tools. Add the package and link the Thrush product to your app target.

.package(url: "https://github.com/lostintangent/thrush", from: "0.10.0")

Create a TerminalSession and show it in a TerminalView. Keep the session in a main-actor model that outlives the view, since it owns the terminal and its history.

import Thrush

// The same ID comes back to the same shell. Leave it out for a shell that ends when its socket closes.
let session = TerminalSession(url: URL(string: "https://example.com/terminal")!, id: shellID)

TerminalView(session)

The session opens url as you give it, with the shell's ID and grid added to its query, so your server takes the socket at whatever path and query you choose.

The view fits its grid to the space it's given, draws its own padding around it, and runs under bars and the home indicator on its own, with no .padding() or .ignoresSafeArea(). Links open through SwiftUI's openURL, so your app decides where they go. ⌘F finds in history, on the Mac in a bar over the terminal and on iPhone in the system's find navigator, which Find Selection in the edit menu opens too. Each argument after the session is optional.

TerminalView(
    session,
    isActive: isSelectedTab,        // false while a tab stays in the hierarchy but is hidden
    theme: .dark,                   // nil follows the system appearance
    fontSize: 15,                   // nil is 13 pt, following Dynamic Type on iPhone
    blinksCursor: false,            // keeps the cursor solid while it takes typing
    showsKeyRow: false              // iPhone only. The row is shown by default
)

For your own colors, edit a copy of TerminalTheme.dark or .light and pass it as theme:. Text under the cursor and in the selection takes black or white, whichever reads better, unless the theme sets cursorForeground or selectionForeground.

Show the session's status

SwiftUI observes session.title, session.workingDirectory, session.progress and session.status directly. The working directory is the file URL a shell reports, which fish does on its own, and the progress is how far a long task such as a build says it has come, or nil. The status is .connected, .disconnected, .full or .closed. A session is .full while the server has every shell it allows open. It keeps trying and connects once one lets go. A closed session keeps its last screen and history readable, and passing a new TerminalSession to the same view starts over. Session lifecycle

TerminalView(session)
    .toolbar {
        if session.status == .closed {
            Button("New Shell", action: newShell)
        }
    }

Connect over WebSocket

The session opens a WebSocket at url each time it attaches, and your server speaks the Thrush terminal protocol. Give each shell a stable ID, such as a UUID the app saves, so a reconnect or a relaunch comes back to the same shell. Pass your own urlSession: for the server's cookies, headers, proxy or certificate trust. The sample's window

Bring your own transport

For SSH or a local PTY, supply a TerminalTransport. In this example, the app provides the SSH client and its sendable ShellChannel.

import Foundation
import Thrush

struct SSHTransport: TerminalTransport {
    let channel: ShellChannel

    func read() async throws -> Data? { try await channel.readOutput() }
    func write(_ bytes: Data) async throws { try await channel.sendInput(bytes) }
    func resize(to size: Terminal.Size) async throws {
        try await channel.setWindowSize(columns: size.columns, rows: size.rows)
    }
    func close() async { await channel.shutdown() }
}

let session = TerminalSession(openTransport: { size in
    let channel = try await ssh.openShell(columns: size.columns, rows: size.rows)
    return SSHTransport(channel: channel)
})

TerminalView(session)

Return nil from read() after the last output, and make close() release the transport and wake pending reads. When the transport ends, the session closes with its last screen intact.

Add a terminal to a web app

The same terminal runs in a web page, drawn with WebGL2, and needs Safari 26.2 or Chrome 143 or later. Each release attaches it as thrush-wasm.tgz, a package named thrush with types and no dependencies. Install it from a release's own URL, since your lockfile records the tarball's hash.

bun add https://github.com/lostintangent/thrush/releases/download/v0.10.0/thrush-wasm.tgz

Create a TerminalSession and show it in a TerminalView. The view fills the element you give it and draws its own padding, so give the element none.

import { TerminalSession, TerminalView } from "thrush";

// The same ID comes back to the same shell, after a reload too. Leave it out for a shell that ends when its socket closes.
const session = new TerminalSession({ url: "/terminal", id: shellID });

const view = new TerminalView({ element: document.getElementById("terminal")!, session });

The session works as a native one does. It opens url, which may be relative to the page, with the shell's ID and grid added to its query, so your server takes the socket at whatever path you choose. It reconnects and resumes on its own, and holds what a person types until the shell can take it. A React app makes the view with a ref and needs no component.

Each option after the session is optional.

const view = new TerminalView({
    element,
    session,
    autoFocus: true,                // takes the keyboard as the view is made
    theme: TerminalTheme.dark,      // without one, the view follows the system appearance
    fontFamily: "Menlo",            // the system's monospaced font by default
    fontSize: 15,                   // 13 px by default
    blinksCursor: false,            // keeps the cursor solid while it takes typing
    showsKeyRow: false,             // touch screens only. The row is shown by default
});

The view tells the app what the program reports about itself whenever it changes, with or without a session. onTitle receives the title, onWorkingDirectory the URL of the directory the shell is in, such as file://host/Users/me, and onProgress how far a long task such as a build has come, as { state, percent } where the state is "normal", "error", "indeterminate" or "paused", or undefined once it ends.

For your own colors, edit a copy of TerminalTheme.dark or .light, such as { ...TerminalTheme.dark, background: "#1e1e1e" }. The view draws outside the page's styles, so give it resolved colors, as getComputedStyle returns them, rather than a var().

The view takes a new theme, fontFamily or fontSize while it shows, such as view.fontSize += 1 for ⌘+. A new font fits the grid again, as a resize does.

A ⌘-click on a link opens it in a new tab, as a Control-click does off Apple's systems and a tap does on a touch screen. An app that opens links itself passes onLink, such as onLink: (url, event) => openPane(url, event.shiftKey), which gets each link and its click in the new tab's place.

On Apple's systems ⌘C and ⌘V copy and paste. Elsewhere Control-Shift-C and Control-Shift-V do, so Control-C and Control-V reach the program.

An app reads what a copy would, with view.selection for what's selected, or "", and view.text(lines) for the last lines of history and the screen, such as view.text(Infinity) to save the whole transcript. A line the program wrapped reads as one.

Find runs from the app's own bar. As a person types a query or presses Return, the bar calls view.findNext(query), with view.findPrevious(query) for Shift-Return and view.endFind() as the bar closes, which selects the current match. Every match is highlighted, and next goes older, up the screen. Case doesn't count unless the app passes { matchCase: true }. onMatches receives the count and the current match's number from the newest, so the bar can read "3 of 12" while the program writes.

An app that draws keys of its own on a touch screen passes showsKeyRow: false, and each of its keys calls sendKey, such as view.sendKey({ key: "c", ctrlKey: true }). The program gets what that key would type under the modes it set.

Show the session's status

const session = new TerminalSession({
    url: "/terminal",
    id: shellID,
    onStatus: (status) => render(status), // "connected", "disconnected", "full" or "closed"
});

// To end the shell for good, as a Close button does, close the session, and its status turns "closed".
closeButton.onclick = () => session.close();

// Disposing the view is all the cleanup it needs. The server keeps a shell with an ID for a while, so a new view
// with the same ID comes back to it.
view.dispose();

A session shows in one view at a time, so keep one view per session and move it to another element with view.mount(element).

Connect any other program

Without a session, write the program's output to the view and send the program the view's input.

import { TerminalView } from "thrush";

// `pty` stands for your app's connection to the program's PTY, such as a WebSocket to its server.
const view = new TerminalView({
    element: document.getElementById("terminal")!,
    // Send what a person types and pastes, and the terminal's replies to the program's queries, to the program.
    onInput: (bytes) => pty.write(bytes),
    // Resize the program's PTY to the grid that fits the view. The first call comes once the element is laid out,
    // so start the program then to open it at that size. Without onFit, the view resizes itself.
    onFit: (columns, rows) => pty.resize(columns, rows),
});
pty.onOutput = (bytes) => view.write(bytes);
// Resize the view when the PTY's server answers, in order with the output the program draws for the new grid.
pty.onResize = (columns, rows) => view.resize(columns, rows);

// A replay redraws a terminal on a blank one, so reset the view and write the whole replay at once. The view keeps
// its theme, its focus and the reader's place in history.
view.reset();
view.write(replay);

Bundle and serve the package

The view's module fetches thrush.wasm and session.wasm from beside it, so serve the package's files together, and serve .wasm files as application/wasm, which browsers need to compile them as they download.

Vite 8 bundles the package as it is. Vite 7 and earlier need it kept out of their dev server's prebundling, which moves the module away from its WebAssembly, and Vite 6 and earlier need a build target with top-level await.

import { defineConfig } from "vite";

export default defineConfig({
    optimizeDeps: { exclude: ["thrush"] }, // Vite 7 and earlier
    build: {
        target: "es2022", // Vite 6 and earlier
        // Keep session.wasm a file, rather than a data: URL.
        assetsInlineLimit: (file) => (file.endsWith(".wasm") ? false : undefined),
    },
});

A page's Content Security Policy needs 'wasm-unsafe-eval' in script-src, and the session's server in connect-src, which 'self' covers on the page's own host. A Vite build inlines session.wasm as a data: URL unless you keep it a file, as above, so otherwise allow data: in connect-src too.

Keep terminals on a JavaScript server

The package's thrush/core runs the same emulator on Bun and Node 22 and later. A TerminalHost keeps a terminal for each shell and serves TerminalSessions, native or in a browser, over the terminal protocol, with the same rules as the ThrushServer the sample connects to. You supply how a shell starts and who may reach it, and the host does the rest.

  • A client that drops resumes, and one that attaches later sees the screen it missed.
  • A shell goes to the client that asked for it last.
  • A shell no client shows ends once it's written nothing for 5 minutes. A shell with a client never times out.
  • Past 16 shells, a new one ends the detached shell idle longest. When every shell has a client, the host turns a new client away, and its session reports full while it keeps trying.
  • A client that falls behind skips the shell's output and catches up with a replay.
import { TerminalHost } from "thrush/core";

// The host makes a terminal for each shell. Start the shell's program in a PTY for it, here Bun's, and write what
// the PTY reads to the terminal. node-pty works too, with `encoding: null` for bytes and its `kill` as `close`.
const host = new TerminalHost((terminal) => {
    const pty = Bun.spawn([process.env.SHELL ?? "/bin/bash", "-l"], {
        env: { ...process.env, TERM: "xterm-256color", COLORTERM: "truecolor" },
        terminal: { cols: terminal.columns, rows: terminal.rows, data: (_, bytes) => terminal.write(bytes) },
    });
    pty.exited.then(() => terminal.close());
    // The host writes what clients type to the PTY, resizes it and closes it, which hangs up the shell.
    return pty.terminal!;
});

Bun.serve({
    routes: {
        // Sessions open the URL your app gives them, here /terminal. Check who may reach the shell before you upgrade.
        "/terminal": (request, server) =>
            server.upgrade(request, { data: { url: request.url } }) ? undefined : new Response(null, { status: 400 }),
    },
    websocket: {
        data: {} as { url: string; attachment?: ReturnType<TerminalHost["attach"]> },
        open(socket) {
            socket.data.attachment = host.attach(socket, socket.data.url);
        },
        message: (socket, data) => socket.data.attachment?.message(data),
        close: (socket) => socket.data.attachment?.close(),
    },
});

// When the server stops, end every shell and close every socket.
process.on("SIGTERM", () => host.dispose().then(() => process.exit()));

attach takes a socket from Bun, ws or crossws and the URL of the request that opened it. Its attachment takes each message the socket receives as the library hands it over, and tells the protocol's controls from keys itself.

// Bun
message: (socket, data) => socket.data.attachment?.message(data),
// ws, whose second argument says whether the message was binary
socket.on("message", attachment.message);
// crossws, whose peer is the socket
message: (peer, message) => attachment.message(message.rawData),

To change the defaults, pass { spawn, idleTimeout, limit } instead, with idleTimeout in minutes.

Use a protocol of your own

Keep a Terminal for each shell. Its replay redraws the screen on any VT client, such as Thrush or xterm.js.

import { Terminal } from "thrush/core";

const terminal = new Terminal(80, 24);

// Write each chunk of the shell's output to the terminal. An attached client also receives it and
// answers its queries, such as a cursor position request, so send the terminal's reply to the shell
// only when no client is attached.
const reply = terminal.write(output);
if (client) client.send(output);
else if (reply) pty.write(reply);

// Resize the terminal with the shell's PTY, then answer the client. It keeps the old grid until the
// answer, so both terminals take the new one between the same bytes of output.
terminal.resize(120, 40);
client.send(JSON.stringify({ type: "resize", cols: 120, rows: 40 }));

// A client that attaches at the terminal's size gets the replay, and then live output.
client.send(terminal.replay());

// Free the terminal when its shell ends.
terminal.dispose();

Try the sample app

The sample in examples/swiftui is one SwiftUI app for Mac and iPhone that depends only on Thrush. From the repository root, start the local server, which opens a real shell when the app connects.

swift run ThrushServer

In a second terminal, build and open the Mac app.

scripts/build-app.sh sample mac && open .build/sample/mac/Thrush.app

Or run it in the iPhone Simulator.

scripts/build-app.sh sample simulator
xcrun simctl install booted .build/sample/simulator/Thrush.app
xcrun simctl launch booted app.thrush.sample

Launch either app with -server http://host:port to use another server. Each window keeps its shell's ID when the system restores it, so it reattaches to the shell if the app is back within the 5 minutes the bundled server keeps a dropped shell. Windows come back after Quit and Keep Windows (⌥⌘Q) on Mac and after iOS ends the app in the background. A plain Quit, or swiping the app away on iPhone, opens a new shell.

Benchmarks

swift run -c release ThrushBench checks every recording against the reference emulator, then measures it. These numbers come from one M1 Max.

Measure Result
Sustained output 1,596 MiB/s at 80 × 24
Resize with full history Under 0.7 ms at p95, well inside one 120 Hz frame
Idle Zero frames

Benchmarks covers each measurement and how to run it.

Develop

AGENTS.md lists the build and test commands, Testing Thrush covers every test layer, and the plan is the source of truth for requirements, contracts and budgets.

License

Thrush is available under the MIT License.

About

🪶 A GPU-accelerated terminal emulator for your web, macOS, and iOS apps

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages