How Orbit works

Orbit is a tmux-style terminal multiplexer for AI coding agents. You run multiple Claude / Codex / Cursor CLI sessions across git repos and worktrees, and they keep running after you close the UI.

Process model

There are two processes, same binary:

  1. Daemon (orbit daemon) — owns every PTY, SQLite, git worktrees, and agent status. Lives in the background.
  2. TUI (orbit) — a ratatui client. Quit it and nothing dies; relaunch and scrollback is replayed.

On launch the TUI connects to a unix socket ($XDG_RUNTIME_DIR/orbit/daemon.sock, mode 0700). If nothing is listening, it spawns orbit daemon in its own session (setsid) so the daemon outlives the client, does not get Ctrl+C, and holds no controlling terminal — daemon subprocesses that run the user's interactive shell must not be able to reach the TUI's tty via /dev/tty.

IPC is length-prefixed MessagePack: the client sends ClientRequests (CRUD, attach, keystrokes, resize); the daemon pushes ServerEvents (entity deltas, status, PTY output).

The handshake advertises PROTOCOL_VERSION and accepts any peer at or above MIN_COMPATIBLE_PROTOCOL. Bump PROTOCOL_VERSION for every IPC schema change. Leave MIN_COMPATIBLE_PROTOCOL alone for additive changes that older peers can safely ignore or never send: new optional struct fields must carry #[serde(default)], and a new request/event kind must be gated so a peer that does not know it is never asked to decode it. Bump both constants when a change removes or renames a field or variant, changes the meaning of existing data, or otherwise requires every connected client and daemon to move together. The compact MessagePack enum frames make the handshake itself part of that stable surface: do not add fields to Hello/HelloOk as an additive change.

In-place restart (orbit reload, and orbit upgrade when sessions are live) moves the daemon onto a new binary without stopping a session (orbit-daemon/src/handoff.rs). The daemon execs the new binary over itself: the pid stays the same, so every agent CLI is still its child and is reaped as before, and the fds it clears FD_CLOEXEC on survive — each PTY master, the client socket (so no client sees "no daemon" and spawns a second one), the hook receiver's socket (every live agent carries its port and token in its environment) and the pidfile with its flock. What lives only in memory goes into a MessagePack state file the new image reads as it boots (orbit daemon --adopt <file>): each session's scrollback ring at its original seqs, its size, and the terminal modes and title its scanners had read, plus pending orbit worktree relocations. The boot sweep spares the agents it carried, so their status survives; PREWARM POOL spares are carried only to be reaped. The request travels outside the socket protocol, because the asking client is usually the newer build: it writes restart.request (the binary to restart onto) into the runtime dir and sends SIGWINCH — ignored by default, so a daemon too old to listen survives being asked — and reads restart.result, which the old image writes on a refusal and the new one on success. A daemon advertises that it listens by writing daemon.restart (<pid> <version>), and only restarts onto a binary whose orbit _restart-version is at least its own state-file version. Connected TUIs lose their connection at the exec and are relaunched.

Domain tree

Everything is nested:

Project (a git repo) → Worktree (main checkout or git worktree add) → Session (an agent or a plain terminal tab).

Every project is in one list — there is no grouping above it. One repo is one project: adding a path that resolves to a repo already registered (its root or any checkout of it) is refused. The TUI shows one project's sessions at a time and moves between projects with its PROJECT TABS; every other project's sessions keep running (and keep receiving status updates) in the background. Databases through 0.33 grouped projects into named workspaces; migration 28 folds the groups away, merging a repo that sat in two of them into its older row.

Worktrees are real git worktrees, created under <repo>/../<repo-name>-worktrees/<branch>. The daemon also polls git metadata so worktrees created outside Orbit still show up.

An agent is a PTY running claude, codex, cursor-agent, pi, muse, grok, or opencode in that worktree. Restart resumes the stored session id when there is one, the way each CLI takes it (--resume <id> for Claude, Cursor and Grok; codex resume <id>, pi --session-id <id>, opencode --session <id>; muse always boots fresh: no resume flag mapped yet).

Persistence is SQLite at ~/.local/share/orbit/orbit.db: projects, worktrees, agents (kind + CLI session id, plus a PR URL when the AGENT was created from one), links, last UI selection.

Worktrees can still carry a persisted link list from earlier versions: URLs pinned to a checkout and normalized to http(s) on the way in. Nothing creates one any more (the request that did is gone) and the grid draws no link rows; the daemon keeps the stored rows, and the UpdateLink / DeleteLink requests, so no stored data disappears. What a band does show is the row nothing stores: the pull request on that branch, looked up client-side with gh pr view on the git-poll tick and cached per worktree.

The PULL REQUESTS MODAL has a separate creation path: Enter, Tab or Shift+Tab on a pull request creates a local SESSION for it. The TUI sends CreatePrAgent with the PR URL and the branch the PR's checkout is on — its head branch, or <owner>/<head> for a fork's (pull_request::checkout_branch), since a fork's main must match neither the ROOT WORKTREE nor origin/main; the daemon finds the project's worktree on that branch, or cuts one (from origin's branch of that name, else from refs/pull/N/head, which it then makes the branch's upstream), and the AGENT starts there — and that checkout's band wears the pull request on its rule. The daemon validates and stores it, refuses to adopt a PREWARM POOL process that started without the constraint, and composes the URL plus the PR-only work rule into Claude's existing --append-system-prompt. Every later cold spawn or RESUME rebuilds the same system prompt from SQLite. Enter in the modal opens the QUICK PROMPT for the PR, and Shift+Tab picks an AGENT PRESET; both send the same CreatePrAgent with the typed task — wrapped in the preset's prefix and postfix when one is on — as its starting_prompt, so the first prompt and the PR rule arrive together; the daemon finds the project's worktree on the PR's head branch, or cuts one, either way.

The ISSUES MODAL (i) is the same idea for GitHub issues: the TUI lists the selected project's open issues with gh issue list (prefetched in the background as the cursor rests on the project, and kept fresh on a slow beat, so the modal opens on rows), reads one with gh issue view, posts a comment on one with gh issue comment (Ctrl+c), rewrites one's title and description with gh issue edit (Ctrl+e, a form in the reading pane's place), and launches a QUICK PROMPT or an AGENT PRESET on it. That create is an ordinary CreateAgent carrying issue_url; the daemon validates it, stores it in its own column beside pr_url, skips PREWARM POOL adoption, and folds an issue-context rule (URL, checkout, branch) into the same launch prompts the PR rule uses — Claude and Pi's appended system prompt, Grok's --rules, a Codex / Cursor / Muse / OpenCode cold spawn's first prompt — on every spawn and RESUME.

How the pieces talk

┌──────────── TUI (ratatui) ────────────┐
│  grid: project tabs / bands / cards      │
│  attached terminal: vt100 parser + PTY   │
└───────────────┬───────────────────────┘
                │ unix socket
┌───────────────▼───────────────────────┐
│  Daemon                                 │
│  ┌ registry ┐  ┌ PTY ring buffers ┐   │
│  │ SQLite   │  │ portable-pty     │   │
│  └──────────┘  └──────────────────┘   │
│  ┌ hook HTTP (loopback) ──────────┐   │
│  │ claude/codex/cursor POSTs      │   │
│  │ → status state machine         │   │
│  └────────────────────────────────┘   │
└───────────────────────────────────────┘

Attach path: TUI sends Attach { session, from_seq, cols, rows }. Daemon replays the PTY ring as Scrollback, then streams live Output. Keystrokes go the other way as Input. Detach does not kill the child.

Daemon locking: the daemon uses parking_lot for its in-memory maps, the SQLite connection guard and PTY locks, so a panic in one task cannot poison production state. Locks are held briefly and never across .await except the async operation gates called out here. The lock order is: worktree_ops before spawn_gate before store/session install work; warm-pool decisions take prewarmed before checking sessions; session install/removal touches session_interest and sessions only in those short critical sections; relocation/status maps (pending_moves, status_machines, last_cwd, resumes, finished_runs, transcripts) are taken one at a time, with relocation state read and dropped before status_machines. PTY scanners are fed one at a time before appending to the ring; no code may take the ring and then a scanner. SQLite is synchronous (rusqlite), so async request/background paths use the daemon's blocking-store helper (or an outer spawn_blocking) before calling Store.

Status path (not MCP): at spawn, Orbit writes managed hooks into the worktree (.claude/settings.local.json or .cursor/hooks.json) or, for Codex, into Codex's home (~/.codex/hooks.json). Those hooks curl a loopback HTTP server with a per-boot bearer token. Events like UserPromptSubmit, Stop, PermissionRequest, SubagentStart feed a status machine that maps to the colored dots (running / finished / needs feedback / …). Stop is gated on active subagents so a turn is not marked done while workers are still going. A launch that hands the CLI a first prompt (a QUICK PROMPT, an AGENT PRESET, a Codex / Cursor PR or issue rule) is created running rather than gray: the CLI submits that prompt as it boots, and the row would otherwise sit idle — and sort under every session mid-turn — for the seconds until the first hook lands. Such a row's machine is seeded with a one-shot reprieve for the 9;4;0 the CLI prints as it draws its input box, so the boot is not read as that turn ending. Claude and Codex share one hooks dialect; Cursor speaks its own (camelCase events like beforeSubmitPrompt/stop, flat {"command"} entries, JSON replies on stdout), so its installer translates event names into the hookEvent query param and the receiver aliases its payload fields (conversation_id → session id, first workspace_roots entry → cwd). Cursor has no permission-request hook and runs with --force, so cursor agents report busy/idle but never needs-feedback. The UserPromptSubmit payload's prompt text is captured on the same route — condensed to one line, the newest ten kept per agent row — for the RECENT PROMPTS line each session card carries.

Auto-title path (hooks again, still not MCP): a session created with the default agent-N name carries a store-only auto_title_pending flag. While it's set, the daemon answers the Claude/Codex UserPromptSubmit hook POST with an instruction body instead of the usual discarded JSON — the installer's UserPromptSubmit command (alone among the hooks) pipes the response to stdout, which those CLIs add to the model's context. The instruction tells the agent to run orbit rename <3-4 word title> once; that subcommand resolves the agent from ORBIT_AGENT_ID, does a one-shot IPC AutoRenameAgent, and the daemon applies it only while the flag is still pending (atomic conditional update), so a user rename — which clears the flag — always wins and repeated attempts get a polite "already titled" error. Claude also gets a Bash(orbit rename:*) entry merged into permissions.allow so the command runs unprompted; Codex/Cursor already run with --yolo/--force. Cursor's hooks can't inject context, so it gets a managed, env-guarded .cursor/rules/orbit-title.mdc project rule carrying the same instruction — safe to fire repeatedly because the daemon-side flag is the arbiter.

Follow-up path: Space on a session card (or Follow-up prompt in its menu) opens a small modal over the grid holding the next turn for the agent already running there. Enter sends what is in it straight down the PTY as two ClientRequest::Inputs — the text (a BRACKETED PASTE only when it has line breaks, so a one-liner stays out of the CLI's "[Pasted text]" placeholder), then the that submits it, as two writes so the child reads the prompt before the Enter — and closes the box. A session with no live PTY is attached first and the box kept as it is: the daemon drops Input for a session it has not spawned.

Session context path: every agent can run orbit sessions, orbit read <session> and orbit ask <session> "<question>" from inside its PTY. These are ordinary same-user one-shot IPC clients, not orchestrator-only commands: ListSessions returns model-sized rows from the same PROJECT/WORKTREE/SESSION tree the orchestrator reads, ReadSession resolves an id or unambiguous fuzzy name and prefers a remembered Claude transcript before falling back to ANSI-stripped PTY scrollback, and AskSession writes a labelled prompt into the target agent's PTY. If the target is mid-turn, ask subscribes to the existing status broadcasts and waits for the row to become idle before sending (unless --no-wait was requested), then waits for the next turn to finish and returns only the clean output written after the question was sent. The target conversation keeps the question and answer, by design.

Metrics path: the memory modal (Shift+M) asks the daemon for one reading (GetMetrics → Metrics). The daemon runs a single machine-wide ps sweep and sums RSS over each live session's process subtree (the PTY child plus its descendants — an agent CLI fans out into workers and MCP servers), reporting itself separately since sessions are its own descendants. The TUI adds its own RSS client-side (it is not a daemon child) and re-polls every 2s while the modal is open.

Remote hosts path: orbit ssh host [dir] execs ssh -t with a self-installing remote command, and first records the destination in ~/.local/share/orbit/ssh_hosts.json (newest first, capped at 20, keyed by host + start dir). The TUI's Shift+H picker lists that file; choosing an entry — or typing a new user@host [dir] with a — quits the TUI cleanly (UI state saved, terminal restored) and hands the destination back to the binary, which execs a fresh orbit ssh over the same terminal. The local daemon and its sessions keep running; exiting the remote orbit lands back in the local shell. d in the picker forgets an entry.

Sandbox path: orbit sbx [name] is the remote-hosts path with docker exec -it as the transport. It makes sure a container named orbit-sbx[-name] is running — docker run -d --init … sleep infinity from buildpack-deps:bookworm-scm (or --image) when there is none, docker start when it is stopped — then execs docker exec -it <container> sh -c <ssh's REMOTE_SCRIPT> … with the install URL, an empty start dir and the settings bundle as plain argv, since no login shell sits in between. The container is kept, so the daemon orbit leaves running inside it (reaped by --init's PID 1) and everything it holds is there on the next run. No sshd, keys or ports, and no daemon protocol involvement: it is a launcher only. Not recorded in ssh_hosts.json.

Settings path: both halves read settings through orbit-core/src/settings.rs: config.json (or ORBIT_CONFIG_FILE) with <data dir>/config.local.json merged over it key by key. When the merged object won't deserialize whole, it is read one top-level key at a time, so a value one release can't read costs only that key; the TUI keeps those keys in Config::skipped, and a save leaves their stored JSON alone and writes a key the local layer holds back into that layer. Writes go tmp-then-rename through settings::write_atomic, which follows a symlink to the file it names, and the presets and hosts lists are read entry by entry, with a save keeping the entries this build can't parse. orbit-tui/src/bundle.rs moves settings between machines as raw JSON sections under a orbit_bundle marker — never through the typed structs, so keys and fields a newer release wrote survive the trip. orbit config export / import write and merge one; orbit ssh and orbit tunnel base64 one (config and presets, not hosts) into one more positional parameter of their remote script, which exports it as ORBIT_IMPORT_BUNDLE before exec'ing orbit, and the binary's main merges it and removes the variable before any thread or child exists. A remote orbit too old to know the variable ignores it.

Presets path: e on a card lists the agent presets in <data dir>/agent_presets.json (orbit-tui/src/agent_presets.rs, a sibling of ssh_hosts.json, written tmp-then-rename): each is a name, an agent kind, a model / effort choice (or "follow Settings → Agents") and optional prefix / postfix text. Letters type ahead over the names (fuzzy::rank, recomputed per key — the list is short — with AgentPresetsView::selected kept as the stored index so every verb reads the right row), so the verbs are chords: Ctrl+a / Ctrl+e open the preset editor form, Ctrl+d deletes behind a confirm, and Enter opens the same multi-line task editor the cloud launch uses. Submitting composes prefix + task + postfix (blank-line separated, empty parts skipped, capped at the cloud task's 16 KiB) and sends CreateAgent { starting_prompt }; the daemon validates it, skips warm-spare adoption (a CLI already booted bare cannot be handed an argument) and passes it to the fresh spawn as the CLI's trailing positional prompt (claude … "<text>", codex … "<text>", cursor-agent … "<text>", pi … "<text>", muse … "<text>", grok … "<text>", and opencode … --prompt "<text>" — the one CLI whose positional is a project path, so its descriptor's prompt_flag carries the text). Like the cloud task it is request-only — nothing is persisted, so a restart or resume rebuilds the ordinary argv — and the row it creates is an ordinary agent from then on (auto-title, hooks, status, resume).

Cursor catalogue path: cursor-agent --model takes one flat id per (family, effort, fast) triple — claude-opus-5-thinking-high-fast — and refuses the bracket form its --help shows, so the TUI keeps the family as the model and the suffix (high, high-fast, fast) as the effort and the daemon joins them with a - at spawn (registry.rs::agent_spawn_command_with). orbit-tui/src/cursor_catalogue.rs builds the lists from one parser over two sources: a built-in seed of the ids observed on 2026-08-28 and cursor-agent --list-models, which bootstrap (TUI startup, skipped when Cursor is switched off or under ORBIT_AGENT_CMD) reads from <data dir>/cursor_models.json and refreshes on a background thread once the cache is a day old; the two are unioned, seed order first, because --list-models prints only the featured ids. Most families have no bare id, so "default" effort for them launches the family's fallback (high, else medium, else its first variant) — config::fit_effort is the one place that decides, and every surface that changes the family (Agents tab, preset editor, picker) runs it.

Tunnel path: orbit tunnel host [dir] is the remote-hosts path and the browser path joined into one command: a single ssh -tt -L 127.0.0.1:<local>:127.0.0.1:<remote> whose remote command is the same self-installing prelude with a different tail — orbit browser --no-open --port <remote> >/dev/null. The remote stays on its own loopback, so the ssh channel is the only way in and there is no port to firewall and no ttyd password to set; --no-open because the desktop that should get the tab is the local one, and the redirect because the remote's own "serving on …" names a port that means nothing here (its stderr is kept — the install progress, a missing ttyd, and a port clash are the whole diagnosis). Before starting anything the remote command asks its own loopback port whether a ttyd is already there (curl -I, matched on the server: ttyd/… header, which a 401 behind --credential carries too); if so — a orbit browser the user left serving on that box, typically a --public one — it says so and execs a long sleep instead of a second server, so the forward reaches the existing one and Ctrl+C or hang-up still ends the session. The probe is plain shell, so it needs nothing new from the remote's orbit. Unlike orbit ssh this spawns rather than execs, because work remains after the connection: the local port is settled first (same rules as orbit browser, so the printed URL and the forward agree), then the tunnel is polled with a real GET / — a bare connect proves nothing, since ssh accepts on the forwarded port from the moment the session is up and only then discovers the far end is refusing — and the URL is opened once bytes come back. Each poll before the remote is listening is a refused channel OpenSSH logs, so ssh's stderr is filtered through a thread that drops exactly that line and keeps the rest. The pty is forced (-tt, not -t) so hanging up reaps the remote ttyd and its TUI; -t allocates nothing when stdin is not a terminal, which is precisely when nobody is watching for orphans. Destinations land in the same ssh_hosts.json orbit ssh writes, so a host tunnelled into shows up in the Shift+H picker (which reconnects over orbit ssh, not the tunnel).

Browser path: orbit browser shells out to ttyd rather than serving anything itself — ttyd runs a command in a PTY and bridges it to xterm.js in the page, so pointing it at this binary (current_exe, not whatever orbit resolves to on PATH) puts the real TUI in a browser tab, grid and all. The command polls 127.0.0.1:<port> until it accepts, opens the URL, then blocks on ttyd; Ctrl+C reaches both through the shared process group. It binds loopback and stays unauthenticated by default — ttyd ships no auth and what it serves is a live terminal, so local access needs neither and remote access is normally ssh -L or a tunnel. --bind ADDR / --public widen the bind for the case a tunnel cannot cover — orbit running on the remote box, where the access control is the firewall or security group in front of the port — and --credential USER:PASSWORD adds ttyd's HTTP basic auth. Any non-loopback bind warns on stderr, twice as loudly without a credential. Widening also moves the readiness poll and the opened URL off 127.0.0.1: the free-port probe asks the address ttyd will actually bind (a port free on one interface may be taken on another), and an unspecified bind (0.0.0.0/::) is polled and opened on loopback of its family, since it names every interface rather than a destination. The daemon is uninvolved: this is a second TUI client like any other, so it sees the same projects and sessions.

Run path: Run in the project menu (or a card's right-click menu) sends StartRun { worktree } — or StopRun, when that worktree's RUN TERMINAL is alive. The daemon reads the project's run_command out of config.json's projects entry (its own config.rs, fresh each time — the TUI's Project tab writes it) and, when that is empty, .orbit.json (orbit-core/src/project_file.rs: the worktree's checkout, else the project's main checkout), and spawns the run line in a terminal row whose run_command column is set, as $SHELL -l -i -c '<prelude>; <run>' — the agent launch's login-shell wrapper — instead of a bare -l shell. One run per worktree: the check-and-spawn holds the spawn gate, a live run is the reply as it stands, and an exited run's row is reused. The PTY's life is the RUNNING state the TUI draws (TerminalTab.alive on a row with a run_command), and StopRun is CloseTerminal on that row. A run terminal is never spawned any other way — ensure_session refuses it, the prewarm sweep skips it, the idle reaper spares it — and one whose command exits on its own keeps its PtySession in finished_runs, so an attach replays the output and is sent SessionExited straight after. Shift+Enter (or Shift+O / Alt+Enter) is TUI-only: it reads the project's open_command out of the same projects entry, else the same file's open, and runs it once through $SHELL -c in the checkout, detached, output discarded. Nothing in the file runs without a keypress, which is what lets it live in the repository when WORKTREE HOOKS cannot.

Crate layout

Crate Role
orbit Thin CLI: no args → TUI; add, daemon, kill, reload, rename, worktree, spawn, open, config, browser, ssh, tunnel, upgrade
orbit-core Shared protocol, entities, IDs, paths, codec
orbit-daemon PTYs, SQLite, git, hook receiver, status engine
orbit-tui ratatui UI, keyboard/mouse, attach/scrollback
orbit-fuzzy The list filters' matcher — dependency-free, and a crate of its own only so dev builds optimise it ([profile.dev.package.orbit-fuzzy])

The TUI also has extras on top of the multiplexer: git diff viewer, grep, the root checkout's branch switcher, a vim-like terminal overlay, fuzzy finders — those are client-side. The daemon is the source of truth for sessions and the tree.

Input is not action. In orbit-tui a key arm and a mouse arm only translate: they say which row (list_hit::row_at for the pointer) and then call the one function that says what choosing it does — event_loop::activate for the grid and the modals event_loop owns, a modal's own activate_selected or Cmd executor (run_settings_cmd, file_tabs::run, preset_overlays::activate_selected) for the rest, select_clicked_row / select_*_row for moving a cursor, context_menu_items for the right button's menu. Nothing that closes a modal, sends a request, spawns a process or moves a cursor lives inline in handle_mouse or in a key arm beside a twin that does the same. The rule exists because its absence shipped bugs: a click in a pull request's preset picker launched a plain session into the ROOT WORKTREE while Enter launched the PR SESSION, a click in the file finder skipped the markdown reader Enter had learned, and a right-click moved the cursor without the pane. The INPUT PARITY tests in event_loop.rs build the same app twice, choose a row once by key and once by pointer, and compare everything observable.

How to add a modal

Use crates/orbit-tui/src/issues.rs as the reference for a list-style modal: the view state owns a FilterList<T> for query text, filtered matches, cursor, scroll window and row hit-testing; the module owns the actions that activate a row, refresh data, and reopen after a child prompt. Key and mouse dispatch should delegate to that module, and clicks should only identify/select rows before calling the same action path Enter uses. Draw list rows with ui::render_row and row content helpers from ui/rows.rs so labels, badges, status dots and width fitting stay consistent across overlays and launcher layouts.

Checklist:

  • Add an Overlay variant and a small view struct; put long-lived row list state in FilterList<T>.
  • Keep slow work off the key handler: ask through the existing background job/channel pattern, then land answers back into the modal state.
  • Record area and list/body rects during draw for outside-click and row hit-testing.
  • Route Esc in two stages for fuzzy lists: clear the query first, close on the second Esc.
  • Add input-parity coverage for any row action reachable by both key and mouse.

A key handler never blocks. orbit-tui's event loop is one task: while a handler runs nothing paints, no PTY output is parsed and no other key is read. So a handler does bookkeeping and nothing else — anything that spawns a process, reads a file of unknown size or waits on the network is a BACKGROUND READ (view_jobs.rs: the worktree views' git and disk, keyed by ticket so a late answer nobody is waiting for is dropped) or one of the per-feature channels main_loop owns (gh, the BRANCH SWITCHER, issues), and a view built without a handle — every unit test — reads inline through the same parsers. What the DAEMON will confirm is shown first (event_loop/optimistic.rs, event_loop/placeholder.rs) and rolled back on Error. event_loop/pacing.rs decides when the loop may paint. The INPUT LATENCY PROBE (perf.rs, ORBIT_PERF_LOG) and make perf are how a change to any of it is judged: handler, paint, settle and echo per scripted step, with peak RSS beside them, because holding more to feel faster is not a trade this codebase makes — the pane's screen cache got quicker by holding less.

Mental model: tmux, but the “windows” are agent CLIs bound to git worktrees, and the grid is a mission-control view of which agents are working, waiting, or dead.