Skip to content

Latest commit

 

History

History
174 lines (154 loc) · 11.9 KB

ARCHITECTURE.md

File metadata and controls

174 lines (154 loc) · 11.9 KB

Architecture

RedShell is a Cargo workspace. Each crate has one job, and only redshell-ui and redshell-app depend on GPUI, so the rest of the workspace builds and tests quickly without a GPU.

redshell-app ──► redshell-ui ──► redshell-theme (feature "gpui")
     │
     ├──► redshell-terminal ──► redshell-theme, alacritty_terminal, portable-pty
     ├──► redshell-history  ──► rusqlite (bundled, FTS5)
     ├──► redshell-remote   (ssh, sftp, tmux, screen, WSL)
     ├──► redshell-agents
     ├──► redshell-plugin   ──► redshell-theme
     ├──► redshell-protocol (talking to RedShell servers)
     └──► redshell-core     (shared by every crate) ──► redshell-protocol (SSH hosts on the wire)

redshell-server ──► axum, tokio, rustls (ring), rusqlite, argon2, webauthn-rs, web-push-native
     ├──► redshell-terminal, redshell-agents, redshell-remote, redshell-core
     └──► redshell-protocol ──► serde (ts-rs in tests: web/src/protocol/*.ts)

redshell-server and redshell-protocol do not depend on GPUI either; the server is a separate binary with no OpenSSL, which cross-builds for a Raspberry Pi with the C compiler SQLite and ring need.

Key abstractions

  • Launchable / LaunchProfile (core): anything that can open in a tab. Local shells, SSH hosts, AI agents, multiplexer sessions and plugin profiles all implement it and resolve to a CommandSpec. The UI has a single code path for opening, recording and restoring tabs.
  • LaunchProvider: SSH, agents and plugins each provide profiles, and the app concatenates them.
  • SessionObserver (core): the terminal I/O thread reports output, input, resizes, titles, the working directory, commands and exit to it. The history Recorder is one observer. ObserverSet fans out to several.
  • Replay (terminal): the screen, recent scrollback and the modes a program set, as ANSI bytes that redraw them in a fresh terminal, cut at the exact output offset the live stream continues from. A client that joins a server session gets one.
  • Terminal (terminal): owns the PTY and the VT state. An I/O thread parses output and scans OSC 7, 9;9 and 133. The parser is advanced exactly up to each mark, and cells printed after OSC 133;A carry an internal hyperlink id, so prompt positions follow scrolling and reflow. Wakeups are coalesced with an atomic flag, so a burst of output triggers one repaint. Snapshot turns the grid into colour-resolved segments, which keeps all ANSI logic unit-testable without a GPU.
  • Multiplexer × MuxTarget (remote): what to run (tmux or screen argv) is kept separate from where to run it (locally, over SSH or through WSL). MuxClient combines them. MuxTarget::of_profile reads where any tab's program runs from its profile; Paste Image uploads clipboard images there (upload).
  • ControlClient (remote, tmux_control): a tmux -C client on any MuxTarget. It parses the control-mode stream, matches %begin/%end replies to commands, and routes %output straight from its reader thread into per-pane sinks, after replaying a capture-pane of the pane. In the app, tmux_native maps tmux windows to tabs and panes to TerminalViews built on Terminal::external (no PTY: input becomes send-keys -H, resizes refresh-client -C).
  • Askpass (remote askpass, app askpass and secrets): ssh processes RedShell starts for a host get SSH_ASKPASS pointing at RedShell itself plus a per-process token, added at spawn time (SshProfile::piped for background runs, terminal_view for tabs) and never saved in a profile. Run by ssh, main becomes the helper and asks the app's Broker over loopback. Its Policy (pure, unit-tested) decides between a secret from the keychain (Secrets), a refusal and a question for the UI, delivered as AskpassEvents.
  • Plugin + PluginHost (plugin): built-in and external plugins share one API, and actions flow back through a channel.
  • Command table (commands.rs): a single macro declares the GPUI actions, default keys, palette entries and the config ids. Every entry point (keys, palette, plugins) ends up in Workspace::run_command. Default keys are listed for macOS and Linux, with the few Windows differences in one table. Bindings need the Workspace key context without Overlay, which the workspace adds while a modal is open, so keys reach the modal instead.
  • ssh_hosts (app): every change to the saved SSH hosts (saving, renaming, duplicating and deleting one) and the checks behind it go through this module; the host editor (host_editor.rs) only collects the form. A host only in ~/.ssh/config is saved as an entry with just the changed fields, which ssh layers over the file's alias.
  • Sftp (remote sftp): a host's files over the system ssh's sftp subsystem, with russh-sftp speaking the protocol on its stdio. Each connection runs on a thread with a tokio runtime of its own, so its calls are plain futures any executor (GPUI's) can await. In the app, FileBrowser (sftp_view.rs, drawn by sftp_render.rs) is the dialog, and the workspace (files.rs) keeps a closed browser only while its transfers run.
  • ServerClient (app, remote/): the desktop's connection to one RedShell server, with no GPUI in it so it is tested against a real server in-process: the REST API, and one WebSocket on a tokio thread that reconnects with backoff, resyncs the session list and re-attaches what was attached. Each attachment streams into a Sink from that thread; for a tab it feeds a Terminal::external whose grid the server sizes (ExternalIo::sizes_grid), so snapshots, output and resizes land in order. The app's Servers global keeps one client per configured server and its tokens in the keychain; remote_tabs turns sessions into tabs and sidebar rows.
  • PaneNode<L> (panes.rs): the split layout of a tab, generic over its leaf so splitting, closing and divider dragging are plain, unit-tested data operations. Each split keeps one size ratio per child, and a tree of session ids with its ratios is what open_tabs saves as a tab's layout.
  • ActiveTheme (ui): a GPUI global. Components read shadcn tokens from it and never use hard-coded colours.
  • Icon / IconName (ui): a small Lucide SVG set compiled into the binary and served to GPUI through redshell_ui::Assets. Icons are painted as masks in a theme colour at a fixed size scale, so they line up with text regardless of the UI font's symbol coverage.

History storage

sessions(id, profile_json, title, cwd, started_at, ended_at, exit_code, bytes, cols, rows, open_tab, tab_order, pinned)
chunks(session_id, seq, ts_ms, kind[out|in|resize], data BLOB)   -- byte-exact recording
commands(session_id, ts_ms, command, cwd)
search_index FTS5(session_id, kind, ts_ms, body)                  -- stripped output, commands, titles
open_tabs(position, layout, name, active)                         -- layout: JSON split tree of session ids

The schema is versioned with PRAGMA user_version: changes after the base schema are listed in MIGRATIONS in store.rs and each runs once, so a database from an older release is updated when it is opened.

A dedicated writer thread batches inserts into one transaction about every 250 ms (a flush request commits at once). Recorders never block the terminal's I/O thread: if more than 64 MiB of output is waiting for the writer (it indexes roughly 50 MiB/s), further chunks are left out of the history until it catches up, so memory stays bounded. On startup, sessions marked open_tab are reopened, and their recorded output (the last 4 MiB) is replayed before the new process starts, followed by a dim restored separator. Each tab comes back with its open_tabs layout, name and active pane; panes that cannot come back are left out of the layout, and sessions no layout holds (a database from before layouts were saved) open as a tab each. restore::plan decides per pane: multiplexer panes skip the replay because tmux and screen redraw themselves on attach, a session the user picked is re-attached without being created (attach-session -t =NAME), and a native tmux session is attached once in control mode, which brings back all of its windows. The session a tab belongs to is read back from its profile id (redshell_remote::session_ref).

Server

redshell-server (see REMOTE.md) keeps sessions on an always-on machine:

  • Sessions / Session (sessions/): each session owns a Terminal and a small thread that drains its events and writes input, so a program that stops reading never blocks an async worker. The session's SessionObserver (Tap) publishes output, tagged with its byte offset, to an OutputHub: one bounded queue per attached client, filled with try_send, so a slow client is dropped and resynced with a fresh Replay instead of slowing anyone down.
  • Auth (auth/): setup codes, Argon2id passwords, per-address and per-name backoff, passkeys (webauthn-rs), desktop pairing and re-authentication, with browser sessions and device tokens stored as SHA-256 hashes.
  • Store (store/): SQLite with user_version migrations, like the history database: accounts, credentials, passkeys, push subscriptions, the audit log and session records.
  • Agent hooks (agents/): a loopback-only listener for Claude Code HTTP hooks and Codex's notify, and Approvals, the permission requests held open until a client answers.
  • Push (push/): Web Push to subscribed browsers when a session wants attention, with the checks that keep a browser-supplied endpoint from reaching private addresses.
  • HostBook (hosts.rs): the hosts API's view of [[ssh.hosts]] and ~/.ssh/config, written back through LiveSettings, which edits config.toml in place.
  • Web (web/): the REST routes, the WebSocket and the embedded web app. guard.rs checks the Origin, the X-RedShell header and the sign-in, and connections.rs caps open connections.
  • Bus: a broadcast of session, approval and revocation events that every WebSocket connection (web/ws.rs) filters for its client.

Rendering

TerminalView paints with a single GPUI canvas:

  1. Measure the cell size from the font and resize the PTY to fit the pane.
  2. Take a Snapshot.
  3. Paint background spans, find matches, the block cursor, text segments and the bar, underline or hollow cursor, then the scroll indicator and the dimming of inactive panes.

Keyboard input has two paths. Keys that encode to escape sequences or control bytes (arrows, Enter, Ctrl/Alt chords) are handled on key-down. Keys that produce text are left to the platform, which delivers them, IME commits and dead-key compositions exactly once through TerminalView's EntityInputHandler; pre-edit text is drawn underlined at the cursor and the IME candidate window is anchored there.

Find-in-terminal (search.rs) runs alacritty's lazy-DFA regex over the scrollback. The focused match is the grid selection, so alacritty keeps it in place while output scrolls, and the snapshot carries the visible matches.

Output is parsed through SelectionGuard, a thin VT handler around the grid that keeps the selection when a program erases and repaints selected rows (alacritty would drop it). Full-screen apps such as Codex and Claude Code repaint on every frame, so this is what lets a selection made in them stay until the user clicks elsewhere; scrolling, switching screens and resets still move or drop it.

Each non-ASCII glyph is shaped on its own and placed at its cell column, so font fallback cannot shift the grid. A run whose shaped width does not match its cells (a bold or italic face with different advances) is painted glyph by glyph, and wide glyphs narrower than their two cells are centred. Shaped lines are reused across frames by GPUI's line layout cache, so unchanged rows are not re-shaped.