Visual Studio Code, rebuilt in Rust
Terminal
The integrated terminal is a shell behind a pty, a VT screen that parses its output, the shell integration read from that output, and the view that draws the screen. This file goes one level under ARCHITECTURE.md, "Terminal, webviews, updates". The code is app/src/terminal.rs, the folder app/src/terminal, the crate ghostty_vt, and the terminal_*.rs files of app/src/workbench. Upstream is src/vs/workbench/contrib/terminal, src/vs/workbench/contrib/terminalContrib and src/vs/platform/terminal.
What is where
app/src/terminal.rs::TerminalInstance: one terminal, upstream'sterminalInstance.ts. It owns the pty, the screen (term), the shell integration state, the finished commands and the titles. It does not import the workbench: a test builds one and feeds it bytes.app/src/terminal/pty.rs::Pty: the shell process, node-pty'sspawnin Rust. The Windows side isapp/src/terminal/pty/conpty.rs.ghostty_vt/src/lib.rs::Term: the screen, in the place of xterm.js.ghostty_vt/src/selection.rsis the selection on it.app/src/terminal/shell_integration.rs::ShellIntegration: the OSC scanner and the command state machine, upstream'sshellIntegrationAddon.tsandcommandDetectionCapability.ts.app/src/terminal/prompt_input.rsispromptInputModel.ts, andapp/src/terminal/injection.rsdecides how a shell loads the scripts.- The other files of
app/src/terminalport upstream files or an xterm.js addon, named in their//!header (fixed_dims.rshas none): keys, mouse reports, links, search, serialize, history, profiles, quick fixes, completions, OSC 99. app/src/workbench/terminal_view.rs::TerminalView: the terminals of a window, their groups, the tabs. It is a field of theWorkbench, not a GPUI entity.app/src/workbench/terminal_view/grid.rs::paintdraws one terminal.app/src/workbench/terminal_host.rs: the extension API, upstream'smainThreadTerminalService.tsandmainThreadTerminalShellIntegration.ts.app/src/workbench/terminal_editor.rs: terminals in the editor area, and the save and revive of terminals across a restart.
The backend today
The VT parser and screen model is libghostty-vt 1.0.2, through the safe bindings of libghostty-rs. The move from alacritty_terminal has landed: no crate of the workspace depends on alacritty_terminal. The reasons, the fork, its three build.rs changes and the measured throughput are in port/notes.md, "Milestone 15: integrated terminal".
ghostty_vt forbids unsafe and is the only crate that depends on libghostty-vt. The rest of the port sees Term and its plain types.
Termkeeps the shapes the port used with alacritty:ghostty_vt/src/lib.rs::Line0 is the first line of the active area, and a negative line is in the scrollback.app/src/terminal/shell_integration.rs::BufferPointcounts from the first scrollback line instead, so a command's lines stay valid while output scrolls. Convert withhistory_size, asapp/src/terminal.rs::buffer_cursordoes.- Ghostty prunes scrollback by whole pages, so it holds more rows than
terminal.integrated.scrollbackallows.ghostty_vt/src/lib.rs::history_sizeandhidden_rowshide the extra rows. Code that reads the scrollback size from the raw terminal sees lines xterm.js would have dropped. - The parser answers queries through effect callbacks (
ghostty_vt/src/lib.rs::Handler), and the answers wait inghostty_vt/src/lib.rs::Effectsuntiltake_effects. The replies toCSI c,CSI > candCSI > qare set to xterm.js's, the ones VS Code's terminal gives. - A callback runs inside Zig. A panic there unwinds into foreign code, so a callback that can fail keeps the old value (
on_title_changed). - Selection follows alacritty 0.25's rules, which the port's selection tests were written against. Its anchors are tracked grid references, so a selection moves with scrolled output as xterm.js's does.
Invariant: keys and mouse reports are encoded by app/src/terminal/keys.rs and app/src/terminal/mouse.rs with xterm.js's encodings. libghostty-vt's key encoder is not used.
The pty and its threads
Upstream runs every pty in a separate pty host process (ptyService.ts). The port spawns the shell from the app process, so a terminal does not survive the window (see "Restart" below).
app/src/terminal/pty.rs::spawn starts two threads per terminal. pty-read reads the master in 64 KiB chunks and sends PtyEvent::Data. pty-wait waits for the child, then for the reader to finish or 200 ms, then sends PtyEvent::Exit. Both send into one unbounded channel, so the exit follows the last output unless the reader is still reading after the 200 ms, as node-pty's unixTerminal.ts orders them.
app/src/workbench/terminal_view.rs::pump_terminal_events is the one reader of that channel: a task on the main thread that takes every event that is ready and hands the batch to terminal_events. Everything after the channel runs on the main thread: UTF-8 decoding, the parser, shell integration, the calls to the extension host.
- Writes to the pty (
app/src/terminal/pty.rs::write) and the resize are direct calls from the main thread. A write after the shell exited fails and is dropped, as node-pty drops it. - The channel is unbounded and nothing pauses the reader, where upstream has flow control (
FlowControlConstants). A process that prints faster than the main thread parses grows the queue. - A chunk can end inside a UTF-8 character.
app/src/terminal.rs::decodekeeps the cut bytes for the next chunk. Feed the pty's bytes throughprocess, never straight toTerm::advance. Ptykills the shell with SIGHUP when it is dropped, so dropping the instance is the kill. memory-safety.md listskillas a known weak point: after the shell exits, the stored pid can belong to another process.- The foreground process name and the cwd are polled every 200 ms for all terminals (
app/src/workbench/terminal_view.rs::start_title_poll,app/src/terminal.rs::refresh_process). On macOS they are three syscalls per terminal on the main thread (tcgetpgrpand twoproc_pidinfo), on Linuxtcgetpgrpand two reads of/proc. Keep anything slower out of that poll.
Trap: pump_terminal_events returns at once under cfg!(test), because the pty-read thread would wake the task off the test scheduler's thread and abort the run. In a workbench test no shell output arrives by itself: the test calls app/src/workbench/terminal_view.rs::terminal_data with the bytes. The tests of app/src/terminal/tests.rs read the receiver themselves.
From bytes to a frame
app/src/workbench/terminal_view.rs::terminal_data is the one entry for process output, a pty's or an extension pseudoterminal's. It calls app/src/terminal.rs::process, then acts on what the chunk raised: the clipboard (OSC 52), auto replies, task output, history, the events for the extension host, quick fixes, OSC 99 notifications. Then it notifies, and the next frame draws.
process returns app/src/terminal.rs::Processed: the chunk's text and its shell integration events in stream order. Output fed to process without terminal_data still updates the instance's commands, but is invisible to tasks, to onDidWriteTerminalData, to the command history and to the extension host's shell integration events.
app/src/terminal.rs::feed sets the theme's colors and the cell size on the Term before each parse. The parser answers OSC 4, 10, 11 and 12 and CSI 14 t while it parses, so the values must be there first.
There is no cell buffer between the screen and the frame. app/src/workbench/terminal_view/grid.rs::paint reads the visible rows with ghostty_vt/src/lib.rs::viewport_rows each frame and paints each cell's background, find match, selection, underline and strikethrough, then each row's text, the link underlines and the cursor. A focused block cursor is its cell's background.
Invariant: app/src/workbench/terminal_view/grid.rs::paint reads the screen through one viewport_rows call, which reads each row's raw cells in one call. ghostty_vt/src/lib.rs::row and cell resolve a grid reference per cell and are for the code outside paint: links, search, serialize, the command line, the sticky scroll overlay. The numbers are in port/notes.md.
The budget: one echoed key and the draw, over a full scrollback, under 16 ms at p95 (app/src/workbench/scroll_frame_time.rs::terminal_typing_frame_time).
Shell integration
app/src/workbench/terminal_host.rs::prepare_terminal_launch gives each launch a nonce and changes its arguments and environment so that bash, zsh, fish or pwsh loads upstream's own scripts from src/vs/workbench/contrib/terminal/common/scripts under the workbench's app_root (app/src/terminal/injection.rs::injection, upstream's terminalEnvironment.ts). For zsh the four zsh scripts are copied as dotfiles into a ZDOTDIR under the temp folder. A task terminal (is_feature_terminal) and a disabled terminal.integrated.shellIntegration.enabled get no injection.
The sequences are read before the parser, not by it. app/src/terminal/shell_integration.rs::scan finds every OSC sequence in a chunk, and process feeds the screen up to the end of each one before it handles it. So the cursor is where the shell printed the mark, and the text between C and D is the command's output.
- The whole chunk still goes to the screen, sequences included. OSC 633, 133, 1337, 7, 99 and 52 are acted on from the scanner's result, never from a libghostty-vt callback.
- A sequence can be cut by the end of a chunk. The scanner keeps its state between chunks, so one
ShellIntegrationbelongs to one instance for its whole life. - A command line is trusted only when its E sequence carries the launch's nonce (
is_trusted). Any program can print OSC 633. Rerun Command asks before it runs an untrusted line. Keep that check when a new feature runs a recorded command. - Without an E sequence the command line is read from the screen between B and the cursor, with low or medium confidence, as
extractCommandLinedoes.
The extension host side
The exthost crate holds no terminal logic, only the proxy ids of the terminal actors and the activation events of the terminal and terminalQuickFixes contributions (exthost/src/activation_events.rs). The calls of MainThreadTerminalService and MainThreadTerminalShellIntegration are forwarded to the main thread (extension-host.md, "Host calls the port answers") and answered by app/src/workbench/terminal_host.rs::handle_terminal_request.
- State goes to the host as a diff.
app/src/workbench/terminal_host.rs::Reportedholds what the host last heard of each terminal, andsync_terminals_to_hostsends only what changed. Call it after a change to a title, a size, a selection or the active terminal instead of sending the event yourself. - An extension
Pseudoterminalis an instance withextension_ptyand noPty. Its output arrives as$sendProcessDataand entersterminal_datalike a shell's. Its input leaves through theprocess_inputcallback thatconnect_terminal_to_hostsets. Code that writes toptydirectly skips these terminals: write throughapp/src/terminal.rs::inputorsend_text. - The instance id is the id the host knows. A detached terminal (
app/src/workbench/terminal_view.rs::create_detached, used by the test results output) counts down fromu32::MAX, is in no group and is never reported to the host. $acceptTerminalClosedsends a missing exit code asundefined, notnull: the API tests compare withundefined(exthost/src/rpc.rs::undefined).
Restart
On quit the buffers of the persistent terminals are written as escape sequences that redraw them (app/src/terminal/serialize.rs, the serialize addon's format) and the layout of the groups beside them. On start app/src/workbench/terminal_editor.rs::revive_terminals starts new shells and replays the stored text onto each terminal's screen. The processes are new: only the screen content comes back, where upstream's pty host can reconnect to a live process after a window reload.
Check a change
- The screen:
port/tools/cargo-test -p ghostty_vt the_viewport_rows_match_the_rows_read_one_cell_at_a_time, or the whole crate withport/tools/cargo-test -p ghostty_vt. - The instance, the pty and the models:
port/tools/cargo-test terminal::. One test of the pty:port/tools/cargo-test a_shell_runs_in_a_pty_and_its_output_reaches_the_screen. - Shell integration:
port/tools/cargo-test shell_integration::,port/tools/cargo-test prompt_input::,port/tools/cargo-test injection::. - The view and the editor terminals:
port/tools/cargo-test terminal_view::,port/tools/cargo-test terminal_editor::. - The extension API has no Rust test of its events. Run upstream's suites:
MOCHA_GREP='vscode API - terminal' port/tools/api-testsandMOCHA_GREP='vscode API - Terminal.shellIntegration' port/tools/api-tests. - The typing budget:
cargo gc test --release -p app -- --ignored terminal_typing_frame_time --nocapture, on a quiet machine (performance.md). - After a change to
app/src/terminal/pty.rsorapp/src/terminal/pty/conpty.rs:cargo gc clippy -p app -p exthost --all-targets -- -A clippy::alland the inventory row in memory-safety.md.