Skip to content

feat(native): thread terminal drawer - #25

Merged
rynfar merged 4 commits into
nativefrom
nw/w5-terminal
Nov 2, 2026
Merged

rynfar merged 4 commits into
nativefrom
nw/w5-terminal

Conversation

@rynfar

@rynfar rynfar commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Problem

The native client had no terminal. The web's thread terminal drawer (ledger PN-TERMINAL) is one of the most-used surfaces: a bottom drawer under the chat with one or more shells per thread, shared live with every other client attached to the same PTY.

Approach

Ported from ThreadTerminalDrawer.tsx, PersistentThreadTerminals.tsx, useThreadTerminalActions.ts, useChatTerminalActions.ts, terminalUiStateStore.ts, terminalCloseConfirm.ts, and client-runtime/src/state/{terminal,terminalSession}.ts, against the unmodified server protocol (terminal.open/attach/observe/write/resize/close, subscribeTerminalMetadata).

crates/core/src/terminal* (pure, tested)

  • Wire types and payloads for the terminal RPCs, decoded forward-compatibly (unknown event types become Unknown).
  • BufferState: the attach-event reducer (applyTerminalAttachStreamEvent), reporting Reset(history) / Append(data) instead of retaining text, because the emulator owns scrollback.
  • Lifecycle: transitionTerminalLifecycle. A shell that exits while attached is closed and dropped from the drawer. An ended shell found on an explicit visit is reopened. Read-only viewers never touch history.
  • TerminalLayouts: a full port of terminalUiStateStore (open, height, ids, split groups, active terminal and group, close suppression, server reconcile), persisted as terminal-state through store::save_ui_state, with each thread decoded on its own.
  • Labels (getTerminalLabel, nextTerminalId), launch location and env (projectScriptCwd/RuntimeEnv), drawer height clamp, close-confirmation copy.
  • Key input: xterm encoding (app-cursor mode, modifier parameters, Ctrl caret codes, Alt as ESC for special keys) plus the web's macOS readline shortcuts (Option-arrows, Cmd-arrows, Cmd-Backspace, Cmd-K/Ctrl-L clear). Plain printable keys go through GPUI text input, so IME composition works. Pastes honor bracketed paste and the 65,536-unit write limit.
  • emulator: alacritty_terminal 0.26 (Apache-2.0) wrapped as bytes in, snapshot out. It answers DSR/DA/OSC 10/11/4 and size queries. It drops replies while replaying history (as the web's resetAndWrite detaches the PTY writer), so a replay never types garbage into the shell. It flushes stalled synchronized updates and maps the wheel to SGR mouse reports or alternate-screen arrows.

crates/client: ClientHandle::request (from #18) now queues the request before returning, so calls made in order reach the server in order. Terminal input depends on this, and the change is signature-compatible. Added ClientHandle::stream next to it.

crates/app/src/terminal

  • session: one network task per terminal. It attaches (or falls back to terminal.observe, read-only, on EnvironmentAuthorizationError), resumes after reconnects with resume: true, and parses output into the emulator on the tokio runtime behind a FairMutex. It signals the pane with one pending notification at a time, and the pane repaints at most once per 16 ms. Idle cost is zero.
  • element: paints only visible rows. It merges background and selection runs into quads and shapes each row as a few text runs pinned to the cell grid (force_width), splitting only at wide characters. Metrics follow the web's ghostty surface: 12px mono, round(12 * 1.35) line, 4px padding, grid anchored to the bottom once there is scrollback. The cursor is steady (no blink): a block when focused, hollow when not.
  • pane: keyboard, IME (EntityInputHandler, preedit drawn at the cursor), drag/word/line selection with a 2px threshold, shift-click extend, wheel scrollback, focus reports, and the web's context menu (Copy, Paste, Select all, Jump to latest).
  • drawer / drawer_view: a 280px default drawer (min 180, max 75% of the window) with a 6px resize strip that persists height per thread. The active group's panes sit side by side or stacked. The UI is either the floating action group (one terminal) or the 144px session list with group headers (several). The empty state matches the web. Closing asks first with the web's copy; a failed close falls back to typing exit. Opening an empty drawer reuses a terminal the server already runs for the thread before starting a new one.
  • Entry points: terminal.toggle, terminal.split, terminal.splitVertical, terminal.new, and terminal.close now map to the drawer's actions in keymap::action_for, so the web's default keys and the user's keybindings apply. mod+j works everywhere; the rest work while a terminal is focused, via the keymap's terminalFocus → Terminal context, which the pane carries. Copy, paste, select all, and cmd-k clear (keys the web's surface handles itself) are bound in the Terminal context, so they beat the palette's mod+k, as the web's !terminalFocus rule intends. There is also a Terminal toggle in the header's right cluster (design-system §7.4). Tooltips take their shortcuts from keymap::label.
  • Icons: five Lucide icons (square, square-split-horizontal, square-split-vertical, square-terminal, trash-2) added to icons::Icon in the same format.
  • workspace.rs: the drawer sits under the composer. The thread view is now .cached(), so terminal output repaints don't re-render the transcript. (ThreadView already notifies itself, so this is safe.)

Ledger

  • PN-TERMINAL: todo → partial, Native crates/app/src/terminal, crates/core/src/terminal.rs. Web sources now also cover the files this ports.

Verification

  • cargo test -p t3-core -p t3-client: pass, including 33 new terminal tests (reducers, lifecycle, layouts, labels, payloads, key and paste encoding, emulator replies and replay, selection, wheel, hit testing).
  • cargo clippy --workspace --all-targets -- -D warnings: clean. node scripts/gen-theme.ts --check and node --test parity/sync.test.ts: pass.
  • Probe against the isolated dev server (cargo run -p t3-client --example terminal_probe -- --seconds 8):
thread mcp:5fa7c56f-8c79-46cb-a665-7aa90f62ee3d
terminal term-1-79358c14-48d3-4df7-9b78-2e1388f1892e (Terminal 1)
cwd /Volumes/DevSSD/t3code-native/apps/server
metadata: snapshot with 1 terminal(s)
open: status="running" pid=6831 cols=80 rows=24
attach: snapshot status=Running grid=Some(Grid { cols: 80, rows: 24 }) history=0B
write: echo hello && pwd
attach: activity status=Running grid=Some(Grid { cols: 80, rows: 24 })
output (control sequences stripped):
  | echo hello && pwd
  |  /Volumes/D/t3code-native/ap/server  %                                                                                /Volumes/D/t3code-native/ap/server  on native   ✔ eecho hello && pwd❯ echo hello && pwd
  | hello
  | /Volumes/DevSSD/t3code-native/apps/server
  | %                                                                                 /Volumes/D/t3code-native/ap/server  on native   ✔  /Volumes/D/t3code-native/ap/server  on native   ✔  /Volumes/D/t3code-native/ap/server  on native   ✔
resize 100x30: ok
attach: activity grid=Some(Grid { cols: 100, rows: 30 })
close (deleteHistory): ok
attach: closed
metadata: removed term-1-79358c14-48d3-4df7-9b78-2e1388f1892e
  • Live app against the same server, with a persisted open drawer: the app attached term-1 with no window frame drawn yet (sessions don't wait for paint). A second client (terminal_probe --observe term-1 --run …) typed printf '\033[6n'; read -rs -t 2 -d R pos && echo dsr-reply-ok || echo dsr-timeout and got dsr-reply-ok. Only the attached app could answer that query, so it parsed live output and replied over terminal.write.
  • During a 200,000-line seq flood into that terminal (about 1.3 MB), app CPU peaked around 13% (with temporary debug logging on) and returned to 0.0% as soon as output stopped. Idle is 0.0%.
  • When another client settled the thread, the server closed its idle terminals. The app printed [terminal] Terminal closed, dropped the terminal, and closed the drawer, as the web does.

Gaps

  • No screenshots yet. The Mac's lid was closed during this run, so the window never drew a frame. Visual parity (spacing, colors, session list, floating actions) still needs a pass in a real window with test-t3-native.
  • Link detection and opening (terminal-links.ts), "Add to chat" from a selection and the selection action popover, terminal font family and size settings, mouse click/drag reporting (only the wheel is reported), and dragging the scrollbar thumb.
  • Right-panel terminal surfaces (the right panel now exists, so this is next), explicit command palette and menu entries, and project-script runs into the terminal.
  • Permissions are not read from the session's scopes (the client doesn't track them yet). Read-only is detected when terminal.attach fails authorization.

Ported by Claude (Opus 5.5) in Claude Code, as factory worker W5.

@rynfar
rynfar merged commit 6a7da66 into native Nov 2, 2026
rynfar added a commit that referenced this pull request Nov 2, 2026
The workspace draws the transcript .cached() since #25, but a markdown state's
background reparse notifies only that state, which the cached view does not
observe, so a streamed block could stay stale until another transcript update.
Each state now re-notifies the transcript.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant