Repository navigation
feat(rpc): typed-RPC wire contract — consolidate codegen, dual-write typed payloads, adopt @future-os/rpc - #112
Merged
Merged
Conversation
First batch of the typed-RPC milestone (audit rec #1 / P1 #2): create the future-rpc workspace crate that owns the generated proto code for proto/future.proto, emitting both tonic server and client modules. The per-crate checked-in copies in agent/, channels/ and gui/src-tauri/ stay untouched this batch — consumers migrate in later batches. - build.rs regenerates under REGENERATE_PROTO=1 (same opt-in pattern as the existing crates); output checked into src/generated/proto.rs so normal builds never need protoc - smoke tests cover RpcResponse/StreamEvent wire round-trip - README records the contract rules (field-number stability, payload field 20, one-way dependency direction, gui version alignment) Zero behavior change: the crate has no consumers yet. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 2 of the typed-RPC milestone: pure move of the big-read-command payload structs from agent/src/rpc/payloads.rs into the future-rpc crate, preparing the shared decode layer. - All structs gain Deserialize alongside Serialize plus serde aliases for the legacy snake_case spellings, so both the agent's encode path and the clients' JSON fallback land in the same types (parity by construction) - New strip_legacy_aliases helper: the migration window dual-writes canonical + legacy keys and serde rejects duplicate field names, so decoders strip duplicates before deserializing (aliases still accept legacy-only JSON from pre-migration agents) - replay_event_payload splits: the crate keeps the wire struct, the agent keeps the SseEvent→payload adapter (SseEvent is agent-internal) - agent re-exports future_rpc::payloads; all 14 call sites compile unchanged Tests: the file's existing unit tests move with it; added dual-casing round-trip (inject → strip → deserialize → re-serialize equals canonical) and legacy-only decode coverage. Zero behavior change: the agent emits identical JSON. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 3 of the typed-RPC milestone: the wire schema for the migration. Purely additive — all existing field numbers untouched, no consumer breaks. - RpcResponse.payload (ResponsePayload) with 16 typed response members: the four big reads (get_state/list_sessions/get_session_entries/ get_events_since, reusing the former doc-only messages) plus prompt ack, list_models, get_agent_info, get_commands, compact, shell, cycle_model, sync_future_models, refresh_skills, get_session_events_since, get_session_stats, get_runtime_metrics - EventPayload shared by StreamEvent/ProjectedRunEvent/ReplayEvent (all at field 20) with 14 typed event kinds — one member list decoded identically on live, replay and projection-snapshot paths - ApprovalRequestInfo extended with the full approval card (risk_level, summary, requested_action, sandbox_boundary, save_suggestion, reviewer, extras catch-all) so the event and get_state pendingApprovals share one message - null-semantics fields promoted to proto3 optional (wire-compatible): RunStateSnapshot.epoch/run_sequence/last_event_idx, RunTerminalInfo.error, SessionSummary.session_name/first_message, SessionEntry.thinking/meta/ tool_calls/output_tokens/duration_ms; SessionEntry gains content_is_object so decoders can re-inflate content into the exact original JSON value - Only future-rpc's generated code is regenerated this batch; agent/ channels/GUI keep their checked-in copies until their adoption batches Tests: typed oneof round-trip (RpcResponse with SessionState payload, StreamEvent with ToolEnd payload). Full workspace gate green; no behavior change (no consumer reads the new fields yet). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ands Batch 4 of the typed-RPC milestone: the codec goes live and the agent becomes the first consumer of future-rpc. future-rpc: - encode.rs: JSON payload Value -> typed ResponsePayload for get_state / list_sessions / get_session_entries / get_events_since. Defensive by contract: unknown commands or shape mismatches return None so clients fall back to the JSON `data` string; nothing panics. Value-typed fields travel as serialized-JSON strings (source_meta, entry content/ meta/tool_calls, approval action/requested_action/sandbox_boundary/ save_suggestion + an extras catch-all) and are re-inflated on decode; SessionEntry.content_is_object discriminates display text from the session_info object. - decode.rs: response_data (typed-first, JSON fallback, canonical dual-casing Value with the migration aliases re-injected so downstream consumers see exactly what `data` carries) + typed getters (decode_get_state / decode_list_sessions / decode_session_entries / decode_events_since). - parity.rs: wire-parity round-trips for all four commands (encode -> typed -> decode == original fixture) across the full fallback matrix: dual-write, data-only (old agent), typed-only (future). Fixtures pin null-vs-absent semantics (interrupted run's runSequence null, epoch omitted), object source_meta, a full approval card, session_info object content and projection snapshots. agent: - grpc/mod.rs now re-exports future_rpc::proto (single codegen owner); the checked-in generated copy and the build.rs codegen block are gone. - execute_command dual-writes: RpcResponse.payload populated via future_rpc::encode alongside the unchanged JSON `data`. - StreamEvent / ProjectedRunEvent construction sites gain payload: None (event typing lands in a later batch). - New test proves the agent's real read-command envelopes always encode. proto: SessionState.session_file/session_id/session_name/ parent_session_id promoted to optional (wire-compatible) to preserve their null-vs-absent JSON semantics. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batches 5+6 of the typed-RPC milestone (merged — same mechanical codec work): prompt ack, list_models, get_agent_info, get_commands, compact, shell, cycle_model, sync_future_models, refresh_skills, get_session_stats, get_runtime_metrics, get_session_events_since. All 16 ResponsePayload members now dual-write. - payloads_ext.rs: serde carriers for the ad-hoc json! shapes, lifted so encode and decode share one definition. Wire casing preserved per command (camelCase; prompt ack and refresh_skills stay snake_case). null-vs-absent pinned exactly: runtime-metrics activeRunId/ eventJournalError serialize as JSON null (the agent emits null, not omission, for Option fields built with json!), cycle_model isScoped is omitted on the empty-catalog edge, session-stats cost rides as a raw JSON number so the int-vs-float representation survives the JSON path. - RunAck/RunAcceptedState move from agent runtime into the crate (agent re-exports; BusyPolicy stays agent-side as command input). - encode.rs/decode.rs gain the 12 new command arms; decode exposes typed getters (decode_prompt_ack / decode_list_models) with JSON fallback. - proto: ModelEntry.description/description_en and Command.name_zh/ description_zh promoted to optional (the catalog/skill fields are Option on the agent side and emit JSON null — parity pins it), fixtures cover the null cases. - Agent test now proves every real sessionless + session-scoped read envelope encodes (get_agent_info, list_models, get_commands, refresh_skills added alongside the batch-4 set). Untyped commands (trivial acks, get_messages/get_fork_messages) stay on the JSON `data` string by design; clients fall back automatically. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 7 of the typed-RPC milestone: the streaming half of the wire contract. The agent now dual-writes StreamEvent.payload / ProjectedRunEvent.payload / ReplayEvent.payload alongside the unchanged JSON `data` string, on the live stream, the atomic-attach replay tail, and projection snapshots. - event_payloads.rs: serde carriers for the event vocabulary (text_chunk, user_message, thinking_start/delta/end, agent_start/end, tool_start/ delta/end, usage, error, approval_decision). skip_serializing_if mirrors the broadcast serializer exactly — it omits empty strings and absent optionals, and injects a redundant `type` key that the typed form drops (every consumer keys off the envelope type). - encode.rs: event_payload() parses the event `data` JSON into the typed oneof; pass-through events (settings, ping, tool_sandboxed, ...) return None and stay JSON-only. Replay events are typed too via the same path, so reconnect/replay decode matches live. - decode.rs: event_data / event_data_json (+ projected/replay variants). Byte-stability first: during the migration window the original `data` string wins verbatim (GUI journal + NATS republish must not change); the typed reconstruction takes over only when `data` is absent. - agent grpc/mod.rs: map_broadcast_event, the attach-replay tail, and the projection-snapshot builder all populate the typed payload. - Parity fixtures cover all 14 kinds incl. agent_end sparse/full/incomplete shapes, tool_end exit-code/soft-fail/target-path semantics, usage with optional provider fields, both error variants, and the tool_args object-vs-JSON-string forms; a budget test pins text_chunk encode under 5µs/event (measured well below 1µs). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 8 of the typed-RPC milestone: the channel bridge becomes the first client on the shared wire contract. - grpc_client.rs consumes future_rpc::proto (re-exported under the historical module name); the checked-in channels/src/generated/proto.rs copy is deleted and build.rs no longer codegens future.proto (feishu_ws stays, so tonic-build drops out of the build-deps). - call() decodes through future_rpc::decode::response_data — typed payload first, JSON `data` fallback — so every command reads identically against old and new agents. - AgentClient::parse_event now delegates to future_rpc::events:: parse_agent_event; the AgentEvent enum and its parser moved into the crate so every future client decodes events the same way. The parser is typed-first with the JSON fallback; tool_args keeps its wire semantics (string-form only) on both paths. - expand_projection_snapshot carries the typed payload through, so reconnected/replayed events decode through the same path as live ones. - Parse tests moved to the crate, where each case now runs as twins: the JSON-data event (old agent) and the typed-payload event (new agent). Channels keeps projection-expansion, SessionState and ImageInput tests, plus a delegation smoke test on both wire states. - The (ignored, live-agent) integration test switches to future_rpc proto + decode instead of its private generated copy. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 9 of the typed-RPC milestone: the GUI Tauri backend joins the shared wire contract (largest consumer — boundary bridge strategy, not per-site typed migration, so every deep read keeps its exact shape). - agent_proto.rs re-exports future_rpc::proto under the historical paths; the checked-in src/generated/proto.rs and the build.rs codegen block are deleted (future-rpc is the single codegen owner; path dependency with aligned tonic/prost versions). - All unary response parses (remote-bridge pass-throughs, get_state deep reads for crash reconcile/watchdog, prompt ack, sync_future_models, models/skills typed structs, session ensure/entries, import, approval reconcile, run control, observer probes) now go through future_rpc::decode::response_data — typed payload first, JSON `data` fallback — returning the same canonical dual-casing Value the deep reads already expect. - Event pipeline (stream.rs persistence + fold, observer.rs forward/ persist/NATS mirror, remote snapshot republish) routes through event_data_json / projected_event_data_json: byte-stable while the agent dual-writes `data` (the original string wins verbatim), typed reconstruction takes over automatically once `data` is retired. - The observer's get_session_events_since reconstruction populates the typed payload so replayed session events decode like live ones. - New wire_decode_tests pin the GUI-facing guarantees: typed/data parity, old-agent fallback, dual-write byte stability, and typed reconstruction without `data`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 10 of the typed-RPC milestone: the codegen entry points match the new single-owner layout. - `make generate-proto` now regenerates future-rpc (future.proto — server + all clients) and channels (feishu_ws only) plus the TUI embedded proto; the retired agent / gui/src-tauri regeneration lines are gone. - CI rust-quality gains a "proto codegen is fresh" gate: regenerate under REGENERATE_PROTO and `git diff --exit-code` the checked-in generated files, catching proto edits that skipped `make generate-proto` (deterministic for the pinned prost/tonic-build). Verified: a clean-room regenerate of future-rpc + channels is byte-identical (no diff). The TUI/CLI embedded proto syncs when the TS clients adopt the shared package (next batches). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 11 of the typed-RPC milestone: the TypeScript half of the shared contract, mirroring the Rust future-rpc crate. Standalone and additive — no client consumes it yet (adoption is the next batches). - shared/future-rpc: proto.ts (EMBEDDED_PROTO + a loader configured exactly as the TUI/CLI have always loaded it: camelCase, int64→String, enums→String, defaults, oneofs), decode.ts (responseData / streamEventData — JSON `data` first for migration-window shape parity, typed `payload` oneof as the post-`data` fallback), types.ts (merged superset of the duplicated tui/cli payload types), index.ts. - scripts/generate-proto.ts embeds proto/future.proto into EMBEDDED_PROTO; `make generate-proto` now refreshes it alongside the Rust codegen. - decode unit tests cover data-parse, type-key stripping, and the typed oneof fallback. .gitignore covers shared dist/node_modules. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to the @future-os/rpc scaffold: - generate-proto.ts now anchors on an explicit __EMBEDDED_PROTO_END__ marker instead of a bare backtick-semicolon; future.proto comments legitimately contain backticks and a "`;" sequence, which truncated the EMBEDDED_PROTO template literal on regeneration. - proto.ts: marker-anchored EMBEDDED_PROTO plus loadGrpcAgentProto(), the drop-in grpc.loadPackageDefinition(...).proto replacement the TUI/CLI will adopt. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Prepares TUI/CLI to consume the @future-os/rpc wire-contract package. A single root package-lock.json replaces the per-package lockfiles (gui and mobile keep their own installs — separate toolchains). Node modules hoist to the repo root; @future-os/rpc resolves via workspace symlink. Baseline verified: tui and cli typecheck clean under the new install model. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Makefile: a node-workspace target installs the root npm workspace and builds shared/future-rpc; build/test/lint for tui+cli depend on it (gui/mobile keep their per-directory installs). CI: tui/cli jobs run a single root `npm ci`, build shared/future-rpc before typecheck, and cache the root package-lock.json. The changes filter now also triggers tui/cli on shared/future-rpc/** and root manifest edits. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 12 of the typed-RPC milestone. The TUI's grpc-client drops its ~770-line EMBEDDED_PROTO copy and the local proto-loader/resolveProtoPath plumbing in favour of the shared wire-contract package: - proto comes from loadGrpcAgentProto() (@future-os/rpc), the single source of truth for the schema and its loader options. - unary responses decode through responseData(); stream events through streamEventData() — both read the typed payload oneof when present and fall back to the JSON `data` string during the migration window. - tui/scripts/generate-proto.ts now only refreshes the CLI's embedded proto (deleted once the CLI adopts the package in batch 13). The TUI's embedded proto is regenerated via shared/future-rpc/scripts/generate-proto.ts. Verified: tui tsc clean, 162 bun tests pass, `bun build --compile` bundles the workspace package (148 modules), and the standalone binary loads the proto and reaches the gRPC connect step at runtime. Also re-syncs the CLI's embedded proto with the payload-extended schema. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… clients Batch 13 of the typed-RPC milestone. The CLI's grpc-client drops its ~770-line EMBEDDED_PROTO copy and local proto-loader/resolveProtoPath plumbing in favour of the shared wire-contract package, completing the TS consolidation: - proto comes from loadGrpcAgentProto() (@future-os/rpc); unary responses decode through responseData(), streamed events through streamEventData() (typed oneof first, JSON `data` fallback during the migration window). - tui/scripts/generate-proto.ts is deleted — no TS client embeds the proto anymore; the single EMBEDDED_PROTO lives in shared/future-rpc/src/proto.ts and is refreshed via its own generate-proto (wired into `make generate-proto`). tui's build no longer runs a proto-embed step. Verified: tui+cli tsc clean, 162+108 bun tests pass, both standalone binaries \`bun build --compile\` (bundle the workspace package) and load the proto at runtime; \`make generate-proto\` regenerates Rust + TS code idempotently. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Batch 14 (final) of the typed-RPC milestone: - future-rpc/README.md: full contract reference — single codegen ownership, the typed payload oneofs at field 20, the dual-write migration policy, encode/decode module map, and the field-number/optional/null-semantics rules. - CLAUDE.md: corrects the stale per-crate codegen note and adds the wire-contract conventions (future-rpc ownership, dual-write, decode fallback, field-number stability) for future contributors. Full gate green: root cargo fmt/clippy/test, GUI backend fmt/clippy/test, tui (162) + cli (108) + shared (10) bun tests, and both standalone binaries compile and load the shared proto at runtime. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review fix for the "shared types.ts is dead code" finding: the TUI and CLI local rpc/types.ts are now thin re-exports of @future-os/rpc, making the shared package the single source of truth for TS RPC payload types and removing ~425 lines of duplicated definitions. - shared types.ts gains PermissionLevel (CLI needs it) and legacy snake_case aliases on SessionSummary / RecentTerminalAck. The agent emits both canonical camelCase and legacy snake_case during the migration window, and client code reads a mix, so the shared types model both. Fields read as required (updated_at, run_id) are typed required to match existing call sites. - tui/src/rpc/types.ts and cli/src/rpc/types.ts become `export type * from "@future-os/rpc"`; all existing `from "./types.js"` imports keep working. The unused promptCmd helper is dropped. Verified: tui+cli tsc clean, 162+108 bun tests pass, both standalone binaries build. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Bring the typed-RPC branch up to date with main (loop control plane #97/#107, iOS support #100-106, GUI remote rate-limit #101). Conflicts resolved: - Cargo.toml: workspace members now include both future-rpc and orchestration/loop. - Cargo.lock: took main's lockfile and reconciled future-rpc via cargo. - Makefile: merged .PHONY (install-loop + node-workspace). - .gitignore, gui/remote/mod.rs: auto-merged. - orchestration/loop/src/agent_client.rs: added the same clippy::large_enum_variant allow used in future-rpc, since it generates the same proto and the new payload oneofs trip the lint. Verified: cargo test/clippy/fmt green across the merged workspace; tui+cli tsc clean with 162+108 bun tests passing; GUI backend tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Fixes from the external review of the typed-RPC milestone: P1 — TS typed fallback never fired: proto-loader with defaults:true materializes an absent `data` as "" (not undefined), and decode only checked `!= null`, so the typed `payload` fallback could never fire once the agent stops dual-writing. responseData/streamEventData now treat an empty string as absent. Adds real-loader-behavior tests (typed fallback fires on "" for both unary and stream). The shape-normalization layer (camelCase/int64/inflate parity with the legacy JSON) is deferred to a follow-up. P1 — CI path filters missed future-rpc: rust_workspace and gui_tauri now include future-rpc/** (and proto/** for the GUI path-dep), so edits to the shared crate revalidate the Rust workspace and GUI backend. P2 — build.rs rerun-if-changed: future-rpc and channels build.rs now declare rerun-if-changed on the proto source, so `make generate-proto` after a proto edit is not skipped by Cargo's build-script cache. P2 — stale standalone proto temp file: resolveProtoPath now derives the temp filename from a content hash, so a binary whose embedded proto changed never reads a stale temp file left by an older build. Deferred (flagged, separate work): release pipelines must build shared/future-rpc before the CLI/TUI; Makefile node-workspace staleness. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remaining build-chain fixes from the third-party review: P1 — release pipelines did not build shared/future-rpc/dist: package.json exports point at dist/, which is gitignored, so a fresh runner's `npm ci` left the CLI's `@future-os/rpc` import unresolvable. build.yml, build-macos-signed.yml, build-windows-signed.yml and the local macOS/Windows packaging scripts now install the npm workspace at the root (shared/future-rpc + tui + cli) and run `npm run build` in shared/future-rpc before compiling the CLI. P2 — Makefile node-workspace staleness: the rebuild condition only compared proto.ts, so edits to decode.ts/types.ts/index.ts reused a stale dist. It now rebuilds when any shared/future-rpc/src/**/*.ts is newer than dist. `make clean` also removes the root node_modules and shared/future-rpc/dist. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…re-rpc/ Merge the three wire-contract homes into one directory: proto/future.proto moves to future-rpc/proto/, the future-rpc Rust crate moves to future-rpc/rust/, and the shared/future-rpc TS package moves to future-rpc/ts/. Update every caller: root/agent/channels/gui Cargo.toml workspace members and path deps, loop build.rs proto path, npm workspace + package-lock, Makefile, CI path filters and proto-freshness gate, packaging scripts (dmg + both Windows), .gitignore, and comments/docs. Verified: cargo check --workspace + gui lib, proto regeneration is diff-clean for both Rust and TS, npm build succeeds. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…I lockfile refs Address third-party review of the typed-RPC migration: document that TS clients stay JSON-first until replaced by Rust (no typed normalization planned), so the JSON dual-write is not retired prematurely. Fix `make run-tui`/`run-cli` to depend on node-workspace (fresh checkouts otherwise miss the @future-os/rpc dist build), build the rpc package before the CLI in the GUI test scripts, and point the release workflows' npm cache at the root package-lock.json (cli/package-lock.json was removed). Also align stale `proto/future.proto` path references to `future-rpc/proto/` across comments and docs, and fix resolveProtoPath's dev-checkout candidate range. Co-Authored-By: Claude Sonnet 5 <[email protected]>
… freshness Editing future.proto now revalidates the CLI/TUI jobs (added future-rpc/proto/** to their path filters) and the proto codegen freshness gate regenerates the TS embedded proto and includes future-rpc/ts/src/proto.ts in its git diff --exit-code, so a proto edit can no longer land with stale TS generated code while CI stays green. Co-Authored-By: Claude Sonnet 5 <[email protected]>
The proto codegen freshness gate regenerates the TS embedded proto with `node scripts/generate-proto.ts`, which relies on Node 24's native type stripping. The rust-quality job had no Setup Node step, so the runner's preinstalled node (20/22) would fail to parse the TypeScript and the gate could never pass. Add actions/setup-node@v6 pinned to Node 24. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Co-authored-by: tallcode <[email protected]>
auto-merge was automatically disabled
August 7, 2026 00:20
Head branch was pushed to by a user without write access
Copilot stopped work on behalf of
tallcode due to an error
August 7, 2026 00:21
Copilot stopped work on behalf of
tallcode due to an error
August 7, 2026 00:22
The if/else ext assignment did not match rustfmt 1.97 output, failing `cargo fmt --check` in CI. Co-Authored-By: Claude Sonnet 5 <[email protected]>
tallcode
enabled auto-merge (squash)
August 7, 2026 00:33
This was referenced Aug 7, 2026
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
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]>
huichen
pushed a commit
that referenced
this pull request
Aug 7, 2026
…build future-loop was the last crate generating gRPC code in build.rs on every build, which required protoc on PATH. Now that the unified `future` CLI depends on future-loop (cli/Cargo.toml), any CLI build — including CI's `cargo test -p future-cli` — failed without protoc installed. Switch agent_client.rs to future_rpc::proto (the single proto codegen owner, PR #112) like agent/channels/cli/tui already do; delete build.rs and the prost-build/tonic-build/prost build deps. protoc is optional again for all normal builds.
huichen
added a commit
that referenced
this pull request
Aug 7, 2026
…slim build/install, future-* crate names (#116) * feat(cli): unified `future` entry — embed agent/tui/channel/loop, slim build/install surface `future <cmd>` is now the primary entry for every Rust component: future agent|tui|channel|loop <args> (same code as the standalone binaries, which remain buildable via cargo and runnable via make run-*) - cli: dispatch embedded components before the CLI runtime (they build their own tokio runtimes); the old `future agent status` group is removed - agent/tui/channel/loop: entry points moved into their libs so each runs standalone or embedded; loop error hints adapt the program name - crates renamed to future-*: tui-rust->future-tui, cli-rust->future-cli (lib cli_rust->future_cli); all -p tui-rust/-p cli-rust refs updated - Makefile: build = build-cli build-gui; install = install-cli install-gui install-skills (loop skill folded into install-skills); deleted install-nogui/agent/tui/channels/loop and build-agent/tui/channels/loop - GUI bundles a single Tauri sidecar (future) — the agent starts via `future agent`; agent serde_json preserve_order made explicit so the session-list JSON key order is deterministic across build modes - test targets de-rust-ified (test-cli/test-tui, was test-cli-rust/-tui-rust); golden harnesses renamed diff-ts-rust.sh -> golden-diff.sh (TS retired; --record now recaptures from the Rust CLI) - docs: README, build-and-install, loop-control-plane, tui, wiki, installers, portable readmes all updated to the unified CLI * fix(loop): consume future_rpc::proto instead of generating proto per-build future-loop was the last crate generating gRPC code in build.rs on every build, which required protoc on PATH. Now that the unified `future` CLI depends on future-loop (cli/Cargo.toml), any CLI build — including CI's `cargo test -p future-cli` — failed without protoc installed. Switch agent_client.rs to future_rpc::proto (the single proto codegen owner, PR #112) like agent/channels/cli/tui already do; delete build.rs and the prost-build/tonic-build/prost build deps. protoc is optional again for all normal builds. * fix(gui): clippy single-element-loop in sidecar placeholder build script --------- Co-authored-by: chenhui <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Milestone: replace the legacy JSON-in-string gRPC contract with a typed wire contract, consolidated into a single
future-rpc/home.RpcResponse.payload/StreamEvent.payload(field 20) now carry typedoneofpayloads for the Tier-1 commands/events; the agent dual-writes the typedpayloadand the legacy JSONdataduring the migration window. Rust clients decode typed-first with JSON fallback; TS clients stay JSON-first until replaced (no typed normalization planned).future-rpcis the one Rust crate generating proto code (server + all clients). The per-crate copies inagent/,channels/,gui/src-tauri/are retired.proto/future.proto, the Rust crate, and the TS package now live underfuture-rpc/{proto,rust,ts}(previously split acrossproto/,future-rpc/,shared/future-rpc/). All callers updated: Cargo workspace/path deps, loop build.rs, npm workspace + lockfile, Makefile, CI filters and proto-freshness gate, packaging scripts (dmg + Windows), gitignore, comments/docs.future-rpc/ts), built before their tsc in CI and the Makefile.Wire-contract policy (documented in CLAUDE.md)
datafallback.payloadfallback is best-effort raw output.datadual-write is retired only after the TS clients are replaced by Rust implementations — not merely "all clients read typed".optionalmarks fields whose JSON distinguishes null/absent.CI coverage
future-rpc/proto/**added to path filters).proto codegen is freshgate regenerates Rust (future-rpc,channels) and the TS embedded proto, failing on any diff — so a proto edit can no longer land with stale generated code while CI stays green.Test plan
cargo test --workspace(agent/channels/future-rpc/loop) ✅ 852 passedcargo test --libGUI Tauri backend ✅ 188 passedcargo clippy --workspace --all-targets -D warnings+ GUI backend ✅cargo fmt --check(workspace + GUI) ✅@future-os/rpcbuild ✅, CLI tsc + 108 bun tests ✅, TUI tsc + 167 bun tests ✅🤖 Generated with Claude Code