The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(tui): add minimal mouse-driven conversation UI
Steven Enamakel36f6db73c6be
diff --git a/crates/openhuman-tui/README.md b/crates/openhuman-tui/README.mdindex d6e1199891..9697a3308a 100644--- a/crates/openhuman-tui/README.md+++ b/crates/openhuman-tui/README.md@@ -1,245 +1,148 @@# openhuman-tui-The standalone terminal client for OpenHuman, built on [ratatui]. It boots the-core inside its own process, with no HTTP server and no sockets, and gives you-four tabs (Logs, Chat, Config, Settings) plus a slash-command cockpit for-threads, models, permissions, approvals, plan review, agents, skills, MCP-servers, artifacts and Git review. Chat uses the same `web_chat` surface the-desktop app drives, so a turn here behaves like a turn in the app. It ships as-the `openhuman-tui` binary next to `openhuman-core`.--## How it works--### Startup--`main.rs` calls `init_crash_reporting()` (a Sentry client when the-`crash-reporting` feature is on) and keeps its guard alive, then calls-`run_from_cli` with the arguments. `runner.rs` does the rest, in order:--1. Loads `.env` (`embed::process::load_dotenv_for_cli`) and applies any- startup restart delay.-2. Parses flags. `--help` prints usage and returns before anything boots; an- unknown `-` flag is an error.-3. Sets transient provider and model overrides- (`embed::process::set_transient_inference_overrides`).-4. Starts file-only logging under the data dir- (`embed::process::init_for_tui`). The TUI owns the terminal, so nothing is- written to stderr from here on.-5. Initializes the keyring master key.-6. Builds `embed::process::tokio_runtime()`, a multi-thread runtime with the- core's `AGENT_WORKER_STACK_BYTES` stack size, so nested agent turns do not- overflow the default 2 MiB stack.-7. Inside the runtime (`async_main`): boots the core with- `openhuman_rpc::host::tui()` — the embed `tui` preset (every domain, no- background services), connected to the TinyHumans backend, with the- on-disk session store — and keeps the returned `Runtime` alive for the- session. The screens drive it through `Runtime::core_runtime()`- (`CoreRuntime::invoke`).-- Every domain is needed because `channel.web_chat` lives in the- Channels domain group. `ServiceSet::none()` skips background services,- including channel startup, so the runner registers the approval and- artifact surface subscribers itself- (`embed::chat_surface::register_approval_surface_subscriber`,- `register_artifact_surface_subscriber`).-8. Picks a client id (`tui-<12 hex>`), resolves the thread, subscribes to the- web-channel broadcast before the first turn, and hands off to `app::run`.--Thread resolution: `--thread <id>` attaches to that thread unless `--new` is-also given. `--last` or `--resume` picks the first thread from-`openhuman.threads_list`. Otherwise, or if listing fails, it creates one with-`openhuman.threads_create_new`.--### The event loop--```text- crossterm reader thread core (in-process)- (event::poll every 100 ms) web_chat broadcast- | |- | mpsc | broadcast::Receiver<WebChannelEvent>- v v- +--------------------- app::run: tokio::select! ----------------------+- | key / paste -> handle_key -> composer, tabs, overlays, commands |- | web event -> TranscriptState::apply_event (state.rs) |- | 120 ms tick -> spinner |- +-----------------------------+---------------------------------------+- |- v- render::draw(frame, &TranscriptState, &UiState)-- send: runtime.invoke("openhuman.channel_web_chat",- { client_id, thread_id, message, queue_mode, ... })- cancel: runtime.invoke("openhuman.channel_web_cancel",- { client_id, thread_id })-```--Before entering the loop, `app::run` loads the thread's existing transcript-(`openhuman.threads_transcript_get`), refreshes config, auth and agent paths,-and opens the thread picker if `--resume` was given. It then enters the-terminal through `TerminalGuard` and sends the positional prompt, if any.--Sending a message spawns a task that calls `openhuman.channel_web_chat`-through `CoreRuntime::invoke`. The reply streams back as `WebChannelEvent`s on-the broadcast channel, which `TranscriptState::apply_event` folds into the-transcript. Events for another `client_id` or thread are ignored. If the-invoke itself fails, the TUI publishes a synthetic `chat_error` so the-streaming state clears. `Enter` sends with `queue_mode: "interrupt"`; `Tab`-while a turn is streaming queues the text as a follow-up. `Esc` cancels the-in-flight turn.+A conversation-first terminal frontend for OpenHuman, built with ratatui and+crossterm. It embeds the core through `openhuman_rpc::host::tui()` with no HTTP+server or sidecar. Login, saved conversations, model/agent selection, approvals,+tools, child-run inspection, and diagnostics use the existing core contracts.-Logging in or out from Settings sets `identity_changed`, and the loop starts a-new thread afterwards.+## Build and view-### Login+From the repository root:-`session.rs` is the TUI's session owner. It wraps-`openhuman_tinyhumans::SessionManager` around an `InProcessLink`, a `CoreLink`-that calls `CoreRuntime::invoke` directly (no HTTP, no bearer). Login-token-exchange and `/auth/me` happen in the TUI process; the core only receives the-resulting credential through `auth.set_credential`. The Settings tab drives-it: "Log in with one-time token" takes a pasted token (zeroized on cancel),-and "Log out" asks for confirmation.+```bash+bash scripts/ci-cancel-aware.sh cargo build -p openhuman-tui+./target/debug/openhuman-tui --demo+```-## Usage+`--demo` is an offline interactive preview using the production renderer and+pointer geometry with clearly labeled sample events. It does not initialize a+core, authenticate, write conversations, or call a model. Account and execution+actions in the preview explain that they need live mode.-See [Building the Rust Core](../../gitbooks/developing/building-rust-core.md)-for toolchain setup.+For the real runtime and saved conversations:```bash-cargo build --manifest-path Cargo.toml -p openhuman-tui-cargo run -p openhuman-tui -- [OPTIONS] [PROMPT]+./target/debug/openhuman-tui --resume```-| Flag | Effect |-| --- | --- |-| `--thread <id>` | Attach to an existing conversation thread. |-| `--new` | Force a new thread (the default when `--thread` is omitted). |-| `--resume` | Open the saved-thread picker, starting on the latest thread. |-| `--last` | Resume the most recent thread. |-| `--no-alt-screen` | Draw in the current terminal buffer instead of the alternate screen. |-| `-p`, `--provider <id>` | Override the inference provider for this session (also `--provider-id`, `--provider=<id>`). |-| `-m`, `--model <id>` | Override the model for this session (also `--model-id`, `--model=<id>`). |-| `-v`, `--verbose` | Debug-level logging, written to the log file only. |-| `-h`, `--help` | Print usage and exit. |-| positional words | Joined into a prompt and sent right after startup. |--`OPENHUMAN_WORKSPACE` overrides the data dir (default `~/.openhuman`), which-holds the `logs/` the TUI writes to.--Keys: `Ctrl+Tab` / `Ctrl+Shift+Tab` or `Alt+1` to `Alt+4` switch tabs,-`Enter` sends, `Shift+Enter` or `Alt+Enter` inserts a newline, `Tab`-completes a command or opens the file picker, `Up`/`Down` walk composer-history, `Ctrl+R` searches it, `Ctrl+W` deletes a word, `Esc` cancels a-running turn, and `Ctrl+C` / `Ctrl+D` quit.--Slash commands (the full list with descriptions is `COMMANDS` in-[`src/composer.rs`](src/composer.rs)): `/help`, `/new`, `/resume`, `/rename`, `/delete`,-`/model`, `/permissions`, `/status`, `/usage`, `/agents`, `/skills`, `/mcp`,-`/artifacts`, `/approvals`, `/diff`, `/review`, `/copy`, `/export`, `/clear`,-`/logs`, `/config`, `/settings`, `/logout`, `/quit`. `/diff` runs `git` in the-agent's action directory and fails cleanly when that is not a repository.--## Layout--| File | What it does |-| --- | --- |-| [`src/main.rs`](src/main.rs) | Binary entry: crash reporting, then `run_from_cli`. |-| [`src/lib.rs`](src/lib.rs) | Module declarations and the public surface. |-| [`src/runner.rs`](src/runner.rs) | `run_from_cli`: flags, logging, runtime, core boot, thread resolution. |-| [`src/app.rs`](src/app.rs) | The `tokio::select!` event loop, key handling, slash commands, overlays, sending and cancelling turns, the file picker and Git diff. |-| [`src/state.rs`](src/state.rs) | `TranscriptState`, the pure reducer that folds `WebChannelEvent`s into transcript entries. No terminal or I/O dependencies. |-| [`src/ui_state.rs`](src/ui_state.rs) | `UiState`: active tab, composer, scroll, overlays, Config items and Settings actions. Pure data. |-| [`src/render.rs`](src/render.rs) | `draw`, a pure view over `TranscriptState` and `UiState`. The Logs tab reads `core::logging::tui_log_lines`. |-| [`src/composer.rs`](src/composer.rs) | The multiline composer: editing, history, command completion, and the `COMMANDS` table. |-| [`src/cockpit.rs`](src/cockpit.rs) | Overlay types (`OverlayKind`, `Overlay`, `OverlayRow`), pending approval and plan-review records, and JSON helpers; re-exports `openhuman_rpc::unwrap_rpc`. |-| [`src/controls.rs`](src/controls.rs) | Config tab edits (API URL, inference URL, default model, autonomy level, privacy mode) and Settings actions (view account, log in, log out). |-| [`src/session.rs`](src/session.rs) | `InProcessLink` and the process-wide `SessionManager`. |-| [`src/terminal.rs`](src/terminal.rs) | `TerminalGuard` (raw mode, alternate screen, mouse capture, bracketed paste) and a panic hook that restores the terminal first. |-| [`src/crash_reporting.rs`](src/crash_reporting.rs) | `init_crash_reporting`, a no-op without the `crash-reporting` feature. |-| [`tests/cli_e2e.rs`](tests/cli_e2e.rs) | Spawns the built binary to check `--help` output and that flags are validated before the core boots. |--## Key types and entry points--- `run_from_cli(args)` ([`src/runner.rs`](src/runner.rs)) is the public entry point.-- `init_crash_reporting()` ([`src/crash_reporting.rs`](src/crash_reporting.rs)) returns a- `sentry::ClientInitGuard` that must live for the whole process.-- `TranscriptState`, `Entry`, `EntryKind` ([`src/state.rs`](src/state.rs)) are exported so the- reducer can be tested without a terminal. `apply_event` is the single- transition entry point.-- `app::run` ([`src/app.rs`](src/app.rs)) owns the loop; `LaunchOptions` carries the initial- prompt, `resume_picker` and `no_alt_screen`.--## Core methods used--All calls go through `CoreRuntime::invoke`:--| Area | Methods |-| --- | --- |-| Chat | `openhuman.channel_web_chat`, `openhuman.channel_web_cancel`, `openhuman.channel_web_queue_status` |-| Threads | `openhuman.threads_list`, `openhuman.threads_create_new`, `openhuman.threads_transcript_get`, `openhuman.threads_update_title`, `openhuman.threads_delete`, `openhuman.threads_token_usage` |-| Approvals and plans | `openhuman.approval_list_pending`, `openhuman.approval_decide`, `openhuman.plan_review_decide` |-| Browsing | `openhuman.agent_list_definitions`, `openhuman.skills_list`, `openhuman.mcp_clients_installed_list`, `openhuman.ai_list_artifacts` |-| Config | `openhuman.config_get_client_config`, `openhuman.config_get_agent_paths`, `openhuman.config_update_model_settings`, `openhuman.config_get_autonomy_settings`, `openhuman.config_update_autonomy_settings`, `openhuman.config_get_privacy_mode`, `openhuman.config_set_privacy_mode` |-| Account | `openhuman.auth_get_state` (login and logout go through `session.rs`) |--## Feature flags--| Feature | Meaning |-| --- | --- |-| `crash-reporting` (default) | Forwards `openhuman-rpc/crash-reporting`. `init_crash_reporting` loads `.env`, then starts a Sentry client from `embed::process::sentry::client_options`: the shared filter chain, secret scrubbing and the core's Sentry transport, as the CLI and the desktop shell use. |-| `media`, `skills`, `flows`, `mcp`, `channels`, `scheduler-gate`, `file-logging`, `modules` (default) | The core's contributor gates, forwarded to `openhuman-rpc`. Named explicitly: they used to arrive implicitly through a bare `openhuman-core` workspace dependency. `http-server` is not in the set; the TUI never serves. |-| every other product gate, `jev`, `e2e-test-support` | Forwarded 1:1 to `openhuman-rpc`, off by default (`scripts/ci/check-feature-forwarding.mjs` checks the link). |--## Boundaries--- `openhuman-rpc` is the TUI's only OpenHuman dependency- (`scripts/ci/check-crate-chain.mjs`). The core runs in-process through- `host::tui`; there is no `openhuman-core` binary to spawn or connect to.- The TUI also uses `unwrap_rpc` (strips the optional `result`/`data`- envelopes around RPC payloads) and the `embed` facades; it does not use the- server or the HTTP client.-- `openhuman_rpc::tinyhumans` provides the backend transport and the- `SessionManager`; auth endpoint behavior belongs there.-- The ratatui and crossterm dependencies live only in this crate, which keeps- the core free of terminal code.-- Chat semantics (queueing, cancellation, streaming events) belong to the- core's `web_chat` and channel domains. The TUI only renders them.--## Gotchas--- Never print to stdout or stderr after the terminal is entered; use `log::`- with a `[tui]` prefix, which goes to the log file. A stray `println!` corrupts- the display.-- Subscribe to `web_chat::subscribe_web_channel_events` before the first turn.- The runner does this before `app::run`, so streamed events of an initial- prompt are not lost.-- With `ServiceSet::none()`, anything that normally starts as a background- service (channel listeners, schedulers) is off. If a new surface needs- events bridged onto the web channel, register its subscriber in- `async_main` the way the approval and artifact subscribers are.--## Tests--Unit tests are `*_tests.rs` siblings (`state_tests.rs` needs no terminal).-[`tests/cli_e2e.rs`](tests/cli_e2e.rs) spawns the built binary.+In an existing tmux session, open a new window at an unused index:```bash-cargo test -p openhuman-tui+tmux new-window -t workspace:7 -n openhuman -c "$PWD" './target/debug/openhuman-tui --resume'```-## Packaging+If using the user's dedicated Mosh server, add `-L mosh` to tmux commands.+Use a terminal of at least 80×24 for comfortable navigation. Wider screens use+the same compact header, transcript, composer, and status layout.++## Controls++| Action | Keyboard | Mouse |+| --------------------- | ---------------------- | ------------------------------- |+| Commands | Ctrl+P or `/help` | Commands button |+| Send / steer | Enter | Send; Enter steers during a run |+| Queue follow-up | Ctrl+Q during a run | Queue |+| Newline | Shift+Enter or Ctrl+J | — |+| Focus controls | Tab / Shift+Tab | Hover/click |+| Stop | Esc from composer | Stop |+| Scroll transcript | Page Up / Page Down | Wheel |+| Return to live tail | Jump-to-latest control | Jump to latest |+| Expand tool/reasoning | Focus then Enter | Click the row |+| Exit | Ctrl+D or `/quit` | — |++Tab accepts command completion when a slash suggestion is open; otherwise it+moves focus. Ctrl+C closes an overlay, clears a draft, or requests cancellation,+depending on the focused state. It does not immediately quit. Pasting text never+sends it automatically. Closing the TUI shuts down its in-process runtime.++Terminal support for modified Enter, mouse forwarding, and native selection+varies. `--no-mouse` keeps native terminal mouse behavior; `/mouse` toggles+capture in a running TUI. System themes use ANSI colors and the terminal's+default background. Dark, Light, and Monochrome are selectable with `/themes`;+`NO_COLOR` starts in Monochrome. Theme choices apply to the current process.++## Login, agents, and activity++`/login` opens masked one-time-token entry in Settings. Credential exchange and+validation remain in `openhuman_tinyhumans::SessionManager`; the frontend only+hands it the token. Sign-in runs in the background with a deadline, and secret+buffers are zeroized. Account changes clear the prior account's draft/cache and+start a new account-owned conversation. Product login is distinct from an+inference provider's key configuration.++`/agents` loads runnable profiles and writes `config.update_agent_settings`'s+`chat_agent_id` after selection. This is the core's configured chat agent for+subsequent turns, not an isolated per-thread preference. `/model` reads the+current provider's catalog; `/model <id>` offers an explicit override. Catalog+requests run in the background; a dismissed or superseded view cannot be+replaced by a late response.++Tool results update their originating call. Calls retain bounded arguments and+output, timing, and status; `/tools` opens the stored preview. `/subagents`+opens read-only child output. Pending approvals and plan review have a persistent+attention control. Inspecting a child does not switch the parent conversation+or discard its draft. Failed/incomplete stored activity is labeled honestly;+unsettled historical activity is marked stale.++`/sessions` or `/resume` switches saved conversations while retaining each+draft. History failures keep the current conversation. The initial history page+contains up to 500 projected items. Full session branching, child steering/+cancellation, older-page loading, and complete uncapped output retrieval are+not implemented by this UI.++Additional commands: `/new`, `/rename`, `/delete`, `/permissions`, `/status`,+`/usage`, `/skills`, `/mcp`, `/artifacts`, `/diff`, `/review`, `/copy`, `/export`,+`/clear`, `/chat`, `/logs`, `/config`, `/settings`, `/logout`, `/quit`.+`/clear` hides the visible transcript without cancelling a run or deleting its+durable history. `/permissions` explicitly reports when the autonomy policy is+off; stored tiers have no enforcement effect until that policy is enabled.++## Rendering and input++The loop redraws only dirty state or active animation. Streaming paints are+coalesced. Settled blocks are wrapped once per content revision and width;+wide row offsets avoid 16-bit history overflow. Only viewport rows are copied+into the frame, and formatted blocks far from the viewport are evicted while+their height metadata and underlying transcript remain available.++Input has a bounded queue with backpressure. Rendered cell rectangles are the+source of pointer hit testing, including overlays. Drag/release events do not+activate controls. Tool/text content is sanitized before terminal rendering.+Large tool previews are bounded; display truncation never deletes core history.+Absolute performance budgets in the design spec are targets, not benchmark+claims about every terminal or platform.++## Source map++| Path under `src/` | Responsibility |+| ----------------------------------- | ------------------------------------------------------------------- |+| `runner.rs`, `main.rs` | CLI parsing, host boot, offline preview entry |+| `app.rs`, `app/` | Event loop, runtime actions, pickers, sessions, file/Git operations |+| `actions.rs`, `input.rs` | Shared actions and cell-based pointer translation |+| `render.rs`, `render/` | Conversation, controls, diagnostics, and overlay rendering |+| `viewport.rs` | Cached wrapping and viewport selection |+| `state.rs`, `activity.rs` | Live/replayed transcript and tool/child projections |+| `composer.rs`, `ui_state.rs` | Unicode editor, navigation, draft, and presentation state |+| `effects.rs` | Background catalog results and stale-view protection |+| `presentation.rs`, `theme.rs` | Local commands, read-only inspection, semantic colors |+| `controls.rs`, `session.rs` | Safe configuration and host-owned account flow |+| `demo.rs` | Offline interactive visual preview |+| `terminal.rs`, `crash_reporting.rs` | Terminal cleanup, panic restoration, crash reporting |++Hosts depend only on `openhuman-rpc` and its curated facades. Harness execution,+tool policy, queueing, and durable session behavior remain with their owners.+No model/tool implementation is copied into the frontend.++## Validation-`openhuman-tui` ships alongside `openhuman-core` in the CLI tarball-([`scripts/release/package-cli-tarball.sh`](../../scripts/release/package-cli-tarball.sh)) and the apt packages-([`scripts/release/build-apt-packages.sh`](../../scripts/release/build-apt-packages.sh)).--[ratatui]: https://ratatui.rs--## Further reading+```bash+bash scripts/ci-cancel-aware.sh cargo test -p openhuman-tui+bash scripts/ci-cancel-aware.sh cargo clippy -p openhuman-tui --all-targets -- -D warnings+cargo fmt -p openhuman-tui --check+```-- [`gitbooks/developing/architecture.md`](../../gitbooks/developing/architecture.md): architecture overview.-- [`gitbooks/developing/architecture/agent-harness.md`](../../gitbooks/developing/architecture/agent-harness.md): the agent harness.-- [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md): embedding the core in another product.-- [`gitbooks/developing/building-rust-core.md`](../../gitbooks/developing/building-rust-core.md): building the Rust core.-- [`crates/README.md`](../README.md): crates overview.-- [`gitbooks/developing/testing-strategy.md`](../../gitbooks/developing/testing-strategy.md): testing strategy.+Tests cover transcript identity/deduplication, tool and child status, replay,+bounded file discovery, Unicode input/wrapping, masked login, overlay hit+precedence, stale catalog results, large history/cache bounds, and CLI parsing.+Live authentication and model execution still require a configured account or+provider. This frontend ships beside `openhuman-core` in the CLI packages.diff --git a/crates/openhuman-tui/src/actions.rs b/crates/openhuman-tui/src/actions.rsnew file mode 100644index 0000000000..da37531fdd--- /dev/null+++ b/crates/openhuman-tui/src/actions.rs@@ -0,0 +1,38 @@+//! Shared hit targets and actions for keyboard and pointer navigation.+use super::ui_state::AppTab;+use crossterm::event::KeyCode;+use ratatui::layout::{Position, Rect};++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Action {+ Command(&'static str),+ View(AppTab),+ Send,+ Queue,+ Stop,+ Latest,+ Entry(usize),+ OverlayRow(usize),+ OverlayKey(KeyCode),+ ConfigRow(usize),+ SettingsRow(usize),+ Composer,+ Complete(&'static str),+}++#[derive(Debug, Clone)]+pub struct Hit {+ pub area: Rect,+ pub action: Action,+}++pub fn hit_at(hits: &[Hit], column: u16, row: u16) -> Option<Action> {+ hits.iter()+ .rev()+ .find(|hit| hit.area.contains(Position::new(column, row)))+ .map(|hit| hit.action.clone())+}++#[cfg(test)]+#[path = "actions_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/actions_tests.rs b/crates/openhuman-tui/src/actions_tests.rsnew file mode 100644index 0000000000..fcb350b6b4--- /dev/null+++ b/crates/openhuman-tui/src/actions_tests.rs@@ -0,0 +1,17 @@+use super::*;++#[test]+fn overlay_targets_take_precedence_and_hidden_controls_have_no_target() {+ let hits = vec![+ Hit {+ area: Rect::new(0, 0, 80, 24),+ action: Action::Composer,+ },+ Hit {+ area: Rect::new(10, 5, 20, 1),+ action: Action::OverlayRow(2),+ },+ ];+ assert_eq!(hit_at(&hits, 12, 5), Some(Action::OverlayRow(2)));+ assert_eq!(hit_at(&hits, 80, 24), None);+}diff --git a/crates/openhuman-tui/src/activity.rs b/crates/openhuman-tui/src/activity.rsnew file mode 100644index 0000000000..ef46008348--- /dev/null+++ b/crates/openhuman-tui/src/activity.rs@@ -0,0 +1,222 @@+//! Bounded, inspectable tool and child-run projections.+use super::theme::safe_text;+use openhuman_rpc::embed::chat_surface::WebChannelEvent;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Status {+ Running,+ Success,+ Error,+ Waiting,+ Cancelled,+ Unknown,+}+impl Status {+ pub fn label(self) -> &'static str {+ match self {+ Self::Running => "running",+ Self::Success => "done",+ Self::Error => "failed",+ Self::Waiting => "needs input",+ Self::Cancelled => "cancelled",+ Self::Unknown => "stale",+ }+ }+ pub fn marker(self) -> &'static str {+ match self {+ Self::Running => "·",+ Self::Success => "✓",+ Self::Error => "✗",+ Self::Waiting => "!",+ Self::Cancelled => "–",+ Self::Unknown => "?",+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Activity {+ pub id: String,+ pub label: String,+ pub status: Status,+ pub args: String,+ pub output: String,+ pub history: String,+ pub elapsed_ms: Option<u64>,+ pub child: bool,+ pub tools: u64,+}++impl Activity {+ pub fn from_event(id: String, event: &WebChannelEvent, child: bool) -> Self {+ Self {+ id,+ label: safe_text(+ event+ .tool_display_label+ .as_deref()+ .or(event.tool_name.as_deref())+ .unwrap_or(if child { "Subagent" } else { "Tool" }),+ ),+ status: Status::Running,+ args: String::new(),+ output: String::new(),+ history: String::new(),+ elapsed_ms: None,+ child,+ tools: 0,+ }+ }+ pub fn update(&mut self, event: &WebChannelEvent) {+ if let Some(args) = &event.args {+ self.args = bounded(&args.to_string(), 4096);+ }+ if let Some(elapsed) = event.elapsed_ms.filter(|_| {+ !self.child+ || matches!(+ event.event.as_str(),+ "subagent_completed" | "subagent_failed"+ )+ }) {+ self.elapsed_ms = Some(elapsed);+ }+ if self.child {+ if let Some(detail) = &event.subagent {+ if let Some(name) = &detail.display_name {+ self.label = safe_text(name);+ }+ if let Some(elapsed) = detail.elapsed_ms {+ self.elapsed_ms = Some(elapsed);+ }+ if let Some(output) = &detail.output {+ self.output = bounded(output, 65536);+ }+ }+ match event.event.as_str() {+ "subagent_completed" => self.status = Status::Success,+ "subagent_failed" => self.status = Status::Error,+ "subagent_awaiting_user" => self.status = Status::Waiting,+ "subagent_spawned" => self.status = Status::Running,+ "subagent_tool_call" => {+ self.tools += 1;+ append_bounded(+ &mut self.history,+ &format!(+ "\nTool: {}\n{}",+ event.tool_name.as_deref().unwrap_or("tool"),+ self.args+ ),+ 65536,+ );+ }+ "subagent_tool_result" => {+ append_bounded(+ &mut self.history,+ &format!(+ "\nResult: {}\n{}",+ if event.success == Some(false) {+ "failed"+ } else {+ "done"+ },+ event.output.as_deref().unwrap_or("No output")+ ),+ 65536,+ );+ }+ "subagent_text_delta" => {+ if let Some(delta) = &event.delta {+ append_bounded(&mut self.output, delta, 65536);+ }+ }+ _ => {}+ }+ if matches!(+ event.event.as_str(),+ "subagent_failed" | "subagent_awaiting_user"+ ) {+ append_bounded(+ &mut self.history,+ &format!(+ "\n{}: {}",+ self.status.label(),+ event.message.as_deref().unwrap_or("No details supplied")+ ),+ 65536,+ );+ }+ } else if event.event == "tool_result" {+ self.status = if event.success == Some(false) {+ Status::Error+ } else {+ Status::Success+ };+ if let Some(output) = &event.output {+ self.output = bounded(output, 65536);+ } else if self.output.is_empty() {+ self.output = "No output".into();+ }+ if let Some(failure) = &event.failure {+ self.output = bounded(&format!("{}\n{failure}", self.output), 65536);+ }+ }+ }+ pub fn summary(&self) -> String {+ let time = self+ .elapsed_ms+ .map(|ms| format!(" · {ms} ms"))+ .unwrap_or_default();+ let count = if self.child {+ format!(" · {} tools", self.tools)+ } else {+ String::new()+ };+ format!(+ "{} {} · {}{count}{time}",+ self.status.marker(),+ self.label,+ self.status.label()+ )+ }+ pub fn details(&self) -> String {+ let mut result = String::new();+ if !self.args.is_empty() {+ result.push_str("Arguments\n");+ result.push_str(&self.args);+ result.push('\n');+ }+ result.push_str(if self.child {+ "Child output (read-only)\n"+ } else {+ "Output\n"+ });+ result.push_str(if self.output.is_empty() {+ "No output available yet"+ } else {+ &self.output+ });+ if !self.history.is_empty() {+ result.push_str("\nTool activity\n");+ result.push_str(&self.history);+ }+ result+ }+}++pub fn bounded(value: &str, limit: usize) -> String {+ let safe = safe_text(value);+ if safe.len() <= limit {+ return safe;+ }+ let mut end = limit;+ while !safe.is_char_boundary(end) {+ end -= 1;+ }+ format!("{}\n[preview truncated]", &safe[..end])+}+fn append_bounded(value: &mut String, delta: &str, limit: usize) {+ if value.len() >= limit {+ return;+ }+ *value = bounded(&format!("{value}{delta}"), limit);+}diff --git a/crates/openhuman-tui/src/app.rs b/crates/openhuman-tui/src/app.rsindex 6a187a4c44..0942048e3d 100644--- a/crates/openhuman-tui/src/app.rs+++ b/crates/openhuman-tui/src/app.rs@@ -18,7 +18,7 @@ use std::sync::Arc;use std::time::Duration;use base64::Engine as _;-use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};+use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEvent};use serde_json::json;use tokio::sync::broadcast;@@ -26,19 +26,31 @@ use openhuman_rpc::embed::chat_surface as web_chat;use openhuman_rpc::embed::chat_surface::WebChannelEvent;use openhuman_rpc::embed::CoreRuntime;-use super::cockpit::{- array_at, row_from_value, Overlay, OverlayKind, OverlayRow, PendingApproval, PendingPlanReview,-};+use super::actions::Action;+use super::cockpit::{Overlay, OverlayKind, OverlayRow, PendingApproval, PendingPlanReview};use super::render;use super::state::TranscriptState;use super::terminal::TerminalGuard;use super::ui_state::{AppTab, UiState};+mod artifacts;+mod commands;+mod events;+mod files;+mod overlays;+mod thread_actions;+use artifacts::*;+use commands::execute_command;+use events::handle_web_event;+use files::*;+use overlays::*;+use thread_actions::*;#[derive(Debug, Clone, Default)]pub struct LaunchOptions {pub initial_prompt: Option<String>,pub resume_picker: bool,pub no_alt_screen: bool,+ pub no_mouse: bool,}/// Run the tabbed terminal loop until the user quits (Ctrl+C / Ctrl+D) or the@@ -54,6 +66,11 @@ pub async fn run(let mut state = TranscriptState::new(client_id.clone());state.set_thread(thread_id.clone());let mut ui = UiState::new(thread_id, client_id.clone());+ let (overlay_tx, mut overlay_rx) = tokio::sync::mpsc::unbounded_channel();+ ui.overlay_tx = Some(overlay_tx);+ let (auth_tx, mut auth_rx) = tokio::sync::mpsc::unbounded_channel();+ ui.auth_tx = Some(auth_tx);+ ui.mouse_enabled = !options.no_mouse && !options.no_alt_screen;load_transcript(&runtime, &mut state, &ui.thread_id).await;if state.entries().is_empty() {state.push_system("OpenHuman is ready. Type /help for the agent cockpit.".to_string());@@ -78,6 +95,7 @@ pub async fn run(// Resolve local startup state before taking over the terminal. A slow or// locked config must never strand the user on a blank raw-mode screen.let mut guard = TerminalGuard::enter_with_options(!options.no_alt_screen)?;+ guard.set_mouse(ui.mouse_enabled)?;if let Some(prompt) = options.initial_prompt {ui.composer.set_text(prompt);@@ -85,7 +103,7 @@ pub async fn run(}// Blocking crossterm reader → async channel.- let (input_tx, mut input_rx) = tokio::sync::mpsc::unbounded_channel::<Event>();+ let (input_tx, mut input_rx) = tokio::sync::mpsc::channel::<Event>(256);let shutdown = Arc::new(AtomicBool::new(false));let reader_shutdown = shutdown.clone();let reader = std::thread::spawn(move || {@@ -93,7 +111,7 @@ pub async fn run(match event::poll(Duration::from_millis(100)) {Ok(true) => match event::read() {Ok(ev) => {- if input_tx.send(ev).is_err() {+ if input_tx.blocking_send(ev).is_err() {break;}}@@ -106,42 +124,83 @@ pub async fn run(});let mut ticker = tokio::time::interval(Duration::from_millis(120));+ let mut last_animation = std::time::Instant::now();let mut quit = false;+ let mut dirty = true;+ let mut last_draw = std::time::Instant::now() - Duration::from_secs(1);while !quit {- guard.terminal().draw(|f| render::draw(f, &state, &ui))?;+ if dirty && last_draw.elapsed() >= Duration::from_millis(33) {+ guard.set_mouse(ui.mouse_enabled)?;+ guard+ .terminal()+ .draw(|f| render::draw(f, &state, &mut ui))?;+ dirty = false;+ last_draw = std::time::Instant::now();+ }tokio::select! {+ _ = tokio::time::sleep_until(tokio::time::Instant::from_std(last_draw+Duration::from_millis(33))), if dirty => {},+ Some(result)=auth_rx.recv()=>{+ ui.auth_pending=false;+ match result {+ Ok(())=>{ui.settings_status="Signed in.".into();super::controls::refresh_auth(&runtime,&mut ui).await;ui.identity_changed=true;},+ Err(error)=>{ui.settings_status=format!("Sign-in failed: {error}");ui.login_token=Some(String::new());ui.active_tab=AppTab::Settings;}+ } dirty=true;+ },+ Some(reply)=overlay_rx.recv()=>{super::effects::apply(reply,&mut ui);dirty=true;},maybe_ev = input_rx.recv() => match maybe_ev {Some(Event::Key(key)) => {+ dirty = true;if handle_key(key, &runtime, &client_id, &mut state, &mut ui).await {quit = true;- } else if ui.identity_changed {- ui.identity_changed = false;- new_thread(&runtime, &mut state, &mut ui).await;}}- Some(Event::Paste(text)) => handle_paste(&text, &mut ui),- Some(_) => {} // resize / mouse / paste — redraw next iteration+ Some(Event::Paste(text)) => { handle_paste(&text, &mut ui); dirty = true; },+ Some(Event::Mouse(mouse)) => {+ if ui.mouse_enabled { quit = handle_mouse(mouse, &runtime, &client_id, &mut state, &mut ui).await; dirty = true; }+ }+ Some(Event::Resize(_, _)) => { ui.hits.clear(); dirty = true; },+ Some(_) => {},None => quit = true, // reader thread gone},recv = web_rx.recv() => match recv {- Ok(ev) => handle_web_event(&ev, &mut state, &mut ui),+ Ok(ev) => {+ let before=ui.viewport.total_rows();handle_web_event(&ev, &mut state, &mut ui);+ if ui.scroll_from_bottom>0 {ui.viewport.rows(&state,ui.transcript_area.width.saturating_sub(2),ui.transcript_area.height,ui.scroll_from_bottom);ui.scroll_from_bottom=ui.scroll_from_bottom.saturating_add(ui.viewport.total_rows().saturating_sub(before));}+ dirty = true;+ },Err(broadcast::error::RecvError::Lagged(n)) => {log::warn!("[tui] web-channel lagged, dropped {n} events");+ state.push_system("Some activity events were missed; /resume reloads stored history."); dirty = true;}Err(broadcast::error::RecvError::Closed) => {log::warn!("[tui] web-channel closed — exiting");quit = true;}},- _ = ticker.tick() => {- ui.spinner_tick = ui.spinner_tick.wrapping_add(1);+ _ = ticker.tick(), if state.is_streaming() => {+ if state.is_streaming() && last_animation.elapsed()>=Duration::from_millis(120) { ui.spinner_tick = ui.spinner_tick.wrapping_add(1); dirty = true; last_animation=std::time::Instant::now(); }}}+ if ui.identity_changed {+ ui.identity_changed = false;+ ui.drafts.clear();+ ui.composer.clear();+ ui.pending_approvals.clear();+ ui.pending_plan_review = None;+ ui.model_override = None;+ ui.viewport = Default::default();+ ui.overlay = None;+ state = TranscriptState::new(client_id.clone());+ super::controls::refresh_config(&runtime, &mut ui).await;+ new_thread(&runtime, &mut state, &mut ui).await;+ dirty = true;+ }}shutdown.store(true, Ordering::Relaxed);+ drop(input_rx); // Release a reader blocked on a full input queue before joining.let _ = reader.join();log::info!("[tui] event loop exited");Ok(())@@ -161,15 +220,99 @@ async fn handle_key(}let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ if ui.active_tab == AppTab::Chat+ && ui.overlay.is_none()+ && ui.composer.command_query().is_some()+ {+ let matches = ui.composer.command_matches();+ match key.code {+ KeyCode::Up => {+ ui.suggestion_selected = ui.suggestion_selected.saturating_sub(1);+ return false;+ }+ KeyCode::Down => {+ ui.suggestion_selected =+ (ui.suggestion_selected + 1).min(matches.len().saturating_sub(1));+ return false;+ }+ KeyCode::Enter | KeyCode::Tab+ if !key.modifiers.intersects(+ KeyModifiers::SHIFT | KeyModifiers::ALT | KeyModifiers::CONTROL,+ ) =>+ {+ if let Some((name, _)) =+ matches.get(ui.suggestion_selected.min(matches.len().saturating_sub(1)))+ {+ ui.composer.set_text(format!("/{name} "));+ ui.suggestion_selected = 0;+ if key.code == KeyCode::Enter {+ return send_or_command(runtime, client_id, state, ui).await;+ }+ return false;+ }+ }+ KeyCode::Char(_) | KeyCode::Backspace => ui.suggestion_selected = 0,+ _ => {}+ }+ }+if matches!(key.code, KeyCode::Char('c')) && ctrl {- log::info!("[tui] quit via Ctrl+C");- return true;+ if ui.login_token.is_some() {+ super::controls::handle_settings_key(+ KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),+ runtime,+ ui,+ )+ .await;+ } else if ui.overlay.is_some() {+ ui.overlay = None;+ } else if !ui.composer.is_empty() {+ ui.composer.clear();+ } else if state.is_streaming() {+ cancel_turn(runtime, client_id, &ui.thread_id, state);+ ui.stopping = true;+ } else {+ state.push_system(+ "Ctrl+D or /quit exits. Closing this TUI shuts down its local runtime.",+ );+ }+ return false;}if matches!(key.code, KeyCode::Char('d')) && ctrl {log::info!("[tui] quit via Ctrl+D");return true;}+ if ctrl+ && key.code == KeyCode::Char('p')+ && ui.login_token.is_none()+ && ui.config_edit.is_none()+ {+ return execute_command("help", runtime, client_id, state, ui).await;+ }+ if key.code == KeyCode::Tab+ && !ctrl+ && ui.composer.command_query().is_none()+ && !ui.is_editing()+ {+ ui.focus = (ui.focus + 1) % (ui.hits.len() + 1);+ return false;+ }+ if key.code == KeyCode::BackTab && !ctrl && !ui.is_editing() {+ ui.focus = if ui.focus == 0 {+ ui.hits.len()+ } else {+ ui.focus - 1+ };+ return false;+ }+ if ui.focus > 0 && key.code == KeyCode::Enter && ui.overlay.is_none() && !ui.is_editing() {+ if let Some(hit) = ui.hits.get(ui.focus - 1) {+ let action = hit.action.clone();+ return dispatch_action(action, runtime, client_id, state, ui).await;+ }+ }+if ui.overlay.is_some() {let previous_kind = ui.overlay.as_ref().map(|overlay| overlay.kind);let should_quit = handle_overlay_key(key, runtime, client_id, state, ui).await;@@ -207,6 +350,95 @@ fn tab_shortcut(key: KeyEvent, current: AppTab) -> Option<AppTab> {}}+async fn handle_mouse(+ mouse: MouseEvent,+ runtime: &Arc<CoreRuntime>,+ client_id: &str,+ state: &mut TranscriptState,+ ui: &mut UiState,+) -> bool {+ let action = super::input::mouse_action(mouse, ui);+ if let Some(action) = action {+ return dispatch_action(action, runtime, client_id, state, ui).await;+ }+ false+}++async fn dispatch_action(+ action: Action,+ runtime: &Arc<CoreRuntime>,+ client_id: &str,+ state: &mut TranscriptState,+ ui: &mut UiState,+) -> bool {+ if (ui.login_token.is_some() || ui.config_edit.is_some() || ui.logout_confirm)+ && !matches!(action, Action::OverlayKey(_))+ {+ return false;+ }+ match action {+ Action::Command(command) => {+ return execute_command(command, runtime, client_id, state, ui).await+ }+ Action::View(tab) => {+ ui.active_tab = tab;+ ui.focus = 0;+ }+ Action::Send => return send_or_command(runtime, client_id, state, ui).await,+ Action::Queue => send_message(runtime, client_id, state, ui, "followup"),+ Action::Stop => {+ cancel_turn(runtime, client_id, &ui.thread_id, state);+ ui.stopping = state.is_streaming();+ }+ Action::Latest => ui.scroll_from_bottom = 0,+ Action::Entry(index) => state.toggle_entry(index),+ Action::Composer => ui.focus = 0,+ Action::Complete(command) => {+ ui.composer.set_text(format!("/{command} "));+ ui.focus = 0;+ }+ Action::OverlayRow(index) => {+ if let Some(overlay) = &mut ui.overlay {+ overlay.selected = index;+ }+ return handle_overlay_key(+ KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),+ runtime,+ client_id,+ state,+ ui,+ )+ .await;+ }+ Action::OverlayKey(code) => {+ let key = KeyEvent::new(code, KeyModifiers::NONE);+ if ui.overlay.is_some() {+ return handle_overlay_key(key, runtime, client_id, state, ui).await;+ }+ return handle_tab_key(key, runtime, client_id, state, ui).await;+ }+ Action::ConfigRow(index) => {+ ui.config_selected = index;+ super::controls::handle_config_key(+ KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),+ runtime,+ ui,+ )+ .await;+ }+ Action::SettingsRow(index) => {+ ui.settings_selected = index;+ super::controls::handle_settings_key(+ KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),+ runtime,+ ui,+ )+ .await;+ }+ }+ false+}+fn handle_paste(text: &str, ui: &mut UiState) {if let Some(overlay) = &mut ui.overlay {if let Some(input) = &mut overlay.input {@@ -261,7 +493,11 @@ async fn handle_tab_key(return true;}KeyCode::Char('n') if ctrl => new_thread(runtime, state, ui).await,- KeyCode::Esc => cancel_turn(runtime, client_id, &ui.thread_id, state),+ KeyCode::Esc => {+ cancel_turn(runtime, client_id, &ui.thread_id, state);+ ui.stopping = state.is_streaming();+ ui.focus = 0;+ }KeyCode::PageUp => {ui.scroll_from_bottom = ui.scroll_from_bottom.saturating_add(5);}@@ -276,9 +512,10 @@ async fn handle_tab_key(ui.composer.newline()}KeyCode::Enter => return send_or_command(runtime, client_id, state, ui).await,- KeyCode::Tab if state.is_streaming() => {+ KeyCode::Char('q') if ctrl && state.is_streaming() => {send_message(runtime, client_id, state, ui, "followup")}+ KeyCode::Char('j') if ctrl => ui.composer.newline(),KeyCode::Tab => {if !ui.composer.complete_command() && ui.composer.file_query().is_some() {open_file_picker(ui).await;@@ -305,106 +542,6 @@ async fn handle_tab_key(false}-/// Queue a chat turn on the current thread. Fire-and-forget: the reply streams-/// back over the web-channel bus and is folded in by the reducer.-fn send_message(- runtime: &Arc<CoreRuntime>,- client_id: &str,- state: &mut TranscriptState,- ui: &mut UiState,- queue_mode: &str,-) {- let Some(message) = ui.composer.take_for_send() else {- return;- };- ui.scroll_from_bottom = 0;- state.begin_user_turn(&message);- log::info!(- "[tui] send message len={} thread={}",- message.len(),- ui.thread_id- );-- let rt = runtime.clone();- let cid = client_id.to_string();- let tid = ui.thread_id.clone();- let mode = queue_mode.to_string();- let model_override = ui.model_override.clone();- tokio::spawn(async move {- let params = json!({- "client_id": cid,- "thread_id": tid,- "message": message,- "source": "type",- "queue_mode": mode,- "model_override": model_override,- });- if let Err(e) = rt.invoke("openhuman.channel_web_chat", params).await {- log::error!("[tui] openhuman.channel_web_chat failed: {e}");- // Surface the failure in-transcript via a synthetic chat_error so- // the reducer clears the streaming state and shows the reason.- web_chat::publish_web_channel_event(WebChannelEvent {- event: "chat_error".to_string(),- client_id: cid,- thread_id: tid,- message: Some(format!("Failed to send: {e}")),- error_type: Some("transport".to_string()),- ..Default::default()- });- }- });-}--/// Cancel the in-flight turn on the current thread. The core emits a-/// `chat_error` ("Cancelled") which the reducer renders.-fn cancel_turn(- runtime: &Arc<CoreRuntime>,- client_id: &str,- thread_id: &str,- state: &TranscriptState,-) {- if !state.is_streaming() {- return;- }- log::info!("[tui] cancel turn thread={thread_id}");- let rt = runtime.clone();- let cid = client_id.to_string();- let tid = thread_id.to_string();- tokio::spawn(async move {- // Omit `request_id` → stop whatever is running on the thread.- let params = json!({ "client_id": cid, "thread_id": tid });- if let Err(e) = rt.invoke("openhuman.channel_web_cancel", params).await {- log::error!("[tui] openhuman.channel_web_cancel failed: {e}");- }- });-}--/// Create a fresh thread and switch the UI to it. Awaited inline (fast, local-/// SQLite write) so `ui.thread_id` can be updated with the result.-async fn new_thread(runtime: &Arc<CoreRuntime>, state: &mut TranscriptState, ui: &mut UiState) {- log::info!("[tui] creating new thread");- match runtime- .invoke("openhuman.threads_create_new", json!({}))- .await- .ok()- .and_then(|v| super::runner::extract_thread_id(&v))- {- Some(new_id) => {- let client_id = state.client_id().to_string();- *state = TranscriptState::new(client_id);- ui.thread_id = new_id.clone();- state.set_thread(new_id.clone());- ui.scroll_from_bottom = 0;- state.push_system(format!("Started a new thread · {new_id}"));- log::info!("[tui] switched to new thread {new_id}");- }- None => {- state.push_system("Could not create a new thread (see logs).".to_string());- log::error!("[tui] threads.create_new returned no thread id");- }- }-}-async fn send_or_command(runtime: &Arc<CoreRuntime>,client_id: &str,@@ -428,879 +565,6 @@ async fn send_or_command(false}-async fn execute_command(- command_line: &str,- runtime: &Arc<CoreRuntime>,- client_id: &str,- state: &mut TranscriptState,- ui: &mut UiState,-) -> bool {- let mut parts = command_line.split_whitespace();- let command = parts.next().unwrap_or("help");- let argument = parts.collect::<Vec<_>>().join(" ");- match command {- "quit" => return true,- "new" => new_thread(runtime, state, ui).await,- "help" => {- let mut overlay = Overlay::new(OverlayKind::Help, "Agent cockpit help");- overlay.status = "Type to filter · Esc closes".into();- overlay.rows = super::composer::COMMANDS- .iter()- .map(|(name, description)| OverlayRow {- id: (*name).into(),- label: format!("/{name}"),- detail: (*description).into(),- payload: serde_json::Value::Null,- })- .collect();- ui.overlay = Some(overlay);- }- "resume" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Threads,- "Saved threads",- "openhuman.threads_list",- json!({}),- &["threads", "items"],- &["id", "thread_id"],- &["title", "name", "id"],- )- .await;- }- "rename" => {- let mut overlay = Overlay::new(OverlayKind::Rename, "Rename thread");- overlay.input = Some(argument);- overlay.status = "Enter saves · Esc cancels".into();- ui.overlay = Some(overlay);- }- "delete" => {- let mut overlay = Overlay::new(OverlayKind::ConfirmDelete, "Delete thread?");- overlay.status = "Press y to permanently delete this conversation, or Esc.".into();- ui.overlay = Some(overlay);- }- "model" => {- let mut overlay = Overlay::new(OverlayKind::Model, "Model override");- overlay.input = Some(argument);- overlay.status = "Enter applies a model id to subsequent turns · empty clears".into();- ui.overlay = Some(overlay);- }- "permissions" => {- let mut overlay = Overlay::new(OverlayKind::Permissions, "Agent access");- overlay.status = "Choose an access tier · Enter applies".into();- overlay.rows = [- (- "readonly",- "Read-only",- "Writes, network, and installs are blocked",- ),- ("supervised", "Supervised", "Risky actions ask for approval"),- (- "full",- "Full access",- "Allowed actions run without prompting",- ),- ]- .into_iter()- .map(|(id, label, detail)| OverlayRow {- id: id.into(),- label: label.into(),- detail: detail.into(),- payload: serde_json::Value::Null,- })- .collect();- ui.overlay = Some(overlay);- }- "status" => {- let mut overlay = Overlay::new(OverlayKind::Status, "Session status");- refresh_agent_paths(runtime, ui).await;- if let Ok(value) = runtime- .invoke(- "openhuman.channel_web_queue_status",- json!({"thread_id": ui.thread_id}),- )- .await- {- ui.queue_status = serde_json::to_string(super::cockpit::unwrap_rpc(&value))- .unwrap_or_else(|_| "unavailable".into());- }- overlay.rows = vec![- text_row("thread", "Thread", &ui.thread_id),- text_row(- "model",- "Model",- ui.model_override.as_deref().unwrap_or("configured default"),- ),- text_row(- "cwd",- "Action directory",- if ui.action_dir.is_empty() {- "unavailable"- } else {- &ui.action_dir- },- ),- text_row(- "queue",- "Run queue",- if ui.queue_status.is_empty() {- "idle"- } else {- &ui.queue_status- },- ),- ];- ui.overlay = Some(overlay);- }- "usage" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Usage,- "Token and cost usage",- "openhuman.threads_token_usage",- json!({"thread_id": ui.thread_id}),- &[],- &[],- &[],- )- .await- }- "agents" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Agents,- "Agents",- "openhuman.agent_list_definitions",- json!({}),- &["definitions", "items"],- &["id"],- &["name", "display_name", "id"],- )- .await- }- "skills" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Skills,- "Skills",- "openhuman.skills_list",- json!({"include_skills": true}),- &["skills", "items"],- &["id"],- &["name", "title", "id"],- )- .await- }- "mcp" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Mcp,- "MCP servers",- "openhuman.mcp_clients_installed_list",- json!({}),- &["installed", "servers"],- &["id", "server_id"],- &["name", "display_name", "id"],- )- .await- }- "artifacts" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Artifacts,- "Artifacts",- "openhuman.ai_list_artifacts",- json!({"thread_id": ui.thread_id, "limit": 100}),- &["artifacts", "items"],- &["id", "artifact_id"],- &["title", "name", "filename", "id"],- )- .await- }- "approvals" => {- open_rpc_overlay(- runtime,- ui,- OverlayKind::Approvals,- "Pending approvals",- "openhuman.approval_list_pending",- json!({}),- &["pending", "approvals"],- &["request_id", "id"],- &["tool_name", "message", "request_id"],- )- .await- }- "diff" => open_git_diff(ui).await,- "review" => {- ui.composer.set_text("Review the current Git working tree. Explain correctness risks, regressions, and missing tests with file and line references.");- send_message(- runtime,- client_id,- state,- ui,- if state.is_streaming() {- "followup"- } else {- "interrupt"- },- );- }- "copy" => copy_latest_answer(state),- "export" => export_transcript(state, ui, &argument),- "clear" => state.clear(),- "logs" => ui.active_tab = AppTab::Logs,- "config" => ui.active_tab = AppTab::Config,- "settings" => ui.active_tab = AppTab::Settings,- "logout" => {- ui.active_tab = AppTab::Settings;- ui.logout_confirm = true;- }- _ => state.push_system(format!("Unknown command /{command}. Type /help.")),- }- false-}--fn text_row(id: &str, label: &str, detail: &str) -> OverlayRow {- OverlayRow {- id: id.into(),- label: label.into(),- detail: detail.into(),- payload: serde_json::Value::Null,- }-}--fn plan_review_overlay(review: &PendingPlanReview) -> Overlay {- let mut overlay = Overlay::new(OverlayKind::PlanReview, "Plan review");- overlay.rows = review- .steps- .iter()- .enumerate()- .map(|(index, step)| text_row(&index.to_string(), &format!("{}. {step}", index + 1), ""))- .collect();- overlay- .rows- .insert(0, text_row("summary", &review.summary, ""));- overlay.status = "a approve · r reject · e request revision · Esc leaves pending".into();- overlay-}--fn present_pending_plan_review(ui: &mut UiState) {- if let Some(review) = ui.pending_plan_review.as_ref() {- ui.overlay = Some(plan_review_overlay(review));- }-}--#[allow(clippy::too_many_arguments)]-async fn open_rpc_overlay(- runtime: &Arc<CoreRuntime>,- ui: &mut UiState,- kind: OverlayKind,- title: &str,- method: &str,- params: serde_json::Value,- array_keys: &[&str],- id_keys: &[&str],- label_keys: &[&str],-) {- let mut overlay = Overlay::new(kind, title);- match runtime.invoke(method, params).await {- Ok(value) => {- let items = array_at(&value, array_keys);- if items.is_empty() {- let detail = serde_json::to_string_pretty(super::cockpit::unwrap_rpc(&value))- .unwrap_or_else(|_| "No data".into());- overlay.rows.push(text_row("result", "Result", &detail));- } else {- overlay.rows = items- .iter()- .map(|item| row_from_value(item, id_keys, label_keys))- .collect();- }- overlay.status = format!(- "{} item(s) · type to filter · Esc closes",- overlay.rows.len()- );- }- Err(error) => overlay.status = format!("Could not load: {error}"),- }- ui.overlay = Some(overlay);-}--fn open_history_search(ui: &mut UiState) {- let mut overlay = Overlay::new(OverlayKind::HistorySearch, "Composer history");- overlay.rows = ui- .composer- .history_search("")- .into_iter()- .enumerate()- .map(|(index, text)| text_row(&index.to_string(), &text, "Enter restores this prompt"))- .collect();- overlay.status = "Type to filter · Enter restores · Esc closes".into();- ui.overlay = Some(overlay);-}--async fn handle_overlay_key(- key: KeyEvent,- runtime: &Arc<CoreRuntime>,- _client_id: &str,- state: &mut TranscriptState,- ui: &mut UiState,-) -> bool {- let kind = ui.overlay.as_ref().map(|overlay| overlay.kind).unwrap();- if key.code == KeyCode::Esc {- ui.overlay = None;- return false;- }- if kind == OverlayKind::ConfirmDelete && matches!(key.code, KeyCode::Char('y' | 'Y')) {- let result = runtime- .invoke(- "openhuman.threads_delete",- json!({- "thread_id": ui.thread_id,- "deleted_at": chrono::Utc::now().to_rfc3339(),- }),- )- .await;- ui.overlay = None;- match result {- Ok(_) => new_thread(runtime, state, ui).await,- Err(error) => state.push_system(format!("Could not delete thread: {error}")),- }- return false;- }- let typing = ui- .overlay- .as_ref()- .is_some_and(|overlay| overlay.input.is_some());- if kind == OverlayKind::Approvals {- let decision = decision_shortcut(kind, typing, key.code);- if let Some(decision) = decision {- let request_id = selected_overlay_row(ui)- .map(|row| row.id)- .unwrap_or_default();- decide_approval(runtime, &request_id, decision, state, ui).await;- return false;- }- }- if kind == OverlayKind::PlanReview && !typing {- if matches!(key.code, KeyCode::Char('e' | 'E')) {- if let Some(overlay) = &mut ui.overlay {- overlay.input = Some(String::new());- overlay.status = "Describe the needed revision, then press Enter".into();- }- return false;- }- let decision = decision_shortcut(kind, typing, key.code);- if let Some(decision) = decision {- if let Some(review) = ui.pending_plan_review.take() {- match runtime- .invoke(- "openhuman.plan_review_decide",- json!({"request_id": review.request_id, "decision": decision}),- )- .await- {- Ok(_) => state.push_system(format!("Plan {decision}d.")),- Err(error) => state.push_system(format!("Could not decide plan: {error}")),- }- }- ui.overlay = None;- return false;- }- }-- let Some(overlay) = &mut ui.overlay else {- return false;- };- match key.code {- KeyCode::Up => overlay.selected = overlay.selected.saturating_sub(1),- KeyCode::Down => {- let max = overlay.visible_rows().len().saturating_sub(1);- overlay.selected = (overlay.selected + 1).min(max);- }- KeyCode::Backspace => {- if let Some(input) = &mut overlay.input {- input.pop();- } else {- overlay.filter.pop();- overlay.clamp_selection();- }- }- KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {- if let Some(input) = &mut overlay.input {- input.push(c);- } else {- overlay.filter.push(c);- overlay.clamp_selection();- }- }- KeyCode::Enter => {- let input = overlay.input.clone().unwrap_or_default();- let selected = overlay- .visible_rows()- .get(overlay.selected)- .cloned()- .cloned();- match kind {- OverlayKind::Threads => {- if let Some(row) = selected {- switch_thread(runtime, state, ui, row.id).await;- }- }- OverlayKind::HistorySearch => {- if let Some(row) = selected {- ui.composer.set_text(row.label);- }- ui.overlay = None;- }- OverlayKind::Rename => {- if !input.trim().is_empty() {- match runtime- .invoke(- "openhuman.threads_update_title",- json!({"thread_id": ui.thread_id, "title": input.trim()}),- )- .await- {- Ok(_) => {- state.push_system(format!("Thread renamed to {}.", input.trim()))- }- Err(error) => {- state.push_system(format!("Could not rename thread: {error}"))- }- }- }- ui.overlay = None;- }- OverlayKind::Model => {- ui.model_override =- (!input.trim().is_empty()).then(|| input.trim().to_string());- state.push_system(match &ui.model_override {- Some(model) => format!("Using model override {model}."),- None => "Using the configured default model.".into(),- });- ui.overlay = None;- }- OverlayKind::Permissions => {- if let Some(row) = selected {- match runtime- .invoke(- "openhuman.config_update_autonomy_settings",- json!({"level": row.id}),- )- .await- {- Ok(_) => {- state.push_system(format!("Agent access set to {}.", row.label))- }- Err(error) => {- state.push_system(format!("Could not update access: {error}"))- }- }- }- ui.overlay = None;- }- OverlayKind::Agents => {- ui.overlay = None;- }- OverlayKind::Files => {- if let Some(row) = selected {- ui.composer.replace_current_token(&format!("@{}", row.id));- }- ui.overlay = None;- }- OverlayKind::PlanReview if !input.trim().is_empty() => {- if let Some(review) = ui.pending_plan_review.take() {- match runtime- .invoke(- "openhuman.plan_review_decide",- json!({- "request_id": review.request_id,- "decision": "revise",- "feedback": input.trim(),- }),- )- .await- {- Ok(_) => state.push_system("Plan sent back for revision."),- Err(error) => {- state.push_system(format!("Could not revise plan: {error}"))- }- }- }- ui.overlay = None;- }- _ => {}- }- }- _ => {}- }- false-}--fn decision_shortcut(kind: OverlayKind, typing: bool, code: KeyCode) -> Option<&'static str> {- if typing {- return None;- }- match (kind, code) {- (OverlayKind::Approvals, KeyCode::Char('1')) => Some("approve_once"),- (OverlayKind::Approvals, KeyCode::Char('2')) => Some("approve_always_for_tool"),- (OverlayKind::Approvals, KeyCode::Char('3')) => Some("approve_always_for_flow"),- (OverlayKind::Approvals, KeyCode::Delete) => Some("deny"),- (OverlayKind::PlanReview, KeyCode::Char('a' | 'A')) => Some("approve"),- (OverlayKind::PlanReview, KeyCode::Char('r' | 'R')) => Some("reject"),- _ => None,- }-}--fn selected_overlay_row(ui: &UiState) -> Option<OverlayRow> {- let overlay = ui.overlay.as_ref()?;- overlay- .visible_rows()- .get(overlay.selected)- .cloned()- .cloned()-}--async fn decide_approval(- runtime: &Arc<CoreRuntime>,- request_id: &str,- decision: &str,- state: &mut TranscriptState,- ui: &mut UiState,-) {- if request_id.is_empty() {- return;- }- match runtime- .invoke(- "openhuman.approval_decide",- json!({"request_id": request_id, "decision": decision}),- )- .await- {- Ok(_) => {- ui.pending_approvals- .retain(|approval| approval.request_id != request_id);- state.push_system(format!("Approval decision: {decision}."));- ui.overlay = None;- }- Err(error) => state.push_system(format!("Could not decide approval: {error}")),- }-}--async fn switch_thread(- runtime: &Arc<CoreRuntime>,- state: &mut TranscriptState,- ui: &mut UiState,- thread_id: String,-) {- let client_id = state.client_id().to_string();- *state = TranscriptState::new(client_id);- state.set_thread(thread_id.clone());- ui.thread_id = thread_id;- ui.scroll_from_bottom = 0;- ui.overlay = None;- load_transcript(runtime, state, &ui.thread_id).await;-}--async fn load_transcript(runtime: &Arc<CoreRuntime>, state: &mut TranscriptState, thread_id: &str) {- match runtime- .invoke(- "openhuman.threads_transcript_get",- json!({"thread_id": thread_id, "limit": 500}),- )- .await- {- Ok(value) => state.load_transcript(&value),- Err(error) => log::warn!("[tui] could not load transcript thread={thread_id}: {error}"),- }-}--async fn refresh_agent_paths(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {- if let Ok(value) = runtime- .invoke("openhuman.config_get_agent_paths", json!({}))- .await- {- let paths = super::cockpit::unwrap_rpc(&value);- ui.action_dir = paths- .get("action_dir")- .or_else(|| paths.get("actionDir"))- .and_then(serde_json::Value::as_str)- .unwrap_or_default()- .to_string();- }-}--async fn open_file_picker(ui: &mut UiState) {- let root = ui.action_dir.clone();- let query = ui- .composer- .file_query()- .unwrap_or_default()- .to_ascii_lowercase();- let result = tokio::task::spawn_blocking(move || collect_files(&root, &query, 500)).await;- let mut overlay = Overlay::new(OverlayKind::Files, "Workspace files");- match result {- Ok(Ok(files)) => {- overlay.rows = files- .into_iter()- .map(|path| text_row(&path, &path, "Enter inserts this path"))- .collect();- overlay.status = format!(- "{} match(es) · type to filter · Esc closes",- overlay.rows.len()- );- }- Ok(Err(error)) => overlay.status = error,- Err(error) => overlay.status = error.to_string(),- }- ui.overlay = Some(overlay);-}--fn collect_files(root: &str, query: &str, limit: usize) -> Result<Vec<String>, String> {- const MAX_VISITED: usize = 25_000;- const MAX_DEPTH: usize = 8;- if root.is_empty() {- return Err("Action directory is unavailable.".into());- }- let root_path = std::path::Path::new(root);- let mut pending = vec![(root_path.to_path_buf(), 0usize)];- let mut files = Vec::new();- let mut visited = 0usize;- while let Some((dir, depth)) = pending.pop() {- if visited >= MAX_VISITED {- break;- }- let entries = match std::fs::read_dir(&dir) {- Ok(entries) => entries,- Err(error) if dir == root_path => {- return Err(format!("{}: {error}", dir.display()));- }- Err(_) => continue,- };- for entry in entries.flatten() {- visited += 1;- if visited > MAX_VISITED {- break;- }- let path = entry.path();- let name = entry.file_name();- let name = name.to_string_lossy();- let Ok(file_type) = entry.file_type() else {- continue;- };- if file_type.is_symlink() {- continue;- }- if file_type.is_dir() {- if depth < MAX_DEPTH- && !matches!(- name.as_ref(),- ".git" | "target" | "node_modules" | "worktrees"- )- {- pending.push((path, depth + 1));- }- continue;- }- let relative = path- .strip_prefix(root_path)- .unwrap_or(&path)- .to_string_lossy()- .replace('\\', "/");- if query.is_empty() || relative.to_ascii_lowercase().contains(query) {- files.push(relative);- if files.len() >= limit {- files.sort();- return Ok(files);- }- }- }- }- files.sort();- Ok(files)-}--fn handle_web_event(ev: &WebChannelEvent, state: &mut TranscriptState, ui: &mut UiState) {- if ev.client_id != state.client_id() || ev.thread_id != ui.thread_id {- return;- }- match ev.event.as_str() {- "approval_request" => {- let approval = PendingApproval {- request_id: ev.request_id.clone(),- tool_name: ev.tool_name.clone().unwrap_or_else(|| "tool".into()),- summary: ev- .message- .clone()- .unwrap_or_else(|| "Approval required".into()),- args: ev.args.clone().unwrap_or(serde_json::Value::Null),- };- ui.pending_approvals- .retain(|item| item.request_id != approval.request_id);- ui.pending_approvals.push(approval.clone());- let preserves_typed_input = ui- .overlay- .as_ref()- .is_some_and(|overlay| overlay.input.is_some());- if !preserves_typed_input {- let mut overlay = Overlay::new(OverlayKind::Approvals, "Approval required");- overlay.rows.push(OverlayRow {- id: approval.request_id,- label: approval.tool_name,- detail: format!("{}\n{}", approval.summary, approval.args),- payload: approval.args,- });- overlay.status =- "1 approve once · 2 always for tool · 3 always for flow · Delete deny".into();- ui.overlay = Some(overlay);- }- }- "plan_review_request" => {- let steps = ev- .args- .as_ref()- .and_then(|args| args.get("steps"))- .and_then(serde_json::Value::as_array)- .map(|items| {- items- .iter()- .map(|item| {- item.as_str()- .map(str::to_string)- .unwrap_or_else(|| item.to_string())- })- .collect()- })- .unwrap_or_default();- let review = PendingPlanReview {- request_id: ev.request_id.clone(),- summary: ev- .message- .clone()- .unwrap_or_else(|| "Review the proposed plan".into()),- steps,- };- let preserves_typed_input = ui- .overlay- .as_ref()- .is_some_and(|overlay| overlay.input.is_some());- ui.pending_plan_review = Some(review);- if !preserves_typed_input {- present_pending_plan_review(ui);- }- }- _ => state.apply_event(ev),- }-}--async fn open_git_diff(ui: &mut UiState) {- let cwd = ui.action_dir.clone();- let result = tokio::task::spawn_blocking(move || {- if cwd.is_empty() {- return Err("Action directory is unavailable; run /status first.".to_string());- }- let inside = std::process::Command::new("git")- .args(["-C", &cwd, "rev-parse", "--is-inside-work-tree"])- .output()- .map_err(|error| error.to_string())?;- if !inside.status.success() {- return Err("The action directory is not a Git repository.".into());- }- let status = std::process::Command::new("git")- .args(["-C", &cwd, "status", "--short", "--branch"])- .output()- .map_err(|error| error.to_string())?;- let output = std::process::Command::new("git")- .args(["-C", &cwd, "diff", "--no-ext-diff", "--stat", "--patch"])- .output()- .map_err(|error| error.to_string())?;- Ok(format!(- "{}\n{}",- String::from_utf8_lossy(&status.stdout),- String::from_utf8_lossy(&output.stdout)- ))- })- .await- .unwrap_or_else(|error| Err(error.to_string()));- let mut overlay = Overlay::new(OverlayKind::Diff, "Working-tree diff");- match result {- Ok(diff) if diff.trim().is_empty() => overlay.rows.push(text_row(- "clean",- "Working tree is clean",- "No tracked changes",- )),- Ok(diff) => {- const MAX_DIFF_LINES: usize = 2_000;- let line_count = diff.lines().count();- overlay.rows = diff- .lines()- .take(MAX_DIFF_LINES)- .enumerate()- .map(|(index, line)| text_row(&index.to_string(), line, ""))- .collect();- if line_count > MAX_DIFF_LINES {- overlay.status = format!(- "Showing {MAX_DIFF_LINES} of {line_count} lines; remaining lines omitted"- );- }- }- Err(error) => overlay.status = error,- }- ui.overlay = Some(overlay);-}--fn export_transcript(state: &mut TranscriptState, ui: &UiState, argument: &str) {- let path = if argument.trim().is_empty() {- let base = if ui.action_dir.is_empty() {- std::env::current_dir().unwrap_or_default()- } else {- std::path::PathBuf::from(&ui.action_dir)- };- base.join(format!(- "openhuman-{}.md",- ui.thread_id.replace(['/', '\\'], "-")- ))- } else {- let supplied = std::path::PathBuf::from(argument);- if supplied.is_absolute() || ui.action_dir.is_empty() {- supplied- } else {- std::path::PathBuf::from(&ui.action_dir).join(supplied)- }- };- match std::fs::write(&path, state.export_markdown()) {- Ok(()) => state.push_system(format!("Transcript exported to {}.", path.display())),- Err(error) => state.push_system(format!("Could not export transcript: {error}")),- }-}--fn copy_latest_answer(state: &mut TranscriptState) {- let Some(answer) = state.last_assistant().map(str::to_string) else {- state.push_system("There is no completed answer to copy.");- return;- };- // OSC 52 works over local terminals and SSH without taking a platform GUI- // clipboard dependency. Terminals that disable it safely ignore the code.- let encoded = base64::engine::general_purpose::STANDARD.encode(answer.as_bytes());- let result = std::io::stdout()- .write_all(format!("\x1b]52;c;{encoded}\x07").as_bytes())- .and_then(|_| std::io::stdout().flush());- state.push_system(if result.is_ok() {- "Latest answer copied to the terminal clipboard."- } else {- "The terminal clipboard could not be updated."- });-}-#[cfg(test)]#[path = "app_tests.rs"]mod tests;diff --git a/crates/openhuman-tui/src/app/artifacts.rs b/crates/openhuman-tui/src/app/artifacts.rsnew file mode 100644index 0000000000..026fbf3c0d--- /dev/null+++ b/crates/openhuman-tui/src/app/artifacts.rs@@ -0,0 +1,101 @@+//! Git review, clipboard and export actions.+use super::*;++pub(super) async fn open_git_diff(ui: &mut UiState) {+ let cwd = ui.action_dir.clone();+ let result = tokio::task::spawn_blocking(move || {+ if cwd.is_empty() {+ return Err("Action directory is unavailable; run /status first.".to_string());+ }+ let inside = std::process::Command::new("git")+ .args(["-C", &cwd, "rev-parse", "--is-inside-work-tree"])+ .output()+ .map_err(|error| error.to_string())?;+ if !inside.status.success() {+ return Err("The action directory is not a Git repository.".into());+ }+ let status = std::process::Command::new("git")+ .args(["-C", &cwd, "status", "--short", "--branch"])+ .output()+ .map_err(|error| error.to_string())?;+ let output = std::process::Command::new("git")+ .args(["-C", &cwd, "diff", "--no-ext-diff", "--stat", "--patch"])+ .output()+ .map_err(|error| error.to_string())?;+ Ok(format!(+ "{}\n{}",+ String::from_utf8_lossy(&status.stdout),+ String::from_utf8_lossy(&output.stdout)+ ))+ })+ .await+ .unwrap_or_else(|error| Err(error.to_string()));+ let mut overlay = Overlay::new(OverlayKind::Diff, "Working-tree diff");+ match result {+ Ok(diff) if diff.trim().is_empty() => overlay.rows.push(text_row(+ "clean",+ "Working tree is clean",+ "No tracked changes",+ )),+ Ok(diff) => {+ const MAX_DIFF_LINES: usize = 2_000;+ let line_count = diff.lines().count();+ overlay.rows = diff+ .lines()+ .take(MAX_DIFF_LINES)+ .enumerate()+ .map(|(index, line)| text_row(&index.to_string(), line, ""))+ .collect();+ if line_count > MAX_DIFF_LINES {+ overlay.status = format!(+ "Showing {MAX_DIFF_LINES} of {line_count} lines; remaining lines omitted"+ );+ }+ }+ Err(error) => overlay.status = error,+ }+ ui.overlay = Some(overlay);+}++pub(super) fn export_transcript(state: &mut TranscriptState, ui: &UiState, argument: &str) {+ let path = if argument.trim().is_empty() {+ let base = if ui.action_dir.is_empty() {+ std::env::current_dir().unwrap_or_default()+ } else {+ std::path::PathBuf::from(&ui.action_dir)+ };+ base.join(format!(+ "openhuman-{}.md",+ ui.thread_id.replace(['/', '\\'], "-")+ ))+ } else {+ let supplied = std::path::PathBuf::from(argument);+ if supplied.is_absolute() || ui.action_dir.is_empty() {+ supplied+ } else {+ std::path::PathBuf::from(&ui.action_dir).join(supplied)+ }+ };+ match std::fs::write(&path, state.export_markdown()) {+ Ok(()) => state.push_system(format!("Transcript exported to {}.", path.display())),+ Err(error) => state.push_system(format!("Could not export transcript: {error}")),+ }+}++pub(super) fn copy_latest_answer(state: &mut TranscriptState) {+ let Some(answer) = state.last_assistant().map(str::to_string) else {+ state.push_system("There is no completed answer to copy.");+ return;+ };+ // OSC 52 works over local terminals and SSH without taking a platform GUI+ // clipboard dependency. Terminals that disable it safely ignore the code.+ let encoded = base64::engine::general_purpose::STANDARD.encode(answer.as_bytes());+ let result = std::io::stdout()+ .write_all(format!("\x1b]52;c;{encoded}\x07").as_bytes())+ .and_then(|_| std::io::stdout().flush());+ state.push_system(if result.is_ok() {+ "Latest answer copied to the terminal clipboard."+ } else {+ "The terminal clipboard could not be updated."+ });+}diff --git a/crates/openhuman-tui/src/app/commands.rs b/crates/openhuman-tui/src/app/commands.rsnew file mode 100644index 0000000000..4a9d873e57--- /dev/null+++ b/crates/openhuman-tui/src/app/commands.rs@@ -0,0 +1,277 @@+//! Slash command effects.+use super::*;++pub(super) async fn execute_command(+ command_line: &str,+ runtime: &Arc<CoreRuntime>,+ client_id: &str,+ state: &mut TranscriptState,+ ui: &mut UiState,+) -> bool {+ let mut parts = command_line.split_whitespace();+ let command = parts.next().unwrap_or("help");+ let argument = parts.collect::<Vec<_>>().join(" ");+ if crate::presentation::open(command, state, ui) {+ return false;+ }+ match command {+ "quit" => return true,+ "new" => new_thread(runtime, state, ui).await,+ "help" => {+ let mut overlay = Overlay::new(OverlayKind::Help, "Agent cockpit help");+ overlay.status = "Type to filter · Esc closes".into();+ overlay.rows = crate::composer::COMMANDS+ .iter()+ .map(|(name, description)| OverlayRow {+ id: (*name).into(),+ label: format!("/{name}"),+ detail: (*description).into(),+ payload: serde_json::Value::Null,+ })+ .collect();+ ui.overlay = Some(overlay);+ }+ "resume" | "sessions" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Threads,+ "Saved threads",+ "openhuman.threads_list",+ json!({}),+ &["threads", "items"],+ &["id", "thread_id"],+ &["title", "name", "id"],+ )+ .await;+ }+ "rename" => {+ let mut overlay = Overlay::new(OverlayKind::Rename, "Rename thread");+ overlay.input = Some(argument);+ overlay.status = "Enter saves · Esc cancels".into();+ ui.overlay = Some(overlay);+ }+ "delete" => {+ let mut overlay = Overlay::new(OverlayKind::ConfirmDelete, "Delete thread?");+ overlay.status = "Press y to permanently delete this conversation, or Esc.".into();+ ui.overlay = Some(overlay);+ }+ "model" | "models" => {+ if argument.is_empty() {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Model,+ "Available models",+ "openhuman.inference_list_models",+ json!({"provider_id":ui.provider_id}),+ &["models"],+ &["id"],+ &["name", "id"],+ )+ .await;+ if let Some(overlay) = &mut ui.overlay {+ overlay.rows.insert(+ 0,+ text_row("", "Configured default", "Use the configured model"),+ );+ overlay.status = "Enter selects · /model <id> sets an explicit override".into();+ }+ return false;+ }+ let mut overlay = Overlay::new(OverlayKind::Model, "Model override");+ overlay.input = Some(argument);+ overlay.status = "Enter applies a model id to subsequent turns · empty clears".into();+ ui.overlay = Some(overlay);+ }+ "permissions" => {+ let mut overlay = Overlay::new(OverlayKind::Permissions, "Agent access");+ overlay.status = if ui.policy_enabled {+ "Choose an access tier · Enter applies".into()+ } else {+ "Policy is OFF · stored tiers take effect only when core autonomy policy is enabled"+ .into()+ };+ overlay.rows = [+ (+ "readonly",+ "Read-only",+ "With policy enabled: writes, network, and installs are blocked",+ ),+ ("supervised", "Supervised", "Risky actions ask for approval"),+ (+ "full",+ "Full access",+ "Allowed actions run without prompting",+ ),+ ]+ .into_iter()+ .map(|(id, label, detail)| OverlayRow {+ id: id.into(),+ label: label.into(),+ detail: detail.into(),+ payload: serde_json::Value::Null,+ })+ .collect();+ ui.overlay = Some(overlay);+ }+ "status" => {+ let mut overlay = Overlay::new(OverlayKind::Status, "Session status");+ refresh_agent_paths(runtime, ui).await;+ if let Ok(value) = runtime+ .invoke(+ "openhuman.channel_web_queue_status",+ json!({"thread_id": ui.thread_id}),+ )+ .await+ {+ ui.queue_status = serde_json::to_string(crate::cockpit::unwrap_rpc(&value))+ .unwrap_or_else(|_| "unavailable".into());+ }+ overlay.rows = vec![+ text_row("thread", "Thread", &ui.thread_id),+ text_row(+ "model",+ "Model",+ ui.model_override.as_deref().unwrap_or("configured default"),+ ),+ text_row(+ "cwd",+ "Action directory",+ if ui.action_dir.is_empty() {+ "unavailable"+ } else {+ &ui.action_dir+ },+ ),+ text_row(+ "queue",+ "Run queue",+ if ui.queue_status.is_empty() {+ "idle"+ } else {+ &ui.queue_status+ },+ ),+ ];+ ui.overlay = Some(overlay);+ }+ "usage" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Usage,+ "Token and cost usage",+ "openhuman.threads_token_usage",+ json!({"thread_id": ui.thread_id}),+ &[],+ &[],+ &[],+ )+ .await+ }+ "agents" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Agents,+ "Agents",+ "openhuman.agent_list_definitions",+ json!({}),+ &["definitions", "items"],+ &["id"],+ &["display_name", "name", "id"],+ )+ .await+ }+ "skills" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Skills,+ "Skills",+ "openhuman.skills_list",+ json!({"include_skills": true}),+ &["skills", "items"],+ &["id"],+ &["name", "title", "id"],+ )+ .await+ }+ "mcp" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Mcp,+ "MCP servers",+ "openhuman.mcp_clients_installed_list",+ json!({}),+ &["installed", "servers"],+ &["id", "server_id"],+ &["name", "display_name", "id"],+ )+ .await+ }+ "artifacts" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Artifacts,+ "Artifacts",+ "openhuman.ai_list_artifacts",+ json!({"thread_id": ui.thread_id, "limit": 100}),+ &["artifacts", "items"],+ &["id", "artifact_id"],+ &["title", "name", "filename", "id"],+ )+ .await+ }+ "approvals" => {+ open_rpc_overlay(+ runtime,+ ui,+ OverlayKind::Approvals,+ "Pending approvals",+ "openhuman.approval_list_pending",+ json!({}),+ &["pending", "approvals"],+ &["request_id", "id"],+ &["tool_name", "message", "request_id"],+ )+ .await+ }+ "diff" => open_git_diff(ui).await,+ "review" => {+ ui.composer.set_text("Review the current Git working tree. Explain correctness risks, regressions, and missing tests with file and line references.");+ send_message(+ runtime,+ client_id,+ state,+ ui,+ if state.is_streaming() {+ "followup"+ } else {+ "interrupt"+ },+ );+ }+ "copy" => copy_latest_answer(state),+ "export" => export_transcript(state, ui, &argument),+ "clear" => state.clear(),+ "logs" => ui.active_tab = AppTab::Logs,+ "config" => ui.active_tab = AppTab::Config,+ "settings" => ui.active_tab = AppTab::Settings,+ "login" => {+ ui.active_tab = AppTab::Settings;+ ui.login_token = Some(String::new());+ ui.overlay = None;+ }+ "plan" => present_pending_plan_review(ui),+ "logout" => {+ ui.active_tab = AppTab::Settings;+ ui.logout_confirm = true;+ }+ _ => state.push_system(format!("Unknown command /{command}. Type /help.")),+ }+ false+}diff --git a/crates/openhuman-tui/src/app/events.rs b/crates/openhuman-tui/src/app/events.rsnew file mode 100644index 0000000000..4532b4e106--- /dev/null+++ b/crates/openhuman-tui/src/app/events.rs@@ -0,0 +1,82 @@+//! Runtime event projection and pending decisions.+use super::*;++pub(super) fn handle_web_event(+ ev: &WebChannelEvent,+ state: &mut TranscriptState,+ ui: &mut UiState,+) {+ if ev.client_id != state.client_id() || ev.thread_id != ui.thread_id {+ return;+ }+ if matches!(ev.event.as_str(), "chat_done" | "chat_error") {+ ui.stopping = false;+ }+ match ev.event.as_str() {+ "approval_request" => {+ let approval = PendingApproval {+ request_id: ev.request_id.clone(),+ tool_name: ev.tool_name.clone().unwrap_or_else(|| "tool".into()),+ summary: ev+ .message+ .clone()+ .unwrap_or_else(|| "Approval required".into()),+ args: ev.args.clone().unwrap_or(serde_json::Value::Null),+ };+ ui.pending_approvals+ .retain(|item| item.request_id != approval.request_id);+ ui.pending_approvals.push(approval.clone());+ let preserves_typed_input = ui+ .overlay+ .as_ref()+ .is_some_and(|overlay| overlay.input.is_some());+ if !preserves_typed_input {+ let mut overlay = Overlay::new(OverlayKind::Approvals, "Approval required");+ overlay.rows.push(OverlayRow {+ id: approval.request_id,+ label: approval.tool_name,+ detail: format!("{}\n{}", approval.summary, approval.args),+ payload: approval.args,+ });+ overlay.status =+ "1 approve once · 2 always for tool · 3 always for flow · Delete deny".into();+ ui.overlay = Some(overlay);+ }+ }+ "plan_review_request" => {+ let steps = ev+ .args+ .as_ref()+ .and_then(|args| args.get("steps"))+ .and_then(serde_json::Value::as_array)+ .map(|items| {+ items+ .iter()+ .map(|item| {+ item.as_str()+ .map(str::to_string)+ .unwrap_or_else(|| item.to_string())+ })+ .collect()+ })+ .unwrap_or_default();+ let review = PendingPlanReview {+ request_id: ev.request_id.clone(),+ summary: ev+ .message+ .clone()+ .unwrap_or_else(|| "Review the proposed plan".into()),+ steps,+ };+ let preserves_typed_input = ui+ .overlay+ .as_ref()+ .is_some_and(|overlay| overlay.input.is_some());+ ui.pending_plan_review = Some(review);+ if !preserves_typed_input {+ present_pending_plan_review(ui);+ }+ }+ _ => state.apply_event(ev),+ }+}diff --git a/crates/openhuman-tui/src/app/files.rs b/crates/openhuman-tui/src/app/files.rsnew file mode 100644index 0000000000..f7abd298b5--- /dev/null+++ b/crates/openhuman-tui/src/app/files.rs@@ -0,0 +1,92 @@+//! Bounded workspace file discovery.+use super::*;++pub(super) async fn open_file_picker(ui: &mut UiState) {+ let root = ui.action_dir.clone();+ let query = ui+ .composer+ .file_query()+ .unwrap_or_default()+ .to_ascii_lowercase();+ let result = tokio::task::spawn_blocking(move || collect_files(&root, &query, 500)).await;+ let mut overlay = Overlay::new(OverlayKind::Files, "Workspace files");+ match result {+ Ok(Ok(files)) => {+ overlay.rows = files+ .into_iter()+ .map(|path| text_row(&path, &path, "Enter inserts this path"))+ .collect();+ overlay.status = format!(+ "{} match(es) · type to filter · Esc closes",+ overlay.rows.len()+ );+ }+ Ok(Err(error)) => overlay.status = error,+ Err(error) => overlay.status = error.to_string(),+ }+ ui.overlay = Some(overlay);+}++pub(super) fn collect_files(root: &str, query: &str, limit: usize) -> Result<Vec<String>, String> {+ const MAX_VISITED: usize = 25_000;+ const MAX_DEPTH: usize = 8;+ if root.is_empty() {+ return Err("Action directory is unavailable.".into());+ }+ let root_path = std::path::Path::new(root);+ let mut pending = vec![(root_path.to_path_buf(), 0usize)];+ let mut files = Vec::new();+ let mut visited = 0usize;+ while let Some((dir, depth)) = pending.pop() {+ if visited >= MAX_VISITED {+ break;+ }+ let entries = match std::fs::read_dir(&dir) {+ Ok(entries) => entries,+ Err(error) if dir == root_path => {+ return Err(format!("{}: {error}", dir.display()));+ }+ Err(_) => continue,+ };+ for entry in entries.flatten() {+ visited += 1;+ if visited > MAX_VISITED {+ break;+ }+ let path = entry.path();+ let name = entry.file_name();+ let name = name.to_string_lossy();+ let Ok(file_type) = entry.file_type() else {+ continue;+ };+ if file_type.is_symlink() {+ continue;+ }+ if file_type.is_dir() {+ if depth < MAX_DEPTH+ && !matches!(+ name.as_ref(),+ ".git" | "target" | "node_modules" | "worktrees"+ )+ {+ pending.push((path, depth + 1));+ }+ continue;+ }+ let relative = path+ .strip_prefix(root_path)+ .unwrap_or(&path)+ .to_string_lossy()+ .replace('\\', "/");+ if query.is_empty() || relative.to_ascii_lowercase().contains(query) {+ files.push(relative);+ if files.len() >= limit {+ files.sort();+ return Ok(files);+ }+ }+ }+ }+ files.sort();+ Ok(files)+}diff --git a/crates/openhuman-tui/src/app/overlays.rs b/crates/openhuman-tui/src/app/overlays.rsnew file mode 100644index 0000000000..6e314f6267--- /dev/null+++ b/crates/openhuman-tui/src/app/overlays.rs@@ -0,0 +1,400 @@+//! Picker and decision handling.+use super::*;++pub(super) fn text_row(id: &str, label: &str, detail: &str) -> OverlayRow {+ OverlayRow {+ id: id.into(),+ label: label.into(),+ detail: detail.into(),+ payload: serde_json::Value::Null,+ }+}++pub(super) fn plan_review_overlay(review: &PendingPlanReview) -> Overlay {+ let mut overlay = Overlay::new(OverlayKind::PlanReview, "Plan review");+ overlay.rows = review+ .steps+ .iter()+ .enumerate()+ .map(|(index, step)| text_row(&index.to_string(), &format!("{}. {step}", index + 1), ""))+ .collect();+ overlay+ .rows+ .insert(0, text_row("summary", &review.summary, ""));+ overlay.status = "a approve · r reject · e request revision · Esc leaves pending".into();+ overlay+}++pub(super) fn present_pending_plan_review(ui: &mut UiState) {+ if let Some(review) = ui.pending_plan_review.as_ref() {+ ui.overlay = Some(plan_review_overlay(review));+ }+}++#[allow(clippy::too_many_arguments)]+pub(super) async fn open_rpc_overlay(+ runtime: &Arc<CoreRuntime>,+ ui: &mut UiState,+ kind: OverlayKind,+ title: &str,+ method: &str,+ params: serde_json::Value,+ array_keys: &[&str],+ id_keys: &[&str],+ label_keys: &[&str],+) {+ ui.overlay_generation = ui.overlay_generation.wrapping_add(1);+ let generation = ui.overlay_generation;+ let thread_id = ui.thread_id.clone();+ let mut overlay = Overlay::new(kind, title);+ overlay.status = "Loading… · Esc closes".into();+ ui.overlay = Some(overlay);+ let runtime = runtime.clone();+ let title = title.to_string();+ let method = method.to_string();+ let array_keys: Vec<String> = array_keys.iter().map(|key| key.to_string()).collect();+ let id_keys: Vec<String> = id_keys.iter().map(|key| key.to_string()).collect();+ let label_keys: Vec<String> = label_keys.iter().map(|key| key.to_string()).collect();+ let future = async move {+ let result =+ match tokio::time::timeout(Duration::from_secs(20), runtime.invoke(&method, params))+ .await+ {+ Ok(result) => result,+ Err(_) => Err("Request timed out".into()),+ };+ let overlay =+ crate::effects::build(kind, &title, result, &array_keys, &id_keys, &label_keys);+ crate::effects::OverlayReply {+ thread_id,+ generation,+ overlay,+ }+ };+ if let Some(tx) = ui.overlay_tx.clone() {+ tokio::spawn(async move {+ let _ = tx.send(future.await);+ });+ } else {+ let reply = future.await;+ crate::effects::apply(reply, ui);+ }+}+pub(super) fn open_history_search(ui: &mut UiState) {+ let mut overlay = Overlay::new(OverlayKind::HistorySearch, "Composer history");+ overlay.rows = ui+ .composer+ .history_search("")+ .into_iter()+ .enumerate()+ .map(|(index, text)| text_row(&index.to_string(), &text, "Enter restores this prompt"))+ .collect();+ overlay.status = "Type to filter · Enter restores · Esc closes".into();+ ui.overlay = Some(overlay);+}++pub(super) async fn handle_overlay_key(+ key: KeyEvent,+ runtime: &Arc<CoreRuntime>,+ _client_id: &str,+ state: &mut TranscriptState,+ ui: &mut UiState,+) -> bool {+ let kind = ui.overlay.as_ref().map(|overlay| overlay.kind).unwrap();+ if key.code == KeyCode::Esc {+ ui.overlay = None;+ return false;+ }+ if kind == OverlayKind::ConfirmDelete && matches!(key.code, KeyCode::Char('y' | 'Y')) {+ let result = runtime+ .invoke(+ "openhuman.threads_delete",+ json!({+ "thread_id": ui.thread_id,+ "deleted_at": chrono::Utc::now().to_rfc3339(),+ }),+ )+ .await;+ ui.overlay = None;+ match result {+ Ok(_) => new_thread(runtime, state, ui).await,+ Err(error) => state.push_system(format!("Could not delete thread: {error}")),+ }+ return false;+ }+ let typing = ui+ .overlay+ .as_ref()+ .is_some_and(|overlay| overlay.input.is_some());+ if kind == OverlayKind::Approvals {+ let decision = decision_shortcut(kind, typing, key.code);+ if let Some(decision) = decision {+ let request_id = selected_overlay_row(ui)+ .map(|row| row.id)+ .unwrap_or_default();+ decide_approval(runtime, &request_id, decision, state, ui).await;+ return false;+ }+ }+ if kind == OverlayKind::PlanReview && !typing {+ if matches!(key.code, KeyCode::Char('e' | 'E')) {+ if let Some(overlay) = &mut ui.overlay {+ overlay.input = Some(String::new());+ overlay.status = "Describe the needed revision, then press Enter".into();+ }+ return false;+ }+ let decision = decision_shortcut(kind, typing, key.code);+ if let Some(decision) = decision {+ if let Some(review) = ui.pending_plan_review.take() {+ match runtime+ .invoke(+ "openhuman.plan_review_decide",+ json!({"request_id": review.request_id, "decision": decision}),+ )+ .await+ {+ Ok(_) => state.push_system(format!("Plan {decision}d.")),+ Err(error) => state.push_system(format!("Could not decide plan: {error}")),+ }+ }+ ui.overlay = None;+ return false;+ }+ }++ let Some(overlay) = &mut ui.overlay else {+ return false;+ };+ match key.code {+ KeyCode::Up => overlay.selected = overlay.selected.saturating_sub(1),+ KeyCode::Down => {+ let max = overlay.visible_rows().len().saturating_sub(1);+ overlay.selected = (overlay.selected + 1).min(max);+ }+ KeyCode::Backspace => {+ if let Some(input) = &mut overlay.input {+ input.pop();+ } else {+ overlay.filter.pop();+ overlay.clamp_selection();+ }+ }+ KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {+ if let Some(input) = &mut overlay.input {+ input.push(c);+ } else {+ overlay.filter.push(c);+ overlay.clamp_selection();+ }+ }+ KeyCode::Enter => {+ let input = overlay.input.clone().unwrap_or_default();+ let selected = overlay+ .visible_rows()+ .get(overlay.selected)+ .cloned()+ .cloned();+ match kind {+ OverlayKind::Threads => {+ if let Some(row) = selected {+ switch_thread(runtime, state, ui, row.id).await;+ }+ }+ OverlayKind::HistorySearch => {+ if let Some(row) = selected {+ ui.composer.set_text(row.label);+ }+ ui.overlay = None;+ }+ OverlayKind::Rename => {+ if !input.trim().is_empty() {+ match runtime+ .invoke(+ "openhuman.threads_update_title",+ json!({"thread_id": ui.thread_id, "title": input.trim()}),+ )+ .await+ {+ Ok(_) => {+ state.push_system(format!("Thread renamed to {}.", input.trim()))+ }+ Err(error) => {+ state.push_system(format!("Could not rename thread: {error}"))+ }+ }+ }+ ui.overlay = None;+ }+ OverlayKind::Model => {+ let model = if overlay.input.is_some() {+ input.trim().to_string()+ } else {+ selected.map(|row| row.id).unwrap_or_default()+ };+ ui.model_override = (!model.is_empty()).then_some(model);+ state.push_system(match &ui.model_override {+ Some(model) => format!("Using model override {model}."),+ None => "Using the configured default model.".into(),+ });+ ui.overlay = None;+ }+ OverlayKind::Permissions => {+ if let Some(row) = selected {+ match runtime+ .invoke(+ "openhuman.config_update_autonomy_settings",+ json!({"level": row.id}),+ )+ .await+ {+ Ok(_) => {+ state.push_system(format!("Agent access set to {}.", row.label))+ }+ Err(error) => {+ state.push_system(format!("Could not update access: {error}"))+ }+ }+ }+ ui.overlay = None;+ }+ OverlayKind::Agents => {+ if let Some(row) = selected {+ if row.id != "orchestrator"+ && row+ .payload+ .get("can_run_as_user_facing_worker")+ .and_then(serde_json::Value::as_bool)+ != Some(true)+ {+ return false;+ }+ match runtime+ .invoke(+ "openhuman.config_update_agent_settings",+ json!({"chat_agent_id":row.id}),+ )+ .await+ {+ Ok(_) => {+ ui.agent_name = row.id;+ state.push_system(format!(+ "Chat agent: {}. Configured for subsequent turns.",+ ui.agent_name+ ));+ ui.overlay = None;+ }+ Err(error) => {+ if let Some(overlay) = &mut ui.overlay {+ overlay.status = format!("Could not select agent: {error}");+ }+ }+ }+ }+ }+ OverlayKind::Help => {+ if let Some(row) = selected {+ ui.overlay = None;+ return Box::pin(execute_command(&row.id, runtime, _client_id, state, ui))+ .await;+ }+ }+ OverlayKind::Themes => {+ if let Some(row) = selected {+ crate::presentation::select_theme(&row.id, ui);+ }+ }+ OverlayKind::Tools | OverlayKind::Subagents => {+ if let Some(row) = selected {+ crate::presentation::inspect(&row.id, state, ui);+ }+ }+ OverlayKind::Files => {+ if let Some(row) = selected {+ ui.composer.replace_current_token(&format!("@{}", row.id));+ }+ ui.overlay = None;+ }+ OverlayKind::PlanReview if !input.trim().is_empty() => {+ if let Some(review) = ui.pending_plan_review.take() {+ match runtime+ .invoke(+ "openhuman.plan_review_decide",+ json!({+ "request_id": review.request_id,+ "decision": "revise",+ "feedback": input.trim(),+ }),+ )+ .await+ {+ Ok(_) => state.push_system("Plan sent back for revision."),+ Err(error) => {+ state.push_system(format!("Could not revise plan: {error}"))+ }+ }+ }+ ui.overlay = None;+ }+ _ => {}+ }+ }+ _ => {}+ }+ false+}++pub(super) fn decision_shortcut(+ kind: OverlayKind,+ typing: bool,+ code: KeyCode,+) -> Option<&'static str> {+ if typing {+ return None;+ }+ match (kind, code) {+ (OverlayKind::Approvals, KeyCode::Char('1')) => Some("approve_once"),+ (OverlayKind::Approvals, KeyCode::Char('2')) => Some("approve_always_for_tool"),+ (OverlayKind::Approvals, KeyCode::Char('3')) => Some("approve_always_for_flow"),+ (OverlayKind::Approvals, KeyCode::Delete) => Some("deny"),+ (OverlayKind::PlanReview, KeyCode::Char('a' | 'A')) => Some("approve"),+ (OverlayKind::PlanReview, KeyCode::Char('r' | 'R')) => Some("reject"),+ _ => None,+ }+}++pub(super) fn selected_overlay_row(ui: &UiState) -> Option<OverlayRow> {+ let overlay = ui.overlay.as_ref()?;+ overlay+ .visible_rows()+ .get(overlay.selected)+ .cloned()+ .cloned()+}++pub(super) async fn decide_approval(+ runtime: &Arc<CoreRuntime>,+ request_id: &str,+ decision: &str,+ state: &mut TranscriptState,+ ui: &mut UiState,+) {+ if request_id.is_empty() {+ return;+ }+ match runtime+ .invoke(+ "openhuman.approval_decide",+ json!({"request_id": request_id, "decision": decision}),+ )+ .await+ {+ Ok(_) => {+ ui.pending_approvals+ .retain(|approval| approval.request_id != request_id);+ state.push_system(format!("Approval decision: {decision}."));+ ui.overlay = None;+ }+ Err(error) => state.push_system(format!("Could not decide approval: {error}")),+ }+}diff --git a/crates/openhuman-tui/src/app/thread_actions.rs b/crates/openhuman-tui/src/app/thread_actions.rsnew file mode 100644index 0000000000..9eeb0527cc--- /dev/null+++ b/crates/openhuman-tui/src/app/thread_actions.rs@@ -0,0 +1,180 @@+//! Conversation send, cancel and session loading.+use super::*;++/// Queue a chat turn on the current thread. Fire-and-forget: the reply streams+/// back over the web-channel bus and is folded in by the reducer.+pub(super) fn send_message(+ runtime: &Arc<CoreRuntime>,+ client_id: &str,+ state: &mut TranscriptState,+ ui: &mut UiState,+ queue_mode: &str,+) {+ if ui.auth_pending {+ state.push_system("Authentication is still in progress; your draft is preserved.");+ return;+ }+ let Some(message) = ui.composer.take_for_send() else {+ return;+ };+ ui.scroll_from_bottom = 0;+ state.begin_user_turn(&message);+ log::info!(+ "[tui] send message len={} thread={}",+ message.len(),+ ui.thread_id+ );++ let rt = runtime.clone();+ let cid = client_id.to_string();+ let tid = ui.thread_id.clone();+ let mode = queue_mode.to_string();+ let model_override = ui.model_override.clone();+ tokio::spawn(async move {+ let params = json!({+ "client_id": cid,+ "thread_id": tid,+ "message": message,+ "source": "type",+ "queue_mode": mode,+ "model_override": model_override,+ });+ if let Err(e) = rt.invoke("openhuman.channel_web_chat", params).await {+ log::error!("[tui] openhuman.channel_web_chat failed: {e}");+ // Surface the failure in-transcript via a synthetic chat_error so+ // the reducer clears the streaming state and shows the reason.+ web_chat::publish_web_channel_event(WebChannelEvent {+ event: "chat_error".to_string(),+ client_id: cid,+ thread_id: tid,+ message: Some(format!("Failed to send: {e}")),+ error_type: Some("transport".to_string()),+ ..Default::default()+ });+ }+ });+}++/// Cancel the in-flight turn on the current thread. The core emits a+/// `chat_error` ("Cancelled") which the reducer renders.+pub(super) fn cancel_turn(+ runtime: &Arc<CoreRuntime>,+ client_id: &str,+ thread_id: &str,+ state: &TranscriptState,+) {+ if !state.is_streaming() {+ return;+ }+ log::info!("[tui] cancel turn thread={thread_id}");+ let rt = runtime.clone();+ let cid = client_id.to_string();+ let tid = thread_id.to_string();+ tokio::spawn(async move {+ // Omit `request_id` → stop whatever is running on the thread.+ let params = json!({ "client_id": cid, "thread_id": tid });+ if let Err(e) = rt.invoke("openhuman.channel_web_cancel", params).await {+ log::error!("[tui] openhuman.channel_web_cancel failed: {e}");+ }+ });+}++/// Create a fresh thread and switch the UI to it. Awaited inline (fast, local+/// SQLite write) so `ui.thread_id` can be updated with the result.+pub(super) async fn new_thread(+ runtime: &Arc<CoreRuntime>,+ state: &mut TranscriptState,+ ui: &mut UiState,+) {+ log::info!("[tui] creating new thread");+ match runtime+ .invoke("openhuman.threads_create_new", json!({}))+ .await+ .ok()+ .and_then(|v| crate::runner::extract_thread_id(&v))+ {+ Some(new_id) => {+ ui.drafts+ .insert(ui.thread_id.clone(), ui.composer.text().to_string());+ ui.composer.clear();+ ui.viewport = Default::default();+ let client_id = state.client_id().to_string();+ *state = TranscriptState::new(client_id);+ ui.thread_id = new_id.clone();+ state.set_thread(new_id.clone());+ ui.scroll_from_bottom = 0;+ state.push_system(format!("Started a new thread · {new_id}"));+ log::info!("[tui] switched to new thread {new_id}");+ }+ None => {+ state.push_system("Could not create a new thread (see logs).".to_string());+ log::error!("[tui] threads.create_new returned no thread id");+ }+ }+}+pub(super) async fn switch_thread(+ runtime: &Arc<CoreRuntime>,+ state: &mut TranscriptState,+ ui: &mut UiState,+ thread_id: String,+) {+ match runtime+ .invoke(+ "openhuman.threads_transcript_get",+ json!({"thread_id":thread_id,"limit":500}),+ )+ .await+ {+ Ok(value) => {+ ui.drafts+ .insert(ui.thread_id.clone(), ui.composer.text().to_string());+ let client_id = state.client_id().to_string();+ *state = TranscriptState::new(client_id);+ state.set_thread(thread_id.clone());+ state.load_transcript(&value);+ ui.composer+ .set_text(ui.drafts.get(&thread_id).cloned().unwrap_or_default());+ ui.thread_id = thread_id;+ ui.viewport = Default::default();+ ui.scroll_from_bottom = 0;+ ui.overlay = None;+ }+ Err(error) => {+ if let Some(overlay) = &mut ui.overlay {+ overlay.status = format!("History unavailable: {error}");+ }+ }+ }+}++pub(super) async fn load_transcript(+ runtime: &Arc<CoreRuntime>,+ state: &mut TranscriptState,+ thread_id: &str,+) {+ match runtime+ .invoke(+ "openhuman.threads_transcript_get",+ json!({"thread_id": thread_id, "limit": 500}),+ )+ .await+ {+ Ok(value) => state.load_transcript(&value),+ Err(error) => log::warn!("[tui] could not load transcript thread={thread_id}: {error}"),+ }+}++pub(super) async fn refresh_agent_paths(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {+ if let Ok(value) = runtime+ .invoke("openhuman.config_get_agent_paths", json!({}))+ .await+ {+ let paths = crate::cockpit::unwrap_rpc(&value);+ ui.action_dir = paths+ .get("action_dir")+ .or_else(|| paths.get("actionDir"))+ .and_then(serde_json::Value::as_str)+ .unwrap_or_default()+ .to_string();+ }+}diff --git a/crates/openhuman-tui/src/cockpit.rs b/crates/openhuman-tui/src/cockpit.rsindex e85521aa79..80ee354744 100644--- a/crates/openhuman-tui/src/cockpit.rs+++ b/crates/openhuman-tui/src/cockpit.rs@@ -23,6 +23,10 @@ pub enum OverlayKind {Diff,HistorySearch,Files,+ Themes,+ Tools,+ Subagents,+ ToolDetail,}#[derive(Debug, Clone)]@@ -114,6 +118,7 @@ pub fn row_from_value(value: &Value, id_keys: &[&str], label_keys: &[&str]) -> Olabel: if label.is_empty() { id } else { label },detail: value.get("description")+ .or_else(|| value.get("when_to_use")).or_else(|| value.get("status")).and_then(Value::as_str).unwrap_or_default()diff --git a/crates/openhuman-tui/src/composer.rs b/crates/openhuman-tui/src/composer.rsindex 1b7a103f05..f1ca7bcf9a 100644--- a/crates/openhuman-tui/src/composer.rs+++ b/crates/openhuman-tui/src/composer.rs@@ -6,6 +6,13 @@ use unicode_width::UnicodeWidthChar;/// OpenHuman-native: commands either map to a stable core RPC or a local view.pub const COMMANDS: &[(&str, &str)] = &[("help", "show commands and keyboard shortcuts"),+ ("login", "sign in with a one-time token"),+ ("sessions", "browse saved conversations"),+ ("subagents", "inspect child agent activity"),+ ("tools", "inspect tool calls and output"),+ ("themes", "choose system, dark, light or monochrome"),+ ("mouse", "toggle terminal mouse capture"),+ ("chat", "return to the conversation"),("new", "start a new thread"),("resume", "browse saved threads"),("rename", "rename the current thread"),@@ -253,22 +260,26 @@ impl Composer {let mut cursor_row = 0usize;let mut cursor_col = 0usize;for (idx, ch) in self.text.chars().enumerate() {- if idx == self.cursor {- cursor_row = row;- cursor_col = col;- }if ch == '\n' {+ if idx == self.cursor {+ cursor_row = row;+ cursor_col = col;+ }rows.push(String::new());row += 1;col = 0;continue;}- let cw = ch.width().unwrap_or(0).max(1);+ let cw = ch.width().unwrap_or(0);if col + cw > width {rows.push(String::new());row += 1;col = 0;}+ if idx == self.cursor {+ cursor_row = row;+ cursor_col = col;+ }rows[row].push(ch);col += cw;}@@ -278,6 +289,34 @@ impl Composer {}(rows, cursor_row, cursor_col)}++ /// Position the cursor at a cell coordinate in the wrapped editor.+ pub fn click(&mut self, target_row: usize, target_col: usize, width: usize) {+ let mut row = 0;+ let mut col = 0;+ let width = width.max(1);+ for (index, ch) in self.text.chars().enumerate() {+ let cells = ch.width().unwrap_or(0);+ if ch != '\n' && cells > 0 && col + cells > width {+ row += 1;+ col = 0;+ }+ if row > target_row+ || (row == target_row && col + cells > target_col)+ || (ch == '\n' && row == target_row)+ {+ self.cursor = index;+ return;+ }+ if ch == '\n' {+ row += 1;+ col = 0;+ } else {+ col += cells;+ }+ }+ self.cursor = self.text.chars().count();+ }}fn char_to_byte(value: &str, char_index: usize) -> usize {diff --git a/crates/openhuman-tui/src/composer_tests.rs b/crates/openhuman-tui/src/composer_tests.rsindex f72efad973..43bc7255c9 100644--- a/crates/openhuman-tui/src/composer_tests.rs+++ b/crates/openhuman-tui/src/composer_tests.rs@@ -1,5 +1,16 @@use super::*;+#[test]+fn mouse_cursor_uses_wrapped_cells_and_combining_marks() {+ let mut composer = Composer::default();+ composer.set_text("界e\u{301}界");+ composer.click(1, 0, 3);+ let (_, row, col) = composer.display(3);+ assert_eq!((row, col), (1, 0));+ composer.insert_char('X');+ assert_eq!(composer.text(), "界e\u{301}X界");+}+#[test]fn unicode_editing_uses_character_indices() {let mut c = Composer::default();diff --git a/crates/openhuman-tui/src/controls.rs b/crates/openhuman-tui/src/controls.rsindex 4a8c2f3623..6dd6bc4fc7 100644--- a/crates/openhuman-tui/src/controls.rs+++ b/crates/openhuman-tui/src/controls.rs@@ -84,10 +84,28 @@ pub async fn refresh_config(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {let privacy = runtime.invoke("openhuman.config_get_privacy_mode", json!({})).await;+ if let Ok(snapshot) = runtime.invoke("openhuman.config_get", json!({})).await {+ ui.agent_name = rpc_payload(&snapshot)+ .pointer("/config/agent/chat_agent_id")+ .and_then(serde_json::Value::as_str)+ .unwrap_or("orchestrator")+ .to_string();+ }match (client, autonomy, privacy) {(Ok(client), Ok(autonomy), Ok(privacy)) => {let client = rpc_payload(&client);+ ui.provider_id = catalog_provider(client);+ ui.effective_model = client+ .get("default_model")+ .and_then(serde_json::Value::as_str)+ .filter(|model| !model.is_empty())+ .unwrap_or("Configured model")+ .to_string();let autonomy = rpc_payload(&autonomy);+ ui.policy_enabled = autonomy+ .get("enabled")+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false);let privacy = rpc_payload(&privacy);for item in &mut ui.config_items {item.value = match item.key {@@ -105,6 +123,11 @@ pub async fn refresh_config(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {}pub async fn handle_settings_key(key: KeyEvent, runtime: &Arc<CoreRuntime>, ui: &mut UiState) {+ if ui.auth_pending {+ ui.settings_status =+ "Signing in… You can browse views while authentication completes.".into();+ return;+ }if let Some(token) = ui.login_token.as_mut() {match key.code {KeyCode::Esc => {@@ -197,6 +220,24 @@ async fn login_with_token(runtime: &Arc<CoreRuntime>, ui: &mut UiState) {return;}ui.settings_status = "Signing in…".to_string();+ if let Some(tx) = ui.auth_tx.clone() {+ ui.auth_pending = true;+ let manager = crate::session::session_manager(runtime);+ let token = zeroize::Zeroizing::new(token);+ tokio::spawn(async move {+ let result = match tokio::time::timeout(+ std::time::Duration::from_secs(30),+ manager.login_with_token(token.trim()),+ )+ .await+ {+ Ok(result) => result.map(|_| ()).map_err(|error| error.to_string()),+ Err(_) => Err("Sign-in timed out. Check Account before retrying.".into()),+ };+ let _ = tx.send(result);+ });+ return;+ }// Exchange, validate against `/auth/me`, and install in the core — all// owned by `openhuman-tinyhumans`; the JWT never passes through this module.let result = crate::session::session_manager(runtime)@@ -229,6 +270,28 @@ fn rpc_payload(value: &serde_json::Value) -> &serde_json::Value {openhuman_rpc::unwrap_rpc(value)}+fn catalog_provider(client: &serde_json::Value) -> String {+ let route = client+ .get("chat_provider")+ .and_then(serde_json::Value::as_str)+ .unwrap_or("cloud")+ .trim();+ if let Some(id) = route.strip_prefix("pid:") {+ return id.split(':').next().unwrap_or("openhuman").to_string();+ }+ let prefix = route.split(':').next().unwrap_or("cloud");+ if matches!(prefix, "cloud" | "primary" | "") {+ client+ .get("primary_cloud")+ .and_then(serde_json::Value::as_str)+ .filter(|id| !id.trim().is_empty())+ .unwrap_or("openhuman")+ .to_string()+ } else {+ prefix.to_string()+ }+}+fn string_at(value: &serde_json::Value, path: &[&str]) -> String {path.iter().try_fold(value, |current, key| current.get(*key))diff --git a/crates/openhuman-tui/src/controls_tests.rs b/crates/openhuman-tui/src/controls_tests.rsindex d0fbd4287f..d056dee791 100644--- a/crates/openhuman-tui/src/controls_tests.rs+++ b/crates/openhuman-tui/src/controls_tests.rs@@ -1,5 +1,22 @@use super::*;+#[test]+fn model_catalog_uses_the_actual_configured_provider() {+ assert_eq!(catalog_provider(&json!({})), "openhuman");+ assert_eq!(+ catalog_provider(&json!({"chat_provider":"cloud","primary_cloud":"my-provider-id"})),+ "my-provider-id"+ );+ assert_eq!(+ catalog_provider(&json!({"chat_provider":"ollama:local"})),+ "ollama"+ );+ assert_eq!(+ catalog_provider(&json!({"chat_provider":"pid:opaque-id:model"})),+ "opaque-id"+ );+}+#[test]fn rpc_payload_unwraps_runtime_and_api_envelopes() {let value = json!({"result": {"data": {"mode": "standard"}}, "logs": []});diff --git a/crates/openhuman-tui/src/demo.rs b/crates/openhuman-tui/src/demo.rsnew file mode 100644index 0000000000..260820c222--- /dev/null+++ b/crates/openhuman-tui/src/demo.rs@@ -0,0 +1,280 @@+//! Offline preview: the production renderer and input geometry over sample events.+use super::actions::Action;+use super::cockpit::{Overlay, OverlayKind};+use super::state::TranscriptState;+use super::ui_state::{AppTab, UiState};+use crossterm::event::{self, Event, KeyCode, KeyModifiers};+use openhuman_rpc::embed::chat_surface::WebChannelEvent;++pub fn sample() -> TranscriptState {+ let mut state = TranscriptState::new("preview");+ state.set_thread("preview");+ state.begin_user_turn("Make the terminal UI simpler, with mouse controls.");+ let ev = |name: &str| WebChannelEvent {+ event: name.into(),+ client_id: "preview".into(),+ thread_id: "preview".into(),+ request_id: "sample-turn".into(),+ ..Default::default()+ };+ state.apply_event(&WebChannelEvent {+ delta: Some("I’ll keep the conversation central and make the work easy to inspect.".into()),+ ..ev("text_delta")+ });+ state.apply_event(&WebChannelEvent {+ tool_name: Some("Read source".into()),+ tool_call_id: Some("read-1".into()),+ args: Some(serde_json::json!({"path":"src/render.rs"})),+ ..ev("tool_call")+ });+ state.apply_event(&WebChannelEvent {tool_name:Some("Read source".into()),tool_call_id:Some("read-1".into()),success:Some(true),elapsed_ms:Some(12),output:Some("Header → conversation → composer → status\nCached viewport rendering\nShared mouse and keyboard actions".into()),..ev("tool_result")});+ state.apply_event(&WebChannelEvent {+ tool_name: Some("Explore".into()),+ skill_id: Some("child-1".into()),+ ..ev("subagent_spawned")+ });+ state.apply_event(&WebChannelEvent {skill_id:Some("child-1".into()),delta:Some("Checked the command, login, and tool-call surfaces.\nMouse targets use the displayed layout.".into()),..ev("subagent_text_delta")});+ state.apply_event(&WebChannelEvent {+ skill_id: Some("child-1".into()),+ elapsed_ms: Some(840),+ ..ev("subagent_completed")+ });+ state.apply_event(&WebChannelEvent {full_response:Some("Ready to inspect. Click a tool row to expand it, use Tools or /subagents for details, and choose a theme in Settings.\n\nThis is an offline preview; no model or account calls are made.".into()),..ev("chat_done")});+ state+}++pub fn run(no_mouse: bool) -> anyhow::Result<()> {+ let mut state = sample();+ let mut ui = UiState::new("preview".into(), "preview".into());+ ui.demo = true;+ ui.mouse_enabled = !no_mouse;+ ui.auth_summary = "Offline preview".into();+ ui.model_override = Some("Preview model".into());+ ui.action_dir = "preview".into();+ let mut terminal = super::terminal::TerminalGuard::enter_with_options(true)?;+ terminal.set_mouse(ui.mouse_enabled)?;+ let mut dirty = true;+ loop {+ if dirty {+ terminal.set_mouse(ui.mouse_enabled)?;+ terminal+ .terminal()+ .draw(|f| super::render::draw(f, &state, &mut ui))?;+ dirty = false;+ }+ if !event::poll(std::time::Duration::from_millis(100))? {+ continue;+ }+ match event::read()? {+ Event::Key(key) => {+ if key.kind == crossterm::event::KeyEventKind::Release {+ continue;+ }+ let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);+ if ctrl && key.code == KeyCode::Char('d') {+ break;+ }+ if ctrl && key.code == KeyCode::Char('p') {+ command("help", &mut state, &mut ui);+ } else if ui.overlay.is_some() {+ match key.code {+ KeyCode::Esc => ui.overlay = None,+ KeyCode::Enter => {+ if activate_overlay(&mut state, &mut ui) {+ break;+ }+ }+ KeyCode::Up => {+ let o = ui.overlay.as_mut().unwrap();+ o.selected = o.selected.saturating_sub(1);+ }+ KeyCode::Down => {+ let o = ui.overlay.as_mut().unwrap();+ o.selected =+ (o.selected + 1).min(o.visible_rows().len().saturating_sub(1));+ }+ KeyCode::Backspace => {+ let o = ui.overlay.as_mut().unwrap();+ o.filter.pop();+ o.clamp_selection();+ }+ KeyCode::Char(c) if !ctrl => {+ let o = ui.overlay.as_mut().unwrap();+ o.filter.push(c);+ o.clamp_selection();+ }+ _ => {}+ }+ } else {+ match key.code {+ KeyCode::Char('c') if ctrl => ui.composer.clear(),+ KeyCode::Char('j') if ctrl => ui.composer.newline(),+ KeyCode::Tab => {+ if !ui.composer.complete_command() {+ ui.focus = (ui.focus + 1) % (ui.hits.len() + 1);+ }+ }+ KeyCode::BackTab => ui.focus = ui.focus.saturating_sub(1),+ KeyCode::Enter if key.modifiers.contains(KeyModifiers::SHIFT) => {+ ui.composer.newline()+ }+ KeyCode::Enter => {+ let action = if ui.focus > 0 {+ ui.hits+ .get(ui.focus - 1)+ .map(|hit| hit.action.clone())+ .unwrap_or(Action::Send)+ } else {+ Action::Send+ };+ if act(action, &mut state, &mut ui) {+ break;+ }+ }+ KeyCode::Esc => {+ ui.active_tab = AppTab::Chat;+ ui.focus = 0;+ }+ KeyCode::PageUp => {+ ui.scroll_from_bottom = ui.scroll_from_bottom.saturating_add(10)+ }+ KeyCode::PageDown => {+ ui.scroll_from_bottom = ui.scroll_from_bottom.saturating_sub(10)+ }+ KeyCode::Backspace => ui.composer.backspace(),+ KeyCode::Delete => ui.composer.delete(),+ KeyCode::Left => ui.composer.move_left(),+ KeyCode::Right => ui.composer.move_right(),+ KeyCode::Home => ui.composer.move_home(),+ KeyCode::End => ui.composer.move_end(),+ KeyCode::Char(c) if !ctrl => ui.composer.insert_char(c),+ _ => {}+ }+ }+ dirty = true;+ }+ Event::Mouse(mouse) if ui.mouse_enabled => {+ if let Some(action) = super::input::mouse_action(mouse, &mut ui) {+ if act(action, &mut state, &mut ui) {+ break;+ }+ }+ dirty = true;+ }+ Event::Resize(_, _) => {+ ui.hits.clear();+ dirty = true;+ }+ Event::Paste(text) => {+ if let Some(o) = &mut ui.overlay {+ o.filter.push_str(&text);+ o.clamp_selection();+ } else {+ ui.composer.insert_str(&text);+ }+ dirty = true;+ }+ _ => {}+ }+ }+ Ok(())+}++fn act(action: Action, state: &mut TranscriptState, ui: &mut UiState) -> bool {+ match action {+ Action::Command(cmd) => return command(cmd, state, ui),+ Action::View(tab) => {+ ui.active_tab = tab;+ ui.focus = 0;+ }+ Action::Send => {+ if let Some(message) = ui.composer.take_for_send() {+ if let Some(cmd) = message.strip_prefix('/') {+ return command(cmd, state, ui);+ }+ state+ .push_system("Offline preview: use the live TUI to send messages to an agent.");+ ui.scroll_from_bottom = 0;+ }+ }+ Action::Entry(index) => state.toggle_entry(index),+ Action::Latest => ui.scroll_from_bottom = 0,+ Action::Complete(cmd) => {+ ui.composer.set_text(format!("/{cmd} "));+ ui.focus = 0;+ }+ Action::Composer => ui.focus = 0,+ Action::OverlayRow(index) => {+ if let Some(o) = &mut ui.overlay {+ o.selected = index;+ }+ return activate_overlay(state, ui);+ }+ Action::OverlayKey(KeyCode::Esc) => ui.overlay = None,+ Action::OverlayKey(KeyCode::Enter) => return activate_overlay(state, ui),+ Action::SettingsRow(_) => {+ ui.settings_status =+ "Offline preview. Start without --demo for real account login.".into()+ }+ _ => {}+ }+ false+}+fn command(cmd: &str, state: &mut TranscriptState, ui: &mut UiState) -> bool {+ let cmd = cmd.trim();+ if super::presentation::open(cmd, state, ui) {+ return false;+ }+ match cmd {+ "quit" => return true,+ "new" => {+ *state = TranscriptState::new("preview");+ ui.viewport = Default::default();+ ui.scroll_from_bottom = 0;+ }+ "settings" | "login" | "logout" => {+ ui.active_tab = AppTab::Settings;+ ui.settings_status = "Offline preview. Start without --demo to sign in.".into();+ }+ "config" => ui.active_tab = AppTab::Config,+ "logs" => ui.active_tab = AppTab::Logs,+ "agents" | "sessions" | "resume" | "model" => {+ let kind = match cmd {+ "agents" => OverlayKind::Agents,+ "model" => OverlayKind::Model,+ _ => OverlayKind::Threads,+ };+ let mut o = Overlay::new(kind, "Preview choices");+ o.rows = vec![super::presentation::row(+ "preview",+ "Preview conversation / agent / model",+ "Sample data; live mode reads the runtime catalog",+ )];+ ui.overlay = Some(o);+ }+ _ => state.push_system("This action needs live mode. Start the TUI without --demo."),+ }+ ui.focus = 0;+ false+}+fn activate_overlay(state: &mut TranscriptState, ui: &mut UiState) -> bool {+ let Some(o) = &ui.overlay else {+ return false;+ };+ let kind = o.kind;+ let selected = o.visible_rows().get(o.selected).map(|row| row.id.clone());+ if let Some(id) = selected {+ match kind {+ OverlayKind::Help => {+ ui.overlay = None;+ return command(&id, state, ui);+ }+ OverlayKind::Themes => super::presentation::select_theme(&id, ui),+ OverlayKind::Tools | OverlayKind::Subagents => {+ super::presentation::inspect(&id, state, ui)+ }+ _ => ui.overlay = None,+ }+ }+ false+}diff --git a/crates/openhuman-tui/src/effects.rs b/crates/openhuman-tui/src/effects.rsnew file mode 100644index 0000000000..236572ae3f--- /dev/null+++ b/crates/openhuman-tui/src/effects.rs@@ -0,0 +1,84 @@+//! Generation-tagged background reads; stale responses never replace a new view.+use super::cockpit::{array_at, row_from_value, Overlay, OverlayKind};+use super::ui_state::UiState;+use serde_json::Value;+pub struct OverlayReply {+ pub thread_id: String,+ pub generation: u64,+ pub overlay: Overlay,+}++pub fn build(+ kind: OverlayKind,+ title: &str,+ result: Result<Value, String>,+ array_keys: &[String],+ id_keys: &[String],+ label_keys: &[String],+) -> Overlay {+ let mut overlay = Overlay::new(kind, title);+ match result {+ Ok(value) => {+ let keys: Vec<_> = array_keys.iter().map(String::as_str).collect();+ let ids: Vec<_> = id_keys.iter().map(String::as_str).collect();+ let labels: Vec<_> = label_keys.iter().map(String::as_str).collect();+ let items = array_at(&value, &keys);+ overlay.rows = items+ .iter()+ .filter(|item| {+ kind != OverlayKind::Agents+ || item.get("id").and_then(Value::as_str) == Some("orchestrator")+ || item+ .get("can_run_as_user_facing_worker")+ .and_then(Value::as_bool)+ == Some(true)+ })+ .map(|item| row_from_value(item, &ids, &labels))+ .collect();+ if array_keys.is_empty() {+ let detail = serde_json::to_string_pretty(super::cockpit::unwrap_rpc(&value))+ .unwrap_or_default();+ overlay.rows = detail+ .lines()+ .enumerate()+ .map(|(index, line)| super::presentation::row(index.to_string(), line, ""))+ .collect();+ }+ overlay.status = format!(+ "{} item(s) · type to filter · Enter selects · Esc closes",+ overlay.rows.len()+ );+ }+ Err(error) => {+ overlay.status = format!("Could not load: {error}. Reopen this view to retry.")+ }+ }+ if kind == OverlayKind::Model {+ overlay.rows.insert(+ 0,+ super::presentation::row(+ "",+ "Configured default",+ "Use the provider's configured model",+ ),+ );+ }+ overlay+}+pub fn apply(reply: OverlayReply, ui: &mut UiState) {+ if reply.thread_id != ui.thread_id || reply.generation != ui.overlay_generation {+ return;+ }+ if let Some(current) = &ui.overlay {+ if current.kind == reply.overlay.kind {+ let mut next = reply.overlay;+ next.filter = current.filter.clone();+ next.selected = current.selected;+ next.clamp_selection();+ ui.overlay = Some(next);+ }+ }+}+#[cfg(test)]+#[path = "effects_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/effects_tests.rs b/crates/openhuman-tui/src/effects_tests.rsnew file mode 100644index 0000000000..451b389be1--- /dev/null+++ b/crates/openhuman-tui/src/effects_tests.rs@@ -0,0 +1,42 @@+use super::*;+#[test]+fn stale_catalog_cannot_replace_another_thread_or_closed_overlay() {+ let mut ui = UiState::new("new".into(), "client".into());+ ui.overlay_generation = 2;+ ui.overlay = Some(Overlay::new(OverlayKind::Model, "current"));+ apply(+ OverlayReply {+ thread_id: "old".into(),+ generation: 2,+ overlay: Overlay::new(OverlayKind::Model, "stale"),+ },+ &mut ui,+ );+ assert_eq!(ui.overlay.as_ref().unwrap().title, "current");+ ui.overlay = None;+ apply(+ OverlayReply {+ thread_id: "new".into(),+ generation: 2,+ overlay: Overlay::new(OverlayKind::Model, "stale"),+ },+ &mut ui,+ );+ assert!(ui.overlay.is_none());+}+#[test]+fn refreshing_catalog_preserves_typed_filter() {+ let mut ui = UiState::new("t".into(), "c".into());+ let mut current = Overlay::new(OverlayKind::Model, "models");+ current.filter = "fast".into();+ ui.overlay = Some(current);+ apply(+ OverlayReply {+ thread_id: "t".into(),+ generation: 0,+ overlay: Overlay::new(OverlayKind::Model, "models"),+ },+ &mut ui,+ );+ assert_eq!(ui.overlay.as_ref().unwrap().filter, "fast");+}diff --git a/crates/openhuman-tui/src/input.rs b/crates/openhuman-tui/src/input.rsnew file mode 100644index 0000000000..b70d6e8bbd--- /dev/null+++ b/crates/openhuman-tui/src/input.rs@@ -0,0 +1,83 @@+//! Pointer translation is independent of runtime effects.+use super::actions::{hit_at, Action};+use super::ui_state::{AppTab, UiState};+use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};+use ratatui::layout::Position;++pub fn mouse_action(mouse: MouseEvent, ui: &mut UiState) -> Option<Action> {+ let position = Position::new(mouse.column, mouse.row);+ match mouse.kind {+ MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {+ let up = mouse.kind == MouseEventKind::ScrollUp;+ if let Some(overlay) = &mut ui.overlay {+ overlay.selected = if up {+ overlay.selected.saturating_sub(3)+ } else {+ (overlay.selected + 3).min(overlay.visible_rows().len().saturating_sub(1))+ };+ } else if ui.active_tab == AppTab::Logs {+ ui.log_scroll_from_bottom = if up {+ ui.log_scroll_from_bottom.saturating_add(3)+ } else {+ ui.log_scroll_from_bottom.saturating_sub(3)+ };+ } else if ui.transcript_area.contains(position) {+ ui.scroll_from_bottom = if up {+ ui.scroll_from_bottom.saturating_add(3)+ } else {+ ui.scroll_from_bottom.saturating_sub(3)+ };+ }+ None+ }+ MouseEventKind::Down(MouseButton::Left) => {+ let action = hit_at(&ui.hits, mouse.column, mouse.row);+ if action.is_none()+ && !ui.overlay_area.contains(position)+ && ui.overlay.as_ref().is_some_and(|o| {+ !matches!(+ o.kind,+ super::cockpit::OverlayKind::Approvals+ | super::cockpit::OverlayKind::PlanReview+ | super::cockpit::OverlayKind::ConfirmDelete+ )+ })+ {+ ui.overlay = None;+ ui.focus = 0;+ return None;+ }+ if action == Some(Action::Composer) {+ let area = ui.composer_area;+ ui.composer.click(+ (mouse.row - area.y) as usize + ui.composer_first_row,+ (mouse.column - area.x) as usize,+ area.width.saturating_sub(1) as usize,+ );+ ui.focus = 0;+ }+ action+ }+ MouseEventKind::Moved => {+ if let Some(index) = ui.hits.iter().position(|hit| hit.area.contains(position)) {+ if let Action::OverlayRow(row) = ui.hits[index].action {+ if let Some(overlay) = &mut ui.overlay {+ overlay.selected = row;+ }+ } else {+ ui.focus = if ui.hits[index].action == Action::Composer {+ 0+ } else {+ index + 1+ };+ }+ }+ None+ }+ _ => None,+ }+}++#[cfg(test)]+#[path = "input_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/input_tests.rs b/crates/openhuman-tui/src/input_tests.rsnew file mode 100644index 0000000000..9bac3152fb--- /dev/null+++ b/crates/openhuman-tui/src/input_tests.rs@@ -0,0 +1,25 @@+use super::super::actions::Hit;+use super::*;+use crossterm::event::KeyModifiers;+use ratatui::layout::Rect;+#[test]+fn release_and_drag_do_not_activate_and_wheel_unfollows() {+ let mut ui = UiState::new("t".into(), "c".into());+ ui.transcript_area = Rect::new(0, 2, 80, 15);+ ui.hits.push(Hit {+ area: Rect::new(0, 2, 80, 1),+ action: Action::Entry(3),+ });+ let mut mouse = MouseEvent {+ kind: MouseEventKind::Up(MouseButton::Left),+ column: 2,+ row: 2,+ modifiers: KeyModifiers::NONE,+ };+ assert_eq!(mouse_action(mouse, &mut ui), None);+ mouse.kind = MouseEventKind::ScrollUp;+ mouse_action(mouse, &mut ui);+ assert_eq!(ui.scroll_from_bottom, 3);+ mouse.kind = MouseEventKind::Down(MouseButton::Left);+ assert_eq!(mouse_action(mouse, &mut ui), Some(Action::Entry(3)));+}diff --git a/crates/openhuman-tui/src/lib.rs b/crates/openhuman-tui/src/lib.rsindex 81e20711eb..f7a90fcf64 100644--- a/crates/openhuman-tui/src/lib.rs+++ b/crates/openhuman-tui/src/lib.rs@@ -1,6 +1,6 @@//! OpenHuman terminal client, embedding the core in-process.//!-//! A [ratatui]-based agent cockpit with Chat, Logs, Config, and Settings,+//! A [ratatui]-based conversation UI with mouse control, themes, and diagnostics,//! persistent thread resume, command/file pickers, approvals, plan review,//! agent/skill/MCP/artifact views, Git review, and a multiline composer.//! Chat uses the **same `web_chat` surface** the desktop app drives (`openhuman.channel_web_chat` /@@ -30,17 +30,25 @@//!//! See `README.md` for build/run instructions and the packaging story.+mod actions;+mod activity;mod app;mod cockpit;mod composer;mod controls;mod crash_reporting;+mod demo;+mod effects;+mod input;+mod presentation;mod render;mod runner;mod session;mod state;mod terminal;+mod theme;mod ui_state;+mod viewport;pub use crash_reporting::init_crash_reporting;pub use runner::run_from_cli;diff --git a/crates/openhuman-tui/src/main.rs b/crates/openhuman-tui/src/main.rsindex eaa5d4abd6..b8b59d4397 100644--- a/crates/openhuman-tui/src/main.rs+++ b/crates/openhuman-tui/src/main.rs@@ -5,8 +5,13 @@ fn main() {// Keep the guard alive for the entire terminal session. `init_for_tui`// installs the tracing layer, while this creates the client that receives// its events and installs Sentry's panic integration.- let _sentry_guard = openhuman_tui::init_crash_reporting();- if let Err(error) = openhuman_tui::run_from_cli(&std::env::args().skip(1).collect::<Vec<_>>()) {+ let args = std::env::args().skip(1).collect::<Vec<_>>();+ let _sentry_guard = if args.iter().any(|arg| arg == "--demo") {+ None+ } else {+ Some(openhuman_tui::init_crash_reporting())+ };+ if let Err(error) = openhuman_tui::run_from_cli(&args) {eprintln!("Error: {error:#}");std::process::exit(1);}diff --git a/crates/openhuman-tui/src/presentation.rs b/crates/openhuman-tui/src/presentation.rsnew file mode 100644index 0000000000..67aa8b2243--- /dev/null+++ b/crates/openhuman-tui/src/presentation.rs@@ -0,0 +1,105 @@+//! Local commands and read-only inspection shared with preview mode.+use super::cockpit::{Overlay, OverlayKind, OverlayRow};+use super::state::TranscriptState;+use super::theme::Theme;+use super::ui_state::{AppTab, UiState};+pub fn row(+ id: impl Into<String>,+ label: impl Into<String>,+ detail: impl Into<String>,+) -> OverlayRow {+ OverlayRow {+ id: id.into(),+ label: label.into(),+ detail: detail.into(),+ payload: serde_json::Value::Null,+ }+}+pub fn open(command: &str, state: &TranscriptState, ui: &mut UiState) -> bool {+ match command {+ "help" => {+ let mut o = Overlay::new(OverlayKind::Help, "Commands");+ o.rows = super::composer::COMMANDS+ .iter()+ .map(|(n, d)| row(*n, format!("/{n}"), *d))+ .collect();+ o.status = "Search · ↑↓ navigate · Enter runs · Esc closes".into();+ ui.overlay = Some(o);+ }+ "themes" => {+ let mut o = Overlay::new(OverlayKind::Themes, "Appearance");+ o.rows = Theme::ALL+ .iter()+ .map(|t| row(t.name(), t.name(), "Applies to this terminal session"))+ .collect();+ o.status = "Enter selects · System uses terminal colors".into();+ ui.overlay = Some(o);+ }+ "tools" | "subagents" => {+ let child = command == "subagents";+ let mut o = Overlay::new(+ if child {+ OverlayKind::Subagents+ } else {+ OverlayKind::Tools+ },+ if child { "Subagents" } else { "Tool calls" },+ );+ o.rows = state+ .entries()+ .iter()+ .enumerate()+ .filter_map(|(i, e)| {+ e.activity.as_ref().filter(|a| a.child == child).map(|a| {+ row(+ i.to_string(),+ a.summary(),+ "Enter inspects arguments/output · read-only",+ )+ })+ })+ .collect();+ o.status = if o.rows.is_empty() {+ "No activity in this conversation".into()+ } else {+ "Enter inspects · Esc returns to the parent".into()+ };+ ui.overlay = Some(o);+ }+ "mouse" => ui.mouse_enabled = !ui.mouse_enabled,+ "chat" => {+ ui.active_tab = AppTab::Chat;+ ui.overlay = None;+ }+ _ => return false,+ }+ ui.focus = 0;+ true+}+pub fn select_theme(id: &str, ui: &mut UiState) {+ if let Some(t) = Theme::ALL.iter().find(|t| t.name() == id) {+ ui.theme = *t;+ }+ ui.overlay = None;+ ui.focus = 0;+}+pub fn inspect(id: &str, state: &TranscriptState, ui: &mut UiState) {+ let Some(a) = id+ .parse::<usize>()+ .ok()+ .and_then(|i| state.entries().get(i))+ .and_then(|e| e.activity.as_ref())+ else {+ return;+ };+ let mut o = Overlay::new(OverlayKind::ToolDetail, a.summary());+ o.rows = a+ .details()+ .lines()+ .enumerate()+ .map(|(i, l)| row(i.to_string(), l, ""))+ .collect();+ o.status = "Stored preview · ↑↓ / wheel scroll · Esc returns to parent".into();+ ui.overlay = Some(o);+ ui.focus = 0;+}diff --git a/crates/openhuman-tui/src/render.rs b/crates/openhuman-tui/src/render.rsindex 09d59cb9f1..7e50860885 100644--- a/crates/openhuman-tui/src/render.rs+++ b/crates/openhuman-tui/src/render.rs@@ -1,508 +1,384 @@-//! Ratatui rendering for the tabbed terminal UI — pure view over-//! [`TranscriptState`] + [`UiState`]. No state mutation happens here.-//!-//! Layout (top → bottom):-//! * transcript viewport (fills remaining height, wraps + scrolls)-//! * single-line input box (bordered)-//! * status bar (thread id, turn state, key hints)--use ratatui::layout::{Constraint, Direction, Layout, Rect};-use ratatui::style::{Color, Modifier, Style};-use ratatui::text::{Line, Span, Text};-use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Tabs, Wrap};-use ratatui::Frame;-use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};-+//! Conversation-first rendering; each frame owns its cell-based input targets.+use super::actions::{Action, Hit};+use super::activity::Status;+use super::cockpit::OverlayKind;use super::state::{EntryKind, TranscriptState};+use super::theme::{safe_text, Palette};use super::ui_state::{AppTab, SettingsAction, UiState};+mod overlay;+mod views;+use overlay::overlay;+use ratatui::layout::{Position, Rect};+use ratatui::style::{Modifier, Style};+use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};+use ratatui::Frame;+use unicode_width::UnicodeWidthStr;+use views::{config, logs, settings};-/// Ocean accent from the design tokens (`#4A83DD`), kept terminal-native.-const OCEAN: Color = Color::Rgb(0x4A, 0x83, 0xDD);--const SPINNER_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];--/// Draw one frame.-pub fn draw(frame: &mut Frame, state: &TranscriptState, ui: &UiState) {- let chunks = Layout::default()- .direction(Direction::Vertical)- .constraints([- Constraint::Length(3),- Constraint::Min(1),- Constraint::Length(1),- ])- .split(frame.area());-- draw_tabs(frame, chunks[0], ui);- match ui.active_tab {- AppTab::Logs => draw_logs(frame, chunks[1], ui),- AppTab::Chat => draw_chat(frame, chunks[1], state, ui),- AppTab::Config => draw_config(frame, chunks[1], ui),- AppTab::Settings => draw_settings(frame, chunks[1], ui),- }- draw_footer(frame, chunks[2], state, ui);- if let Some(overlay) = &ui.overlay {- draw_overlay(frame, overlay);- }-}--fn draw_tabs(frame: &mut Frame, area: Rect, ui: &UiState) {- let selected = AppTab::ALL- .iter()- .position(|tab| *tab == ui.active_tab)- .unwrap_or(0);- let titles = AppTab::ALL- .iter()- .enumerate()- .map(|(idx, tab)| Line::from(format!(" {} {} ", idx + 1, tab.title())))- .collect::<Vec<_>>();- let tabs = Tabs::new(titles)- .select(selected)- .block(- Block::default()- .borders(Borders::ALL)- .title(" OpenHuman CLI "),- )- .style(Style::default().fg(Color::DarkGray))- .highlight_style(Style::default().fg(OCEAN).add_modifier(Modifier::BOLD));- frame.render_widget(tabs, area);-}--fn draw_chat(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &UiState) {- let width = area.width.saturating_sub(4).max(1) as usize;- let (rows, _, _) = ui.composer.display(width);- let suggestions = ui.composer.command_matches().len().min(6);- let composer_height = (rows.len().min(8) + suggestions + 2).max(3) as u16;- let chunks = Layout::default()- .direction(Direction::Vertical)- .constraints([Constraint::Min(1), Constraint::Length(composer_height)])- .split(area);- draw_transcript(frame, chunks[0], state, ui);- draw_input(frame, chunks[1], ui);-}--fn draw_logs(frame: &mut Frame, area: Rect, ui: &UiState) {- let lines = openhuman_rpc::embed::process::tui_log_lines();- let text = if lines.is_empty() {- Text::from("Core logs will appear here as OpenHuman starts.")- } else {- Text::from(lines.join("\n"))- };- let inner_height = area.height.saturating_sub(2).max(1);- let inner_width = area.width.saturating_sub(2).max(1);- let total_rows = text- .lines- .iter()- .map(|line| u32::from(wrapped_line_count(line, inner_width)))- .sum::<u32>();- let max_scroll = total_rows- .saturating_sub(u32::from(inner_height))- .min(u32::from(u16::MAX)) as u16;- let top = max_scroll.saturating_sub(ui.log_scroll_from_bottom.min(max_scroll));- let paragraph = Paragraph::new(text)- .block(Block::default().borders(Borders::ALL).title(" Core logs "))- .style(Style::default().fg(Color::Gray))- .wrap(Wrap { trim: false })- .scroll((top, 0));- frame.render_widget(paragraph, area);-}--fn draw_config(frame: &mut Frame, area: Rect, ui: &UiState) {- let chunks = Layout::default()- .direction(Direction::Vertical)- .constraints([Constraint::Min(5), Constraint::Length(4)])- .split(area);- let items = ui- .config_items- .iter()- .map(|item| {- ListItem::new(Line::from(vec![- Span::styled(- format!("{:<18}", item.label),- Style::default().fg(Color::Gray),- ),- Span::styled(- if item.value.is_empty() {- "(not set)"- } else {- &item.value- },- Style::default().fg(Color::White),- ),- ]))- })- .collect::<Vec<_>>();- let mut list_state = ListState::default().with_selected(Some(ui.config_selected));- let list = List::new(items)- .block(- Block::default()- .borders(Borders::ALL)- .title(" Safe configuration "),- )- .highlight_symbol("› ")- .highlight_style(Style::default().fg(OCEAN).add_modifier(Modifier::BOLD));- frame.render_stateful_widget(list, chunks[0], &mut list_state);-- let selected = &ui.config_items[ui.config_selected.min(ui.config_items.len() - 1)];- let detail = if let Some(input) = &ui.config_edit {- let visible = tail_to_width(input, chunks[1].width.saturating_sub(5) as usize);- format!("Editing {}\n> {}▏", selected.label, visible)- } else {- format!("{}\n{}", selected.hint, ui.config_status)- };+pub fn draw(frame: &mut Frame, state: &TranscriptState, ui: &mut UiState) {+ let area = frame.area();+ let p = ui.theme.palette();+ ui.hits.clear();frame.render_widget(- Paragraph::new(detail)- .block(Block::default().borders(Borders::ALL).title(" Edit "))- .wrap(Wrap { trim: false }),- chunks[1],+ Block::default().style(Style::default().fg(p.text).bg(p.background)),+ area,);-}--fn draw_settings(frame: &mut Frame, area: Rect, ui: &UiState) {- let chunks = Layout::default()- .direction(Direction::Vertical)- .constraints([- Constraint::Length(5),- Constraint::Length(5),- Constraint::Min(3),- ])- .split(area);- frame.render_widget(- Paragraph::new(vec![- Line::from(Span::styled(- &ui.auth_summary,- Style::default()- .fg(Color::White)- .add_modifier(Modifier::BOLD),- )),- Line::from(ui.account_detail.clone()),- ])- .block(Block::default().borders(Borders::ALL).title(" Account "))- .wrap(Wrap { trim: false }),- chunks[0],+ if area.width < 24 || area.height < 8 {+ text(+ frame,+ area,+ "Resize terminal · Ctrl+D exits",+ Style::default().fg(p.text),+ );+ return;+ }+ text(+ frame,+ Rect::new(area.x + 1, area.y, 12, 1),+ "OpenHuman",+ Style::default().fg(p.text).add_modifier(Modifier::BOLD),);-- let actions = SettingsAction::ALL- .iter()- .map(|action| ListItem::new(action.label()))- .collect::<Vec<_>>();- let mut action_state = ListState::default().with_selected(Some(ui.settings_selected));- frame.render_stateful_widget(- List::new(actions)- .block(Block::default().borders(Borders::ALL).title(" Actions "))- .highlight_symbol("› ")- .highlight_style(Style::default().fg(OCEAN).add_modifier(Modifier::BOLD)),- chunks[1],- &mut action_state,+ button(+ frame,+ Rect::new(area.x + 13, area.y, 6, 1),+ "Chat",+ Action::View(AppTab::Chat),+ ui,+ p,);-- let detail = if let Some(token) = &ui.login_token {- let visible = "•".repeat(- token- .chars()- .count()- .min(chunks[2].width.saturating_sub(5) as usize),- );- format!(- "Paste a one-time login token, then press Enter.\n> {}▏",- visible- )- } else if ui.logout_confirm {- "Log out and stop account-bound services? Press y to confirm or Esc to cancel.".to_string()+ let mut x = area.right().saturating_sub(39).max(area.x + 20);+ for (label, cmd) in [+ ("Sessions", "sessions"),+ ("Agents", "agents"),+ ("Tools", "tools"),+ ("Settings", "settings"),+ ] {+ let width = label.len() as u16 + 2;+ if x + width <= area.right() {+ button(+ frame,+ Rect::new(x, area.y, width, 1),+ label,+ Action::Command(cmd),+ ui,+ p,+ );+ }+ x += width;+ }+ text(+ frame,+ Rect::new(area.x + 1, area.y + 1, area.width - 2, 1),+ "─".repeat(area.width.saturating_sub(2) as usize),+ Style::default().fg(p.border),+ );+ let body = Rect::new(area.x, area.y + 2, area.width, area.height - 3);+ match ui.active_tab {+ AppTab::Chat => chat(frame, body, state, ui, p),+ AppTab::Logs => logs(frame, body, ui, p),+ AppTab::Config => config(frame, body, ui, p),+ AppTab::Settings => settings(frame, body, ui, p),+ }+ let run = if ui.stopping {+ "Stopping".to_string()+ } else if state.is_streaming() {+ format!("{} Working", ["·", "•", "●", "•"][ui.spinner_tick % 4])} else {- ui.settings_status.clone()+ if ui.active_tab == AppTab::Chat {+ "Ready".into()+ } else {+ ui.active_tab.title().into()+ }};- frame.render_widget(- Paragraph::new(detail)- .block(Block::default().borders(Borders::ALL).title(" Status "))- .wrap(Wrap { trim: false }),- chunks[2],+ text(+ frame,+ Rect::new(area.x, area.bottom() - 1, area.width, 1),+ format!(+ " {run} · {}{} Ctrl+P commands · Ctrl+J newline · Ctrl+D exit",+ ui.auth_summary,+ if ui.demo { " · DEMO" } else { "" }+ ),+ Style::default().fg(p.muted),);+ if ui.overlay.is_some() {+ overlay(frame, area, ui, p);+ }+ ui.focus = ui.focus.min(ui.hits.len());}-fn draw_transcript(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &UiState) {- let block = Block::default()- .borders(Borders::ALL)- .title(" OpenHuman chat ")- .border_style(Style::default().fg(OCEAN));- let inner = block.inner(area);-- let text = transcript_text(state);- // Inner width available for wrapping (borders eat 2 cols).- let wrap_width = inner.width.max(1);- let total_lines: u16 = text- .lines- .iter()- .map(|line| wrapped_line_count(line, wrap_width))- .sum::<u16>();- let viewport = inner.height.max(1);- let max_scroll = total_lines.saturating_sub(viewport);- let scroll_from_bottom = ui.scroll_from_bottom.min(max_scroll);- let top = max_scroll.saturating_sub(scroll_from_bottom);-- let paragraph = Paragraph::new(text)- .block(block)- .wrap(Wrap { trim: false })- .scroll((top, 0));- frame.render_widget(paragraph, area);+fn text(frame: &mut Frame, area: Rect, value: impl Into<String>, style: Style) {+ frame.render_widget(Paragraph::new(safe_text(&value.into())).style(style), area);}--fn draw_input(frame: &mut Frame, area: Rect, ui: &UiState) {- let block = Block::default()- .borders(Borders::ALL)- .title(" Message ")- .border_style(Style::default().fg(Color::DarkGray));- let inner_width = block.inner(area).width.max(1) as usize;- let matches = ui.composer.command_matches();- let (mut rows, cursor_row, cursor_col) = ui.composer.display(inner_width.saturating_sub(1));- if let Some(row) = rows.get_mut(cursor_row) {- let byte = byte_at_display_column(row, cursor_col);- row.insert(byte, '▏');+fn button(+ frame: &mut Frame,+ area: Rect,+ label: &str,+ action: Action,+ ui: &mut UiState,+ p: Palette,+) {+ if area.width == 0+ || area.height == 0+ || area.right() > frame.area().right()+ || area.bottom() > frame.area().bottom()+ {+ return;}- let mut lines = matches- .iter()- .take(6)- .map(|(name, description)| {- Line::from(vec![- Span::styled(- format!("/{name:<13}"),- Style::default().fg(OCEAN).add_modifier(Modifier::BOLD),- ),- Span::styled(*description, Style::default().fg(Color::DarkGray)),- ])- })- .collect::<Vec<_>>();- lines.extend(- rows.into_iter()- .take(8)- .map(|row| Line::from(Span::styled(row, Style::default().fg(Color::White)))),- );- let paragraph = Paragraph::new(lines)- .block(block)- .wrap(Wrap { trim: false });- frame.render_widget(paragraph, area);+ let focused = ui.focus > 0 && ui.focus - 1 == ui.hits.len();+ let style = if focused {+ Style::default()+ .fg(p.background)+ .bg(p.accent)+ .add_modifier(Modifier::BOLD)+ } else {+ Style::default().fg(p.muted)+ };+ text(frame, area, label, style);+ ui.hits.push(Hit { area, action });}-fn draw_footer(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &UiState) {- let context = match ui.active_tab {- AppTab::Logs => "PgUp/PgDn scroll",- AppTab::Chat => "Enter send/steer · Shift+Enter newline · Tab queue · / commands",- AppTab::Config => {- if ui.config_edit.is_some() {- "Enter save · Esc cancel"- } else {- "↑↓ navigate · Enter edit"+fn chat(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiState, p: Palette) {+ let (rows, _, _) = ui+ .composer+ .display(area.width.saturating_sub(3).max(1) as usize);+ let count = ui.composer.command_matches().len().min(4);+ let height = ((rows.len().min(5) + 3 + count) as u16)+ .min(area.height.saturating_sub(3))+ .max(3);+ let transcript_height = area.height.saturating_sub(height + 1);+ ui.transcript_area = Rect::new(area.x + 1, area.y, area.width - 2, transcript_height);+ let (visible, max_scroll) = ui.viewport.rows(+ state,+ ui.transcript_area.width.saturating_sub(2),+ transcript_height,+ ui.scroll_from_bottom,+ );+ ui.scroll_from_bottom = ui.scroll_from_bottom.min(max_scroll);+ if visible.is_empty() {+ text(+ frame,+ Rect::new(area.x + 3, area.y + 2, area.width.saturating_sub(6), 1),+ "What would you like to work on?",+ Style::default().fg(p.text).add_modifier(Modifier::BOLD),+ );+ text(+ frame,+ Rect::new(area.x + 3, area.y + 4, area.width.saturating_sub(6), 1),+ "Describe a task, or open Commands to get started.",+ Style::default().fg(p.muted),+ );+ }+ for (row, visible) in visible.iter().enumerate() {+ let entry = &state.entries()[visible.entry];+ let color = if let Some(a) = &entry.activity {+ match a.status {+ Status::Success => p.success,+ Status::Error => p.error,+ Status::Waiting => p.warning,+ _ => p.muted,}- }- AppTab::Settings => {- if ui.is_editing() {- "Enter confirm · Esc cancel"- } else {- "↑↓ navigate · Enter select"+ } else {+ match visible.kind {+ EntryKind::User => p.accent,+ EntryKind::Thinking | EntryKind::System => p.muted,+ EntryKind::Error => p.error,+ _ => p.text,}+ };+ let mut style = Style::default().fg(color);+ if visible.first && matches!(visible.kind, EntryKind::User | EntryKind::Assistant) {+ style = style.add_modifier(Modifier::BOLD);}- };- let turn = if !ui.pending_approvals.is_empty() {- format!("{} approval(s)", ui.pending_approvals.len())+ let target = Rect::new(+ ui.transcript_area.x,+ ui.transcript_area.y + row as u16,+ ui.transcript_area.width,+ 1,+ );+ if entry.activity.is_some() || visible.kind == EntryKind::Thinking {+ let prefix = if entry.expanded { "▾ " } else { "▸ " };+ text(+ frame,+ target,+ if visible.first {+ format!("{prefix}{}", visible.text)+ } else {+ format!(" {}", visible.text)+ },+ style,+ );+ ui.hits.push(Hit {+ area: target,+ action: Action::Entry(visible.entry),+ });+ } else {+ text(frame, target, &visible.text, style);+ }+ }+ let y = area.y + transcript_height;+ if !ui.pending_approvals.is_empty() {+ button(+ frame,+ Rect::new(area.x + 1, y, area.width.saturating_sub(20).min(36), 1),+ "! Pending approval · Review",+ Action::Command("approvals"),+ ui,+ p,+ );} else if ui.pending_plan_review.is_some() {- "plan review".to_string()- } else if ui.active_tab == AppTab::Chat && state.is_streaming() {- let frame_ch = SPINNER_FRAMES[ui.spinner_tick % SPINNER_FRAMES.len()];- format!("{frame_ch} streaming")- } else {- ui.active_tab.title().to_string()- };-- let left = Span::styled(- format!(" {turn} "),- Style::default().fg(Color::Black).bg(OCEAN),- );- let navigation = if ui.is_editing() {- "Finish or Esc before switching tabs"- } else {- "Ctrl+Tab switch · Alt+1-4 tabs"- };- let session = format!(- "{} · {}",- ui.model_override.as_deref().unwrap_or("default model"),- short_id(&ui.thread_id)- );- let hints = Span::styled(- format!(" {session} · {navigation} · {context} · Ctrl+C quit"),- Style::default().fg(Color::DarkGray),- );- let paragraph = Paragraph::new(Line::from(vec![left, hints]));- frame.render_widget(paragraph, area);-}--fn short_id(id: &str) -> &str {- match id.char_indices().nth(12) {- Some((byte, _)) => &id[..byte],- None => id,+ button(+ frame,+ Rect::new(area.x + 1, y, area.width.saturating_sub(20).min(36), 1),+ "! Plan review · Open",+ Action::Command("plan"),+ ui,+ p,+ );}-}--fn draw_overlay(frame: &mut Frame, overlay: &super::cockpit::Overlay) {- let area = centered_rect(84, 78, frame.area());- frame.render_widget(Clear, area);- let chunks = Layout::default()- .direction(Direction::Vertical)- .constraints([Constraint::Min(1), Constraint::Length(2)])- .split(area);- let visible = overlay.visible_rows();- let items = visible- .iter()- .map(|row| {- let mut lines = vec![Line::from(Span::styled(- &row.label,- Style::default()- .fg(Color::White)- .add_modifier(Modifier::BOLD),- ))];- if !row.detail.is_empty() {- lines.push(Line::from(Span::styled(- &row.detail,- Style::default().fg(Color::Gray),- )));- } else if !row.payload.is_null() {- lines.push(Line::from(Span::styled(- row.payload.to_string(),- Style::default().fg(Color::DarkGray),- )));- }- ListItem::new(lines)- })- .collect::<Vec<_>>();- let mut state =- ListState::default().with_selected((!visible.is_empty()).then_some(overlay.selected));- frame.render_stateful_widget(- List::new(items)- .block(- Block::default()- .borders(Borders::ALL)- .title(format!(" {} ", overlay.title))- .border_style(Style::default().fg(OCEAN)),- )- .highlight_symbol("› ")- .highlight_style(Style::default().fg(OCEAN)),- chunks[0],- &mut state,- );- let prompt = if let Some(input) = &overlay.input {- format!("> {input}▏ {}", overlay.status)- } else if overlay.filter.is_empty() {- overlay.status.clone()- } else {- format!("Filter: {}▏ {}", overlay.filter, overlay.status)- };- frame.render_widget(- Paragraph::new(prompt)- .block(Block::default().borders(Borders::LEFT | Borders::RIGHT | Borders::BOTTOM)),- chunks[1],+ if ui.scroll_from_bottom > 0 && area.width >= 40 {+ button(+ frame,+ Rect::new(area.right() - 18, y, 17, 1),+ "Jump to latest ↓",+ Action::Latest,+ ui,+ p,+ );+ }+ composer(+ frame,+ Rect::new(area.x, y + 1, area.width, height),+ state,+ ui,+ p,);}-fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {- let vertical = Layout::default()- .direction(Direction::Vertical)- .constraints([- Constraint::Percentage((100 - percent_y) / 2),- Constraint::Percentage(percent_y),- Constraint::Percentage((100 - percent_y) / 2),- ])- .split(area);- Layout::default()- .direction(Direction::Horizontal)- .constraints([- Constraint::Percentage((100 - percent_x) / 2),- Constraint::Percentage(percent_x),- Constraint::Percentage((100 - percent_x) / 2),- ])- .split(vertical[1])[1]-}--/// Build the styled transcript body from the reducer state.-fn transcript_text(state: &TranscriptState) -> Text<'static> {- let mut lines: Vec<Line> = Vec::new();- for entry in state.entries() {- let (prefix, style) = match entry.kind {- EntryKind::User => (- "You ",- Style::default().fg(OCEAN).add_modifier(Modifier::BOLD),- ),- EntryKind::Assistant => ("AI ", Style::default().fg(Color::White)),- EntryKind::Thinking => (- "··· ",- Style::default()- .fg(Color::DarkGray)- .add_modifier(Modifier::ITALIC),- ),- EntryKind::Tool => ("tool ", Style::default().fg(Color::Yellow)),- EntryKind::Error => (- "err ",- Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),+fn composer(frame: &mut Frame, area: Rect, state: &TranscriptState, ui: &mut UiState, p: Palette) {+ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(Style::default().fg(if ui.focus == 0 { p.accent } else { p.border }));+ let inner = block.inner(area);+ frame.render_widget(block, area);+ let matches = ui.composer.command_matches();+ let count = matches+ .len()+ .min(4)+ .min(inner.height.saturating_sub(2) as usize);+ let selected = ui.suggestion_selected.min(matches.len().saturating_sub(1));+ let first = selected.saturating_sub(count.saturating_sub(1));+ for (row, (name, desc)) in matches.iter().skip(first).take(count).enumerate() {+ button(+ frame,+ Rect::new(inner.x, inner.y + row as u16, inner.width, 1),+ &format!(+ "{} /{name:<12} {desc}",+ if row + first == selected { "›" } else { " " }),- EntryKind::System => (" ", Style::default().fg(Color::DarkGray)),- };-- let mut first = true;- for raw in entry.text.split('\n') {- let gutter = if first { prefix } else { " " };- lines.push(Line::from(vec![- Span::styled(gutter.to_string(), style.add_modifier(Modifier::DIM)),- Span::styled(raw.to_string(), style),- ]));- first = false;- }- // Blank spacer between entries for readability.- lines.push(Line::from(""));+ Action::Complete(name),+ ui,+ p,+ );}- Text::from(lines)-}--/// Approximate the number of visual rows a wrapped line occupies at `width`.-/// ratatui wraps on word boundaries; this display-width estimate is close-/// enough for scroll bookkeeping (off-by-one at most, harmless).-fn wrapped_line_count(line: &Line, width: u16) -> u16 {- let w = width.max(1) as usize;- let content_width: usize = line- .spans- .iter()- .map(|s| UnicodeWidthStr::width(s.content.as_ref()))- .sum();- if content_width == 0 {- 1+ let editor_height = inner.height.saturating_sub(count as u16 + 1).max(1);+ ui.composer_area = Rect::new(inner.x, inner.y + count as u16, inner.width, editor_height);+ let width = inner.width.saturating_sub(1).max(1) as usize;+ let (rows, cursor_row, cursor_col) = ui.composer.display(width);+ let first = cursor_row.saturating_sub(editor_height as usize - 1);+ ui.composer_first_row = first;+ if ui.composer.is_empty() {+ text(+ frame,+ ui.composer_area,+ "Describe a task…",+ Style::default().fg(p.muted),+ );} else {- content_width.div_ceil(w).max(1) as u16+ for (row, line) in rows+ .iter()+ .skip(first)+ .take(editor_height as usize)+ .enumerate()+ {+ text(+ frame,+ Rect::new(inner.x, ui.composer_area.y + row as u16, inner.width, 1),+ line,+ Style::default().fg(p.text),+ );+ }}-}--/// Return the trailing slice of `s` that fits within `width` display columns.-fn tail_to_width(s: &str, width: usize) -> String {- if width == 0 {- return String::new();+ ui.hits.push(Hit {+ area: ui.composer_area,+ action: Action::Composer,+ });+ if ui.focus == 0 && ui.overlay.is_none() {+ frame.set_cursor_position(Position::new(+ inner.x + cursor_col.min(width) as u16,+ ui.composer_area.y + (cursor_row - first) as u16,+ ));}- let mut out: Vec<char> = Vec::new();- let mut used = 0usize;- for ch in s.chars().rev() {- let cw = UnicodeWidthStr::width(ch.to_string().as_str()).max(1);- if used + cw > width {- break;- }- used += cw;- out.push(ch);+ let y = inner.bottom().saturating_sub(1);+ let agent = format!("{} ▾", ui.agent_name);+ let aw = (UnicodeWidthStr::width(agent.as_str()) as u16)+ .min(inner.width / 3)+ .max(1);+ button(+ frame,+ Rect::new(inner.x, y, aw, 1),+ &agent,+ Action::Command("agents"),+ ui,+ p,+ );+ button(+ frame,+ Rect::new(inner.x + aw + 1, y, (inner.width / 3).min(28), 1),+ &format!(+ "{} ▾",+ ui.model_override.as_deref().unwrap_or(&ui.effective_model)+ ),+ Action::Command("model"),+ ui,+ p,+ );+ if inner.width >= 64 {+ button(+ frame,+ Rect::new(inner.right() - 29, y, 10, 1),+ "Commands",+ Action::Command("help"),+ ui,+ p,+ );}- out.into_iter().rev().collect()-}--fn byte_at_display_column(value: &str, target: usize) -> usize {- let mut column = 0usize;- for (byte, ch) in value.char_indices() {- if column >= target {- return byte;- }- column += ch.width().unwrap_or(0).max(1);+ if state.is_streaming() {+ button(+ frame,+ Rect::new(inner.right() - 18, y, 8, 1),+ "Queue",+ Action::Queue,+ ui,+ p,+ );+ button(+ frame,+ Rect::new(inner.right() - 9, y, 8, 1),+ "Stop",+ Action::Stop,+ ui,+ p,+ );+ } else {+ button(+ frame,+ Rect::new(inner.right() - 9, y, 8, 1),+ "Send ↵",+ Action::Send,+ ui,+ p,+ );}- value.len()}#[cfg(test)]diff --git a/crates/openhuman-tui/src/render/overlay.rs b/crates/openhuman-tui/src/render/overlay.rsnew file mode 100644index 0000000000..26f0c41dd9--- /dev/null+++ b/crates/openhuman-tui/src/render/overlay.rs@@ -0,0 +1,143 @@+use super::*;+pub(super) fn overlay(frame: &mut Frame, area: Rect, ui: &mut UiState, p: Palette) {+ let width = area.width.saturating_sub(4).min(100);+ let height = area.height.saturating_sub(4).min(30);+ let panel = Rect::new(+ area.x + (area.width - width) / 2,+ area.y + (area.height - height) / 2,+ width,+ height,+ );+ frame.render_widget(Clear, panel);+ ui.overlay_area = panel;+ let current = ui.overlay.as_ref().unwrap();+ let block = Block::default()+ .borders(Borders::ALL)+ .title(format!(" {} ", safe_text(¤t.title)))+ .style(Style::default().fg(p.text).bg(p.surface))+ .border_style(Style::default().fg(p.border));+ let inner = block.inner(panel);+ frame.render_widget(block, panel);+ ui.hits.clear();+ let current = ui.overlay.as_ref().unwrap();+ let selected = current.selected;+ let kind = current.kind;+ let visible = current.visible_rows();+ let detail_height = if kind == OverlayKind::ToolDetail {+ 0+ } else {+ 5.min(inner.height / 3)+ };+ let list_height = inner.height.saturating_sub(detail_height + 3).max(1) as usize;+ let start = selected+ .saturating_sub(list_height / 2)+ .min(visible.len().saturating_sub(list_height));+ let rows: Vec<_> = visible+ .iter()+ .skip(start)+ .take(list_height)+ .enumerate()+ .map(|(offset, row)| (start + offset, row.label.clone()))+ .collect();+ let detail = visible+ .get(selected)+ .map(|row| row.detail.clone())+ .unwrap_or_else(|| "No matching items".into());+ let prompt = if let Some(input) = ¤t.input {+ format!("> {input}▏")+ } else {+ format!("Search: {}▏", current.filter)+ };+ let status = current.status.clone();+ for (offset, (index, label)) in rows.into_iter().enumerate() {+ let target = Rect::new(inner.x, inner.y + offset as u16, inner.width, 1);+ let style = if index == selected {+ Style::default().fg(p.accent).add_modifier(Modifier::BOLD)+ } else {+ Style::default().fg(p.text)+ };+ text(+ frame,+ target,+ format!("{} {label}", if index == selected { "›" } else { " " }),+ style,+ );+ ui.hits.push(Hit {+ area: target,+ action: Action::OverlayRow(index),+ });+ }+ if detail_height > 0 {+ frame.render_widget(+ Paragraph::new(safe_text(&detail))+ .style(Style::default().fg(p.muted))+ .wrap(Wrap { trim: false }),+ Rect::new(+ inner.x,+ inner.y + list_height as u16,+ inner.width,+ detail_height,+ ),+ );+ }+ text(+ frame,+ Rect::new(inner.x, inner.bottom() - 3, inner.width, 1),+ prompt,+ Style::default().fg(p.text),+ );+ text(+ frame,+ Rect::new(inner.x, inner.bottom() - 2, inner.width, 1),+ status,+ Style::default().fg(p.muted),+ );+ let y = inner.bottom() - 1;+ if kind == OverlayKind::Approvals {+ for (x, label, key) in [+ (0, "Approve once", crossterm::event::KeyCode::Char('1')),+ (15, "Deny", crossterm::event::KeyCode::Delete),+ ] {+ button(+ frame,+ Rect::new(inner.x + x, y, 13, 1),+ label,+ Action::OverlayKey(key),+ ui,+ p,+ );+ }+ } else if kind == OverlayKind::PlanReview {+ for (x, label, key) in [+ (0, "Approve", 'a'),+ (12, "Reject", 'r'),+ (24, "Revise", 'e'),+ ] {+ button(+ frame,+ Rect::new(inner.x + x, y, 10, 1),+ label,+ Action::OverlayKey(crossterm::event::KeyCode::Char(key)),+ ui,+ p,+ );+ }+ } else {+ button(+ frame,+ Rect::new(inner.x, y, 12, 1),+ "Select ↵",+ Action::OverlayKey(crossterm::event::KeyCode::Enter),+ ui,+ p,+ );+ }+ button(+ frame,+ Rect::new(inner.right().saturating_sub(10), y, 10, 1),+ "Close Esc",+ Action::OverlayKey(crossterm::event::KeyCode::Esc),+ ui,+ p,+ );+}diff --git a/crates/openhuman-tui/src/render/views.rs b/crates/openhuman-tui/src/render/views.rsnew file mode 100644index 0000000000..1e45cb03ae--- /dev/null+++ b/crates/openhuman-tui/src/render/views.rs@@ -0,0 +1,168 @@+use super::*;+pub(super) fn config(frame: &mut Frame, area: Rect, ui: &mut UiState, p: Palette) {+ text(+ frame,+ Rect::new(area.x + 2, area.y, area.width.saturating_sub(4), 1),+ "Configuration · changes apply through the core",+ Style::default().fg(p.text),+ );+ for index in 0..ui.config_items.len() {+ let item = &ui.config_items[index];+ let label = format!(+ "{} {:<18} {}",+ if index == ui.config_selected {+ "›"+ } else {+ " "+ },+ item.label,+ item.value+ );+ button(+ frame,+ Rect::new(+ area.x + 2,+ area.y + 2 + index as u16,+ area.width.saturating_sub(4),+ 1,+ ),+ &label,+ Action::ConfigRow(index),+ ui,+ p,+ );+ }+ let detail = if let Some(value) = &ui.config_edit {+ format!("> {value}▏\nEnter save · Esc cancel")+ } else {+ format!(+ "{}\n{}",+ ui.config_items[ui.config_selected].hint, ui.config_status+ )+ };+ if area.height > 9 {+ frame.render_widget(+ Paragraph::new(safe_text(&detail))+ .style(Style::default().fg(p.muted))+ .wrap(Wrap { trim: false }),+ Rect::new(+ area.x + 2,+ area.y + 9,+ area.width.saturating_sub(4),+ area.height - 9,+ ),+ );+ }+}+pub(super) fn settings(frame: &mut Frame, area: Rect, ui: &mut UiState, p: Palette) {+ text(+ frame,+ Rect::new(area.x + 2, area.y, area.width.saturating_sub(4), 1),+ format!("Account · {}", ui.auth_summary),+ Style::default().fg(p.text).add_modifier(Modifier::BOLD),+ );+ text(+ frame,+ Rect::new(area.x + 2, area.y + 1, area.width.saturating_sub(4), 1),+ &ui.account_detail,+ Style::default().fg(p.muted),+ );+ for (index, action) in SettingsAction::ALL.iter().enumerate() {+ button(+ frame,+ Rect::new(+ area.x + 2,+ area.y + 3 + index as u16,+ area.width.saturating_sub(4),+ 1,+ ),+ action.label(),+ Action::SettingsRow(index),+ ui,+ p,+ );+ }+ button(+ frame,+ Rect::new(area.x + 2, area.y + 7, 25, 1),+ &format!("Appearance · {} ▾", ui.theme.name()),+ Action::Command("themes"),+ ui,+ p,+ );+ button(+ frame,+ Rect::new(area.x + 2, area.y + 8, 30, 1),+ if ui.mouse_enabled {+ "Mouse · on (click to disable)"+ } else {+ "Mouse · off"+ },+ Action::Command("mouse"),+ ui,+ p,+ );+ let detail = if let Some(token) = &ui.login_token {+ format!(+ "Paste a one-time login token\n> {}▏\nEnter sign in · Esc cancel",+ "•".repeat(+ token+ .chars()+ .count()+ .min(area.width.saturating_sub(6) as usize)+ )+ )+ } else if ui.logout_confirm {+ "Log out of this account?\nChoose Confirm or Cancel.".into()+ } else {+ ui.settings_status.clone()+ };+ if area.height > 10 {+ frame.render_widget(+ Paragraph::new(detail)+ .style(Style::default().fg(p.muted))+ .wrap(Wrap { trim: false }),+ Rect::new(+ area.x + 2,+ area.y + 10,+ area.width.saturating_sub(4),+ area.height - 10,+ ),+ );+ }+ if ui.login_token.is_some() || ui.logout_confirm {+ button(+ frame,+ Rect::new(area.x + 2, area.bottom().saturating_sub(2), 12, 1),+ "Confirm",+ Action::OverlayKey(crossterm::event::KeyCode::Enter),+ ui,+ p,+ );+ button(+ frame,+ Rect::new(area.x + 16, area.bottom().saturating_sub(2), 12, 1),+ "Cancel",+ Action::OverlayKey(crossterm::event::KeyCode::Esc),+ ui,+ p,+ );+ }+}+pub(super) fn logs(frame: &mut Frame, area: Rect, ui: &mut UiState, p: Palette) {+ let lines = openhuman_rpc::embed::process::tui_log_lines();+ let end = lines+ .len()+ .saturating_sub(ui.log_scroll_from_bottom as usize);+ let start = end.saturating_sub(area.height as usize);+ text(+ frame,+ area,+ lines[start..end]+ .iter()+ .map(|line| safe_text(line))+ .collect::<Vec<_>>()+ .join("\n"),+ Style::default().fg(p.muted),+ );+}diff --git a/crates/openhuman-tui/src/render_tests.rs b/crates/openhuman-tui/src/render_tests.rsindex f8737ecabc..0981172b1c 100644--- a/crates/openhuman-tui/src/render_tests.rs+++ b/crates/openhuman-tui/src/render_tests.rs@@ -1,68 +1,63 @@use super::*;use ratatui::backend::TestBackend;use ratatui::Terminal;--fn rendered(ui: &UiState) -> String {- let backend = TestBackend::new(180, 24);- let mut terminal = Terminal::new(backend).expect("test terminal");- let transcript = TranscriptState::new("test-client");- terminal- .draw(|frame| draw(frame, &transcript, ui))- .expect("draw");+fn rendered(width: u16, height: u16, state: &TranscriptState, ui: &mut UiState) -> String {+ let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();+ terminal.draw(|f| draw(f, state, ui)).unwrap();terminal.backend().buffer().content().iter().map(|cell| cell.symbol())- .collect::<String>()+ .collect()}-#[test]-fn tab_bar_and_navigation_footer_are_always_rendered() {- let ui = UiState::new("thread-1".into(), "client-1".into());- let output = rendered(&ui);- for title in ["1 Logs", "2 Chat", "3 Config", "4 Settings"] {- assert!(output.contains(title), "missing tab {title}");+fn conversation_and_click_targets_fit_standard_terminal() {+ let mut ui = UiState::new("thread".into(), "client".into());+ let state = TranscriptState::new("client");+ let output = rendered(80, 24, &state, &mut ui);+ for label in [+ "OpenHuman",+ "Sessions",+ "Agents",+ "Tools",+ "Settings",+ "Describe a task",+ ] {+ assert!(output.contains(label), "{label}");}- assert!(output.contains("Ctrl+Tab switch"));- assert!(output.contains("Shift+Enter newline"));-}--#[test]-fn editing_footer_explains_that_tab_switching_is_paused() {- let mut ui = UiState::new("thread-1".into(), "client-1".into());- ui.active_tab = AppTab::Config;- ui.config_edit = Some("value".to_string());- let output = rendered(&ui);- assert!(output.contains("Finish or Esc before switching tabs"));- assert!(!output.contains("Alt+1-4 tabs"));-}--#[test]-fn tail_to_width_keeps_the_end() {- assert_eq!(tail_to_width("hello world", 5), "world");- assert_eq!(tail_to_width("hi", 10), "hi");- assert_eq!(tail_to_width("anything", 0), "");+ assert!(!output.contains("1 Logs"));+ assert!(ui.hits.iter().any(|hit| hit.action == Action::Send));+ assert!(ui+ .hits+ .iter()+ .all(|hit| hit.area.right() <= 80 && hit.area.bottom() <= 24));}-#[test]-fn wrapped_line_count_divides_by_width() {- let line = Line::from("a".repeat(25));- assert_eq!(wrapped_line_count(&line, 10), 3);- let empty = Line::from("");- assert_eq!(wrapped_line_count(&empty, 10), 1);+fn masked_login_does_not_render_a_secret() {+ let mut ui = UiState::new("thread".into(), "client".into());+ ui.active_tab = AppTab::Settings;+ ui.login_token = Some("private-token-never-render".into());+ let output = rendered(80, 24, &TranscriptState::new("client"), &mut ui);+ assert!(!output.contains("private-token"));+ assert!(output.contains("••••"));}-#[test]-fn cursor_byte_lookup_handles_wide_unicode() {- assert_eq!(byte_at_display_column("界a", 2), "界".len());- assert_eq!(byte_at_display_column("界a", 3), "界a".len());+fn overlay_removes_covered_controls() {+ let mut ui = UiState::new("thread".into(), "client".into());+ ui.overlay = Some(super::super::cockpit::Overlay::new(+ OverlayKind::Help,+ "Commands",+ ));+ rendered(80, 24, &TranscriptState::new("client"), &mut ui);+ assert!(!ui.hits.iter().any(|hit| hit.action == Action::Send));}-#[test]-fn short_id_truncates_non_ascii_at_a_character_boundary() {- let id = "12345678901界xyz";- assert_eq!(short_id(id), "12345678901界");- assert_eq!(short_id("abcdefghijklmnop"), "abcdefghijkl");+fn small_terminal_and_unicode_do_not_panic() {+ let mut ui = UiState::new("thread".into(), "client".into());+ ui.composer.set_text("界界e\u{301}\n".repeat(20));+ for (width, height) in [(20, 5), (40, 12), (80, 24), (120, 40)] {+ rendered(width, height, &TranscriptState::new("client"), &mut ui);+ }}diff --git a/crates/openhuman-tui/src/runner.rs b/crates/openhuman-tui/src/runner.rsindex 59939a204c..c99c94c444 100644--- a/crates/openhuman-tui/src/runner.rs+++ b/crates/openhuman-tui/src/runner.rs@@ -35,6 +35,8 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {let mut resume_picker = false;let mut use_last = false;let mut no_alt_screen = false;+ let mut no_mouse = false;+ let mut demo = false;let mut provider: Option<String> = None;let mut model: Option<String> = None;let mut prompt_parts = Vec::new();@@ -42,6 +44,14 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {let mut i = 0usize;while i < args.len() {match args[i].as_str() {+ "--demo" => {+ demo = true;+ i += 1;+ }+ "--no-mouse" => {+ no_mouse = true;+ i += 1;+ }"--thread" => {thread_id = Some(args.get(i + 1)@@ -100,6 +110,9 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {}}+ if demo {+ return super::demo::run(no_mouse);+ }process::set_transient_inference_overrides(provider.as_deref(), model.as_deref());// File-only logging — never stderr while the TUI owns the terminal.@@ -123,6 +136,7 @@ pub fn run_from_cli(args: &[String]) -> anyhow::Result<()> {initial_prompt: (!prompt_parts.is_empty()).then(|| prompt_parts.join(" ")),resume_picker,no_alt_screen,+ no_mouse,};rt.block_on(async_main(thread_id,@@ -266,9 +280,11 @@ fn short_hex() -> String {fn print_help() {println!("Usage: openhuman-tui [OPTIONS] [PROMPT]");println!();- println!("Open the tabbed terminal UI for core logs, orchestrator chat, configuration,");+ println!("Open the conversation-first terminal UI for agent chat, tools, configuration,");println!("and account settings. Runs the core in-process — no server, no ports.");println!();+ println!(" --demo Offline interactive UI preview (no model calls).");+ println!(" --no-mouse Keep native terminal mouse selection.");println!(" --thread <id> Attach to an existing conversation thread.");println!(" --new Force a new thread (default when --thread is omitted).");println!(" --resume Open the saved-thread picker (starts on the latest thread).");@@ -278,8 +294,8 @@ fn print_help() {println!(" -m, --model <id> Override the model for this TUI session.");println!(" -v, --verbose Debug-level logging (written to the log file, never the UI).");println!();- println!("Keys: Ctrl+Tab or Alt+1-4 switch tabs · Enter send · Shift+Enter newline ·");- println!(" / opens commands · Ctrl+C / Ctrl+D quit.");+ println!("Keys: Ctrl+P commands · Enter send/steer · Ctrl+Q queue · Shift+Enter newline ·");+ println!(" Ctrl+J newline · Tab focus · / opens commands · Ctrl+D quit.");}#[cfg(test)]diff --git a/crates/openhuman-tui/src/runner_tests.rs b/crates/openhuman-tui/src/runner_tests.rsindex bc59cdc902..b77dceb4cf 100644--- a/crates/openhuman-tui/src/runner_tests.rs+++ b/crates/openhuman-tui/src/runner_tests.rs@@ -58,6 +58,9 @@ fn tui_invokes_use_canonical_registered_rpc_method_names() {"openhuman.approval_decide","openhuman.plan_review_decide","openhuman.config_get_client_config",+ "openhuman.config_get",+ "openhuman.config_update_agent_settings",+ "openhuman.inference_list_models","openhuman.config_get_agent_paths","openhuman.config_update_model_settings","openhuman.config_get_autonomy_settings",diff --git a/crates/openhuman-tui/src/state.rs b/crates/openhuman-tui/src/state.rsindex 8ac5fcf912..b59b3f73cc 100644--- a/crates/openhuman-tui/src/state.rs+++ b/crates/openhuman-tui/src/state.rs@@ -10,7 +10,15 @@//! into the transcript. Events for a different `client_id` are ignored, so a//! process-wide broadcast bus can be drained safely.+use super::activity::{Activity, Status};use openhuman_rpc::embed::chat_surface::WebChannelEvent;+use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};++static REVISION: AtomicU64 = AtomicU64::new(1);+fn revision() -> u64 {+ REVISION.fetch_add(1, Ordering::Relaxed)+}/// The kind of a transcript entry — drives colour / prefix in the renderer.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -34,6 +42,9 @@ pub enum EntryKind {pub struct Entry {pub kind: EntryKind,pub text: String,+ pub(crate) revision: u64,+ pub(crate) activity: Option<Activity>,+ pub(crate) expanded: bool,}impl Entry {@@ -41,6 +52,9 @@ impl Entry {Self {kind,text: text.into(),+ revision: revision(),+ activity: None,+ expanded: false,}}}@@ -62,6 +76,8 @@ pub struct TranscriptState {/// Index into `entries` of the thinking entry currently accumulating/// thinking deltas for the in-flight turn, if any.cur_thinking: Option<usize>,+ activity_index: HashMap<String, usize>,+ sequences: HashMap<String, u64>,}impl TranscriptState {@@ -74,6 +90,8 @@ impl TranscriptState {streaming: false,cur_assistant: None,cur_thinking: None,+ activity_index: HashMap::new(),+ sequences: HashMap::new(),}}@@ -98,7 +116,9 @@ impl TranscriptState {pub fn clear(&mut self) {self.entries.clear();- self.finish_turn();+ self.activity_index.clear();+ self.cur_assistant = None;+ self.cur_thinking = None;}pub fn last_assistant(&self) -> Option<&str> {@@ -135,6 +155,8 @@ impl TranscriptState {/// Replace the view with a newest-first `threads.transcript_get` page.pub fn load_transcript(&mut self, value: &serde_json::Value) {self.entries.clear();+ self.activity_index.clear();+ self.sequences.clear();let page = super::cockpit::unwrap_rpc(value);let Some(items) = page.get("items").and_then(serde_json::Value::as_array) else {return;@@ -182,6 +204,19 @@ impl TranscriptState {return;}+ if let Some(seq) = ev.seq {+ if !ev.request_id.is_empty() {+ if self+ .sequences+ .get(&ev.request_id)+ .is_some_and(|prior| seq <= *prior)+ {+ return;+ }+ self.sequences.insert(ev.request_id.clone(), seq);+ }+ }+match ev.event.as_str() {"text_delta" => {if let Some(delta) = ev.delta.as_deref() {@@ -193,48 +228,8 @@ impl TranscriptState {self.append_thinking(delta);}}- "tool_call" => {- let name = ev.tool_name.as_deref().unwrap_or("tool");- let args = ev.args.as_ref().map(summarize_json).unwrap_or_default();- log::debug!("[tui] state: tool_call {name}");- self.entries- .push(Entry::new(EntryKind::Tool, format!("→ {name}{args}")));- }- "tool_result" => {- let name = ev.tool_name.as_deref().unwrap_or("tool");- let ok = ev.success.unwrap_or(true);- let marker = if ok { "✓" } else { "✗" };- let detail = ev- .output- .as_deref()- .map(truncate_line)- .filter(|s| !s.is_empty())- .or_else(|| ev.failure.as_ref().map(summarize_json))- .map(|s| format!(" — {s}"))- .unwrap_or_default();- log::debug!("[tui] state: tool_result {name} ok={ok}");- self.entries.push(Entry::new(- EntryKind::Tool,- format!("{marker} {name}{detail}"),- ));- }- "subagent_spawned"- | "subagent_iteration_start"- | "subagent_completed"- | "subagent_tool_call"- | "subagent_tool_result" => {- let agent = ev- .subagent- .as_ref()- .and_then(|detail| detail.display_name.as_deref())- .or(ev.tool_name.as_deref())- .unwrap_or("sub-agent");- let action = ev.event.trim_start_matches("subagent_").replace('_', " ");- self.entries.push(Entry::new(- EntryKind::Tool,- format!("agent {agent} · {action}"),- ));- }+ "tool_call" | "tool_result" | "tool_args_delta" => self.apply_activity(ev, false),+ event if event.starts_with("subagent_") => self.apply_activity(ev, true),"artifact_pending" | "artifact_ready" | "artifact_failed" => {let status = ev.event.trim_start_matches("artifact_");let detail = ev@@ -262,7 +257,10 @@ impl TranscriptState {// streamed text deltas accumulated (they can lag / be partial).if let Some(full) = ev.full_response.as_deref() {match self.cur_assistant {- Some(idx) => self.entries[idx].text = full.to_string(),+ Some(idx) => {+ self.entries[idx].text = full.to_string();+ self.entries[idx].revision = revision();+ }None => self.entries.push(Entry::new(EntryKind::Assistant, full.to_string())),@@ -280,6 +278,19 @@ impl TranscriptState {}log::debug!("[tui] state: chat_error {msg}");self.entries.push(Entry::new(EntryKind::Error, msg));+ for entry in &mut self.entries {+ if let Some(activity) = &mut entry.activity {+ if activity.status == Status::Running && !activity.child {+ activity.status = if ev.error_type.as_deref() == Some("cancelled") {+ Status::Cancelled+ } else {+ Status::Unknown+ };+ entry.text = activity.summary();+ entry.revision = revision();+ }+ }+ }self.finish_turn();}other => {@@ -290,7 +301,10 @@ impl TranscriptState {fn append_assistant(&mut self, delta: &str) {match self.cur_assistant {- Some(idx) => self.entries[idx].text.push_str(delta),+ Some(idx) => {+ self.entries[idx].text.push_str(delta);+ self.entries[idx].revision = revision();+ }None => {self.entries.push(Entry::new(EntryKind::Assistant, delta.to_string()));@@ -301,7 +315,10 @@ impl TranscriptState {fn append_thinking(&mut self, delta: &str) {match self.cur_thinking {- Some(idx) => self.entries[idx].text.push_str(delta),+ Some(idx) => {+ self.entries[idx].text.push_str(delta);+ self.entries[idx].revision = revision();+ }None => {self.entries.push(Entry::new(EntryKind::Thinking, delta.to_string()));@@ -316,6 +333,69 @@ impl TranscriptState {self.cur_thinking = None;}+ pub(crate) fn toggle_entry(&mut self, index: usize) {+ if let Some(entry) = self.entries.get_mut(index) {+ entry.expanded = !entry.expanded;+ entry.revision = revision();+ }+ }++ fn apply_activity(&mut self, ev: &WebChannelEvent, child: bool) {+ let identity = if child {+ ev.subagent+ .as_ref()+ .and_then(|detail| detail.task_id.as_deref())+ .or(ev.skill_id.as_deref())+ } else {+ ev.tool_call_id.as_deref()+ };+ let key = identity.map(|id| {+ format!(+ "{}:{}:{id}",+ ev.request_id,+ if child { "child" } else { "tool" }+ )+ });+ let existing = key+ .as_ref()+ .and_then(|key| self.activity_index.get(key).copied())+ .or_else(|| {+ if identity.is_none() && ev.event == "tool_result" {+ self.entries.iter().rposition(|entry| {+ entry.activity.as_ref().is_some_and(|a| {+ !a.child+ && a.status == Status::Running+ && Some(a.label.as_str()) == ev.tool_name.as_deref()+ })+ })+ } else {+ None+ }+ });+ let index = existing.unwrap_or_else(|| {+ let id = key+ .clone()+ .unwrap_or_else(|| format!("{}:legacy:{}", ev.request_id, self.entries.len()));+ let mut entry = Entry::new(EntryKind::Tool, "");+ entry.activity = Some(Activity::from_event(id.clone(), ev, child));+ let index = self.entries.len();+ self.entries.push(entry);+ self.activity_index.insert(id, index);+ index+ });+ let entry = &mut self.entries[index];+ let activity = entry.activity.as_mut().unwrap();+ if ev.event == "tool_args_delta" {+ if let Some(delta) = &ev.delta {+ activity.args =+ super::activity::bounded(&format!("{}{delta}", activity.args), 4096);+ }+ }+ activity.update(ev);+ entry.text = activity.summary();+ entry.revision = revision();+ }+fn push_projected_item(&mut self, item: &serde_json::Value) {match item.get("kind").and_then(serde_json::Value::as_str) {Some("userMessage") => self.entries.push(Entry::new(@@ -341,13 +421,38 @@ impl TranscriptState {let name = item.get("name").and_then(serde_json::Value::as_str)- .unwrap_or("tool");- let status = item- .get("status")+ .unwrap_or("Tool");+ let id = item+ .get("callId").and_then(serde_json::Value::as_str)- .unwrap_or("running");- self.entries- .push(Entry::new(EntryKind::Tool, format!("{name} · {status}")));+ .unwrap_or("legacy");+ let mut entry = Entry::new(EntryKind::Tool, "");+ let activity = Activity {+ id: format!("history:{id}"),+ label: name.into(),+ status: match item.get("status").and_then(serde_json::Value::as_str) {+ Some("success") => Status::Success,+ Some("error") => Status::Error,+ _ => Status::Unknown,+ },+ args: item+ .get("args")+ .map(|args| super::activity::bounded(&args.to_string(), 4096))+ .unwrap_or_default(),+ output: super::activity::bounded(+ item.get("result")+ .and_then(serde_json::Value::as_str)+ .unwrap_or("No stored output"),+ 65536,+ ),+ history: String::new(),+ elapsed_ms: None,+ child: false,+ tools: 0,+ };+ entry.text = activity.summary();+ entry.activity = Some(activity);+ self.entries.push(entry);}Some("interruptedPartial") => self.entries.push(Entry::new(EntryKind::Assistant,@@ -359,14 +464,58 @@ impl TranscriptState {let id = item.get("id").and_then(serde_json::Value::as_str)- .unwrap_or("sub-agent");- self.entries- .push(Entry::new(EntryKind::Tool, format!("agent {id}")));- if let Some(items) = item.get("items").and_then(serde_json::Value::as_array) {- for nested in items {- self.push_projected_item(nested);- }- }+ .unwrap_or("Subagent");+ let label = item+ .get("agentId")+ .and_then(serde_json::Value::as_str)+ .unwrap_or(id);+ let items = item.get("items").and_then(serde_json::Value::as_array);+ let output = items+ .map(|items| {+ items+ .iter()+ .map(|nested| {+ nested+ .get("content")+ .or_else(|| nested.get("text"))+ .or_else(|| nested.get("result"))+ .or_else(|| nested.get("name"))+ .and_then(serde_json::Value::as_str)+ .unwrap_or_default()+ })+ .collect::<Vec<_>>()+ .join("\n")+ })+ .unwrap_or_default();+ let activity = Activity {+ id: format!("history:child:{id}"),+ label: label.into(),+ status: match item.get("status").and_then(serde_json::Value::as_str) {+ Some("completed") => Status::Success,+ Some("failed" | "incomplete") => Status::Error,+ Some("interrupted") => Status::Cancelled,+ _ => Status::Unknown,+ },+ args: String::new(),+ output: super::activity::bounded(&output, 65536),+ history: String::new(),+ elapsed_ms: None,+ child: true,+ tools: items+ .map(|items| {+ items+ .iter()+ .filter(|nested| {+ nested.get("kind").and_then(serde_json::Value::as_str)+ == Some("toolCall")+ })+ .count() as u64+ })+ .unwrap_or(0),+ };+ let mut entry = Entry::new(EntryKind::Tool, activity.summary());+ entry.activity = Some(activity);+ self.entries.push(entry);}Some("compaction") => self.entries.push(Entry::new(EntryKind::System,@@ -377,16 +526,6 @@ impl TranscriptState {}}-/// One-line, length-capped summary of a JSON value for tool-call args display.-fn summarize_json(value: &serde_json::Value) -> String {- let rendered = match value {- serde_json::Value::Object(_) | serde_json::Value::Array(_) => value.to_string(),- serde_json::Value::String(s) => s.clone(),- other => other.to_string(),- };- format!("({})", truncate_line(&rendered))-}-/// Collapse to a single line and cap length so a rogue tool output can't blow/// up the transcript width.fn truncate_line(s: &str) -> String {diff --git a/crates/openhuman-tui/src/state_tests.rs b/crates/openhuman-tui/src/state_tests.rsindex 4b8724f7c9..33eca8235d 100644--- a/crates/openhuman-tui/src/state_tests.rs+++ b/crates/openhuman-tui/src/state_tests.rs@@ -220,7 +220,7 @@ fn projected_transcript_is_restored_in_chronological_order() {}#[test]-fn tool_call_and_result_produce_tool_entries() {+fn tool_result_updates_the_originating_activity() {let mut s = TranscriptState::new(CLIENT);s.begin_user_turn("do it");let call = WebChannelEvent {@@ -242,11 +242,11 @@ fn tool_call_and_result_produce_tool_entries() {.iter().filter(|e| e.kind == EntryKind::Tool).collect();- assert_eq!(tools.len(), 2);- assert!(tools[0].text.starts_with("→ web_search"));- assert!(tools[0].text.contains("rust ratatui"));- assert!(tools[1].text.starts_with("✓ web_search"));- assert!(tools[1].text.contains("3 results"));+ assert_eq!(tools.len(), 1);+ assert!(tools[0].text.starts_with("✓ web_search"));+ let activity = tools[0].activity.as_ref().unwrap();+ assert!(activity.args.contains("rust ratatui"));+ assert_eq!(activity.output, "3 results");}#[test]@@ -297,3 +297,103 @@ fn truncate_line_collapses_newlines_and_caps_length() {assert!(!out.contains('\n'));assert!(out.chars().count() <= 121, "capped to MAX + ellipsis");}++#[test]+fn concurrent_same_named_tools_match_results_by_call_identity() {+ let mut state = TranscriptState::new(CLIENT);+ state.set_thread("thread-1");+ for id in ["a", "b"] {+ state.apply_event(&WebChannelEvent {+ tool_call_id: Some(id.into()),+ tool_name: Some("read".into()),+ request_id: "turn".into(),+ ..ev("tool_call")+ });+ }+ state.apply_event(&WebChannelEvent {+ tool_call_id: Some("b".into()),+ tool_name: Some("read".into()),+ request_id: "turn".into(),+ success: Some(false),+ output: Some("failure".into()),+ ..ev("tool_result")+ });+ assert_eq!(+ state.entries()[0].activity.as_ref().unwrap().status,+ Status::Running+ );+ assert_eq!(+ state.entries()[1].activity.as_ref().unwrap().status,+ Status::Error+ );+ state.apply_event(&WebChannelEvent {+ tool_call_id: Some("b".into()),+ request_id: "turn".into(),+ success: Some(false),+ ..ev("tool_result")+ });+ assert_eq!(state.entries().len(), 2);+}++#[test]+fn child_activity_accumulates_output_and_failed_status_in_one_record() {+ let mut state = TranscriptState::new(CLIENT);+ for (event, delta) in [+ ("subagent_spawned", None),+ ("subagent_text_delta", Some("partial")),+ ("subagent_failed", None),+ ] {+ state.apply_event(&WebChannelEvent {+ skill_id: Some("task".into()),+ request_id: "turn".into(),+ delta: delta.map(str::to_string),+ message: Some("Timed out".into()),+ ..ev(event)+ });+ }+ assert_eq!(state.entries().len(), 1);+ let child = state.entries()[0].activity.as_ref().unwrap();+ assert!(child.child);+ assert_eq!(child.status, Status::Error);+ assert_eq!(child.output, "partial");+ assert!(child.details().contains("Timed out"));+}++#[test]+fn sequence_duplicates_do_not_duplicate_streamed_text() {+ let mut state = TranscriptState::new(CLIENT);+ let event = WebChannelEvent {+ request_id: "turn".into(),+ seq: Some(0),+ ..text_delta("one")+ };+ state.apply_event(&event);+ state.apply_event(&event);+ assert_eq!(state.entries()[0].text, "one");+}++#[test]+fn replay_restores_inspectable_tool_and_child_output_without_flattening() {+ let mut state = TranscriptState::new(CLIENT);+ state.load_transcript(&serde_json::json!({"items":[{"kind":"subagent","id":"child","agentId":"Explore","status":"completed","items":[{"kind":"assistantMessage","content":"child answer"}]},{"kind":"toolCall","callId":"a","name":"read","args":{"file":"a.rs"},"result":"file body","status":"success"}]}));+ assert_eq!(state.entries().len(), 2);+ assert_eq!(+ state.entries()[0].activity.as_ref().unwrap().output,+ "file body"+ );+ assert_eq!(+ state.entries()[1].activity.as_ref().unwrap().output,+ "child answer"+ );+}++#[test]+fn clearing_display_during_streaming_keeps_turn_and_resets_cursors() {+ let mut state = TranscriptState::new(CLIENT);+ state.begin_user_turn("question");+ state.apply_event(&text_delta("first"));+ state.clear();+ state.apply_event(&text_delta("next"));+ assert!(state.is_streaming());+ assert_eq!(state.entries()[0].text, "next");+}diff --git a/crates/openhuman-tui/src/terminal.rs b/crates/openhuman-tui/src/terminal.rsindex cd1ace30e3..a845bae25e 100644--- a/crates/openhuman-tui/src/terminal.rs+++ b/crates/openhuman-tui/src/terminal.rs@@ -27,6 +27,7 @@ pub type Tui = Terminal<CrosstermBackend<Stdout>>;pub struct TerminalGuard {terminal: Tui,alternate_screen: bool,+ mouse: bool,}impl TerminalGuard {@@ -50,6 +51,7 @@ impl TerminalGuard {Ok(Self {terminal,alternate_screen,+ mouse: alternate_screen,})}@@ -57,6 +59,17 @@ impl TerminalGuard {pub fn terminal(&mut self) -> &mut Tui {&mut self.terminal}+ pub fn set_mouse(&mut self, enabled: bool) -> io::Result<()> {+ if self.mouse != enabled {+ if enabled {+ execute!(io::stdout(), EnableMouseCapture)?;+ } else {+ execute!(io::stdout(), DisableMouseCapture)?;+ }+ self.mouse = enabled;+ }+ Ok(())+ }}impl Drop for TerminalGuard {diff --git a/crates/openhuman-tui/src/theme.rs b/crates/openhuman-tui/src/theme.rsnew file mode 100644index 0000000000..04c6b46f3e--- /dev/null+++ b/crates/openhuman-tui/src/theme.rs@@ -0,0 +1,93 @@+//! Semantic terminal palettes. System mode leaves surfaces to the terminal.+use ratatui::style::Color;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum Theme {+ #[default]+ System,+ Dark,+ Light,+ Mono,+}++#[derive(Clone, Copy)]+pub struct Palette {+ pub background: Color,+ pub surface: Color,+ pub text: Color,+ pub muted: Color,+ pub border: Color,+ pub accent: Color,+ pub success: Color,+ pub warning: Color,+ pub error: Color,+}++impl Theme {+ pub const ALL: [Self; 4] = [Self::System, Self::Dark, Self::Light, Self::Mono];+ pub fn name(self) -> &'static str {+ match self {+ Self::System => "System",+ Self::Dark => "Dark",+ Self::Light => "Light",+ Self::Mono => "Monochrome",+ }+ }+ pub fn palette(self) -> Palette {+ let rgb = |r, g, b| Color::Rgb(r, g, b);+ match self {+ Self::Dark => Palette {+ background: rgb(17, 19, 21),+ surface: rgb(27, 30, 34),+ text: rgb(231, 233, 236),+ muted: rgb(164, 171, 181),+ border: rgb(58, 66, 77),+ accent: rgb(121, 168, 242),+ success: rgb(124, 201, 154),+ warning: rgb(231, 189, 104),+ error: rgb(241, 139, 139),+ },+ Self::Light => Palette {+ background: rgb(250, 250, 249),+ surface: rgb(255, 255, 255),+ text: rgb(32, 36, 42),+ muted: rgb(89, 97, 110),+ border: rgb(205, 210, 217),+ accent: rgb(36, 94, 181),+ success: rgb(38, 119, 70),+ warning: rgb(136, 98, 13),+ error: rgb(181, 46, 61),+ },+ Self::System => Palette {+ background: Color::Reset,+ surface: Color::Reset,+ text: Color::Reset,+ muted: Color::Gray,+ border: Color::DarkGray,+ accent: Color::Cyan,+ success: Color::Green,+ warning: Color::Yellow,+ error: Color::Red,+ },+ Self::Mono => Palette {+ background: Color::Reset,+ surface: Color::Reset,+ text: Color::Reset,+ muted: Color::Reset,+ border: Color::Reset,+ accent: Color::Reset,+ success: Color::Reset,+ warning: Color::Reset,+ error: Color::Reset,+ },+ }+ }+}++/// Remove terminal commands while retaining ordinary Unicode and line breaks.+pub fn safe_text(value: &str) -> String {+ value+ .chars()+ .filter(|ch| !ch.is_control() || *ch == '\n')+ .collect()+}diff --git a/crates/openhuman-tui/src/ui_state.rs b/crates/openhuman-tui/src/ui_state.rsindex bd90b4991c..6d93a84ddb 100644--- a/crates/openhuman-tui/src/ui_state.rs+++ b/crates/openhuman-tui/src/ui_state.rs@@ -86,7 +86,7 @@ impl SettingsAction {pub struct UiState {pub active_tab: AppTab,pub composer: Composer,- pub scroll_from_bottom: u16,+ pub scroll_from_bottom: usize,pub spinner_tick: usize,pub thread_id: String,pub log_scroll_from_bottom: u16,@@ -107,6 +107,27 @@ pub struct UiState {pub model_override: Option<String>,pub action_dir: String,pub queue_status: String,+ pub theme: super::theme::Theme,+ pub hits: Vec<super::actions::Hit>,+ pub viewport: super::viewport::ViewportCache,+ pub transcript_area: ratatui::layout::Rect,+ pub composer_area: ratatui::layout::Rect,+ pub composer_first_row: usize,+ pub focus: usize,+ pub agent_name: String,+ pub mouse_enabled: bool,+ pub stopping: bool,+ pub demo: bool,+ pub drafts: std::collections::HashMap<String, String>,+ pub provider_id: String,+ pub effective_model: String,+ pub overlay_generation: u64,+ pub overlay_tx: Option<tokio::sync::mpsc::UnboundedSender<super::effects::OverlayReply>>,+ pub auth_tx: Option<tokio::sync::mpsc::UnboundedSender<Result<(), String>>>,+ pub auth_pending: bool,+ pub policy_enabled: bool,+ pub overlay_area: ratatui::layout::Rect,+ pub suggestion_selected: usize,}impl UiState {@@ -161,6 +182,31 @@ impl UiState {model_override: None,action_dir: String::new(),queue_status: String::new(),+ theme: if std::env::var_os("NO_COLOR").is_some() {+ super::theme::Theme::Mono+ } else {+ super::theme::Theme::System+ },+ hits: Vec::new(),+ viewport: Default::default(),+ transcript_area: Default::default(),+ composer_area: Default::default(),+ composer_first_row: 0,+ focus: 0,+ agent_name: "orchestrator".into(),+ mouse_enabled: true,+ stopping: false,+ demo: false,+ drafts: Default::default(),+ provider_id: "openhuman".into(),+ effective_model: "Model".into(),+ overlay_generation: 0,+ overlay_tx: None,+ auth_tx: None,+ auth_pending: false,+ policy_enabled: false,+ overlay_area: Default::default(),+ suggestion_selected: 0,}}diff --git a/crates/openhuman-tui/src/viewport.rs b/crates/openhuman-tui/src/viewport.rsnew file mode 100644index 0000000000..da0841eefa--- /dev/null+++ b/crates/openhuman-tui/src/viewport.rs@@ -0,0 +1,162 @@+//! Cached cell-wrapped blocks and indexed viewport lookup.+use super::state::{EntryKind, TranscriptState};+use super::theme::safe_text;+use unicode_width::UnicodeWidthChar;++#[derive(Default)]+pub struct ViewportCache {+ width: u16,+ blocks: Vec<CachedBlock>,+ ends: Vec<usize>,+}+struct CachedBlock {+ revision: u64,+ height: usize,+ rows: Vec<String>,+}++#[derive(Clone)]+pub struct VisibleRow {+ pub text: String,+ pub entry: usize,+ pub first: bool,+ pub kind: EntryKind,+}++impl ViewportCache {+ pub fn rows(+ &mut self,+ state: &TranscriptState,+ width: u16,+ height: u16,+ offset: usize,+ ) -> (Vec<VisibleRow>, usize) {+ let width = width.max(1);+ if self.width != width {+ self.blocks.clear();+ self.width = width;+ }+ self.blocks.truncate(state.entries().len());+ self.ends.clear();+ let mut total = 0usize;+ for (index, entry) in state.entries().iter().enumerate() {+ let fresh = self+ .blocks+ .get(index)+ .is_none_or(|block| block.revision != entry.revision);+ if fresh {+ let rows = entry_rows(entry, width);+ let block = CachedBlock {+ revision: entry.revision,+ height: rows.len(),+ rows,+ };+ if index == self.blocks.len() {+ self.blocks.push(block);+ } else {+ self.blocks[index] = block;+ }+ }+ total += self.blocks[index].height;+ self.ends.push(total);+ }+ let max_scroll = total.saturating_sub(height as usize);+ let top = max_scroll.saturating_sub(offset.min(max_scroll));+ let mut index = self.ends.partition_point(|end| *end <= top);+ let first_visible = index;+ let mut absolute = if index == 0 { 0 } else { self.ends[index - 1] };+ let mut rows = Vec::with_capacity(height as usize);+ while index < self.blocks.len() && rows.len() < height as usize {+ if self.blocks[index].rows.is_empty() {+ self.blocks[index].rows = entry_rows(&state.entries()[index], width);+ }+ for (line, text) in self.blocks[index].rows.iter().enumerate() {+ if absolute >= top && rows.len() < height as usize {+ rows.push(VisibleRow {+ text: text.clone(),+ entry: index,+ first: line == 0,+ kind: state.entries()[index].kind,+ });+ }+ absolute += 1;+ }+ index += 1;+ }+ for (index, block) in self.blocks.iter_mut().enumerate() {+ if index < first_visible.saturating_sub(64) || index > first_visible + 128 {+ block.rows.clear();+ block.rows.shrink_to_fit();+ }+ }+ (rows, max_scroll)+ }+ pub fn total_rows(&self) -> usize {+ self.ends.last().copied().unwrap_or(0)+ }+}++fn entry_rows(entry: &super::state::Entry, width: u16) -> Vec<String> {+ let text = if entry.kind == EntryKind::Thinking && !entry.expanded {+ "Reasoning · click to expand".to_string()+ } else if let Some(activity) = &entry.activity {+ if entry.expanded {+ format!(+ "{}\n{}",+ activity.summary(),+ activity+ .details()+ .lines()+ .take(20)+ .collect::<Vec<_>>()+ .join("\n")+ )+ } else {+ activity.summary()+ }+ } else {+ entry.text.clone()+ };+ let mut rows = wrap_cells(&safe_text(&text), width as usize);+ if matches!(entry.kind, EntryKind::User | EntryKind::Assistant) {+ rows.insert(+ 0,+ if entry.kind == EntryKind::User {+ "You".into()+ } else {+ "OpenHuman".into()+ },+ );+ }+ if entry.activity.is_some() && entry.expanded {+ rows.push("[Open /tools for stored output details]".into());+ }+ rows.push(String::new());+ rows+}++/// Wrap by terminal cells without splitting UTF-8 or counting combining marks.+pub fn wrap_cells(value: &str, width: usize) -> Vec<String> {+ let width = width.max(1);+ let mut rows = vec![String::new()];+ let mut used = 0;+ for ch in value.chars() {+ if ch == '\n' {+ rows.push(String::new());+ used = 0;+ continue;+ }+ let cells = ch.width().unwrap_or(0);+ if cells > 0 && used + cells > width && used > 0 {+ rows.push(String::new());+ used = 0;+ }+ rows.last_mut().unwrap().push(ch);+ used += cells;+ }+ rows+}++#[cfg(test)]+#[path = "viewport_tests.rs"]+mod tests;diff --git a/crates/openhuman-tui/src/viewport_tests.rs b/crates/openhuman-tui/src/viewport_tests.rsnew file mode 100644index 0000000000..8e1ed2d0fc--- /dev/null+++ b/crates/openhuman-tui/src/viewport_tests.rs@@ -0,0 +1,40 @@+use super::*;++#[test]+fn wrapping_retains_wide_and_combining_characters() {+ assert_eq!(wrap_cells("界e\u{301}界", 3), vec!["界e\u{301}", "界"]);+}++#[test]+fn large_transcript_uses_wide_offsets_and_only_returns_the_viewport() {+ let mut state = TranscriptState::new("test");+ for _ in 0..40000 {+ state.push_system("one line");+ }+ let mut cache = ViewportCache::default();+ let (rows, max_scroll) = cache.rows(&state, 80, 20, 0);+ assert_eq!(rows.len(), 20);+ assert_eq!(max_scroll, 79980);+ assert_eq!(rows[0].entry, 39990);+ let (rows, _) = cache.rows(&state, 80, 20, max_scroll);+ assert_eq!(rows[0].entry, 0);+ assert!(+ cache+ .blocks+ .iter()+ .filter(|block| !block.rows.is_empty())+ .count()+ <= 193+ );+}++#[test]+fn changing_a_message_invalidates_only_its_cached_block() {+ let mut state = TranscriptState::new("test");+ state.begin_user_turn("hi");+ let mut cache = ViewportCache::default();+ cache.rows(&state, 80, 20, 0);+ state.push_system("new");+ let (rows, _) = cache.rows(&state, 80, 20, 0);+ assert!(rows.iter().any(|row| row.text == "new"));+}diff --git a/crates/openhuman-tui/tests/cli_e2e.rs b/crates/openhuman-tui/tests/cli_e2e.rsindex 1e19f1f7af..fb4ec999f6 100644--- a/crates/openhuman-tui/tests/cli_e2e.rs+++ b/crates/openhuman-tui/tests/cli_e2e.rs@@ -21,12 +21,16 @@ fn tui_help_advertises_cockpit_launch_and_navigation_controls() {for expected in ["[OPTIONS] [PROMPT]","--resume",+ "--demo",+ "--no-mouse","--last","--no-alt-screen","--provider","--model","Shift+Enter newline","/ opens commands",+ "Ctrl+Q queue",+ "Ctrl+P commands",] {assert!(stdout.contains(expected),diff --git a/docs/plans/2026-10-10-01-harness-ui-research.md b/docs/plans/2026-10-10-01-harness-ui-research.mdindex eb497e7471..eaa4958547 100644--- a/docs/plans/2026-10-10-01-harness-ui-research.md+++ b/docs/plans/2026-10-10-01-harness-ui-research.md@@ -119,7 +119,7 @@ These are OpenHuman design decisions inferred from the sources above, not additi| Flat `Entry { kind, text }`; separate text rows for call/result | `src/state.rs` | Retain stable call IDs and structured states || Children reduced to descriptive tool rows | `src/state.rs::apply_event` | Retain child lifecycle and parent links || Agents overlay closes on Enter without selecting a profile | `src/app.rs::handle_overlay_key` | Agent browsing is not agent selection yet |-| Enter sends `queue_mode: interrupt` despite steer hint | `src/app.rs`, `src/render.rs::draw_footer` | Align labeling and actual send semantics |+| Enter uses steer during a run; Tab queues | `src/app.rs::send_or_command`, `src/app.rs::handle_tab_key` | Preserve steering; give queue its own action so Tab can move focus || Login is one-time-token entry owned by SessionManager | `src/session.rs`, `src/controls.rs` | Reuse the host auth owner; browser login is a separate enhancement || Rich web-channel call IDs, timing, labels, sequence, child detail | `crates/openhuman-core/src/web_chat/channel_event.rs` | Consume existing contracts before proposing backend work || Desktop already has rich disclosures and child state | `app/src/store/chatRuntimeSlice.ts`, `AssistantUiToolCall.tsx` | Reference semantics; avoid inventing competing states |diff --git a/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md b/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.mdindex 97bf8d8c8a..0a1e848819 100644--- a/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md+++ b/docs/plans/2026-10-10-02-minimal-terminal-ui-spec.md@@ -1,6 +1,6 @@# 2. OpenHuman minimal terminal UI specification-Status: proposed specification, ready for implementation sequencing. Date: 2026-10-10. Scope confirmed: terminal UI first; OpenClaw is the intended third harness. Evidence: [1. Harness UI research](2026-10-10-01-harness-ui-research.md). Code baseline: OpenHuman `f6e17bc343`.+Status: initial terminal implementation delivered; remaining target behavior is recorded below. Date: 2026-10-10. Scope confirmed: terminal UI first; OpenClaw is the intended third harness. Evidence: [1. Harness UI research](2026-10-10-01-harness-ui-research.md). Code baseline: OpenHuman `f6e17bc343`.## Product goal@@ -212,4 +212,8 @@ Focused checks: `cargo test -p openhuman-tui`, `cargo check -p openhuman-tui`, `Agent routing, model catalog shape, child transcript retrieval/cancellation, question response, and complete tool-output retrieval require contract verification before wiring controls. Where an existing API cannot support a proposed action, initially show a clear unavailable state and implement the capability in its owning repository as a separate scoped change. This spec does not authorize replacing the harness or copying vendored implementation into the TUI.-The next implementation milestone is the shell/actions/theme/mouse slice after the baseline checks. No UI code has been changed in this specification phase.+The initial implementation now covers the conversation shell, shared actions and mouse hit testing, session/model/agent pickers, masked token login, tool/child inspection, themes, cached viewport rendering, and offline preview. See [the TUI guide](../../crates/openhuman-tui/README.md) for launch commands and controls.++Verified locally: baseline tests, TUI unit/CLI tests, build, scoped Clippy, crate-chain/layout checks, and live/demo startup plus terminal mouse navigation in macOS tmux. The broader dependency Clippy command encounters a pre-existing `type_complexity` lint in the core relay store. Windows/Linux terminal behavior, real provider execution, and successful backend login were not exercised in this implementation session.++Remaining extensions: browser/device-code login, session branching/older-page loading, scoped child steering/cancellation, interactive question forms, persistent appearance preferences, and Markdown/diff-specific rich formatting. Current themes are process-local; child/output inspectors show stored bounded previews. The performance budgets above remain measurement targets; the implementation does not claim every budget has been met on every platform.