Skip to content

feat(tui): 1:1 Rust port of the TypeScript TUI (tui/rust) - #114

Merged
huichen merged 17 commits into
mainfrom
claude/tui-rust-port
Aug 7, 2026
Merged

huichen merged 17 commits into
mainfrom
claude/tui-rust-port

Conversation

@huichen

@huichen huichen commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

1:1 TypeScript→Rust port of tui/ → the Rust crate at tui/ (bin future-tui, lib future_tui): identical UI rendering / key handling / interaction / argument parsing / help text, with a self-implemented terminal backend — libc (termios/ioctl/sigaction+self-pipe/poll) on POSIX and a windows-sys console backend (raw mode via SetConsoleMode, VT input/output, WaitForSingleObject + window-size-event resize detection) on Windows.

The TypeScript TUI is retired (same as the CLI, #115): TS sources deleted, the crate promoted from tui/rust/ to tui/, and both test harnesses converted to golden mode — tui/tests/golden/parity-ts.golden (render outputs, 97 cases) and the tmux screen goldens (11 scenarios) were recorded from the TS implementation before deletion and are now verified against the Rust TUI alone.

Why self-implemented, not a TUI framework

Researched the Rust ecosystem (RESEARCH.md): ratatui uses an offscreen cell-buffer + full-screen diff model, which does not match the TS TUI's streaming-ANSI architecture (raw escape sequences to stdout, custom key parser, kitty keyboard/image protocols, synchronized output). The TS version itself was framework-free — its only "backend" was Node's internal setRawMode (termios/SetConsoleMode), which is exactly what the port reimplements. A 1:1 port therefore mirrors the TS architecture byte-for-byte.

Architecture alignment with main

Verification (all gates green on this branch)

Gate Result
Golden render parity (Rust vs TS-recorded outputs) 97/97 byte-identical
tmux screen consistency (Rust vs goldens, live app) 11/11 — welcome/typed/streamed-reply//status//help//model//sessions overlays/Ctrl+C exit 0
Unit tests 411 passed (ported TS tests + new)
Workspace tests + clippy -D warnings + fmt clean
3-platform Rust compile check passes — Windows backend added (was failing on the POSIX-only backend)

Also (user request): the startup [Context] block was removed from the welcome screen in the port (and the then-current TS reference), keeping contextFiles state for /status/reload.

Notable bugs caught by the harnesses (fixed + regression-tested)

h1 heading style composition order, dim("queued") suffix placement, table column-width signed-arithmetic underflow, footer token-stat JS truthiness, status-overlay fallbacks, spurious "Connection to agent lost" flap (one-shot watchdog + silent resubscribe).

Known/accepted divergences

Link-reference definitions inside blockquotes/lists (pulldown-cmark vs marked container semantics — not exercised by corpus), timestamp/random-id rendering (excluded), Windows backend type-checked but not runtime-tested (no Windows host — documented in tui/src/terminal_windows.rs), TS event-loop machinery mapped to the app loop (observable behavior identical, tmux-verified).

Full details: docs/verification/tui-rust-port-acceptance.md (divergence list, test matrix, commit inventory, rerun commands).

future-agent and others added 17 commits August 7, 2026 01:03
…future-tui), self-implemented POSIX terminal backend, stdin-buffer/keys/theme/utils ports (P0)

- tui/rust/RESEARCH.md: framework comparison (crossterm/ratatui/termion/termwiz
  rejected), self-implemented backend decision, markdown plan (pulldown-cmark)
- crate tui/rust = workspace member; bin future-tui + lib future_tui;
  build.rs mirrors scripts/version.mjs (FUTURE_VERSION honored, git-derived
  0.0.<count>-<hash>+local[.dirty] byte-identical to version.generated.ts)
- terminal.rs: POSIX backend — tcgetattr/tcsetattr raw mode (Node setRawMode
  flag ops), ioctl TIOCGWINSZ + COLUMNS/LINES env fallback, sigaction +
  O_NONBLOCK self-pipe (async-signal-safe handler; reader thread restores and
  re-raises on SIGINT/TERM/HUP/QUIT), poll(2) reader thread with kitty-query
  150ms fallback + StdinBuffer idle-flush deadlines, drain_input, progress
  keepalive thread, PI_TUI_WRITE_LOG, start/stop with error cleanup
- stdin_buffer.rs / keys.rs / theme.rs / utils.rs: 1:1 ports (regex crate for
  CSI-u/legacy patterns, unicode-segmentation for Intl.Segmenter, thread_local
  caches); help.rs verbatim printHelp; main.rs --version/--help byte-identical
- 96 unit tests (keys.test.ts + utils.test.ts ported incl. xorshift32 wrap
  fuzz; stdin-buffer/theme/terminal tests added); clippy -D warnings + fmt clean
- E2E validated under script-PTY (examples/smoke.rs): raw mode, kitty query,
  modifyOtherKeys fallback, bytes -> key pipeline, clean stop() teardown
- Makefile: test-tui-rust wired into test; lint-tui gains rust clippy
…-list/scoped-models-selector/footer/help-screen/keybindings) + tui.rs core + RPC types

- tui.rs: Component/Container/Focusable architecture, ANSI constants, overlay
  layout math (parseSizeValue/resolveOverlayLayout) ported 1:1
- components/input: multi-line input with history + soft-wrap navigation,
  faithful UTF-16 cursor semantics (JS string indexing), bracketed paste;
  input-bugs.test.ts ported
- components/autocomplete: AutocompleteManager (sync port — debounce is an
  app-loop concern), SlashCommand/FilePath/Attachment providers, popup;
  display-fixes AutocompletePopup cases ported
- components/select_list + scoped_models_selector: filtering/navigation/
  toggle; components.test.ts ported; rpc/types.rs ModelInfo added
- components/footer: status bar with both-side truncation; footer.test.ts
  ported
- help_screen: renderHelp card (every row exactly terminal width);
  help-screen.test.ts ported
- keybindings: KeybindingManager (usize IDs for TS Symbols) + new tests
- 237 unit tests (was 96), clippy -D warnings + fmt clean
- Makefile: define missing lint-tui-rust target (referenced by lint)
…ust render parity harness

Port the P2 rendering core 1:1 from tui/src to tui/rust:
- markdown.rs: pulldown-cmark event stream -> marked-shaped token tree
  adapter + identical rendering (stylePrefix re-application, blank-line
  rules, table column-width algorithm, quote borders, code fences, defs)
- chat_area.rs: scrollable chat view incl. deferred re-render queue and
  streaming prefix-cache path (findStreamCut, streamCaches)
- terminal_image.rs: kitty/iTerm2 protocols, PNG/JPEG/GIF/WebP dimension
  sniffing, image id extraction/collection/deletion, hyperlink, fallback

New render-parity harness (97 cases, byte-identical TS vs Rust):
- tui/render-parity.ts (bun) + tui/rust/examples/render_parity.rs twins
- shared corpus tui/rust/tests/parity-corpus.json (gen_parity_corpus.py)
- tui/rust/tests/diff-ts-rust.sh wired as make test-tui-diff
- serde_json escaping == JSON.stringify verified byte-for-byte

Bugs found by the harness and fixed:
- h1 style composition order (TS heading(bold(underline(t))), not
  heading(underline(bold(t)))); corrected stale unit test that encoded
  the wrong order
- queued message suffix now inside dim() span (TS parity)
- paragraph trailing whitespace restored (pulldown trims Text events,
  marked keeps a trailing text token)

362 unit tests (was 359); workspace clippy -D warnings + fmt clean;
workspace tests 1843 passed / 0 failed.
…app.rs/index.rs/grpc-client.rs)

Port of tui/src/app.ts (2669 lines), tui/src/index.ts (777 lines), and
tui/src/rpc/grpc-client.ts (1397 lines):

- rpc/grpc-client.rs: tonic GrpcClient — persistent StreamEvents manager
  (reconnect via 1s tryConnect polling, 5s first-data watchdog, 10s
  heartbeat, session-change resubscribe), deadline-bounded unary calls,
  run bookkeeping (agent_start/end, queued runs, lost-queued-run recovery),
  typed RpcSessionState/SessionSummary/RunAck parsing (camelCase + legacy
  snake_case TerminalAck keys, null-tolerant fields)
- app.rs: the App — slash-command dispatch (/model /sessions /tree /fork
  /new /clone /status /scoped-models /cwd /approve /reject /stop /cancel
  /compact /reload /name /help + unknown-command fallthrough), overlays
  (SelectList/ScopedModelsSelector/help) with UiCmd-routed callbacks,
  agent-event handling (streaming, thinking, tools, usage, approval,
  settings-change), TUI settings persistence (~/.future/tui/settings.json),
  diff-based render pipeline (doRender: full/diff/deleted-lines paths,
  kitty-image tracking, cursor extraction, overlay compositing,
  autocomplete popup placement, 33ms render scheduler + 150ms resize
  debounce + 20ms autocomplete debounce)
- index.rs: 1:1 parseArgs (model:thinking split, -p message capture, @file
  args, --help exits during scanning, unknown-option exit 1), print mode
  (get_state + cfg1..cfg8 + StreamEvents + prompt), list-models table
  (get_available_models, K/M suffixes), interactive event loop
  (input/events/op-cmds/connection-changes/timers select)
- terminal.rs: optional SIGINT/SIGTERM callback (graceful stop instead of
  restore-and-re-raise)
- tui.rs: Component gains as_any_mut + set_component_focused helper
- All async client ops run as tasks reporting UiCmds (no &mut self held
  across awaits); overlay/keybinding/input callbacks route through UiCmds

Verified: help/version/unknown-option byte-identical to TS; --list-models
surfaces the same agent errors; interactive smoke under a real PTY
(startup, welcome render, /export slash dispatch, clean Ctrl+C exit).
407 unit tests (was 362); workspace 1888 passed / 0 failed; clippy -D
warnings + fmt clean.
…ous connection-lost flap

PTY smoke testing of the P3 app loop against a live agent revealed the
Rust client flapping "⚠️ Connection to agent lost — retrying every 1s..."
right after the welcome screen (TS shows nothing). Two divergences from
grpc-client.ts:

1. Watchdog re-armed on every event. TS arms the 5 s connect watchdog
   once at subscribe time and clears it on the FIRST data event
   (`if (connectWatchdog) { clearTimeout(...) }`) — it is never
   re-armed; long-term dead-stream detection is the 10 s heartbeat's
   job. The port reset the watchdog on every event, so an idle stream
   (no events flowing) fired it 5 s after startup and tore the
   connection down. Fixed with a select precondition: the watchdog arm
   is disabled once the first event arrives.

2. Poke-driven resubscribe notified false. TS connectEvents() cancels
   the old stream and its stale end/error handlers are ignored
   (`this.streamCall !== call` guard), so a session change /
   explicit connectEvents is a SILENT resubscribe — no false
   notification, `connected` stays true. The port's subscribe_stream
   returned on any poke and the manager then unconditionally sent
   conn_tx(false), showing "Connection lost" on every /new /session
   change. Fixed with a StreamExit enum (Lost vs Poked): Poked loops
   straight back to resubscribe without notifying.

Regression tests: in-process mock FutureAgent server (tonic) driving
the real stream manager — idle_stream_does_not_flap_after_first_data
(6.2 s idle > 5 s watchdog, must stay connected) and
session_change_resubscribes_silently (session change must not notify
false). Both fail against the pre-fix mutations, pass now. Requires
build_server(true) in tonic-build codegen (+239 lines generated).

Verified: PTY smoke (startup, /export slash dispatch, Ctrl+C exit)
shows zero connection flaps and byte-matches TS behavior; 409 tests;
render parity 97/97; clippy -D warnings + fmt clean.
Drives the TS and Rust TUIs side by side in tmux panes against
deterministic mock agents (examples/mock_agent), byte-compares
capture-pane screens at each scenario, and records goldens.

Scenarios: welcome, typed input, streamed reply, /status, /help,
/model, /sessions (overlay open + Escape closed), Ctrl+C exit parity.

Bugs the harness caught and fixed:
- footer token stats: JS truthiness skips zero values (Some(0) rendered
  'R0 W0' before; P1 parity only used non-zero data)
- /status overlay: '**Session:** X or (none)' always appended the
  fallback; TS renders 'X || (none)' either-or. Same for '**Model:**'.

Makefile: build-tui-rust, test-tui-tmux (wired into test), lint help.
Port report to docs/verification/tui-rust-port-acceptance.md: divergence
list, known/accepted divergences, test matrix, bugs caught by the
harnesses, commit inventory, and gate rerun commands.
…m CI gate

The CI 'Rust build (Windows)' check failed on the POSIX-only terminal
backend (termios/ioctl/sigaction/poll don't exist on windows-msvc).
Split terminal.rs into a shared orchestration shell + platform backends:

- terminal_posix.rs (cfg unix): the previous implementation, moved
  verbatim — raw mode flag ops, TIOCGWINSZ, sigaction+self-pipe, poll(2)
- terminal_windows.rs (cfg windows): windows-sys console API — raw mode
  via SetConsoleMode (clears ENABLE_PROCESSED_INPUT/LINE_INPUT/ECHO_INPUT,
  sets ENABLE_VIRTUAL_TERMINAL_INPUT|ENABLE_WINDOW_INPUT), VT processing on
  output, GetConsoleScreenBufferInfo size, WaitForSingleObject input waits
  with window-size-event → resize detection, ReadFile/WriteFile byte IO
- shared Terminal: reader-thread loop dispatches a unified ReadWait
  {Input, Timeout, Resize, Signal} so kitty query / modifyOtherKeys
  fallback / StdinBuffer flush / drain_input / exit failsafe are
  platform-neutral

Windows backend is type-checked via cargo check --target
x86_64-pc-windows-msvc (CI's 3-platform gate); runtime-testing on a real
Windows console is a follow-up (documented in terminal_windows.rs header).

Re-verified after refactor: tmux screen consistency 11/11, render parity
97/97, 411 unit tests, workspace clippy -D warnings + fmt clean, and
cargo check -p tui-rust --target x86_64-pc-windows-msvc now passes.
The startup banner showed a '[Context]' section listing context-file
basenames when the agent reported any context files. Remove it from both
the TS reference (tui/src/app.ts) and the Rust port (app.rs) — the
contextFiles state is still tracked for /status and reload events, only
the welcome-screen display is gone.

Verified: tsc --noEmit clean, 411 unit tests, clippy/fmt clean, tmux
screen consistency 11/11 unchanged (mock sends empty contextFiles, so no
golden churn).
# Conflicts:
#	Cargo.toml
#	Makefile
…ode harnesses, future-rpc consumption

Same retirement as the CLI (#115): the TS TUI sources are deleted and the
Rust crate moves from tui/rust/ to tui/ (bin future-tui). The TS render
outputs were recorded into tui/tests/golden/parity-ts.golden BEFORE the
deletion, and the tmux goldens (also recorded from the TS pane) are now
verified against the Rust TUI alone — the goldens are the reference.

- tui/: Cargo.toml, build.rs (version injection only), RESEARCH.md, src/,
  examples/, scripts/, tests/ promoted one level; TS sources, package.json,
  tsconfigs, render-parity.ts deleted
- harnesses → tui/tests/: diff-ts-rust.sh = Rust renderer vs parity-ts.golden
  (--record rewrites); tmux-diff.sh = single Rust pane vs goldens (--record
  rewrites), no bun/TS, one mock agent
- crate consumes future-rpc::proto (single proto codegen owner, PR #112):
  own src/generated/ + tonic-build codegen dropped; imports + mock-server
  tests migrated; RpcResponse payload: None in constructors
- Makefile: build-tui/test-tui/lint-tui/run-tui/install-tui all cargo;
  test-tui alias → test-tui-rust; clean targets updated
- ci.yml: tui job keeps the ruleset-pinned name 'TUI typecheck + test' but
  runs cargo test -p tui-rust + the golden harness (no node/bun)
- docs: build-and-install (en+zh) Windows TUI steps → cargo;
  docs/tui.md source ref → app.rs; RESEARCH.md + acceptance report updated;
  package.json workspaces left as-is (npm tolerates missing dirs, same as
  the cli retirement)

Verified: 411 unit tests, workspace tests all green, clippy -D warnings +
fmt clean, golden render parity 97/97, golden tmux 11/11 (incl. Ctrl+C
exit 0), cargo check -p tui-rust --target x86_64-pc-windows-msvc passes.
… Rust Core scope

- Multi-Interface + intro: 'Feishu, and DingTalk' → 'IM bots' (and zh
  飞书/钉钉 → IM 机器人) — messaging platforms are now implementation
  details, not headline names
- 'channel bridge' → 'IM channel bridge' (zh 渠道桥 → IM 渠道桥) in the
  Rust Core row and the Linux build-component list
- Rust Core row now covers the full Rust surface: agent, IM channel
  bridge, loop control plane, CLI (future), and TUI (future-tui) — both
  CLI (#115) and TUI (this PR) are Rust implementations now
…./..

- welcome skills list: the wrapped lines are joined into a SINGLE message
  (TS parity: add(lines.join("\n"))). One message per line rendered
  blank lines between the wrapped segments — visible when the skills list
  is long enough to wrap; the mock's 2-skill payload never wrapped, so the
  tmux goldens didn't catch it. New regression test asserts the wrap
  happens inside one message with no empty lines.
- /cwd: lexically resolve ./.. components (std::path::Component walk,
  clamping at the root like 'cd ..' at /) before sending to the agent —
  the agent stores the path verbatim after a trailing-separator trim, so
  '/cwd ../../' previously left an unnormalized '/a/b/../..' cwd (and
  relative fallbacks could go wrong with an empty session cwd). New pure
  unit tests cover dotdot resolution and root clamping.

413 unit tests (was 411), clippy/fmt clean, golden parity 97/97 + tmux
11/11 unchanged (mock skills don't wrap; welcome screen identical).
@huichen
huichen merged commit 1467a1c into main Aug 7, 2026
17 checks passed
@huichen
huichen deleted the claude/tui-rust-port branch August 7, 2026 04:27
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