Examples / Sandboxes / durable-tmux

Durable tmux: a Linux machine in every actor

Rendered from durable-tmux/actor/src/actors.ts · Edit on GitHub

A tmux-style terminal in the browser where every pane is its own Linux box.

Each box is a LinuxBox actor that runs a full Linux VM (unkernel: Linux compiled to wasm, booting Debian) inside the actor's own process. Close the tab, kill the server, come back tomorrow: the box is still there, with your files, your shell history, and whatever was on screen.

The pieces:

  • LinuxBox: one actor per machine. Its VM is a @Resource, so it boots (or restores) when the actor wakes up.
  • UnkernelVM (./UnkernelVM.ts): the VM itself, snapshotted into the actor's SQLite so it survives sleep and crashes.
  • ShellSession (./ShellSession.ts): one named shell inside the VM, streamed to every pane watching it.
  • Workspace: the tmux layout and the list of boxes, synced live to every open tab.
actor/src/actors.tsL15–18
import { Actor, Compute, Emittable, Ephemeral, Interleave, Persisted, Resource, unchecked, type ActorSocket, type Unchecked } from "terse-sdk/actor"
import type { PtyEnd } from "unkernel"
import { z } from "zod"
import { UnkernelVM } from "./UnkernelVM.js"

The types the client sees

terse actor generate turns these into the typed client in client/generated.

actor/src/actors.tsL24
export type ExecOutput = { stdout: string; stderr: string; exitCode: number | null }

One socket per pane: the metadata names the shell session on this box that the pane shows.

actor/src/actors.tsL27–35
export type PaneMetadata = { session: string; cols: number; rows: number }
export type TerminalIn = { type: "input"; data: string } | { type: "resize"; cols: number; rows: number } | { type: "close" } | { type: "wake" }
export type TerminalOut = { type: "output"; session: string; data: string } | { type: "ended"; session: string; reason: string }

export type LayoutNode = { kind: "pane"; id: string; box: string } | { kind: "split"; dir: "row" | "column"; ratio: number; a: LayoutNode; b: LayoutNode }
export type LayoutWindow = { name: string; root: LayoutNode; active: string }
export type WorkspaceLayout = { windows: LayoutWindow[]; activeWindow: number }
export type BoxRecord = { name: string; label: string; createdAt: number }
export type WorkspaceState = { layout: Unchecked<WorkspaceLayout> | null; boxes: BoxRecord[] }

Under the runtime's idle timeout, so a heartbeat that finds work keeps the actor awake.

actor/src/actors.tsL38–41
const HEARTBEAT_MS = 5_000
const CHECKPOINT_WHILE_BUSY_MS = 30_000

type PaneSocket = ActorSocket<PaneMetadata, TerminalOut>

LinuxBox: one actor, one machine

The generics are the same three as in hello world:

  • PaneMetadata: what a pane sends when it connects (which shell, and how big the terminal is)
  • TerminalIn: messages from a pane (keystrokes, resizes, close)
  • TerminalOut: messages to the panes (terminal output, "this shell ended")

@Compute asks for a bigger machine than the default: the guest's whole root file system lives in RAM.

actor/src/actors.tsL51–140
@Compute({ cpu: 1, memoryMiB: 3072 })
export class LinuxBox extends Actor<PaneMetadata, TerminalIn, TerminalOut> {
    // @Ephemeral fields aren't saved and may reset between calls, which is fine for bookkeeping like this.
    @Ephemeral private lastCheckpointAt = 0
    @Ephemeral private changedSinceCheckpoint = false

    // @Resource is the interesting bit. The runtime calls the resource's `onResume()` every time the actor wakes,
    // and `onGracefulShutdown()` before it sleeps. UnkernelVM uses those to restore the VM from its last snapshot
    // and to save a fresh one, so the machine keeps running across sleeps as if nothing happened.
    //
    // Shell output arrives on its own schedule, not during an actor call, so it reaches the panes through the
    // actor's own reference (`LinuxBox.get(this.id).broadcast`) rather than `this.broadcast`.
    @Resource private machine = new UnkernelVM(this.db, {
        output: (session, data) => LinuxBox.get(this.id).broadcast({ type: "output", session, data }),
        ended: (session, end) => LinuxBox.get(this.id).broadcast({ type: "ended", session, reason: describeEnd(end) }),
    })

    // ### RPC methods

    // Any async method is callable from the client: `actors.LinuxBox.get("box").exec("uname -a")`.
    // The same ID always reaches the same machine.

    async exec(command: string): Promise<ExecOutput> {
        const { stdout, stderr, exitCode } = await this.machine.exec(command)
        return { stdout: String(stdout), stderr: String(stderr), exitCode }
    }

    async sessions(): Promise<string[]> {
        return this.machine.listSessions()
    }

    async reset(): Promise<void> {
        await this.machine.reset()
    }

    // ### Panes are WebSockets

    // When a pane connects, open (or reattach to) its shell and replay the scrollback, so a reload
    // shows exactly what was on screen before.
    async onConnect(socket: PaneSocket): Promise<void> {
        const { session, cols, rows } = socket.metadata
        const shell = await this.machine.open(session, { cols, rows })
        socket.send({ type: "output", session, data: shell.scrollback })
        this.changedSinceCheckpoint = true
        this.#scheduleHeartbeat()
    }

    // Keystrokes and resizes from a pane. Every message is an actor call, so typing also keeps the box awake.
    async onMessage(socket: PaneSocket, message: TerminalIn): Promise<void> {
        const { session } = socket.metadata
        // A wake (a click, or the focused pane's client heartbeat) only needs to be a call: that alone resets the idle timeout.
        if (message.type === "wake") return
        this.changedSinceCheckpoint = true
        this.#scheduleHeartbeat()
        if (message.type === "close") return this.machine.close(session)
        if (message.type === "resize") {
            socket.metadata = { session, cols: message.cols, rows: message.rows }
            return this.machine.resize(session, message)
        }
        await this.machine.write(session, message.data, socket.metadata)
    }

    // ### Sleeping when idle, with alarms

    // Actors sleep when nobody calls them. That's what we want for an idle box, but not for one running a build
    // with nobody typing. So a heartbeat alarm checks the guest every few seconds:
    // * Busy (CPU, network, disk, or output): set the alarm again. The alarm is a call, so the box stays awake.
    // * Idle: let the alarm lapse, and the actor goes to sleep. The VM snapshot brings it back on the next call.

    // Snapshots are only taken when something changed, since one can be 100+ MB once Claude Code is installed.
    // @Interleave lets keystrokes through while a checkpoint compresses, which takes seconds on a big box.
    @Interleave
    async onAlarm(): Promise<void> {
        const busy = this.machine.isBusy()
        if (busy) this.changedSinceCheckpoint = true
        const due = busy ? Date.now() - this.lastCheckpointAt > CHECKPOINT_WHILE_BUSY_MS : this.changedSinceCheckpoint
        if (due) {
            // Cleared before the await, so input that arrives during the checkpoint marks the box changed again.
            this.changedSinceCheckpoint = false
            this.lastCheckpointAt = Date.now()
            await this.machine.checkpoint()
        }
        if (busy) this.alarm.set(Date.now() + HEARTBEAT_MS)
    }

    // Keystrokes don't push a pending heartbeat back, so a long burst of typing still gets checked and checkpointed.
    #scheduleHeartbeat(): void {
        if (this.alarm.get() === null) this.alarm.set(Date.now() + HEARTBEAT_MS)
    }
}

Workspace: the layout, synced across tabs

The tmux layout plus every box the workspace has ever used. Closing panes never drops a box, so a machine with a login on it can't be lost track of.

No WebSocket messages in or out (null, null): tabs connect only to watch state.

actor/src/actors.tsL148–177
export class Workspace extends Actor<null, null, null> {
    // @Persisted saves every assignment. Arrays and objects are reassigned (never mutated) so the change is saved.
    // @Emittable pushes each change to every connected socket, which is how every open tab stays in sync.
    @Persisted @Emittable layout: Unchecked<WorkspaceLayout> | null = null
    @Persisted @Emittable boxes: BoxRecord[] = []
    @Persisted private boxesCreated = 0

    async getState(): Promise<WorkspaceState> {
        return { layout: this.layout, boxes: this.boxes }
    }

    // The layout comes from the browser, so it's validated with zod. `Unchecked` keeps the recursive layout type
    // out of the generated contract, and zod checks it here instead.
    async setLayout(layout: Unchecked<WorkspaceLayout>): Promise<void> {
        const parsed = workspaceLayoutSchema.parse(layout)
        const known = new Set(this.boxes.map(b => b.name))
        const added = layoutBoxes(parsed).filter(name => !known.has(name))
        if (added.length > 0) this.boxes = [...this.boxes, ...added.map(name => this.#newRecord(name))]
        this.layout = unchecked(parsed)
    }

    async renameBox(name: string, label: string): Promise<void> {
        this.boxes = this.boxes.map(b => (b.name === name ? { ...b, label: label.trim() || b.label } : b))
    }

    #newRecord(name: string): BoxRecord {
        this.boxesCreated += 1
        return { name, label: `box ${this.boxesCreated}`, createdAt: Date.now() }
    }
}

That's it! Two actors, and every pane is a Linux machine that survives anything.

Helpers

actor/src/actors.tsL183–209
const boxNameSchema = z.string().regex(/^[A-Za-z0-9._-]{1,128}$/)
const layoutNodeSchema: z.ZodType<LayoutNode> = z.lazy(() =>
    z.union([
        z.object({ kind: z.literal("pane"), id: z.string(), box: boxNameSchema }),
        z.object({ kind: z.literal("split"), dir: z.enum(["row", "column"]), ratio: z.number(), a: layoutNodeSchema, b: layoutNodeSchema }),
    ]),
)
const workspaceLayoutSchema: z.ZodType<WorkspaceLayout> = z.object({
    windows: z.array(z.object({ name: z.string(), root: layoutNodeSchema, active: z.string() })),
    activeWindow: z.number().int(),
})

function layoutBoxes(layout: WorkspaceLayout): string[] {
    const names: string[] = []
    const walk = (node: LayoutNode): void => {
        if (node.kind === "pane") names.push(node.box)
        else { walk(node.a); walk(node.b) }
    }
    for (const window of layout.windows) walk(window.root)
    return [...new Set(names)]
}

function describeEnd(end: PtyEnd): string {
    if (end.type === "exit") return `exited with code ${end.code}`
    if (end.type === "signal") return `killed by signal ${end.signal}`
    return end.type
}

actor/src/UnkernelVM.ts

UnkernelVM: a Linux machine as an actor Resource

A Resource is any object with two lifecycle hooks the runtime calls for you:

  • onResume(): the actor just woke up. Boot the VM, or restore it from the last snapshot.
  • onGracefulShutdown(): the actor is about to sleep. Snapshot the VM into the actor's SQLite.

Between the two, checkpoint() saves extra snapshots while the box is in use, so even a crash (which skips onGracefulShutdown) loses at most a few seconds.

actor/src/UnkernelVM.tsL10–26
import { readFileSync } from "node:fs"
import { createRequire } from "node:module"
import { promisify } from "node:util"
import { gunzipSync, gzip } from "node:zlib"
import type { ActorDatabase, ActorResource } from "terse-sdk/actor"
import {
    createKernel,
    decodeSnapshot,
    directBackend,
    encodeSnapshot,
    fetchDistro,
    loadKernelModule,
    type ExecResult,
    type KernelHandle,
    type KernelSnapshot,
} from "unkernel"
import { ShellSession, type SessionEvents } from "./ShellSession.js"

Claude Code needs about 360 MB unpacked, and without a data disk the root file system lives in this RAM.

actor/src/UnkernelVM.tsL29–30
const MEMORY_MIB = 2048
const DISTRO = "debian"

Guest monotonic time, which a restore continues from the snapshot, so dormancy doesn't eat into it.

actor/src/UnkernelVM.tsL32
const SHELL_DETACH_TIMEOUT_MS = 10 * 60_000

An idle Debian guest uses a few percent of a host core for timers; real work is well above this.

actor/src/UnkernelVM.tsL34–35
const BUSY_CPU_SHARE = 0.15
const gzipAsync = promisify(gzip)

The actor is bundled, so unkernel can't find its wasm or package.json next to its own entry; resolve them from node_modules.

actor/src/UnkernelVM.tsL38–199
const require = createRequire(import.meta.url)
const kernelModule = loadKernelModule(readFileSync(require.resolve("unkernel/unkernel.wasm")))
const { version: unkernelVersion } = require("unkernel/package.json") as { version: string }
const distroPath = fetchDistro(DISTRO, { releaseUrl: `https://github.com/pithings/unkernel/releases/download/v${unkernelVersion}/` })

export type ShellSize = { cols: number; rows: number }

export class UnkernelVM implements ActorResource {
    private _vm: KernelHandle | undefined
    private readonly sessions = new Map<string, ShellSession>()
    private readonly sessionEvents: SessionEvents
    private outputSinceCheck = false
    private baseline = { cpuMicros: 0, at: 0, io: 0 }

    constructor(
        private readonly db: ActorDatabase,
        events: SessionEvents,
    ) {
        this.sessionEvents = {
            output: (session, data) => {
                this.outputSinceCheck = true
                return events.output(session, data)
            },
            ended: (session, end) => {
                this.sessions.delete(session)
                return events.ended(session, end)
            },
        }
    }

    get vm(): KernelHandle {
        if (this._vm === undefined) throw new Error("VM not running")
        return this._vm
    }

    // Wake up: create the tables on first run, then boot fresh or restore the snapshot and reattach the shells.
    async onResume(): Promise<void> {
        this.db.exec("CREATE TABLE IF NOT EXISTS machine_snapshot (id INTEGER PRIMARY KEY CHECK (id = 1), data BLOB NOT NULL, taken_at INTEGER NOT NULL)")
        this.db.exec("CREATE TABLE IF NOT EXISTS shell_session (name TEXT PRIMARY KEY, tty_id TEXT NOT NULL, scrollback TEXT NOT NULL)")
        const [row] = this.db.exec<{ data: Uint8Array }>("SELECT data FROM machine_snapshot WHERE id = 1")
        if (row === undefined) {
            this._vm = await boot()
            console.log(`booted a fresh ${DISTRO} kernel`)
            return
        }
        const snap = decodeSnapshot(new Uint8Array(gunzipSync(row.data)))
        this._vm = await boot(snap)
        console.log(`restored kernel from a ${row.data.byteLength} byte snapshot with ${snap.ttys?.length ?? 0} shells`)
        await this.reattach(snap)
    }

    // Going to sleep: save the whole machine, open shells included.
    async onGracefulShutdown(): Promise<void> {
        await this.vm.snapshot({ commit: snap => this.save(snap) })
        this._vm = undefined
        this.sessions.clear()
    }

    async open(name: string, size: ShellSize): Promise<ShellSession> {
        const existing = this.sessions.get(name)
        if (existing !== undefined) {
            existing.resize(size.cols, size.rows)
            return existing
        }
        const pty = await this.vm.spawn(undefined, [], { detachable: true, detachTimeout: SHELL_DETACH_TIMEOUT_MS, ...size })
        const session = new ShellSession(name, pty, this.sessionEvents)
        this.sessions.set(name, session)
        return session
    }

    // Whether the guest did anything since the last call: printed to a shell, used the network or disk, or kept the CPU busy.
    // Each actor has its own host process and the kernel runs on its thread, so the process's CPU time is the guest's.
    isBusy(): boolean {
        const { cpuMicros, at, io } = this.baseline
        const now = { cpuMicros: totalCpuMicros(), at: performance.now(), io: this.ioCounter() }
        this.baseline = now
        const output = this.outputSinceCheck
        this.outputSinceCheck = false
        if (at === 0) return true
        const cpuShare = (now.cpuMicros - cpuMicros) / 1000 / (now.at - at)
        return output || now.io !== io || cpuShare > BUSY_CPU_SHARE
    }

    async write(name: string, data: string, size: ShellSize): Promise<void> {
        const session = await this.open(name, size)
        await session.write(data)
    }

    resize(name: string, size: ShellSize): void {
        this.sessions.get(name)?.resize(size.cols, size.rows)
    }

    close(name: string): void {
        this.sessions.get(name)?.close()
        this.sessions.delete(name)
    }

    listSessions(): string[] {
        return [...this.sessions.keys()]
    }

    async exec(command: string): Promise<ExecResult> {
        const result = await this.vm.exec("sh", ["-c", command])
        await this.checkpoint()
        return result
    }

    async reset(): Promise<void> {
        this.vm.stop()
        this.sessions.clear()
        this.db.exec("DELETE FROM machine_snapshot")
        this.db.exec("DELETE FROM shell_session")
        this._vm = await boot()
    }

    // The actor can crash without onGracefulShutdown, so activity also leaves a snapshot behind.
    async checkpoint(): Promise<void> {
        await this.save(await this.vm.snapshot())
        // Encoding and gzipping the snapshot burns host CPU too; don't let the next heartbeat count it as guest work.
        this.baseline = { cpuMicros: totalCpuMicros(), at: performance.now(), io: this.ioCounter() }
    }

    private async reattach(snap: KernelSnapshot): Promise<void> {
        const saved = this.db.exec<{ name: string; tty_id: string; scrollback: string }>("SELECT name, tty_id, scrollback FROM shell_session")
        for (const row of saved) {
            const tty = snap.ttys?.find(t => t.id === row.tty_id)
            if (tty === undefined) continue
            const pty = await this.vm.attach(tty, { replay: false })
            this.sessions.set(row.name, new ShellSession(row.name, pty, this.sessionEvents, row.scrollback))
        }
    }

    private ioCounter(): number {
        const { net, block } = this.vm.stats()
        return (net?.rx ?? 0) + (net?.tx ?? 0) + block.bytesRead + block.bytesWritten
    }

    // Compression runs on zlib's thread pool: gzipSync on a 2 GB box took ~300 ms (seconds once Claude Code is installed),
    // and this thread is also the guest kernel's, so a synchronous gzip froze the machine and every keystroke with it.
    private async save(snap: KernelSnapshot): Promise<void> {
        const shells = [...this.sessions.values()].flatMap(s => (s.ttyId === undefined ? [] : [{ name: s.name, ttyId: s.ttyId, scrollback: s.scrollback }]))
        const data = await gzipAsync(encodeSnapshot(snap))
        this.db.exec(
            "INSERT INTO machine_snapshot (id, data, taken_at) VALUES (1, ?, ?) ON CONFLICT (id) DO UPDATE SET data = excluded.data, taken_at = excluded.taken_at",
            data,
            Date.now(),
        )
        this.db.exec("DELETE FROM shell_session")
        for (const shell of shells) {
            this.db.exec("INSERT INTO shell_session (name, tty_id, scrollback) VALUES (?, ?, ?)", shell.name, shell.ttyId, shell.scrollback)
        }
    }
}

function totalCpuMicros(): number {
    const { user, system } = process.cpuUsage()
    return user + system
}

async function boot(restore?: KernelSnapshot): Promise<KernelHandle> {
    return createKernel({ kernel: await kernelModule, distro: await distroPath, memoryMiB: MEMORY_MIB, net: directBackend(), restore })
}

client/index.ts

client/index.tsL1–25
import { Command } from "commander"
import { actors } from "./generated"

const program = new Command().description("Run commands on a durable Linux box (unkernel inside a Durable Actor)")

program
    .command("exec")
    .argument("<command...>", "shell command to run in the guest")
    .option("--id <id>", "box ID; the same ID is the same machine", "box")
    .action(async (command: string[], { id }: { id: string }) => {
        const { stdout, stderr, exitCode } = await actors.LinuxBox.get(id).exec(command.join(" "))
        process.stdout.write(stdout)
        process.stderr.write(stderr)
        process.exitCode = exitCode ?? 1
    })

program
    .command("reset")
    .option("--id <id>", "box ID", "box")
    .action(async ({ id }: { id: string }) => {
        await actors.LinuxBox.get(id).reset()
        console.log(`reset ${id}`)
    })

await program.parseAsync()