Skip to content

feat(cli): Rust CLI replaces TypeScript — byte-identical future (cli/rust → cli/) - #115

Merged
huichen merged 19 commits into
mainfrom
claude/cli-rust-port
Aug 7, 2026
Merged

huichen merged 19 commits into
mainfrom
claude/cli-rust-port

Conversation

@huichen

@huichen huichen commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The Rust CLI is now THE future CLI. 1:1 port of the TypeScript implementation (byte-identical argument parsing, help text, stdout/stderr, exit codes) — the TS code is retired and cli/rust/* was promoted to cli/.

What's included

  • Full port: dispatch, init/auth/account/models/agent status/session/doctor, run (streaming), tools/skills (MCP HTTP+SSE), browser subsystem (chromium CDP + Safari webdriver + selector/input/screenshot) — 194 unit tests, playwright/ intentionally not ported (TS marked it legacy/dead for the CLI path).
  • Retirement: cli/src (TS), package.json, tsconfig.json deleted; Rust crate lives at cli/ (workspace member, bin future), consuming future-rpc for the proto wire contract.
  • Golden test harness (cli/tests/diff-ts-rust.sh): 163 corpus cases recorded from the TS CLI before deletion; check mode builds only the Rust CLI and compares byte-for-byte against the committed goldens (fixed workdir/ports + normalization for agent instance id / relative times / mock CDP ws port). --record re-captures from an old checkout.
  • Build/CI/install: make build-cli / install-cli / run-cli → cargo; GUI sidecars + portable packages built via cargo in build*.yml and the dmg/Windows scripts; CI cli job = cargo test -p cli-rust + golden harness; docs updated (en/zh).

Verification

Gate Result
Golden harness (Rust vs recorded TS goldens) 163 / 163
cargo test -p cli-rust 194 passed
cargo test --workspace 1735 passed / 0 failed
cargo clippy --workspace --all-targets -- -D warnings clean
cargo fmt --check clean
Real-environment parity (pre-retirement) 53/53 byte-identical vs TS incl. live agent/platform/browser + real run

Accepted divergences (documented, transport-error wording only): gRPC-down phrasing (tonic vs grpc-js → agentdown prefix mode), unreachable HTTP URL (excluded), browser status unreachable endpoint (covered via fixed-message snapshot case). Full list: docs/verification/cli-rust-port-acceptance.md.

Notes

  • TUI remains TypeScript (separate port effort); Bun/Node still needed for TUI + GUI.
  • CI impact: rust-quality/rust-tests/rust-build (3-platform) + reworked cli job; gui/tui checks auto-skip where unchanged.

chenhui added 12 commits August 6, 2026 21:18
…nt (P0)

Create cli/rust as a workspace member (bin name `future`) — a 1:1 Rust port
of the TypeScript CLI, byte-identical in argument parsing, help text, output,
and exit codes.

- build.rs: opt-in proto regeneration (REGENERATE_PROTO, make generate-proto)
  into src/generated/proto.rs (checked in, no protoc needed for normal builds);
  version injection mirroring scripts/version.mjs (FUTURE_VERSION/GITHUB_REF/
  CI + git count/hash, +local[.dirty]) so --version matches the TS CLI.
- lib.rs dispatch: verbatim port of index.ts main() incl. the auth --url parse,
  agent/models quirks, and per-branch exit codes; commands run through a
  catch() mirroring main().catch (stderr message + exit 1).
- help.rs: verbatim help text (help.ts printHelp + all inline index.ts strings,
  incl. the two distinct auth group-help variants).
- commands/: final dispatch predicates (is_tools/skills/account_command) +
  stub bodies to be filled by P1 (local) / P2 (remote).
- utils/ + constants.rs + types.rs: ports of cli/src/utils/*, constants.ts,
  types.ts (string/object/platform/process/files/time helpers).
- output.rs: injectable stdout/stderr sinks (stdio for the binary, memory for
  golden/diff tests in P4).
- Tests: 17 unit tests (utils + dispatch branches). Verified 30/30 local-only
  dispatch paths byte-identical vs the TS CLI (stdout+stderr+exit code);
  clippy -D warnings and cargo fmt clean on the pinned 1.97.0 toolchain.
…nt/session/doctor (P1)

- init: built-in skill bootstrap + ~/.future/bin linking (init.ts port)
- auth: device-code OAuth login/status/credential/logout + auth.json helpers
- account: profile/balance via MCP API
- models/agent/session: gRPC client over proto/future.proto (tonic/prost)
- doctor: env diagnostics incl. execFile-parity version capture (partial
  output survives the 5s timeout; child killed, no leak)
- 57 unit tests green (incl. hanging-binary partial-version case), clippy clean
- help golden test: every --help/-h path prints exactly the ported help
  text (byte-identical vs TS CLI); session help extracted to SESSION_HELP
- serde_json preserve_order: CLI JSON round-trips (auth.json rewrite,
  session list --json) keep JS insertion order instead of BTreeMap sort
- verified: 58 unit tests green, clippy -D warnings clean, fmt clean
…tform server (P4 groundwork)

- diff-ts-rust.sh: TS (cli/dist/future) vs Rust (target/debug/future) same
  argv, byte-identical stdout/stderr/exit-code comparison under a controlled
  env (fake HOME, fixed FUTURE_VERSION, mock MCP server, agent on dedicated
  port); agentdown mode compares exit code + stdout + stderr prefix (grpc-js
  vs tonic phrasing differs by design, documented)
- mock-platform-server.py: tiny MCP platform stub for auth/account/skills
  HTTP paths
…rgets (P4)

- start_mock: redirect the mock server's stdio away from the command
  substitution pipe — a daemon inheriting it keeps the pipe open and the
  caller's $(...) hangs forever (the http/init/doctor scenarios wedged
  with no output)
- wait_port moved out of start_mock so readiness is checked after the
  substitution returns
- make targets: test-cli-rust (cargo test -p cli-rust), test-cli-diff
  (differential harness); test-cli-diff + cli-rust clippy added to help;
  test umbrella now includes test-cli-rust

Verified end-to-end: 90/90 differential cases byte-identical (static help/
version/error paths, auth/account/init/doctor under fake HOME + mock
platform server, agent status/models/session against a real agent on a
dedicated port), cargo test -p cli-rust 58/58, clippy -D warnings clean.
…ff harness (P4)

A concurrent post-commit rebuild of cli/dist/future (regenerating
version.generated.ts with the leaked FUTURE_VERSION) could clobber the TS
binary mid-corpus, producing bogus --version failures ('-v'/'version'
printed the leaked 0.0.0-ada24aab+local while '--version' passed). Copy the
TS binary into the same $WORK isolation already used for the Rust binary,
and fail fast if either binary doesn't bake the pinned 0.0.0-diff+local.
…wser tool surface (P2)

Ports the remaining CLI command bodies 1:1 from the TypeScript CLI:

- run: full arg parser (model:thinking shorthand, @file prompt building,
  all flags), gRPC orchestration via RunClient::run — session resolution
  (fork/session/continue/fresh), config application, concurrent event
  streaming (tonic server-streaming), text/json output, verbose tool_start
  + error-event stderr writes, notifyAgentRefreshSkills.
- tools: list/describe/call over the MCP HTTP protocol (mcp.rs: mcpPost
  with SSE parsing + mcp-session-id header, initializeSession handshake),
  parseToolArgs with the full cmd.exe/PowerShell quote-stripping recovery
  (tools.test.ts ported 1:1 — 20 tests), TOOL_CATALOG + ERROR_TRANSLATIONS,
  all result formatters incl. image file writes.
- browser tool: catalog/describe surface + start/status (HTTP-only, no CDP)
  + config-state port (v1→v2 migration/validation); session commands are a
  documented P3 gap.
- skills: list (catalog table with installed versions), install (with
  --version and v-stripping), install-builtin, update, uninstall + refresh
  notification.
- 100 unit tests (was 58); clippy -D warnings + fmt clean.

Diff harness: mock server now serves the MCP protocol and a skills catalog
mode with deterministic download zips; 41 new cases (run local-only paths,
tools list/describe/call incl. error translation + validation, skills
stateful scenarios, agentdown run) — 131/131 cases byte-identical.
…elector/input/screenshot (P3)

- chromium/: cdp-transport (WebSocket via tokio-tungstenite), cdp-connection,
  cdp-event-router, chromium-manager/page/session/navigation/screenshot,
  target-registry, execution-context, console-hook, endpoint discovery
- safari/: webdriver-client + safari-manager/session (webdriver protocol)
- selector-resolver, tab-order, browser-state (v1→v2 config migration),
  browser-discovery, input (keyboard/mouse), screenshot-writer, windows-process
- browser tool: session commands (start/status/snapshot/click/type/press/
  scroll/screenshot/console/tabs) over CDP — closes the P2 browser-tool gap
- playwright/ NOT ported: TS marks it a legacy wrapper slated for deletion,
  unreferenced by the CLI runtime path (default factory = chromium+safari);
  only TS test infra uses it
- 194 unit tests green (was 100), clippy -D warnings + fmt clean; browser
  status output byte-identical vs TS (tsx)
…/163 diff, 1675 workspace tests, clippy -D warnings clean
Comment thread cli/tests/mock-platform-server.py Fixed
Comment thread cli/tests/mock-platform-server.py Fixed
Comment thread cli/tests/mock-platform-server.py Fixed
Comment thread cli/tests/mock-platform-server.py Fixed
chenhui added 3 commits August 7, 2026 09:11
…ed twice (CI #115)

Windows cargo check failures caught by CI's rust-build (Windows) leg:
- init.rs: tokio::fs::symlink does not exist on Windows (unix-only cfg in
  tokio) — route through a cfg'd create_symlink helper
  (std::os::windows::fs::symlink_file); init never reaches it on Windows
  (platform guard) but it must still compile.
- browser/discovery.rs find_windows_browser: prog (PROGRAMFILES) was moved
  into the first .map closure and reused in a later candidate — use as_ref.

macOS host cannot compile the windows-only paths; fixed by inspection, to be
confirmed by CI. Local gates still green (fmt/clippy clean, 194 tests).
…en-based tests

The Rust CLI is now THE CLI. cli/ contains only the Rust crate (bin
'future'); the TypeScript implementation (cli/src, package.json,
tsconfig.json) is deleted.

- cli/rust/* promoted to cli/ (Cargo.toml build.rs src/ tests/);
  workspace member path updated, future-rpc path dep adjusted
- diff harness converted to golden mode: recorded the TS CLI's output for
  all 163 corpus cases into cli/tests/golden/ before deletion; check mode
  builds only the Rust CLI and compares byte-for-byte against the goldens
  (fixed workdir + fixed mock ports + normalization for agent instance id,
  relative times, mock CDP ws port; --record re-captures from an old
  checkout)
- Makefile: build-cli/install-cli/run-cli = cargo; test-cli = rust tests;
  test-cli-diff drops node-workspace; lint-cli = fmt + clippy; gui-sidecars
  stage target/release/future
- CI: cli job = cargo test -p cli-rust + golden harness (no node/bun);
  build*.yml sidecars + portable packages built via cargo; dmg/windows
  scripts updated; build-and-install docs (en/zh) updated
- verified: workspace tests 1735/0, clippy -D warnings clean, fmt clean,
  golden harness 163/163, make build-cli/test-cli/lint-cli green, release
  binary smoke-tested against the live agent
@huichen huichen changed the title feat(cli): Rust port of the TypeScript CLI — cli/rust, byte-identical future feat(cli): Rust CLI replaces TypeScript — byte-identical future (cli/rust → cli/) Aug 7, 2026
Comment thread cli/tests/mock-platform-server.py Fixed
Comment thread cli/tests/mock-platform-server.py Fixed
Comment thread cli/tests/mock-platform-server.py Fixed
Comment thread cli/tests/mock-platform-server.py Fixed
chenhui added 3 commits August 7, 2026 10:33
…deps to cli job

- golden scenario dirs home:auth / http:errors / init:linked / skills:installed
  etc. contain ':' — an invalid path char on Windows that failed the
  rust-build (Windows) checkout entirely. The harness now maps scenario
  names to on-disk names via golden_dir() (':' -> '_'); recorded dirs
  renamed accordingly.
- the reworked 'CLI tests + golden diff' job was missing the Linux linker
  toolchain (.cargo/config.toml pins -fuse-ld=mold): add build-essential /
  binutils / mold / pkg-config / libssl-dev.
- golden harness re-verified 163/163 with the mapped dirs.
…ignore cli/tests/golden/**

The 163 corpus reference outputs were recorded as <idx>.out files but
'.gitignore' line '*.out' silently excluded them from the restructure
commit (only .argv/.code/.err shipped) — the golden harness then failed
with 'no golden .../0.out' on CI. Add a scoped negation.
- drop unused PORT global (handlers read MODE directly)
- document the intentional empty excepts (client-disconnect races)
@huichen
huichen enabled auto-merge (squash) August 7, 2026 03:24
…Main ruleset

The required_status_checks rule in the 'Protect Main' ruleset lists the
exact context 'CLI typecheck + test'; the reworked Rust CLI job had been
renamed to 'CLI tests + golden diff', so the required check could never
report success and every PR was permanently blocked (mergeable_state:
blocked). Keep the new job body (cargo test + golden harness), restore the
pinned name.
@huichen
huichen merged commit d43460c into main Aug 7, 2026
17 checks passed
@huichen
huichen deleted the claude/cli-rust-port branch August 7, 2026 03:32
huichen pushed a commit that referenced this pull request Aug 7, 2026
…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.
huichen pushed a commit that referenced this pull request Aug 7, 2026
… 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
huichen added a commit that referenced this pull request Aug 7, 2026
* feat(tui): Rust port P0 scaffold — RESEARCH.md, workspace crate (bin 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

* feat(tui): Rust port P1 — components layer (input/autocomplete/select-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)

* test(tui): port display-fixes Input.setValue cursor tests (moves to end by default, honours explicit position)

* feat(tui): Rust port P2 — markdown/chat-area/terminal-image + TS-vs-Rust 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.

* feat(tui): Rust port P3 — gRPC client, App orchestration, CLI entry (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.

* fix(tui): silent resubscribe + one-shot connect watchdog — kill spurious 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.

* feat(tui): Rust port P4 — tmux screen-consistency harness + golden tests

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.

* fix(tui): tmux-diff harness trap kills mock agents — no orphaned processes after verify/record runs

* docs(tui): tui-rust-port final acceptance report (P4 delivery)

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.

* feat(tui): add Windows terminal backend (windows-sys) — fix 3-platform 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.

* feat(tui): drop the [Context] block from the welcome screen

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).

* feat(tui): retire TypeScript TUI — promote tui/rust to tui/, golden-mode 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.

* docs(readme): Feishu/DingTalk → IM bots, channel → IM channel, expand 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

* fix(tui): skills welcome wrap joins into one message; /cwd resolves ../..

- 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).

---------

Co-authored-by: future-agent <[email protected]>
Co-authored-by: chenhui <[email protected]>
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