Skip to main content

rpi_cli/
interactive_tui.rs

1//! Interactive mode for pi-cli.
2//!
3//! Full-screen terminal UI with a streaming transcript, an editor, a live
4//! status indicator, and tool-execution display. Mirrors the TypeScript
5//! `packages/coding-agent/src/modes/interactive/interactive-mode.ts` event→UI
6//! mapping (`handleEvent`), driven by the live `AgentEvent` stream the harness
7//! emits via the `BroadcastEmitter` installed in [`crate::session`].
8//!
9//! This host module owns startup and input dispatch. Feature implementations live
10//! in `interactive_tui/`: commands, extensions, settings, sessions, state, run,
11//! events, selectors, autocomplete, and rendering. Regression tests live in tests.rs.
12//!
13//! Key architecture facts (see the initial port notes (retired)):
14//! - `TuiAltScreen::start()` still has a readerless companion, so this module
15//!   owns a `spawn_blocking` crossterm `read()` loop for key dispatch and a
16//!   `tokio::spawn` task that drains `broadcast::Receiver<AgentEvent>` into UI
17//!   mutations.
18//! - The layout root is built ONCE at startup (mirrors the TS
19//!   `fullscreenLayoutRoot`); per-message we mutate only `chat_container` /
20//!   `status_container` / `autocomplete_container` children and call
21//!   `request_render(false)` so the differential renderer repaints just the
22//!   changed rows.
23//! - Selectors (`/model` `/session` `/theme`) are implemented by **swapping the
24//!   `editor_container` child** (the TS `showSelector` swap pattern,
25//!   `interactive-mode.ts:4354-4377`) — the `show_overlay` stub is avoided
26//!   entirely. An `active_selector` state field holds the live `SelectList`;
27//!   while it is `Some` the key loop routes to it first and restores the editor
28//!   on done/cancel.
29
30// Feature modules share the host state; their helpers stay private to this TUI.
31mod extensions;
32use extensions::*;
33pub(crate) use extensions::{ask_user_frame, parse_ask_user_prompt, AskUserPrompt};
34mod commands;
35use commands::*;
36mod settings;
37use settings::*;
38mod sessions;
39use sessions::*;
40mod run;
41use run::*;
42mod events;
43use events::*;
44mod selectors;
45use selectors::*;
46mod autocomplete;
47use autocomplete::*;
48mod rendering;
49use rendering::*;
50mod panels;
51mod pet;
52
53#[cfg(test)]
54mod tests;
55
56mod state;
57pub(crate) use state::configured_keybindings;
58use state::*;
59
60use std::collections::HashMap;
61use std::io::IsTerminal;
62use std::sync::{Arc, Mutex};
63
64use base64::Engine;
65use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
66use tokio::sync::{broadcast, mpsc};
67use tokio_util::sync::CancellationToken;
68
69use rpi_agent::{AgentEvent, AgentMessage};
70use rpi_ai::types::{AssistantMessage, Content, UserMessage};
71use rpi_harness::agent_harness::{AgentHarness, AgentLane, HarnessRunOutcome};
72use rpi_harness::session::types::{Entry, EntryOrder, EntryQuery};
73use rpi_tui::scroll_view::{OverscrollMode, ScrollbarMode};
74#[cfg(test)]
75use rpi_tui::strip_ansi;
76use rpi_tui::{
77    apply_theme_preset, AltScreenSearch, AssistantBlock, AssistantMessageComponent,
78    AssistantMessageOptions, AutocompleteManager, AutocompleteSuggestions, BashExecutionComponent,
79    BashTruncation, CombinedAutocompleteProvider, Component, Container, DynamicBorder, Editor,
80    EditorOptions, EditorStyle, FilePathAutocompleteProvider, Focusable, FollowMode,
81    FooterComponent, Image, ImageOptions, Input, Loader, Markdown, ProcessTerminal, ScrollView,
82    ScrollViewOptions, SearchBar, SearchableSelectList, SelectItem, SelectList, SettingItem,
83    SettingsList, SlashCommand as SlashCommandEntry, SlashCommandAutocompleteProvider, Spacer,
84    StackChild, StackEntry, StatusIndicator, Text, ThemeManager, ThemePreset,
85    ToolExecutionComponent, ToolStatus, TuiAltScreen, UserMessageComponent, VStack, WorkingState,
86    TUI,
87};
88use rpi_tui::{bold as tui_bold, theme as current_theme};
89
90#[allow(unused_imports)]
91use rpi_tui::BashStatus;
92
93use crate::args::Args;
94use crate::session_driver::{assistant_blocks, assistant_tool_calls};
95use crate::transcript_view::UiEvent;
96
97/// B5e: the markdown-transformer trait object the assistant-message render path
98/// applies to raw text BEFORE the [`Markdown`] renderer styles it. A plain
99/// `Fn(&str) -> String` (NO `rpi-extensions` types) so `rpi-tui` stays free of
100/// an `rpi-extensions` dep — `rpi-cli` (which already depends on
101/// `rpi-extensions`) builds the closure from the live `RegistrySnapshot` and
102/// hands the trait object to `AssistantMessageComponent::set_markdown_transformer`.
103type MarkdownTransformer = Arc<dyn Fn(&str) -> String + Send + Sync>;
104
105/// A synchronous rendezvous between the Node runtime-request thread and the
106/// blocking TUI key loop. Node's `ctx.ui.*` methods are promises, so the host
107/// request must remain pending while the user interacts with the native
108/// B5e: build the `AssistantMessageComponent` markdown-transformer closure the
109/// render path applies to raw assistant text before styling. Wraps any plugin
110/// `register_markdown_transformer` handlers registered in `snapshot` (chained
111/// in registration order: each handler's output feeds the next). `None` when
112/// no markdown transformers are registered (the component defaults to the
113/// identity transform + this avoids a closure allocation on the hot render
114/// path).
115///
116/// The closure captures an `Arc<RegistrySnapshot>` clone so it outlives the
117/// borrow that built it (the snapshot's `active` flag guards dispatch in
118/// `emit_resources_discover`/event translation; a reloaded session's old
119/// snapshot flips false, so a stale closure no-ops rather than driving a
120/// half-swapped registry — the transformer falls back to the input unchanged
121/// on an inactive snapshot, matching the plugin's per-handler skip-on-error).
122///
123/// This is the cycle-free seam: `rpi-tui` takes a `Fn(&str) -> String` trait
124/// object (no `rpi-extensions` dep); `rpi-cli` (which already depends on
125/// `rpi-extensions`) builds the closure from the live `RegistrySnapshot`. The
126/// calling pattern mirrors `plugin_stub_smoke.rs`'s direct `RenderFn` round-
127/// trip (input `{"markdown":…}` → `render_fn` → reclaim `out` via the plugin's
128/// `free_string` → parse `{"markdown":…}`).
129fn build_markdown_transformer(
130    snapshot: Option<std::sync::Arc<rpi_extensions::RegistrySnapshot>>,
131) -> Option<MarkdownTransformer> {
132    let snapshot = snapshot?;
133    // Pre-check: if no markdown renderers are registered, return None so the
134    // component uses the identity path (no per-delta closure call). The
135    // renderers list is a per-call `renderers_of` clone; snapshotting it once
136    // here keeps the closure cheap on the hot path.
137    let renderers = snapshot.renderers_of(rpi_extensions::RegisteredRendererKind::Markdown);
138    if renderers.is_empty() {
139        return None;
140    }
141    Some(Arc::new(move |raw: &str| -> String {
142        transform_markdown_chain(&snapshot, &renderers, raw)
143    }))
144}
145
146/// Drive the markdown-transformer chain for one input string. Each registered
147/// handler receives the previous handler's output (or the raw input for the
148/// first), as a `{"markdown": <text>}` JSON envelope; its `RenderFn` returns
149/// `{"markdown": <transformed>}` (rc=0) or an error (rc!=0). On any failure —
150/// nonzero rc, a panic across the FFI (caught), a missing `markdown` field, or
151/// an inactive snapshot — the chain short-circuits to the current text
152/// unchanged (per-handler skip-on-error, mirroring pi's `runner.ts` fan-out).
153fn transform_markdown_chain(
154    snapshot: &rpi_extensions::RegistrySnapshot,
155    renderers: &[rpi_extensions::RegisteredRenderer],
156    raw: &str,
157) -> String {
158    // A stale snapshot (post-/reload) must not drive a swapped-out registry.
159    // The renderers were captured from this snapshot; if it has gone inactive,
160    // fall back to the raw input so the UI never renders stale-transformed text
161    // from a dead plugin.
162    if !snapshot.is_active() {
163        return raw.to_string();
164    }
165
166    let mut current = raw.to_string();
167    for renderer in renderers {
168        let input = match serde_json::to_string(&serde_json::json!({ "markdown": current })) {
169            Ok(s) => s,
170            Err(_) => return current, // serialize failure — keep current, stop chain
171        };
172        // SAFETY: `render_fn` is a plugin-provided `extern "C" fn` over a
173        // borrowed `StbStringRef` + an out-param. The plugin warrants
174        // `poll`/`render` are non-blocking + thread-safe (the same contract
175        // the tool adapter relies on). `user_data` is the plugin's opaque
176        // pointer, stable for the registry lifetime (the keepalive keeps the
177        // cdylib mapped). We reclaim `out` via the plugin's `free_string`
178        // exactly once. The whole call is `catch_unwind`-wrapped — a plugin
179        // panic must not unwind across the FFI boundary (same policy as the
180        // tool partial cb + the runtime_action trampoline).
181        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
182            let mut out = rpi_plugin_sdk::StbString::empty();
183            let rc = (renderer.render_fn)(
184                rpi_plugin_sdk::StbStringRef::from_str(&input),
185                &mut out as *mut rpi_plugin_sdk::StbString,
186                renderer.user_data,
187            );
188            let text = if rc == 0 {
189                let s = out.to_string_lossy();
190                Some(s)
191            } else {
192                None
193            };
194            // Reclaim the plugin-owned `out` regardless of rc (rc!=0 may still
195            // have written an error JSON the plugin allocated). `free_with` is
196            // idempotent on an empty `StbString`.
197            out.free_with(Some(renderer.plugin_free_string));
198            text
199        }));
200        let out_text = match outcome {
201            Ok(Some(s)) => s,
202            Ok(None) => return current, // rc != 0 — skip this handler, keep current
203            Err(_) => return current,   // panic — skip, keep current (do not abort: the
204                                         // render path is not the action trampoline; a panicking transformer
205                                         // degrades to identity rather than killing the process. Logged via
206                                         // the `tracing` crate's panic hook.)
207        };
208        // Parse `{"markdown": <text>}`; lenient — a missing/non-string field
209        // keeps the current text (skip this handler).
210        let next = serde_json::from_str::<serde_json::Value>(&out_text)
211            .ok()
212            .and_then(|v| {
213                v.get("markdown")
214                    .and_then(|m| m.as_str())
215                    .map(|s| s.to_string())
216            })
217            .unwrap_or(current);
218        current = next;
219    }
220    current
221}
222
223// ===========================================================================
224// Slash commands — trait + registry
225// ===========================================================================
226//
227// Each built-in slash command is one `impl SlashCommand`. The commands are
228// registered at startup into a [`CommandRegistry`] (one source of truth) that
229// serves both dispatch ("given this token, run the command") and autocomplete
230// ("list the visible commands"). This replaces the old two-list + sync-test
231// arrangement, where `handle_slash_command` and `v1_slash_commands()` had to be
232// kept in lock-step by hand.
233//
234// `execute` runs on the blocking key/compose thread (the editor `on_submit`
235// callback and the Ctrl+L hotkey both land there), so it MUST stay synchronous:
236//   - commands needing async (`set_model`/`set_thinking_level`/`set_active_tools`)
237//     `tokio::spawn` the work and return immediately;
238//   - commands needing the main async loop (`compact`/`copy`/`exit`/`clear`/
239//     `user-input`) signal it via `ctx.tx.send(TuiMessage::…)`;
240//   - everything else mutates the chat container + requests a render directly.
241
242/// The borrowed world a slash command runs against. All fields are `Arc` (or a
243/// cheap `String` snapshot), so one `CommandContext` clones freely into each
244/// command without per-capture ceremony — this struct is exactly the set of
245/// `*_for_cb` clones the old submit closure used to make individually.
246#[derive(Clone)]
247struct CommandContext {
248    chat: Arc<Container>,
249    tui: Arc<TuiAltScreen>,
250    tx: mpsc::UnboundedSender<TuiMessage>,
251    state: Arc<TuiState>,
252    editor: Arc<Editor>,
253    editor_container: Arc<Container>,
254    lane: Arc<dyn AgentLane>,
255    model_catalog: Arc<Vec<rpi_ai::Model>>,
256    cwd: std::path::PathBuf,
257    /// Harness resources snapshot (skills + prompt templates) for `/context`.
258    /// Captured once at TUI startup because the blocking submit thread can't
259    /// `.await get_resources()`.
260    resources: Arc<rpi_harness::types::AgentHarnessResources>,
261    /// B5d: the reload context `/reload` drives. `Arc<ReloadContext>` so the
262    /// blocking submit thread can cheaply clone it into the `ReloadCommand`
263    /// without an `.await` (the command can't drive reload directly — it signals
264    /// the main loop via `TuiMessage::ReloadExtensions`, which awaits the shared
265    /// `reload_extension_resources` routine on the async runtime).
266    reload_context: Arc<crate::session::ReloadContext>,
267    /// The product-layer session (`AgentSession`). Commands that need durable
268    /// reads, export, or usage stats go through this instead of reaching into
269    /// the harness directly, so the product surface is one object.
270    session: Arc<crate::agent_session::AgentSession>,
271}
272
273/// One slash command.
274trait SlashCommand: Send + Sync {
275    /// Canonical name, with the leading `/` (e.g. "/model").
276    fn name(&self) -> &str;
277    /// Aliases, also `/`-prefixed. Matched alongside `name()` during dispatch.
278    /// Use [`SlashCommand::alias_visible`] to also surface an alias in the
279    /// `/`-autocomplete list (most aliases stay hidden).
280    fn aliases(&self) -> &'static [&'static str] {
281        &[]
282    }
283    /// Whether the canonical name appears in the `/` autocomplete list. Hidden
284    /// commands (`/context`, `/name`, …) return `false`.
285    fn visible(&self) -> bool {
286        true
287    }
288    /// Aliases that should also appear in the `/` autocomplete list. Defaults to
289    /// none — most aliases (`/q`, `/m`, `/think`, `/resume`, `/v`) are kept off
290    /// the list to keep it short. `/new` and `/quit` override this to surface.
291    fn alias_visible(&self) -> &'static [&'static str] {
292        &[]
293    }
294    /// Description shown in autocomplete and `/help`. A non-empty description is
295    /// required to surface in autocomplete even when `visible()` is true.
296    fn description(&self) -> &'static str {
297        ""
298    }
299    fn description_owned(&self) -> String {
300        self.description().to_string()
301    }
302    /// Execute the command. Only invoked for inputs starting with `/` whose
303    /// first token matches `name()` or an alias. `args` is the whitespace-
304    /// trimmed remainder after the command token ("" when none). Must stay
305    /// synchronous (see the module-level note) — async work goes through
306    /// `ctx.tx.send(TuiMessage::…)` or `tokio::spawn`.
307    fn execute(&self, ctx: &CommandContext, args: &str);
308}
309
310/// Holds all registered slash commands; the single source of truth for both
311/// dispatch and the autocomplete list.
312struct CommandRegistry {
313    commands: Vec<Arc<dyn SlashCommand>>,
314}
315
316impl CommandRegistry {
317    fn new() -> Self {
318        Self {
319            commands: Vec::new(),
320        }
321    }
322
323    fn register(&mut self, cmd: Arc<dyn SlashCommand>) {
324        self.commands.push(cmd);
325    }
326
327    /// Find the command whose `name()` or an alias matches `token` (e.g. "/q").
328    /// `token` is the first whitespace-delimited word of the input, `/`-prefixed.
329    fn find(&self, token: &str) -> Option<&Arc<dyn SlashCommand>> {
330        self.commands
331            .iter()
332            .find(|c| c.name() == token || c.aliases().contains(&token))
333    }
334
335    /// The autocomplete entries, derived from the registry so it can never drift
336    /// from what dispatch recognizes. Surfaces the canonical name when
337    /// `visible()` + non-empty description, plus any `alias_visible()` entries.
338    /// Order = registration order; built-ins are registered before templates,
339    /// so they win on a fuzzy tie (unchanged).
340    fn visible_entries(&self) -> Vec<SlashCommandEntry> {
341        let mut out: Vec<SlashCommandEntry> = Vec::new();
342        for c in &self.commands {
343            let description = c.description_owned();
344            if c.visible() && !description.is_empty() {
345                out.push(SlashCommandEntry {
346                    name: c.name().into(),
347                    description: description.clone(),
348                });
349            }
350            // Surfaced aliases share the command's description.
351            for alias in c.alias_visible() {
352                out.push(SlashCommandEntry {
353                    name: (*alias).into(),
354                    description: description.clone(),
355                });
356            }
357        }
358        out
359    }
360}
361
362/// Dispatch a ui_prompt_start event to extensions.
363fn dispatch_ui_prompt_event(state: &TuiState) {
364    use rpi_plugin_sdk::EventTag;
365
366    if let Ok(session) = state.extension_session.lock() {
367        if let Some(snapshot) = session.snapshot_arc() {
368            rpi_extensions::dispatch_empty_event(&snapshot, EventTag::UiPromptStart);
369        }
370    }
371}
372
373/// Dispatch a ui_prompt_end event to extensions.
374fn dispatch_ui_prompt_event_end(state: &TuiState) {
375    use rpi_plugin_sdk::EventTag;
376
377    if let Ok(session) = state.extension_session.lock() {
378        if let Some(snapshot) = session.snapshot_arc() {
379            rpi_extensions::dispatch_empty_event(&snapshot, EventTag::UiPromptEnd);
380        }
381    }
382}
383
384/// Canonical key name for a key event, matching the vocabulary
385/// [`parse_configured_key`] accepts (`"space"`, `"enter"`, `"f1"`, `"a"`).
386/// `None` for keys that cannot be named (media keys, unknown codes).
387fn key_shortcut_name(code: KeyCode) -> Option<&'static str> {
388    Some(match code {
389        KeyCode::Char(' ') => "space",
390        KeyCode::Enter => "enter",
391        KeyCode::Esc => "escape",
392        KeyCode::Tab => "tab",
393        KeyCode::BackTab => "backtab",
394        KeyCode::Backspace => "backspace",
395        KeyCode::Delete => "delete",
396        KeyCode::Up => "up",
397        KeyCode::Down => "down",
398        KeyCode::Left => "left",
399        KeyCode::Right => "right",
400        KeyCode::Home => "home",
401        KeyCode::End => "end",
402        KeyCode::PageUp => "pageup",
403        KeyCode::PageDown => "pagedown",
404        _ => return None,
405    })
406}
407
408/// Lower-case name for a printable ASCII key (`a`, `1`, `,`), or `None` when the
409/// key needs a dedicated name from [`key_shortcut_name`].
410fn char_shortcut_name(ch: char) -> Option<String> {
411    if ch.is_ascii_graphic() {
412        Some(ch.to_ascii_lowercase().to_string())
413    } else {
414        None
415    }
416}
417
418/// Route one key event to extension `Input` handlers when the key is claimed as
419/// a shortcut. Returns `true` when the key was claimed (the caller must then
420/// skip normal editor handling).
421///
422/// Only keys an extension explicitly claimed via `register_shortcut` are
423/// routed. Function keys also work with a draft; other shortcuts require an
424/// empty editor so they never steal ordinary typing. Press **and** Release (and Repeat) are dispatched, which is
425/// what lets a push-to-talk extension measure how long a key was held — the
426/// normal editor path deliberately drops Release.
427fn dispatch_key_event(state: &TuiState, key: &KeyEvent, editor: &Editor) -> bool {
428    use rpi_plugin_sdk::EventTag;
429
430    let owned_release = key.kind == KeyEventKind::Release
431        && state
432            .extension_claimed_keys
433            .lock()
434            .unwrap()
435            .remove(&key.code);
436    // Modal input owns its keys, including function keys and cancellation.
437    // The draft editor can be empty even while the dialog has text/focus.
438    if !owned_release
439        && (state.extension_dialog_open() || state.selector_open() || state.search.is_active())
440    {
441        return false;
442    }
443
444    let name = key_shortcut_name(key.code)
445        .map(str::to_string)
446        .or_else(|| match key.code {
447            KeyCode::Char(ch) => char_shortcut_name(ch),
448            KeyCode::F(n) => Some(format!("f{n}")),
449            _ => None,
450        });
451    let Some(name) = name else {
452        return false;
453    };
454
455    let Ok(session) = state.extension_session.lock() else {
456        return false;
457    };
458    let Some(snapshot) = session.snapshot_arc() else {
459        return false;
460    };
461    // Nothing claimed this key (or nobody subscribes to Input) — not ours.
462    if !snapshot.has_shortcut(&name) || snapshot.handlers_for(EventTag::Input).is_empty() {
463        return false;
464    }
465    // Function keys do not insert text. Other keys belong to the draft editor
466    // while composing (space especially).
467    if !owned_release && !editor.get_text().is_empty() && !matches!(key.code, KeyCode::F(_)) {
468        return false;
469    }
470
471    let kind = match key.kind {
472        KeyEventKind::Press => "press",
473        KeyEventKind::Repeat => "repeat",
474        KeyEventKind::Release => "release",
475    };
476    let payload = serde_json::json!({
477        "type": "key",
478        "key": name,
479        "kind": kind,
480        "ctrl": key.modifiers.contains(KeyModifiers::CONTROL),
481        "alt": key.modifiers.contains(KeyModifiers::ALT),
482        "shift": key.modifiers.contains(KeyModifiers::SHIFT),
483    })
484    .to_string();
485    // The handler decides whether it actually wants the key: it returns the
486    // `CLAIMED` code while its feature is active and `CONTINUE` otherwise, so a
487    // registered-but-disabled shortcut (push-to-talk toggled off) still lets the
488    // key reach the editor normally.
489    let claimed =
490        rpi_extensions::dispatch_data_event_claiming(&snapshot, EventTag::Input, &payload);
491    if claimed && key.kind == KeyEventKind::Press {
492        state
493            .extension_claimed_keys
494            .lock()
495            .unwrap()
496            .insert(key.code);
497    }
498    claimed
499}
500
501/// Resolve a command for a `/`-prefixed input and run it when one matches.
502///
503/// Unknown slash-prefixed input is deliberately left for the normal prompt
504/// path. In particular, the upstream skill-command behavior keeps an unknown
505/// `/skill:name` intact so the model can still handle it; it must not be
506/// converted into a local error before input handlers or the agent see it.
507/// Returns `true` only when a registered slash command handled the input.
508fn dispatch_slash(text: &str, ctx: &CommandContext, registry: &CommandRegistry) -> bool {
509    let mut parts = text.split_whitespace();
510    let token = parts.next().unwrap_or("");
511    let args = parts.collect::<Vec<_>>().join(" ");
512    match registry.find(token) {
513        Some(cmd) => {
514            cmd.execute(ctx, &args);
515            true
516        }
517        None => false,
518    }
519}
520
521/// Current wall-clock time in milliseconds since the Unix epoch. Used for
522/// `bashExecution` message timestamps (agent-loop messages carry real times, so
523/// the transcript record must too).
524fn now_ms() -> i64 {
525    std::time::SystemTime::now()
526        .duration_since(std::time::UNIX_EPOCH)
527        .map(|d| d.as_millis() as i64)
528        .unwrap_or(0)
529}
530
531/// Parse a submitted line into a user shell command.
532///
533/// Mirrors upstream's `text.startsWith("!")` handling
534/// (`interactive-mode.ts:3225`): `!cmd` runs and is recorded in the session
535/// context, `!!cmd` is excluded from it. Returns `None` for a bare `!` / `!!`
536/// (or whitespace only), so the line falls through to the normal prompt path.
537fn parse_user_bash(text: &str) -> Option<(&str, bool)> {
538    let rest = text.strip_prefix('!')?;
539    let (command, exclude_from_context) = match rest.strip_prefix('!') {
540        Some(command) => (command, true),
541        None => (rest, false),
542    };
543    let command = command.trim();
544    if command.is_empty() {
545        return None;
546    }
547    Some((command, exclude_from_context))
548}
549
550/// Run a `!command` submitted from the editor.
551///
552/// The command executes out-of-band — it never reaches the model. Output
553/// streams into a [`BashExecutionComponent`] in the transcript and the
554/// terminal result is handed to the main loop, which persists it as a
555/// `bashExecution` message (skipped from context for `!!`). Mirrors
556/// `handleBashCommand` (`interactive-mode.ts:6729`).
557fn start_user_bash(ctx: &CommandContext, command: &str, exclude_from_context: bool) {
558    let comp = Arc::new(BashExecutionComponent::new_with_context(
559        command,
560        exclude_from_context,
561    ));
562    comp.set_expanded(*ctx.state.tool_outputs_expanded.lock().unwrap());
563    ctx.chat.add_child(comp.clone());
564
565    // Register the cancellation slot before spawning so an Esc arriving on the
566    // key thread can never miss the run (upstream's `_bashAbortControllers`).
567    let cancel = ctx.state.begin_user_bash();
568    ctx.tui.request_render(false);
569
570    let env: Arc<dyn rpi_tools::ExecutionEnv> =
571        Arc::new(rpi_tools::OsExecutionEnv::with_cwd(ctx.cwd.clone()));
572    let tui = ctx.tui.clone();
573    let tx = ctx.tx.clone();
574    let cwd = ctx.cwd.clone();
575    let command_owned = command.to_string();
576
577    tokio::spawn(async move {
578        let comp_chunk = comp.clone();
579        let tui_chunk = tui.clone();
580        let on_chunk: Box<
581            dyn FnMut(&str, &dyn Fn() -> rpi_tools::shell_output::ShellCaptureProgress) + Send,
582        > = Box::new(move |_chunk, get_progress| {
583            // The capture layer reports the complete tail captured so far, not
584            // a delta; `append_output` replaces its snapshot accordingly.
585            comp_chunk.append_output(&get_progress().output);
586            tui_chunk.request_render(false);
587        });
588        let options = rpi_tools::shell_output::ShellCaptureOptions {
589            cwd: Some(cwd),
590            cancel: Some(&cancel),
591            on_chunk: Some(on_chunk),
592            return_execution_errors: true,
593            ..Default::default()
594        };
595        let result =
596            rpi_tools::shell_output::execute_shell_with_capture(&env, &command_owned, options)
597                .await;
598
599        // `Ok` carries the real exit code/cancellation; `Err` is a transport
600        // level failure (spawn failure, invalid env) which we surface inline.
601        let (exit_code, cancelled, output, truncated, full_output_path) = match result {
602            Ok(capture) => (
603                capture.exit_code,
604                capture.cancelled,
605                capture.output.clone(),
606                capture.truncated,
607                capture
608                    .full_output_path
609                    .as_ref()
610                    .map(|path| path.to_string_lossy().into_owned()),
611            ),
612            Err(error) => (
613                None,
614                false,
615                format!("Bash command failed: {error}"),
616                false,
617                None,
618            ),
619        };
620        comp.append_output(&output);
621        comp.set_complete(
622            exit_code,
623            cancelled,
624            BashTruncation {
625                truncated,
626                full_output_path: full_output_path.clone(),
627            },
628        );
629        tui.render_now(false);
630
631        let _ = tx.send(TuiMessage::UserBashFinished(UserBashReport {
632            command: command_owned,
633            output,
634            exit_code,
635            cancelled,
636            truncated,
637            full_output_path,
638            exclude_from_context,
639        }));
640    });
641}
642
643// ===========================================================================
644// Channel + helpers
645// ===========================================================================
646
647/// Message type for communication between the key/callback threads and the
648/// main async loop.
649enum TuiMessage {
650    UserInput(String, Vec<rpi_ai::types::ImageContent>),
651    OpenTree,
652    NavigateTree(String),
653    Exit,
654    /// Clear the transcript (from `/clear`).
655    ClearChat,
656    /// Compact the conversation (from `/compact`).
657    Compact,
658    /// Copy the last assistant reply to the clipboard (from `/copy`).
659    Copy,
660    /// Hot-switch to another saved session (from the `/session` selector):
661    /// the payload is the session id the selector's item value carried.
662    SwitchSession(String),
663    /// Export the current session to a markdown file (from `/export`).
664    ExportSession,
665    /// Export session with specific format
666    ExportSessionWithFormat(crate::export::ExportFormat),
667    /// Show live usage/context stats (from `/usage` and `/context`).
668    ShowUsage,
669    /// Fork the current session into a new one and switch to it (from `/fork`).
670    ForkSession,
671    /// Rename the current session (from `/name <name>`).
672    SetSessionName(String),
673    /// Import a JSONL session file into the session dir and switch to it
674    /// (from `/import <path>`).
675    ImportSession(String),
676    /// Share the current session (`/share`): `gh gist create` when the gh CLI
677    /// is available, otherwise copy the transcript to the clipboard.
678    ShareSession,
679    /// `/reload` — re-run extension + resource discovery into the live harness
680    /// (B5d). The command (and a plugin's `runtime_action(Reload)` via the
681    /// mailbox) signal the main loop, which awaits
682    /// `reload_extension_resources` on the async runtime.
683    ReloadExtensions,
684    /// Result returned after Ctrl+G edits a temporary file in an external
685    /// editor. Handling it on the async loop keeps editor mutation single-
686    /// threaded with the rest of the TUI state.
687    ExternalEditorResult(Result<String, String>),
688    /// A user-initiated `!command` / `!!command` shell run finished. Routed to
689    /// the main loop so the `bashExecution` transcript record is persisted in
690    /// order relative to agent runs (upstream's `recordBashResult` /
691    /// `_pendingBashMessages`).
692    UserBashFinished(UserBashReport),
693}
694
695/// Terminal result of a user-initiated `!command` shell run.
696///
697/// Carries everything needed to build the persisted `bashExecution` message
698/// plus the `!!` context-exclusion flag. See `start_user_bash`.
699struct UserBashReport {
700    command: String,
701    output: String,
702    exit_code: Option<i32>,
703    cancelled: bool,
704    truncated: bool,
705    full_output_path: Option<String>,
706    exclude_from_context: bool,
707}
708
709/// Extract the concatenated text content from an assistant message (mirrors
710/// the TS `contentText` projection — drops thinking/tool-call/image blocks).
711fn assistant_text(msg: &AssistantMessage) -> String {
712    msg.content
713        .iter()
714        .filter_map(|c| match c {
715            Content::Text(t) => Some(t.text.clone()),
716            _ => None,
717        })
718        .collect()
719}
720
721/// The user message's text (Text content or the text blocks of a Blocks
722/// payload — images are skipped, consistent with the v1 text-only prompt path).
723fn tool_result_message_text(msg: &rpi_ai::types::ToolResultMessage) -> String {
724    msg.content
725        .iter()
726        .filter_map(|c| match c {
727            Content::Text(t) => Some(t.text.clone()),
728            _ => None,
729        })
730        .collect::<Vec<_>>()
731        .join("\n")
732}
733
734fn user_message_text(msg: &rpi_ai::types::UserMessage) -> String {
735    match &msg.content {
736        rpi_ai::types::UserContent::Text(s) => s.clone(),
737        rpi_ai::types::UserContent::Blocks(blocks) => blocks
738            .iter()
739            .filter_map(|c| match c {
740                Content::Text(t) => Some(t.text.clone()),
741                _ => None,
742            })
743            .collect(),
744    }
745}
746
747/// The catalog allowed in the Ctrl+P cycle: the `/scoped-models` set from
748/// settings.json when present, otherwise every model. The current model is
749/// always included (fallback) so cycling can never strand the user off-scope.
750// ===========================================================================
751// interactive_tui — the entry point
752// ===========================================================================
753
754#[derive(Debug, PartialEq)]
755struct TuiStartupSettings {
756    editor_padding_x: usize,
757    autocomplete_max_visible: usize,
758    hide_thinking: bool,
759    quiet_startup: bool,
760    show_terminal_progress: bool,
761    /// Render images inline (`terminal.showImages` / flat `showImages`).
762    show_images: bool,
763    /// Transcript notices for prompt-cache costs (`showCacheMissNotices`).
764    cache_miss_notices: bool,
765}
766
767fn preferred_project_setting<T>(
768    project_settings: &[crate::settings::Settings],
769    field: impl Fn(&crate::settings::Settings) -> Option<T>,
770) -> Option<T> {
771    project_settings.iter().find_map(field)
772}
773
774fn should_show_startup_listing(verbose: bool, quiet_startup: bool) -> bool {
775    verbose || !quiet_startup
776}
777
778/// `project_settings` is ordered by precedence; an explicit `Some`
779/// wins even when the value is `false` or zero.
780fn resolve_tui_startup_settings(
781    global: &crate::settings::Settings,
782    project_settings: &[crate::settings::Settings],
783    project_trusted: bool,
784) -> TuiStartupSettings {
785    let project_settings = if project_trusted {
786        project_settings
787    } else {
788        &[]
789    };
790    let editor_padding_x =
791        preferred_project_setting(project_settings, |settings| settings.editor_padding_x)
792            .or(global.editor_padding_x)
793            .unwrap_or(1)
794            .min(16);
795    let autocomplete_max_visible = preferred_project_setting(project_settings, |settings| {
796        settings.autocomplete_max_visible
797    })
798    .or(global.autocomplete_max_visible)
799    .unwrap_or(5)
800    .clamp(1, 20);
801    let hide_thinking =
802        preferred_project_setting(project_settings, |settings| settings.hide_thinking_block)
803            .or(global.hide_thinking_block)
804            .unwrap_or(false);
805    let quiet_startup =
806        preferred_project_setting(project_settings, |settings| settings.quiet_startup)
807            .or(global.quiet_startup)
808            .unwrap_or(false);
809    let show_terminal_progress = preferred_project_setting(project_settings, |settings| {
810        settings.show_terminal_progress()
811    })
812    .or_else(|| global.show_terminal_progress())
813    .unwrap_or(true);
814    let show_images =
815        preferred_project_setting(project_settings, |settings| settings.show_images())
816            .or_else(|| global.show_images())
817            .unwrap_or(true);
818    let cache_miss_notices = preferred_project_setting(project_settings, |settings| {
819        settings.show_cache_miss_notices
820    })
821    .or(global.show_cache_miss_notices)
822    .unwrap_or(false);
823
824    TuiStartupSettings {
825        editor_padding_x,
826        autocomplete_max_visible,
827        hide_thinking,
828        quiet_startup,
829        show_terminal_progress,
830        show_images,
831        cache_miss_notices,
832    }
833}
834
835/// TUI-based interactive mode.
836///
837/// `event_rx` carries the live `AgentEvent` stream (installed by
838/// [`crate::session::build`]); when `None` (e.g. a non-TUI caller reuses this
839/// fn), it falls back to a blocking, await-final-text path.
840///
841/// `model_catalog` is the read-only catalog the `/model` selector displays.
842///
843/// This implementation mirrors the TypeScript `InteractiveMode` class:
844/// build the layout root once, drain `AgentEvent`s into UI mutations that
845/// mirror `handleEvent`, and dispatch keys from a `spawn_blocking` crossterm
846/// loop (the `TuiAltScreen` start() handler is a stub). Selectors and
847/// autocomplete are layered on via the editor-container swap pattern.
848pub async fn interactive_tui(
849    harness: &AgentHarness,
850    event_rx: Option<broadcast::Receiver<AgentEvent>>,
851    args: &Args,
852    model_catalog: Vec<rpi_ai::Model>,
853    initial: Option<String>,
854    extra_messages: &[String],
855    initial_images: Vec<rpi_ai::types::ImageContent>,
856    theme: Option<&str>,
857    _no_themes: bool,
858    reload_context: &crate::session::ReloadContext,
859) -> i32 {
860    let lane: Arc<dyn AgentLane> = harness.lane("main");
861    // Reuse the startup snapshot captured before provider/session setup. An
862    // extension may mutate the process cwd while loading; that must not change
863    // which project settings or package update roots this TUI observes.
864    let cwd = reload_context.cwd.clone();
865    let saved_settings = crate::settings::load_settings().unwrap_or_default();
866    let project_trusted = reload_context.project_trusted;
867    let project_settings = if project_trusted {
868        crate::settings::load_project_settings(&cwd)
869    } else {
870        Vec::new()
871    };
872    let tui_settings =
873        resolve_tui_startup_settings(&saved_settings, &project_settings, project_trusted);
874    let editor_padding_x = tui_settings.editor_padding_x;
875    let autocomplete_max_visible = tui_settings.autocomplete_max_visible;
876    let mut hide_thinking = tui_settings.hide_thinking;
877    let show_terminal_progress = tui_settings.show_terminal_progress;
878    let show_images = tui_settings.show_images;
879    let cache_miss_notices = tui_settings.cache_miss_notices;
880    let quiet_startup = tui_settings.quiet_startup;
881    // rpi only checks its own update channel.
882    // Session display preferences (durable, latest-wins) override the
883    // settings-file defaults. These are per-session facts stored as custom
884    // entries (see `rpi_harness::session::values`), so resuming a session with
885    // `-c`/`-r` restores the thinking/tool-output display the user last chose
886    // there — independent of global settings. Absent keys leave the settings
887    // value untouched.
888    let session_values = rpi_harness::session::SessionValues::load(harness.session())
889        .await
890        .unwrap_or_default();
891    if let Some(persisted) = session_values.get_as::<bool>("display.hide_thinking") {
892        hide_thinking = persisted;
893    }
894
895    // Resolve the active model once, up front. The full id feeds the TuiState
896    // tracking field + the selectors/key loop (which run on a blocking thread
897    // and can't await `lane.get_model()`); the provider-qualified label feeds
898    // the footer, matching Pi's `(provider) model` display.
899    let lane_model = lane.get_model().await.ok();
900    let lane_model_id = lane_model
901        .as_ref()
902        .map(|model| model.id.clone())
903        .unwrap_or_default();
904    let model_name = lane_model
905        .as_ref()
906        .map(|model| format!("({}) {}", model.provider, short_model_name(&model.id)))
907        .unwrap_or_else(|| short_model_name(&lane_model_id));
908
909    // Snapshot startup capabilities for the welcome screen. Both accessors
910    // return defensive clones, so rendering this summary does not retain a
911    // harness lock or trigger a second resource scan.
912    let mut active_tool_names = lane.get_active_tools().await.unwrap_or_default();
913    // AgentHarness uses an empty active-name list as the default "all tools"
914    // state. Do not expose that implementation sentinel as `Tools (0) none`
915    // in the welcome banner (it is especially visible on the first prompt).
916    if active_tool_names.is_empty() {
917        active_tool_names = harness
918            .get_tools()
919            .await
920            .unwrap_or_default()
921            .into_iter()
922            .map(|tool| tool.tool.schema().name.clone())
923            .collect();
924    }
925    let resources_snapshot = harness.get_resources().await.unwrap_or_default();
926    let skill_names: Vec<String> = resources_snapshot
927        .skills
928        .as_deref()
929        .unwrap_or(&[])
930        .iter()
931        .map(|skill| skill.name.clone())
932        .collect();
933
934    // Channel between the key/callback threads and the main async loop.
935    let (tx, mut rx) = mpsc::unbounded_channel::<TuiMessage>();
936
937    // Apply the saved theme before constructing transcript components. Some
938    // components keep styled text, so doing this after the welcome banner left
939    // the first screen in the dark palette until it was rebuilt.
940    let theme_manager = Arc::new(ThemeManager::new());
941    if let Some(preset) = match theme {
942        Some("light") => Some(ThemePreset::Light),
943        Some("monochrome") => Some(ThemePreset::Monochrome),
944        Some("dark") => Some(ThemePreset::Dark),
945        _ => None,
946    } {
947        apply_theme_preset(preset);
948        theme_manager.apply_preset(preset);
949    }
950
951    // ---- TUI + containers ----
952    let terminal = Box::new(ProcessTerminal::new());
953    let tui = Arc::new(TuiAltScreen::new(terminal, true, None));
954    // Plugin `ask_user` prompts (runtime action 17). Attaching marks this
955    // session as interactive so a detached/headless host fails loudly instead
956    // of returning a fabricated answer. The mailbox is session-scoped (held in
957    // `ReloadContext`) so in-flight prompts survive a `/reload`.
958    let ask_user_bridge = AskUserBridge::new(reload_context.ui_dialog.clone());
959    ask_user_bridge.attach();
960    tui.set_main_screen_mode(matches!(args.tui_mode, crate::args::TuiMode::Regular));
961
962    let chat_container = Arc::new(Container::new());
963    if should_show_startup_listing(args.verbose, quiet_startup) {
964        add_welcome_message_with_capabilities(&chat_container, &active_tool_names, &skill_names);
965    }
966
967    // First-launch gate: if `~/.rpi/.setup_done` is absent, show the welcome
968    // banner once, then write the sentinel. The banner covers the theme hint;
969    // the theme stays pickable via `/theme`. See `extras.rs`.
970    crate::extras::maybe_first_time_setup(&chat_container);
971    let collapse_changelog =
972        preferred_project_setting(&project_settings, |settings| settings.collapse_changelog)
973            .or(saved_settings.collapse_changelog)
974            .unwrap_or(false);
975    maybe_add_startup_changelog(
976        &harness,
977        &chat_container,
978        &saved_settings,
979        collapse_changelog,
980    )
981    .await;
982
983    // A --continue/--resume/--session launch opens on an existing JSONL
984    // session — render its prior user/assistant transcript so the user sees
985    // where they left off (tool executions are skipped: their live display
986    // belongs to the current run, and replaying old results would be noise).
987    let initial_transformer = build_markdown_transformer(
988        reload_context
989            .extension_session
990            .lock()
991            .unwrap()
992            .snapshot_arc(),
993    );
994    // A normal launch creates a fresh session and must not replay records from
995    // another/project harness. Only explicit restore/fork modes render prior
996    // conversation history. This fixes stale prompts appearing every startup.
997    if launch_restores_history(args) {
998        render_session_history(
999            &harness,
1000            &chat_container,
1001            initial_transformer.clone(),
1002            Some(reload_context.extension_session.clone()),
1003            show_images,
1004        )
1005        .await;
1006    }
1007
1008    // `document_container` wraps the welcome header + chat so the scrollview
1009    // follows the whole transcript (mirrors TS `documentContainer`).
1010    let document_container = Arc::new(Container::new());
1011    document_container.add_child(chat_container.clone());
1012    // Add bottom padding to the output area for visual breathing room.
1013    document_container.add_child(Arc::new(Spacer::new(1)));
1014
1015    let pet_document = Arc::new(pet::PetDocument::new(
1016        document_container.clone(),
1017        reload_context.ext_status.clone(),
1018    ));
1019    let scroll_view = Arc::new(ScrollView::new(
1020        pet_document.clone(),
1021        ScrollViewOptions {
1022            follow: FollowMode::End,
1023            primary: true,
1024            overscroll: OverscrollMode::Chain,
1025            // upstream keeps transcript chrome out of the way. Our Auto mode
1026            // has no hide timer yet and therefore became effectively permanent
1027            // after the first wheel event, unlike the upstream experience.
1028            scrollbar: ScrollbarMode::Hidden,
1029            ..Default::default()
1030        },
1031    ));
1032
1033    // ---- Editor ----
1034    // Bordered box matching upstream: no `> ` prompt, no placeholder — the
1035    // editor renders full-width `─` top/bottom borders with padding-only lines
1036    // (see Editor::render). padding_x:1 gives a 1-col inset inside the box.
1037    let keybindings = configured_keybindings();
1038    crate::transcript_navigation::install(&tui, keybindings.clone());
1039    let editor = Arc::new(Editor::new(
1040        EditorOptions {
1041            padding_x: editor_padding_x,
1042            autocomplete_max_visible,
1043            ..Default::default()
1044        },
1045        EditorStyle::default(),
1046        keybindings.clone(),
1047    ));
1048
1049    // Bash-mode border: a `!`-prefixed draft recolors the editor border to the
1050    // bash accent (upstream's `updateEditorBorderColor` / `isBashMode`). The
1051    // editor fires `on_change` for keystrokes and for programmatic
1052    // `clear`/`set_text`, so the color also resets after a `!command` submits.
1053    {
1054        let editor_for_change = editor.clone();
1055        editor.on_change(Arc::new(move |text: &str| {
1056            let colors = current_theme().colors;
1057            let is_bash = text.trim_start().starts_with('!');
1058            editor_for_change.set_border_color(if is_bash {
1059                Some(colors.bash_mode)
1060            } else {
1061                None
1062            });
1063        }));
1064    }
1065
1066    // ---- Footer + status ----
1067    let footer = Arc::new(FooterComponent::new());
1068    footer.set_model(&model_name);
1069    if let Ok(level) = lane.get_thinking_level().await {
1070        footer.set_thinking_level(Some(thinking_level_name(level)));
1071    }
1072    footer.set_cwd(&cwd.to_string_lossy());
1073    footer.set_git_branch(git_branch_for(&cwd).as_deref());
1074    if let Some(m) = model_catalog.iter().find(|m| m.id == lane_model_id) {
1075        footer.set_context_window(m.context_window as i64);
1076    }
1077    footer.set_hints("Enter: Send | Shift+Enter: New line | Ctrl+C: Clear/Exit | Esc: Abort | Ctrl+L: Model | Ctrl+P: Cycle | Ctrl+O: Expand/collapse tools | Ctrl+T: Show/hide thinking | /help");
1078
1079    // Live git-branch refresh (native fs-watch on `.git/HEAD`): a checkout or
1080    // commit updates the footer's branch without a manual refresh.
1081    let _branch_watcher = find_git_head_path(&cwd).map(|head| {
1082        let footer_ref = footer.clone();
1083        let cwd_ref = cwd.clone();
1084        crate::fs_watch::watch_path(head, move || {
1085            footer_ref.set_git_branch(git_branch_for(&cwd_ref).as_deref());
1086        })
1087    });
1088
1089    let status_container = Arc::new(Container::new());
1090    let loader = Arc::new(Loader::with_text("Working…"));
1091
1092    // ---- Autocomplete (slash commands + @file paths, rooted at cwd) ----
1093    // Prompt templates discovered at session build (Part A2) are surfaced as
1094    // `/`-prefixed entries alongside the built-in slash commands: typing
1095    // `/<name>` in the editor expands the template (mirrors pi
1096    // `expandPromptTemplate`, `agent-session.ts:1124`). The description carries
1097    // the template's frontmatter description (or a fallback) so the autocomplete
1098    // popover shows what each template does.
1099    //
1100    // We snapshot the full resources once (skills + prompt-templates): the
1101    // autocomplete builder consumes the templates, and the `/context` command
1102    // (fired from the blocking submit handler, which can't `.await`) reads the
1103    // snapshot to render the discovered-resources panel without touching the
1104    // harness async accessor.
1105    let template_slash_commands: Vec<SlashCommandEntry> = resources_snapshot
1106        .prompt_templates
1107        .clone()
1108        .unwrap_or_default()
1109        .iter()
1110        .map(|t| SlashCommandEntry {
1111            name: format!("/{}", t.name),
1112            description: t
1113                .description
1114                .clone()
1115                .unwrap_or_else(|| "Expand prompt template".to_string()),
1116        })
1117        .collect();
1118    let resources_arc: Arc<rpi_harness::types::AgentHarnessResources> =
1119        Arc::new(resources_snapshot);
1120    // Build the built-in command registry once — the single source of truth for
1121    // both dispatch and the built-in autocomplete entries. The discovered
1122    // prompt-template commands are merged into the autocomplete list separately
1123    // (they dispatch via template expansion, not the registry); built-ins come
1124    // first so they win on a fuzzy tie.
1125    let mut command_registry = build_builtin_registry();
1126    register_extension_commands(
1127        &mut command_registry,
1128        reload_context.extension_session.clone(),
1129    );
1130    let registry = Arc::new(command_registry);
1131    let mut all_slash_commands = registry.visible_entries();
1132    all_slash_commands.extend(template_slash_commands);
1133    let autocomplete = AutocompleteManager::new();
1134    {
1135        let mut combined = CombinedAutocompleteProvider::new();
1136        combined.add_provider(Arc::new(SlashCommandAutocompleteProvider::new(
1137            all_slash_commands,
1138        )));
1139        combined.add_provider(Arc::new(FilePathAutocompleteProvider::with_root(
1140            cwd.clone(),
1141        )));
1142        autocomplete.set_provider(Arc::new(combined));
1143    }
1144    let autocomplete_container = Arc::new(Container::new());
1145
1146    let tool_outputs_expanded = session_values
1147        .get_as::<bool>("display.tool_outputs_expanded")
1148        .unwrap_or(false);
1149    let state = Arc::new(TuiState {
1150        current_assistant: Arc::new(std::sync::Mutex::new(None)),
1151        tool_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
1152        bash_components: Arc::new(std::sync::Mutex::new(HashMap::new())),
1153        hide_thinking: Arc::new(std::sync::Mutex::new(hide_thinking)),
1154        tool_outputs_expanded: Arc::new(std::sync::Mutex::new(tool_outputs_expanded)),
1155        show_terminal_progress,
1156        status: std::sync::Mutex::new(RunStatus::Idle),
1157        ext_status: reload_context.ext_status.clone(),
1158        ext_status_revision: std::sync::atomic::AtomicU64::new(u64::MAX),
1159        editor_text: reload_context.editor_text.clone(),
1160        auto_send: std::sync::Mutex::new(None),
1161        last_editor_text: std::sync::Mutex::new(String::new()),
1162        programmatic_editor_write: std::sync::atomic::AtomicBool::new(false),
1163        js_preparation_cancel: std::sync::Mutex::new(None),
1164        user_bash_cancel: std::sync::Mutex::new(None),
1165        pending_bash_messages: std::sync::Mutex::new(Vec::new()),
1166        footer: footer.clone(),
1167        status_container: status_container.clone(),
1168        chat_container: chat_container.clone(),
1169        loader: loader.clone(),
1170        editor: editor.clone(),
1171        last_assistant_text: std::sync::Mutex::new(String::new()),
1172        active_selector: std::sync::Mutex::new(None),
1173        provider_form: std::sync::Mutex::new(None),
1174        active_provider_input: std::sync::Mutex::new(None),
1175        active_provider_select: std::sync::Mutex::new(None),
1176        active_extension_editor: std::sync::Mutex::new(None),
1177        active_extension_input: std::sync::Mutex::new(None),
1178        active_extension_cancel: std::sync::Mutex::new(None),
1179        autocomplete,
1180        autocomplete_container: autocomplete_container.clone(),
1181        autocomplete_max_visible,
1182        autocomplete_selection: std::sync::Mutex::new(0),
1183        pending_images: std::sync::Mutex::new(Vec::new()),
1184        theme_manager,
1185        tui: Some(tui.clone()),
1186        current_model_id: std::sync::Mutex::new(lane_model_id.clone()),
1187        show_images: std::sync::Mutex::new(show_images),
1188        cache_miss_notices: std::sync::Mutex::new(cache_miss_notices),
1189        history: std::sync::Mutex::new(Vec::new()),
1190        history_index: std::sync::Mutex::new(-1),
1191        history_draft: std::sync::Mutex::new(None),
1192        cache_tracker: std::sync::Mutex::new(rpi_harness::cache_stats::CacheMissTracker::new()),
1193        scoped_edit: std::sync::Mutex::new(None),
1194        markdown_transformer: Arc::new(std::sync::Mutex::new(initial_transformer)),
1195        extension_claimed_keys: Mutex::new(Default::default()),
1196        extension_session: reload_context.extension_session.clone(),
1197        search: Arc::new(AltScreenSearch::new()),
1198        search_bar: Arc::new(SearchBar::new()),
1199        pending_container: Arc::new(Container::new()),
1200        dequeue_hint: pending_dequeue_hint(&keybindings),
1201        pending_snapshot: std::sync::Mutex::new(
1202            rpi_harness::agent_harness::QueuedMessages::default(),
1203        ),
1204        selection_start: std::sync::Mutex::new(None),
1205        selection_end: std::sync::Mutex::new(None),
1206    });
1207
1208    let _compaction_watcher = harness.watch({
1209        let state = Arc::clone(&state);
1210        let tui = Arc::clone(&tui);
1211        move |event| {
1212            if let rpi_harness::events::HarnessEvent::CompactionProgress(event) = event {
1213                if event.lane != "main" {
1214                    return;
1215                }
1216                if event.active {
1217                    if state.show_terminal_progress {
1218                        state.editor.set_working(Some(WorkingState {
1219                            frame: 0,
1220                            started_at: std::time::Instant::now(),
1221                            message: if event.manual {
1222                                "Compacting context… (Esc to cancel)"
1223                            } else {
1224                                "Auto-compacting… (Esc to cancel)"
1225                            }
1226                            .into(),
1227                        }));
1228                    }
1229                } else {
1230                    let status = *state.status.lock().unwrap();
1231                    state.apply_status(status);
1232                }
1233                tui.request_render(false);
1234            }
1235        }
1236    });
1237
1238    // Capture the model catalog + cwd for the selector builders + the key loop
1239    // (the callbacks fire on blocking threads and need owned data).
1240    let model_catalog_arc = Arc::new(model_catalog.clone());
1241
1242    // ---- Layout root (built ONCE; mirrors TS fullscreenLayoutRoot) ----
1243    // root = VStack[ scrollview(basis:0 grow:1 shrink:1 min:1), dock(shrink:1) ]
1244    // dock  = VStack[ status(auto), autocomplete(auto), editor_container(shrink:0 min:3), footer(auto) ]
1245    //
1246    // The scrollview gets `basis(0)` so the constrained stack allocator starts
1247    // it at zero height and grows it to fill the space the dock does not need
1248    // — this keeps the dock (editor borders + footer) pinned to the bottom and
1249    // never shrinks it below the editor's 3 rows (top + content + bottom). The
1250    // editor_container is `shrink(0).min_size(3)` so a tall transcript can
1251    // never clip the input panel below its minimum.
1252    let editor_container = Arc::new(Container::new());
1253    editor_container.add_child(editor.clone());
1254
1255    let dock = Arc::new(VStack::from_children(vec![
1256        StackChild::Entry(StackEntry::new(Arc::new(panels::RegularPanels {
1257            mailbox: reload_context.ext_status.clone(),
1258            enabled: matches!(args.tui_mode, crate::args::TuiMode::Regular),
1259        }))),
1260        StackChild::Entry(StackEntry::new(state.pending_container().clone())),
1261        StackChild::Entry(StackEntry::new(status_container.clone())),
1262        StackChild::Entry(StackEntry::new(autocomplete_container.clone())),
1263        // NOTE: no Spacer here. The scroll content already ends with a blank line
1264        // (`document_container`), and a second one in the dock stacked into a
1265        // two-row gap between the last message and the input box. One row of
1266        // breathing room is the whole safe area now; the transcript keeps its
1267        // own padding so a long message never touches the editor border.
1268        StackChild::Entry(
1269            StackEntry::new(editor_container.clone())
1270                .shrink(0)
1271                .min_size(3),
1272        ),
1273        StackChild::Entry(StackEntry::new(state.search_bar.clone())),
1274        StackChild::Entry(StackEntry::new(footer.clone())),
1275        StackChild::Entry(StackEntry::new(Arc::new(panels::FooterPanels(
1276            reload_context.ext_status.clone(),
1277        )))),
1278    ]));
1279
1280    let transcript_stack = Arc::new(rpi_tui::HStack::from_entries(vec![StackEntry::new(
1281        scroll_view.clone(),
1282    )
1283    .basis(0)
1284    .grow(1)
1285    .shrink(1)
1286    .min_size(1)]));
1287    let root = VStack::from_children(vec![
1288        StackChild::Entry(
1289            StackEntry::new(transcript_stack.clone())
1290                .basis(0)
1291                .grow(1)
1292                .shrink(1)
1293                .min_size(1),
1294        ),
1295        StackChild::Entry(StackEntry::new(dock).shrink(1)),
1296    ]);
1297
1298    tui.set_layout_root(Some(Arc::new(root)));
1299    tui.set_focus(Some(editor.clone()));
1300    editor.set_focused(true);
1301
1302    // ---- Submit handler (fires on the blocking key thread; must stay sync) ----
1303    //
1304    // The handler captures one `CommandContext` (the set of `*_for_cb` clones
1305    // the old version made individually) + the registry, then routes `/`-text
1306    // through `dispatch_slash` and sends plain text directly. Each command's
1307    // `execute` owns its own effects (selector open, `tx.send`, `tokio::spawn`,
1308    // chat mutation) — the handler itself stays a thin router.
1309    //
1310    // One `CommandContext` is built and cloned for both the submit handler and
1311    // the key loop (Ctrl+L routes `/model` through the same registry); all
1312    // fields are `Arc`/cheap, so the clones are free.
1313    //
1314    // The product-layer `AgentSession` wraps a clone of the harness (the
1315    // harness handle is cheap and shares the session/bus), so `/usage`,
1316    // `/export`, and future product commands go through one surface.
1317    let scoped_models = args
1318        .model
1319        .as_deref()
1320        .map(crate::agent_session::ScopedModel::parse)
1321        .into_iter()
1322        .collect();
1323    let agent_session = Arc::new(crate::agent_session::AgentSession::new(
1324        harness.clone(),
1325        model_catalog.clone(),
1326        scoped_models,
1327        cwd.clone(),
1328    ));
1329    let ctx = CommandContext {
1330        chat: chat_container.clone(),
1331        tui: tui.clone(),
1332        tx: tx.clone(),
1333        state: state.clone(),
1334        editor: editor.clone(),
1335        editor_container: editor_container.clone(),
1336        lane: lane.clone(),
1337        model_catalog: model_catalog_arc.clone(),
1338        cwd: cwd.clone(),
1339        resources: resources_arc.clone(),
1340        reload_context: Arc::new(reload_context.clone()),
1341        session: agent_session.clone(),
1342    };
1343
1344    let ctx_for_cb = ctx.clone();
1345    let registry_for_cb = registry.clone();
1346    editor.on_submit(Arc::new(move |text: &str| {
1347        let text = text.trim();
1348        if text.is_empty() && ctx_for_cb.state.pending_images.lock().unwrap().is_empty() {
1349            return;
1350        }
1351
1352        if text.starts_with('/') && dispatch_slash(text, &ctx_for_cb, &registry_for_cb) {
1353            return;
1354        }
1355
1356        // User-initiated shell mode: `!command` runs in the background and is
1357        // recorded in the session context; `!!command` is excluded from it.
1358        // Handled before the agent prompt path so it never reaches the model.
1359        // Mirrors `interactive-mode.ts:3225`.
1360        if let Some((command, exclude_from_context)) = parse_user_bash(text) {
1361            if ctx_for_cb.state.user_bash_running() {
1362                add_error_message(
1363                    &ctx_for_cb.chat,
1364                    "A bash command is already running. Press Esc to cancel it first.",
1365                );
1366                ctx_for_cb.tui.request_render(false);
1367                return;
1368            }
1369            start_user_bash(&ctx_for_cb, command, exclude_from_context);
1370            return;
1371        }
1372
1373        let run_status = *ctx_for_cb.state.status.lock().unwrap();
1374        if run_status != RunStatus::Idle {
1375            let images = ctx_for_cb.state.take_pending_images();
1376            let message = user_message_with_images(text, images.clone());
1377            let lane = ctx_for_cb.lane.clone();
1378            let chat = ctx_for_cb.chat.clone();
1379            let tui = ctx_for_cb.tui.clone();
1380            let state = ctx_for_cb.state.clone();
1381            tokio::spawn(async move {
1382                // Queue immediately while the agent loop is still running.
1383                // Routing this through the TUI's main channel delayed it until
1384                // `prompt_text()` returned, after the loop's drain points had
1385                // passed, so the queued message appeared to disappear.
1386                //
1387                // upstream's `steer()` enqueues unconditionally, even after
1388                // the run ends, and the message stays in the queue for the
1389                // next run. This matches the TS design and avoids the race
1390                // between `activeRun` clearing and the status check.
1391                if let Err(error) = lane.steer(message).await {
1392                    state.restore_pending_images(images);
1393                    add_error_message(&chat, &format!("Could not queue message: {error}"));
1394                    tui.render_now(false);
1395                    return;
1396                }
1397                // Surface the queued entry in the pending dock immediately;
1398                // the drain-time refresh only fires on the next agent event.
1399                refresh_pending_messages(&state, &lane).await;
1400                tui.request_render(false);
1401            });
1402            // A queued prompt is echoed only once the loop actually consumes
1403            // it: the run's `AgentEvent::MessageStart` renders the user bubble
1404            // (upstream renders `message_start` for user messages). Until
1405            // then it is surfaced by the pending-messages display, so the
1406            // transcript never shows a message that is still waiting.
1407            ctx_for_cb.tui.request_render(false);
1408            return;
1409        }
1410
1411        if !ctx_for_cb.state.try_start_working() {
1412            return;
1413        }
1414
1415        // Render the user bubble here, NOT from `AgentEvent::MessageStart`.
1416        //
1417        // The harness persists the prompt itself and then drives
1418        // `run_agent_loop` with an EMPTY prompts vec (so the prompt is not
1419        // double-counted in the provider context), which means the loop emits
1420        // no `message_start` for it — see
1421        // `directly_sent_prompt_emits_no_user_message_start` in
1422        // `crates/rpi-harness/tests/harness_run_e2e.rs`. Queued steering /
1423        // follow-up prompts DO get a `message_start` (the loop drains those
1424        // itself), so those are deliberately rendered from the event instead.
1425        add_user_message(&ctx_for_cb.chat, text);
1426        // A new prompt starts a fresh interaction at the tail even when the
1427        // user had scrolled up to inspect older output.
1428        if let Some(scroll) = ctx_for_cb.tui.get_primary_scroll_view() {
1429            scroll.scroll_to_end();
1430        }
1431        ctx_for_cb.tui.request_render(false);
1432        // Remember the message for ↑ recall (slash commands are not part of
1433        // the replayable message history).
1434        push_history(&ctx_for_cb.state, text);
1435        if ctx_for_cb
1436            .tx
1437            .send(TuiMessage::UserInput(
1438                text.to_string(),
1439                ctx_for_cb.state.take_pending_images(),
1440            ))
1441            .is_err()
1442        {
1443            ctx_for_cb.state.set_status(RunStatus::Idle);
1444        }
1445    }));
1446
1447    // Turn on the native-pi frame throttle before the first frame: from here on
1448    // `request_render(false)` parks a frame and the scheduler thread paints at
1449    // most one per `MIN_RENDER_INTERVAL_MS` (16 ms). A provider that streams one
1450    // `MessageUpdate` per delta would otherwise force a full transcript
1451    // re-render + full-viewport terminal write per token, which is what made
1452    // long output saturate the terminal (and its GPU compositor). Immediate
1453    // renders (selectors, the first frame, `render_now(..)`) are unaffected.
1454    tui.start_render_scheduler();
1455    tui.start_readerless();
1456
1457    // Consume local self-update results even when network checks are disabled.
1458    // Keep package discovery separate so package managers and Git remotes
1459    // cannot delay an rpi update notice or a prior helper failure.
1460    let mut update_check_handles = Vec::new();
1461    let rpi_chat = chat_container.clone();
1462    let rpi_tui = tui.clone();
1463    update_check_handles.push(tokio::spawn(async move {
1464        let report = crate::updates::check_rpi_startup().await;
1465        if !report.is_empty() {
1466            add_update_notices(&rpi_chat, &report);
1467        }
1468        rpi_tui.request_render(false);
1469    }));
1470
1471    // Only the rpi self-update check runs.
1472
1473    // ---- Streaming drain task ----
1474    let drain_handle = if let Some(rx) = event_rx {
1475        let tui_drain = tui.clone();
1476        let state_drain = state.clone();
1477        let chat_drain = chat_container.clone();
1478        let lane_drain = lane.clone();
1479        Some(tokio::spawn(async move {
1480            drain_agent_events(rx, tui_drain, state_drain, chat_drain, lane_drain).await;
1481        }))
1482    } else {
1483        None
1484    };
1485
1486    // ---- B5d: plugin→TUI reload bridge ----
1487    // A plugin's `runtime_action(Reload)` can't drive the reload synchronously
1488    // (its cdylib would be unmapped while the call frame is still on the stack).
1489    // Instead the `ActionBridge`'s reload callback signals `reload_context.mailbox`
1490    // (an `UnboundedSender<()>`); this task drains those signals and forwards
1491    // `TuiMessage::ReloadExtensions` into the main loop, which runs the shared
1492    // `reload_extension_resources` routine asynchronously. The mailbox is the
1493    // cycle-free seam: rpi-extensions carries only `()` (no `TuiMessage` type —
1494    // leaf DAG preserved); the TUI owns the receiver + the reload routine.
1495    let (reload_sig_tx, mut reload_sig_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
1496    reload_context.mailbox.install(reload_sig_tx);
1497    let reload_tx = tx.clone();
1498    let reload_bridge_handle = tokio::spawn(async move {
1499        while reload_sig_rx.recv().await.is_some() {
1500            if reload_tx.send(TuiMessage::ReloadExtensions).is_err() {
1501                break; // main loop gone — stop forwarding
1502            }
1503        }
1504    });
1505
1506    // ---- Render-tick task (advances the loader spinner while Working) ----
1507    //
1508    // The `Loader` only advances its frame on render; without a periodic
1509    // `request_render` the spinner visibly freezes between events.
1510    let tui_tick = tui.clone();
1511    let state_tick = state.clone();
1512    // The tick, not the key loop, drives the voice-draft auto-send: it must
1513    // fire even when the user types nothing.
1514    let tx_tick = tx.clone();
1515    let pet_tick = pet_document.clone();
1516    let mut plugin_panels = panels::Panels::with_sidebar(
1517        transcript_stack,
1518        scroll_view.clone(),
1519        reload_context.ext_status.clone(),
1520    );
1521    plugin_panels.regular_mode = matches!(args.tui_mode, crate::args::TuiMode::Regular);
1522    plugin_panels.sync(tui.as_ref(), &reload_context.ext_status);
1523    let scroll_tick = scroll_view.clone();
1524    let tick_handle = tokio::spawn(async move {
1525        // 80ms per frame — upstream's `DEFAULT_INTERVAL_MS`, i.e. a full
1526        // 10-frame cycle every 800ms. The tick only *requests a repaint*; the
1527        // frame is advanced by `Editor::render` (mirroring `Loader::render`),
1528        // so streaming output — which schedules a frame per token — spins it
1529        // faster, and this interval is the floor when the model is silent.
1530        //
1531        // Advancing here as well would double-step every tick and make the idle
1532        // spinner run at 40ms/frame, twice upstream's rate.
1533        let mut interval = tokio::time::interval(std::time::Duration::from_millis(
1534            rpi_tui::loader::SPINNER_FRAME_MS,
1535        ));
1536        interval.tick().await; // discard immediate
1537        loop {
1538            interval.tick().await;
1539            // Extension status (langfuse ✓ …, …) — cheap revision check, and the
1540            // only reason an idle session repaints its footer.
1541            let panels_changed = plugin_panels.sync(tui_tick.as_ref(), &state_tick.ext_status);
1542            if state_tick.sync_extension_status() || panels_changed {
1543                // Status/panel updates leave chat content untouched. The scroll
1544                // cache regenerates itself if enabling a sidebar changes width.
1545                tui_tick.request_render_reusing_scroll_content();
1546            }
1547            if pet_tick.tick(scroll_tick.viewport_height()) {
1548                tui_tick.request_render(false);
1549            }
1550            // Extension editor-text injection (`SetEditorText`): a voice plugin
1551            // drops a transcription in as an editable draft.
1552            if state_tick.drain_editor_text() {
1553                tui_tick.request_render(false);
1554            }
1555            // Tell extensions the draft changed (voice barge-in). Runs after the
1556            // drain so an injected transcription also counts as a change.
1557            state_tick.sync_editor_change();
1558            // Advance a draft's auto-send countdown (submit / cancel / repaint).
1559            if poll_auto_send(&state_tick, &tx_tick) {
1560                tui_tick.request_render(false);
1561            }
1562            let working = *state_tick.status.lock().unwrap() == RunStatus::Working;
1563            if working {
1564                // A live transcript panel — a running bash command *or* a
1565                // running tool call — computes its elapsed readout from
1566                // `Instant::now()` at render time. A frame that reuses the
1567                // cached scroll content never rebuilds it, so the readout
1568                // froze at the second of the last full rebuild (reported: a
1569                // `search` call stuck at "2.0s" with no way to tell it was
1570                // still running). Rebuild while any such panel is live.
1571                let bash_present = !state_tick.bash_components.lock().unwrap().is_empty();
1572                let has_live_panel = {
1573                    let tools = state_tick.tool_components.lock().unwrap();
1574                    transcript_has_live_panel(bash_present, &tools)
1575                };
1576                if has_live_panel {
1577                    tui_tick.request_render(false);
1578                } else {
1579                    // Only the dock loader animates. Keep the already-rendered
1580                    // transcript instead of rebuilding a long history at 12.5
1581                    // frames per second.
1582                    tui_tick.request_render_reusing_scroll_content();
1583                }
1584            }
1585        }
1586    });
1587
1588    // ---- Key dispatch loop (spawn_blocking crossterm read) ----
1589    let running = Arc::new(std::sync::Mutex::new(true));
1590    let running_key = running.clone();
1591    let tx_for_key = tx.clone();
1592    let tui_for_key = tui.clone();
1593    let editor_for_key = editor.clone();
1594    let scroll_for_key = scroll_view.clone();
1595    let lane_for_key = lane.clone();
1596    let state_for_key = state.clone();
1597    let model_catalog_for_key = model_catalog_arc.clone();
1598    let ask_user_for_key = ask_user_bridge.clone();
1599    // Ctrl+L routes through the same registry as `/model` (one path, not two),
1600    // so the key loop needs the same `CommandContext` + registry the submit
1601    // handler uses. All fields are `Arc`/cheap, so this clone is free.
1602    let ctx_for_key = ctx.clone();
1603    let registry_for_key = registry.clone();
1604    let keybindings_for_key = keybindings.clone();
1605    let double_escape_action = crate::settings::load_settings()
1606        .ok()
1607        .and_then(|settings| settings.double_escape_action)
1608        .unwrap_or_else(|| "tree".to_string())
1609        .to_ascii_lowercase();
1610
1611    let key_handle = tokio::task::spawn_blocking(move || {
1612        let mut last_escape_time = None;
1613        // upstream's `handleCtrlC` "press twice to exit" window: the instant of
1614        // the last lone Ctrl+C. Shares the 500ms with Esc's double-escape.
1615        let mut last_sigint_time: Option<std::time::Instant> = None;
1616        // One event peeked at by the paste-burst probe (which must discard a
1617        // key's Release but never lose a meaningful event it read). Restored
1618        // at the top of the next loop iteration.
1619        let mut pending_event: Option<Event> = None;
1620        let mut windows_paste_run = WindowsPasteRun::default();
1621        if crate::key_trace::enabled() {
1622            crate::key_trace::note(&format!(
1623                "--- rpi TUI key trace start pid={} TERM={} raw_mode={} ---",
1624                std::process::id(),
1625                std::env::var("TERM").unwrap_or_else(|_| "(unset)".to_string()),
1626                crossterm::terminal::is_raw_mode_enabled().unwrap_or(false),
1627            ));
1628        }
1629        loop {
1630            if !*running_key.lock().unwrap() {
1631                break;
1632            }
1633            if !state_for_key.selector_open() && !state_for_key.extension_dialog_open() {
1634                if let Some(request) = ask_user_for_key.take_pending() {
1635                    open_ask_user_dialog(&ctx_for_key, ask_user_for_key.clone(), request);
1636                }
1637            }
1638            let ev = if let Some(ev) = pending_event.take() {
1639                ev
1640            } else {
1641                // `event::read()` blocks indefinitely. Poll first so shutdown can
1642                // stop and join this worker even when no further key arrives.
1643                match crossterm::event::poll(
1644                    if cfg!(windows) && !windows_paste_run.text.is_empty() {
1645                        windows_paste_run.grace()
1646                    } else {
1647                        std::time::Duration::from_millis(50)
1648                    },
1649                ) {
1650                    Ok(true) => {}
1651                    Ok(false) => {
1652                        if cfg!(windows) && !windows_paste_run.text.is_empty() {
1653                            windows_paste_run.flush(&editor_for_key);
1654                            refresh_autocomplete(&state_for_key, &editor_for_key);
1655                            tui_for_key.request_render_reusing_scroll_content();
1656                        }
1657                        continue;
1658                    }
1659                    Err(_) => {
1660                        state_for_key.cancel_js_preparation();
1661                        let _ = tx_for_key.send(TuiMessage::Exit);
1662                        break;
1663                    }
1664                }
1665                let Ok(ev) = crossterm::event::read() else {
1666                    state_for_key.cancel_js_preparation();
1667                    let _ = tx_for_key.send(TuiMessage::Exit);
1668                    break;
1669                };
1670                ev
1671            };
1672            // `Event::Resize` is delivered as its own event (not a Key). With
1673            // `start_readerless` there is no competing terminal-reader thread to
1674            // handle it, so refresh the cached terminal size here and force a
1675            // full redraw so the constrained layout re-fits the new dimensions.
1676            if let Event::Resize(_cols, _rows) = ev {
1677                tui_for_key.refresh_size();
1678                continue;
1679            }
1680            // Mouse wheel scrolls the transcript (pi supports wheel
1681            // scrolling). Previously every non-Key event was dropped, so a
1682            // wheel had zero effect
1683            if let Event::Mouse(m) = ev {
1684                if tui_for_key.handle_scroll_to_end_indicator_mouse_event(&m) {
1685                    *state_for_key.selection_start.lock().unwrap() = None;
1686                    *state_for_key.selection_end.lock().unwrap() = None;
1687                    continue;
1688                }
1689                use crossterm::event::MouseEventKind;
1690                match m.kind {
1691                    MouseEventKind::ScrollUp => {
1692                        let delta = -MOUSE_WHEEL_SCROLL_LINES;
1693                        if scroll_for_key.scroll_by(delta) != delta {
1694                            tui_for_key.request_render_reusing_scroll_content();
1695                        }
1696                    }
1697                    MouseEventKind::ScrollDown => {
1698                        let delta = MOUSE_WHEEL_SCROLL_LINES;
1699                        if scroll_for_key.scroll_by(delta) != delta {
1700                            tui_for_key.request_render_reusing_scroll_content();
1701                        }
1702                    }
1703                    MouseEventKind::Down(crossterm::event::MouseButton::Right) if cfg!(windows) => {
1704                        // upstream treats Windows right-click as a clipboard
1705                        // paste, rather than letting the console deliver the
1706                        // clipboard contents as individual key events. This is
1707                        // what preserves the complete payload for
1708                        // Editor::handle_paste and large-paste folding.
1709                        if let Some(text) = read_clipboard_text() {
1710                            if !text.is_empty() {
1711                                editor_for_key.handle_paste(&text);
1712                                refresh_autocomplete(&state_for_key, &editor_for_key);
1713                                tui_for_key.request_render_reusing_scroll_content();
1714                            }
1715                        }
1716                    }
1717                    MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
1718                        // Start selection tracking. `selection_end` doubles as the
1719                        // "a real drag happened" marker: a plain tap never sets
1720                        // it, so it can never overwrite the clipboard.
1721                        *state_for_key.selection_start.lock().unwrap() = Some((m.column, m.row));
1722                        *state_for_key.selection_end.lock().unwrap() = None;
1723                    }
1724                    MouseEventKind::Drag(crossterm::event::MouseButton::Left) => {
1725                        // Motion with the button held = a genuine selection drag.
1726                        // (Terminals only report this with button-event mouse
1727                        // tracking, which `ProcessTerminal` enables.)
1728                        if state_for_key.selection_start.lock().unwrap().is_some() {
1729                            *state_for_key.selection_end.lock().unwrap() = Some((m.column, m.row));
1730                        }
1731                    }
1732                    MouseEventKind::Up(crossterm::event::MouseButton::Left) => {
1733                        // End selection and auto-copy if enabled
1734                        if let Some(start) = *state_for_key.selection_start.lock().unwrap() {
1735                            let end = (m.column, m.row);
1736
1737                            // Only auto-copy when the pointer actually MOVED with
1738                            // the button held (`Drag` set `selection_end`). A plain
1739                            // click/tap — even one whose Down/Up cells differ by a
1740                            // pixel over RDP — must not touch the clipboard: it used
1741                            // to fire `extract_selected_text`, which copies whatever
1742                            // rendered TUI line sat under the pointer, silently
1743                            // clobbering the user's real clipboard so the next paste
1744                            // returned that stale text.
1745                            let is_drag = state_for_key.selection_end.lock().unwrap().is_some();
1746                            *state_for_key.selection_end.lock().unwrap() = Some(end);
1747
1748                            // Check if auto-copy is enabled
1749                            let auto_copy = crate::settings::load_settings()
1750                                .ok()
1751                                .and_then(|s| s.fullscreen_copy_on_select)
1752                                .unwrap_or(true);
1753
1754                            if auto_copy && is_drag {
1755                                // Try to extract selected text from chat container
1756                                if let Some(selected_text) =
1757                                    extract_selected_text(&state_for_key.chat_container, start, end)
1758                                {
1759                                    if !selected_text.trim().is_empty() {
1760                                        let _ = copy_to_clipboard(&selected_text);
1761                                    }
1762                                }
1763                            }
1764                        }
1765                        *state_for_key.selection_start.lock().unwrap() = None;
1766                        *state_for_key.selection_end.lock().unwrap() = None;
1767                    }
1768                    _ => {}
1769                }
1770                continue;
1771            }
1772            let Event::Key(key) = ev else {
1773                if let Event::Paste(text) = ev {
1774                    crate::key_trace::note(&format!(
1775                        "paste event ({} bytes, bracketed paste supported)",
1776                        text.len()
1777                    ));
1778                    // A provider-form text step owns the input slot: paste into
1779                    // its single-line input instead of the chat editor.
1780                    if state_for_key.provider_form.lock().unwrap().is_some() {
1781                        let active = state_for_key.active_provider_input.lock().unwrap().clone();
1782                        if let Some(input) = active {
1783                            input.handle_paste(&text);
1784                            tui_for_key.request_render_reusing_scroll_content();
1785                            continue;
1786                        }
1787                    }
1788                    if let Some(images) = images_from_pasted_paths(&text) {
1789                        for image in images {
1790                            state_for_key.queue_image(image);
1791                        }
1792                        add_note_message(
1793                            &state_for_key.chat_container,
1794                            "Dropped images attached to the next prompt.",
1795                        );
1796                        tui_for_key.request_render(false);
1797                        continue;
1798                    }
1799                    editor_for_key.handle_paste(&text);
1800                    refresh_autocomplete(&state_for_key, &editor_for_key);
1801                    tui_for_key.request_render_reusing_scroll_content();
1802                }
1803                continue;
1804            };
1805            let key = rpi_tui::terminal::normalize_key_event(key);
1806            // Diagnostic trace (off unless RPI_DEBUG_KEYS is set): records what
1807            // actually arrived before any routing decision, so a client that
1808            // sends LF for Enter is visible as `Char('j') mods=CONTROL`.
1809            crate::key_trace::key(&key, "");
1810            // A key press during a voice-draft auto-send countdown cancels the
1811            // countdown — the user wants to edit, not send. The key still falls
1812            // through to the editor, so it doubles as their first correction.
1813            if key.kind != KeyEventKind::Release && state_for_key.cancel_auto_send_on_key() {
1814                tui_for_key.request_render(false);
1815            }
1816            // Extension shortcuts see Press *and* Release (this is what lets a
1817            // push-to-talk extension time a hold). Checked before the
1818            // release-drop below; a claimed key with an empty editor is routed
1819            // to the plugin's `Input` handler instead of the editor.
1820            if dispatch_key_event(&state_for_key, &key, &editor_for_key) {
1821                continue;
1822            }
1823            // Drop releases but preserve Repeat so holding arrows, Backspace,
1824            // PageUp, etc. behaves naturally. Windows emits Press + Release
1825            // for a tap; terminals with keyboard enhancement may additionally
1826            // emit Repeat while a key is held.
1827            if !should_dispatch_key(key.kind) {
1828                continue;
1829            }
1830
1831            // Prompt preparation runs on a blocking worker before the agent
1832            // lane owns the turn. Cancel it directly: an abort queued only to
1833            // the lane cannot wake a JS factory or lifecycle hook that never
1834            // resolves. This check precedes custom/dialog routing because
1835            // those components may themselves have been opened by the hook.
1836            let prompt_abort = (key.modifiers == KeyModifiers::CONTROL
1837                && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')))
1838                || (key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Esc);
1839            if prompt_abort && state_for_key.cancel_js_preparation() {
1840                state_for_key.set_status(RunStatus::Aborting);
1841                if !run_extension_cancel(&state_for_key) && state_for_key.extension_dialog_open() {
1842                    close_extension_editor(
1843                        &state_for_key,
1844                        &ctx_for_key.editor_container,
1845                        &editor_for_key,
1846                        &tui_for_key,
1847                    );
1848                }
1849                tui_for_key.set_render_suspended(false);
1850                tui_for_key.request_render(false);
1851                continue;
1852            }
1853
1854            // Ctrl+C cancels an open selector before it reaches the global
1855            // abort/exit handler. Route through Esc so selector callbacks run.
1856            if key.modifiers == KeyModifiers::CONTROL
1857                && key.code == KeyCode::Char('c')
1858                && state_for_key.selector_open()
1859            {
1860                let selector = state_for_key
1861                    .active_selector
1862                    .lock()
1863                    .unwrap()
1864                    .clone()
1865                    .expect("selector_open guaranteed Some")
1866                    .0;
1867                selector.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
1868                tui_for_key.request_render_reusing_scroll_content();
1869                continue;
1870            }
1871
1872            // The interactive "Add provider" form owns the input slot while it
1873            // collects a field: route every key to its single-line input (Esc
1874            // and Enter are handled by the Input's own callbacks). Clone the
1875            // input OUTSIDE `if let` so the `active_provider_input` mutex guard
1876            // drops before `handle_key` — the submit path re-enters that mutex
1877            // to swap in the next step's input and would deadlock on it.
1878            if state_for_key.provider_form.lock().unwrap().is_some() {
1879                let active_input = state_for_key.active_provider_input.lock().unwrap().clone();
1880                let active_select = state_for_key.active_provider_select.lock().unwrap().clone();
1881                if let Some(input) = active_input {
1882                    input.handle_key(key);
1883                } else if let Some(select) = active_select {
1884                    select.handle_key(key);
1885                }
1886                tui_for_key.request_render_reusing_scroll_content();
1887                continue;
1888            }
1889
1890            // Extension dialogs own the input slot while awaiting a result.
1891            // Esc and Ctrl+C both resolve the pending command with cancel;
1892            // all other keys go to the active native editor/input widget.
1893            if state_for_key.extension_dialog_open() {
1894                let cancel = key.code == KeyCode::Esc
1895                    || (key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('c'));
1896                if cancel {
1897                    if !run_extension_cancel(&state_for_key) {
1898                        close_extension_editor(
1899                            &state_for_key,
1900                            &ctx_for_key.editor_container,
1901                            &editor_for_key,
1902                            &tui_for_key,
1903                        );
1904                    }
1905                } else if let Some(extension_editor) = state_for_key
1906                    .active_extension_editor
1907                    .lock()
1908                    .unwrap()
1909                    .clone()
1910                {
1911                    extension_editor.handle_key(key);
1912                } else if let Some(extension_input) =
1913                    state_for_key.active_extension_input.lock().unwrap().clone()
1914                {
1915                    extension_input.handle_key(key);
1916                }
1917                tui_for_key.request_render_reusing_scroll_content();
1918                continue;
1919            }
1920
1921            // Pet Esc pauses audio; an active run still reaches normal abort
1922            // routing below. Dialogs and selectors retain their own Escape.
1923            if key.code == KeyCode::Esc
1924                && key.modifiers == KeyModifiers::NONE
1925                && !state_for_key.selector_open()
1926                && pet::active(&state_for_key.ext_status)
1927            {
1928                let _ = invoke_extension_command(&state_for_key.extension_session, "pet", "quiet");
1929                tui_for_key.request_render(false);
1930                if *state_for_key.status.lock().unwrap() == RunStatus::Idle
1931                    && editor_for_key.get_text().is_empty()
1932                {
1933                    continue;
1934                }
1935            }
1936
1937            // 0. Ctrl+C: upstream's `handleCtrlC`. A second press inside the
1938            //    double-press window quits; any other press only clears the
1939            //    editor (text *and* selection — native `clearEditor`). It never
1940            //    aborts — `app.interrupt` (Esc) owns cancelling a run — so a
1941            //    stray Ctrl+C while streaming can no longer kill the turn.
1942            //    Open selectors and extension dialogs are handled above so
1943            //    their cancellation callbacks get first chance.
1944            if keybinding_matches(
1945                &keybindings_for_key,
1946                &key,
1947                rpi_tui::keybindings::keys::CLEAR,
1948            ) {
1949                // A held key auto-repeats: only a fresh Press may arm or
1950                // consume the window, so holding Ctrl+C cannot turn one tap
1951                // into the quit.
1952                if key.kind != KeyEventKind::Repeat {
1953                    let now = std::time::Instant::now();
1954                    match ctrl_c_action(last_sigint_time, now) {
1955                        CtrlCAction::Exit => {
1956                            last_sigint_time = None;
1957                            // The async loop parks inside
1958                            // `run_prompt_streaming(..).await` for the whole run,
1959                            // so a queued `Exit` would not be read until the run
1960                            // returns — force the quit while one is active. Either
1961                            // way the TUI stays quittable.
1962                            if *state_for_key.status.lock().unwrap() == RunStatus::Idle {
1963                                let _ = tx_for_key.send(TuiMessage::Exit);
1964                            } else {
1965                                emergency_exit(&tui_for_key);
1966                            }
1967                        }
1968                        CtrlCAction::Clear => {
1969                            editor_for_key.clear();
1970                            state_for_key.take_pending_images();
1971                            refresh_autocomplete(&state_for_key, &editor_for_key);
1972                            last_sigint_time = Some(now);
1973                            tui_for_key.request_render(false);
1974                        }
1975                    }
1976                }
1977                continue;
1978            }
1979
1980            // 0b. Ctrl+X: upstream's `app.message.copy` — copy the editor
1981            //     selection, else the last assistant reply. Native's Ctrl+C no
1982            //     longer copies, so selection-copy lives here now.
1983            if !state_for_key.selector_open()
1984                && keybinding_matches(
1985                    &keybindings_for_key,
1986                    &key,
1987                    rpi_tui::keybindings::keys::MESSAGE_COPY,
1988                )
1989            {
1990                if editor_for_key.has_selection() && editor_for_key.copy_selection() {
1991                    add_note_message(&state_for_key.chat_container, "Copied!");
1992                } else {
1993                    copy_last_assistant(&state_for_key, &state_for_key.chat_container);
1994                }
1995                tui_for_key.request_render(false);
1996                continue;
1997            }
1998
1999            // 0c. Ctrl+Z (Unix only): upstream's `app.suspend` — hand the
2000            //     terminal back to the shell and stop ourselves; `SIGTSTP`
2001            //     returns when the user resumes with `fg`. Windows binds no key
2002            //     here (native's `defaultKeys` is empty), so this never fires.
2003            if keybinding_matches(
2004                &keybindings_for_key,
2005                &key,
2006                rpi_tui::keybindings::keys::SUSPEND,
2007            ) {
2008                handle_suspend(&tui_for_key);
2009                continue;
2010            }
2011
2012            // 1. A selector overlay is open → route to it first. Only Esc
2013            //    (cancel) and Enter/Up/Down/Ctrl-K/J/P/N (navigate/select)
2014            //    escape to the selector; on done/cancel the selector callbacks
2015            //    restore the editor and clear `active_selector`.
2016            if state_for_key.selector_open() {
2017                // Esc always cancels the selector (even with modifiers off).
2018                // Route through `SelectList::handle_key(Esc)` so the list's
2019                // `on_cancel` fires (the `/scoped-models` toggle selector saves
2020                // its edits there) — the old shortcut called `close_selector`
2021                // directly and skipped the callback.
2022                if key.code == KeyCode::Esc {
2023                    let (selector, _kind) = state_for_key
2024                        .active_selector
2025                        .lock()
2026                        .unwrap()
2027                        .clone()
2028                        .expect("selector_open guaranteed Some");
2029                    selector.handle_key(key);
2030                    continue;
2031                }
2032                let (selector, _kind) = state_for_key
2033                    .active_selector
2034                    .lock()
2035                    .unwrap()
2036                    .clone()
2037                    .expect("selector_open guaranteed Some");
2038                selector.handle_key(key);
2039                tui_for_key.request_render_reusing_scroll_content();
2040                continue;
2041            }
2042
2043            // 2a. Ctrl+D: upstream's `app.exit`. `handleCtrlD` only fires when
2044            //     the editor is empty; with text present the key falls through to
2045            //     the editor's deleteCharForward (`tui.editor.deleteCharForward`).
2046            //     It never aborts — that is `app.interrupt` (Esc)'s job.
2047            if keybinding_matches(&keybindings_for_key, &key, rpi_tui::keybindings::keys::EXIT) {
2048                if !editor_for_key.get_text().is_empty() {
2049                    // Editor holds text — delete the char forward (pi parity).
2050                    editor_for_key.handle_key(key);
2051                    refresh_autocomplete(&state_for_key, &editor_for_key);
2052                    tui_for_key.request_render_reusing_scroll_content();
2053                    continue;
2054                }
2055                // Empty editor → quit. A parked run needs the forced path: a
2056                // queued `Exit` is unread until the run returns.
2057                if *state_for_key.status.lock().unwrap() == RunStatus::Idle {
2058                    let _ = tx_for_key.send(TuiMessage::Exit);
2059                } else {
2060                    emergency_exit(&tui_for_key);
2061                }
2062                continue;
2063            }
2064
2065            // 2b. Esc: interrupt an active run (mirrors Ctrl+C abort). When a
2066            //     selector is open Esc already cancelled it above; when idle,
2067            //     Esc falls through to the editor (no-op-ish). Only fire while
2068            //     Working so an idle Esc doesn't abort a non-existent run.
2069            if keybinding_matches(
2070                &keybindings_for_key,
2071                &key,
2072                rpi_tui::keybindings::keys::INTERRUPT,
2073            ) {
2074                let status = *state_for_key.status.lock().unwrap();
2075                if status == RunStatus::Working {
2076                    state_for_key.set_status(RunStatus::Aborting);
2077                    ask_user_for_key.cancel_all();
2078                    if !run_extension_cancel(&state_for_key)
2079                        && state_for_key.extension_dialog_open()
2080                    {
2081                        close_extension_editor(
2082                            &state_for_key,
2083                            &ctx_for_key.editor_container,
2084                            &editor_for_key,
2085                            &tui_for_key,
2086                        );
2087                    }
2088                    // upstream's `onEscape` restores the queue before it
2089                    // aborts, so an interrupt hands the staged messages back.
2090                    abort_run_restoring_queue(
2091                        lane_for_key.clone(),
2092                        editor_for_key.clone(),
2093                        state_for_key.clone(),
2094                        tui_for_key.clone(),
2095                    );
2096                    continue;
2097                }
2098                // A running `!command` takes Esc next (upstream's `onEscape`
2099                // precedence: streaming → bash → bash-mode editor →
2100                // double-escape). The run slot stays occupied until the capture
2101                // resolves, so a second Esc is a no-op rather than a
2102                // double-escape trigger.
2103                if state_for_key.user_bash_running() {
2104                    state_for_key.cancel_user_bash();
2105                    tui_for_key.request_render(false);
2106                    continue;
2107                }
2108                if status == RunStatus::Idle
2109                    && editor_for_key.get_text().trim().is_empty()
2110                    && double_escape_action != "none"
2111                {
2112                    let now = std::time::Instant::now();
2113                    if double_escape_trigger(last_escape_time, now) {
2114                        last_escape_time = None;
2115                        match double_escape_action.as_str() {
2116                            "tree" => {
2117                                let _ = tx_for_key.send(TuiMessage::OpenTree);
2118                            }
2119                            "fork" => {
2120                                let _ = tx_for_key.send(TuiMessage::ForkSession);
2121                            }
2122                            _ => {}
2123                        }
2124                    } else {
2125                        last_escape_time = Some(now);
2126                    }
2127                }
2128                continue;
2129            }
2130
2131            // 2c. Ctrl+G: edit the current draft in the user's external
2132            // editor, matching upstream's VISUAL/EDITOR fallback chain.
2133            if keybinding_matches(
2134                &keybindings_for_key,
2135                &key,
2136                rpi_tui::keybindings::keys::EXTERNAL_EDITOR,
2137            ) {
2138                launch_external_editor(editor_for_key.get_expanded_text(), tx_for_key.clone());
2139                continue;
2140            }
2141
2142            // 2d. Ctrl+O: toggle all tool output panels between compact and
2143            // expanded rendering (upstream's global output toggle).
2144            if keybinding_matches(
2145                &keybindings_for_key,
2146                &key,
2147                rpi_tui::keybindings::keys::TOOLS_EXPAND,
2148            ) {
2149                let expanded = state_for_key.toggle_tool_outputs();
2150                // Persist per-session so a later `-c`/`-r` restores it.
2151                let session = ctx_for_key.session.clone();
2152                tokio::spawn(async move {
2153                    let _ = session
2154                        .set_value("display.tool_outputs_expanded", serde_json::json!(expanded))
2155                        .await;
2156                });
2157                tui_for_key.request_render(false);
2158                continue;
2159            }
2160
2161            // 2e. Ctrl+T: toggle visibility of reasoning/thinking blocks.
2162            if keybinding_matches(
2163                &keybindings_for_key,
2164                &key,
2165                rpi_tui::keybindings::keys::THINKING_TOGGLE,
2166            ) {
2167                let hide = state_for_key.toggle_thinking();
2168                // Persist per-session so a later `-c`/`-r` restores it.
2169                let session = ctx_for_key.session.clone();
2170                tokio::spawn(async move {
2171                    let _ = session
2172                        .set_value("display.hide_thinking", serde_json::json!(hide))
2173                        .await;
2174                });
2175                tui_for_key.request_render(false);
2176                continue;
2177            }
2178
2179            // 2f. Ctrl+P: cycle to the next model in the catalog after the one
2180            //     currently tracked in `current_model_id`, apply it live via
2181            //     `lane.set_model` (takes effect on the next user message — the
2182            //     in-flight run's config is already snapshotted), and update the
2183            //     footer. `set_model` is async so it runs on a spawned task.
2184            if keybinding_matches(
2185                &keybindings_for_key,
2186                &key,
2187                rpi_tui::keybindings::keys::MODEL_CYCLE_FORWARD,
2188            ) {
2189                let current = state_for_key.current_model_id();
2190                // Cycle within the `/scoped-models` set (settings.json) when
2191                // configured; otherwise the full catalog, restricted to the
2192                // current provider (the lane cannot route another provider).
2193                let scope = scoped_catalog(&ctx_for_key.model_catalog, &current);
2194                let scope = same_provider_catalog(&scope, &current);
2195                if let Some(next) = cycle_next_model(&scope, &current) {
2196                    state_for_key.set_current_model(&next);
2197                    let lane = lane_for_key.clone();
2198                    tokio::spawn(async move {
2199                        let _ = lane.set_model(next).await;
2200                    });
2201                    tui_for_key.request_render_reusing_scroll_content();
2202                }
2203                continue;
2204            }
2205
2206            // 2f-bis. Shift+Ctrl+P (Alt+P on Windows): cycle to the *previous*
2207            //     model, the mirror of the Ctrl+P hotkey above.
2208            if keybinding_matches(
2209                &keybindings_for_key,
2210                &key,
2211                rpi_tui::keybindings::keys::MODEL_CYCLE_BACKWARD,
2212            ) {
2213                let current = state_for_key.current_model_id();
2214                let scope = scoped_catalog(&ctx_for_key.model_catalog, &current);
2215                let scope = same_provider_catalog(&scope, &current);
2216                if let Some(prev) = cycle_prev_model(&scope, &current) {
2217                    state_for_key.set_current_model(&prev);
2218                    let lane = lane_for_key.clone();
2219                    tokio::spawn(async move {
2220                        let _ = lane.set_model(prev).await;
2221                    });
2222                    tui_for_key.request_render_reusing_scroll_content();
2223                }
2224                continue;
2225            }
2226
2227            // 2f. Shift+Tab / BackTab: cycle the current model's supported
2228            // thinking levels, matching upstream's thinking-level shortcut.
2229            if keybinding_matches(
2230                &keybindings_for_key,
2231                &key,
2232                rpi_tui::keybindings::keys::THINKING_CYCLE,
2233            ) {
2234                let lane = lane_for_key.clone();
2235                let catalog = model_catalog_for_key.clone();
2236                let state = state_for_key.clone();
2237                tokio::spawn(async move {
2238                    let Ok(current_model) = lane.get_model().await else {
2239                        return;
2240                    };
2241                    let levels = catalog
2242                        .iter()
2243                        .find(|model| {
2244                            model.provider == current_model.provider && model.id == current_model.id
2245                        })
2246                        .map(|model| model.supported_thinking_levels())
2247                        .unwrap_or_else(|| vec![rpi_ai::types::ThinkingLevel::Medium]);
2248                    if levels.is_empty() {
2249                        return;
2250                    }
2251                    let current = lane
2252                        .get_thinking_level()
2253                        .await
2254                        .unwrap_or(rpi_ai::types::ThinkingLevel::Medium);
2255                    let next = levels
2256                        .iter()
2257                        .position(|level| *level == current)
2258                        .map(|index| levels[(index + 1) % levels.len()])
2259                        .unwrap_or(levels[0]);
2260                    if lane.set_thinking_level(next).await.is_ok() {
2261                        state
2262                            .footer
2263                            .set_thinking_level(Some(thinking_level_name(next)));
2264                        state.tui.as_ref().map(|tui| tui.request_render(false));
2265                    }
2266                });
2267                continue;
2268            }
2269
2270            // Ctrl+V (or a configured paste-image key): if the system
2271            // clipboard holds an image, queue it for the next prompt;
2272            // otherwise paste the clipboard TEXT into the editor. Previously
2273            // a text-only clipboard fell through to the editor's Ctrl+V,
2274            // which yanks from the internal KILL RING — not the system
2275            // clipboard. On platforms without bracketed-paste `Event::Paste`
2276            // (Windows console, some remote clients) that meant Ctrl+V pasted
2277            // stale/other content instead of the user's real clipboard
2278            // ("不是系统的粘贴的内容").
2279            if keybinding_matches(
2280                &keybindings_for_key,
2281                &key,
2282                rpi_tui::keybindings::keys::PASTE_IMAGE,
2283            ) {
2284                if let Some(paths) = read_clipboard_file_paths() {
2285                    let text = paths.join("\n");
2286                    if let Some(images) = images_from_pasted_paths(&text) {
2287                        for image in images {
2288                            state_for_key.queue_image(image);
2289                        }
2290                        add_note_message(
2291                            &state_for_key.chat_container,
2292                            "Clipboard images attached to the next prompt.",
2293                        );
2294                    } else {
2295                        editor_for_key.handle_paste(&text);
2296                    }
2297                    tui_for_key.request_render(false);
2298                    continue;
2299                }
2300                match read_clipboard_image() {
2301                    Ok(Some(image)) => {
2302                        state_for_key.queue_image(image);
2303                        add_note_message(
2304                            &state_for_key.chat_container,
2305                            "Clipboard image attached to the next prompt.",
2306                        );
2307                        tui_for_key.request_render(false);
2308                        continue;
2309                    }
2310                    Ok(None) | Err(_) => {}
2311                }
2312                // Local Ctrl+V can paste clipboard text as Pi does. Under SSH,
2313                // text must arrive from the client via bracketed paste rather
2314                // than reading the remote host's unrelated clipboard.
2315                if cfg!(windows) || std::env::var_os("SSH_CONNECTION").is_none() {
2316                    if let Some(text) = read_clipboard_text() {
2317                        if !text.is_empty() {
2318                            if !attach_pasted_images(&state_for_key, &text) {
2319                                editor_for_key.handle_paste(&text);
2320                            }
2321                            refresh_autocomplete(&state_for_key, &editor_for_key);
2322                            tui_for_key.request_render_reusing_scroll_content();
2323                            continue;
2324                        }
2325                    }
2326                }
2327            }
2328
2329            // 3. Ctrl+Shift+F: open transcript search
2330            if key
2331                .modifiers
2332                .contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT)
2333                && key.code == KeyCode::Char('F')
2334            {
2335                state_for_key.search.activate();
2336                state_for_key.search_bar.set_visible(true);
2337                state_for_key.search_bar.set_query("");
2338                state_for_key.search_bar.set_match_info(0, 0);
2339                tui_for_key.request_render(false);
2340                continue;
2341            }
2342
2343            // Handle search mode input
2344            if state_for_key.search.is_active() {
2345                let search_bar = state_for_key.search_bar.clone();
2346                match key.code {
2347                    KeyCode::Esc => {
2348                        state_for_key.search.deactivate();
2349                        search_bar.set_visible(false);
2350                        tui_for_key.request_render(false);
2351                        continue;
2352                    }
2353                    KeyCode::Enter => {
2354                        if key.modifiers.contains(KeyModifiers::SHIFT) {
2355                            state_for_key.search.previous_match();
2356                        } else {
2357                            state_for_key.search.next_match();
2358                        }
2359                        // Update search bar with current match info
2360                        let match_index = state_for_key.search.get_match_index();
2361                        let match_count = state_for_key.search.get_match_count();
2362                        search_bar.set_match_info(match_index, match_count);
2363                        tui_for_key.request_render(false);
2364                        continue;
2365                    }
2366                    KeyCode::Backspace => {
2367                        state_for_key.search.backspace();
2368                        // Re-search with updated query
2369                        let lines = collect_transcript_lines(&state_for_key.chat_container);
2370                        state_for_key.search.find_matches(&lines);
2371                        // Update search bar
2372                        let query = state_for_key.search.get_query();
2373                        let match_count = state_for_key.search.get_match_count();
2374                        search_bar.set_query(&query);
2375                        search_bar.set_match_info(0, match_count);
2376                        tui_for_key.request_render(false);
2377                        continue;
2378                    }
2379                    KeyCode::Char(c) => {
2380                        state_for_key.search.append_char(c);
2381                        // Re-search with updated query
2382                        let lines = collect_transcript_lines(&state_for_key.chat_container);
2383                        state_for_key.search.find_matches(&lines);
2384                        // Update search bar
2385                        let query = state_for_key.search.get_query();
2386                        let match_count = state_for_key.search.get_match_count();
2387                        search_bar.set_query(&query);
2388                        search_bar.set_match_info(0, match_count);
2389                        tui_for_key.request_render(false);
2390                        continue;
2391                    }
2392                    _ => continue,
2393                }
2394            }
2395
2396            // 3. Ctrl+L: open the model selector. Routed through the `/model`
2397            //    command so the hotkey and the slash command share one path
2398            //    (TS binds Ctrl+L to model-select).
2399            if keybinding_matches(
2400                &keybindings_for_key,
2401                &key,
2402                rpi_tui::keybindings::keys::MODEL_SELECT,
2403            ) {
2404                if let Some(cmd) = registry_for_key.find("/model") {
2405                    cmd.execute(&ctx_for_key, "");
2406                }
2407                continue;
2408            }
2409
2410            // 4. Tab: accept the top autocomplete suggestion (if any).
2411            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Tab {
2412                if accept_top_suggestion(&state_for_key, &editor_for_key) {
2413                    tui_for_key.request_render_reusing_scroll_content();
2414                }
2415                continue;
2416            }
2417
2418            // 5. Global transcript scroll. PageUp/PageDown use the actual
2419            // viewport height with four rows of overlap (upstream behavior),
2420            // while Home/End jump to the transcript boundaries.
2421            if crate::transcript_navigation::handle_key(&tui_for_key, &keybindings_for_key, &key) {
2422                continue;
2423            }
2424
2425            // 5a-bis. ↑/↓ navigate the autocomplete list while it is open
2426            //     (typed `/` or `@`), then Tab accepts the highlighted row.
2427            if key.modifiers == KeyModifiers::NONE
2428                && (key.code == KeyCode::Up || key.code == KeyCode::Down)
2429            {
2430                let direction = if key.code == KeyCode::Up { -1 } else { 1 };
2431                if navigate_autocomplete(&state_for_key, &editor_for_key, direction) {
2432                    tui_for_key.request_render_reusing_scroll_content();
2433                    continue;
2434                }
2435            }
2436
2437            // 5b. ↑/↓ browse submitted-message history when the editor is
2438            //     EMPTY (a fresh prompt) — mirrors TS historyPrevious/Next
2439            //     without the surprise of replacing typed text. When the
2440            //     editor holds content, ↑/↓ fall through to cursor movement
2441            //     (typing "hello", pressing ↑ at the start, must never swap
2442            //     the draft for a history entry — reported as "text
2443            //     disappeared"). Once browsing, ↓ walks back and restores the
2444            //     draft.
2445            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Up {
2446                let browsing = *state_for_key.history_index.lock().unwrap() != -1;
2447                if editor_for_key.get_text().is_empty() || browsing {
2448                    navigate_history(&state_for_key, &editor_for_key, -1);
2449                    tui_for_key.request_render_reusing_scroll_content();
2450                    continue;
2451                }
2452            }
2453            if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Down {
2454                let browsing = *state_for_key.history_index.lock().unwrap() != -1;
2455                if editor_for_key.get_text().is_empty() || browsing {
2456                    navigate_history(&state_for_key, &editor_for_key, 1);
2457                    tui_for_key.request_render_reusing_scroll_content();
2458                    continue;
2459                }
2460            }
2461
2462            // `app.message.dequeue` (Alt+Q on Windows, Alt+Up elsewhere):
2463            // restore every queued steering/follow-up message into the editor
2464            // so it can be edited before resending. Mirrors upstream's
2465            // `handleDequeue`; the pending-messages display shows the hint.
2466            if keybinding_matches(
2467                &keybindings_for_key,
2468                &key,
2469                rpi_tui::keybindings::keys::DEQUEUE,
2470            ) {
2471                // Handled here, on the key worker — NOT via the mailbox. The
2472                // async main loop parks inside `run_prompt_streaming(..).await`
2473                // for the whole run, and a queue only exists *while* a run is
2474                // in flight, so a `TuiMessage::Dequeue` sat unread until the
2475                // run finished (after the lane had already consumed the queue).
2476                // Alt+Q therefore looked like a no-op while it was most needed.
2477                // Spawn the drain so it lands while the user is still looking at
2478                // the queue, exactly like the Alt+Enter `follow_up` path above.
2479                // Routed through `handle_dequeue` (not the raw restore) so the
2480                // `Restored N queued message(s)` status note fires, mirroring
2481                // upstream's `handleDequeue`.
2482                tokio::spawn(handle_dequeue(
2483                    lane_for_key.clone(),
2484                    editor_for_key.clone(),
2485                    state_for_key.clone(),
2486                    tui_for_key.clone(),
2487                ));
2488                continue;
2489            }
2490
2491            // `app.message.followUp` (Alt+Enter; Ctrl+Q and Alt+Enter on
2492            // Windows) queues a follow-up while a run is active. It is handled
2493            // here because Editor treats only a bare Enter as submit; when idle
2494            // the same key keeps the normal prompt behavior.
2495            if keybinding_matches(
2496                &keybindings_for_key,
2497                &key,
2498                rpi_tui::keybindings::keys::MESSAGE_FOLLOW_UP,
2499            ) {
2500                let prompt = editor_for_key.get_expanded_text().trim().to_string();
2501                if prompt.is_empty() && state_for_key.pending_images.lock().unwrap().is_empty() {
2502                    continue;
2503                }
2504                editor_for_key.clear();
2505                let status = *state_for_key.status.lock().unwrap();
2506                if status == RunStatus::Idle {
2507                    if state_for_key.try_start_working() {
2508                        // Direct send: the harness emits no user `message_start`
2509                        // for it, so render the bubble here (see the submit
2510                        // handler in `interactive_tui`).
2511                        add_user_message(&state_for_key.chat_container, &prompt);
2512                        push_history(&state_for_key, &prompt);
2513                        let _ = tx_for_key.send(TuiMessage::UserInput(
2514                            prompt,
2515                            state_for_key.take_pending_images(),
2516                        ));
2517                    }
2518                } else {
2519                    // Follow-ups are echoed by the loop's
2520                    // `AgentEvent::MessageStart` once they are consumed; while
2521                    // they wait, the pending-messages display shows them.
2522                    let images = state_for_key.take_pending_images();
2523                    let message = user_message_with_images(&prompt, images.clone());
2524                    let lane = lane_for_key.clone();
2525                    let chat = state_for_key.chat_container.clone();
2526                    let tui = tui_for_key.clone();
2527                    let state = state_for_key.clone();
2528                    tokio::spawn(async move {
2529                        if let Err(error) = lane.follow_up(message).await {
2530                            state.restore_pending_images(images);
2531                            add_error_message(&chat, &format!("Could not queue message: {error}"));
2532                            tui.request_render(false);
2533                            return;
2534                        }
2535                        refresh_pending_messages(&state, &lane).await;
2536                        tui.request_render(false);
2537                    });
2538                }
2539                tui_for_key.request_render(false);
2540                continue;
2541            }
2542
2543            // Windows' console backend has no Event::Paste. Assemble text keys
2544            // into one payload; only absorb Enter when another key is queued
2545            // or the clipboard confirms a trailing pasted newline. A standalone
2546            // Enter must reach Editor::handle_key so it submits normally.
2547            if cfg!(windows) {
2548                let text_key = match key.code {
2549                    KeyCode::Char(c)
2550                        if !key
2551                            .modifiers
2552                            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
2553                    {
2554                        Some(c)
2555                    }
2556                    _ => None,
2557                };
2558                if let Some(ch) = text_key {
2559                    if ch == '\r' || ch == '\n' {
2560                        // Treat these the same as KeyCode::Enter below.
2561                    } else {
2562                        windows_paste_run.feed(ch, std::time::Instant::now());
2563                        continue;
2564                    }
2565                }
2566                if key.modifiers.is_empty()
2567                    && matches!(
2568                        key.code,
2569                        KeyCode::Enter | KeyCode::Char('\n') | KeyCode::Char('\r')
2570                    )
2571                {
2572                    let (more_queued, stashed) = probe_paste_input(pending_event.take(), || {
2573                        if crossterm::event::poll(PASTE_PROBE).unwrap_or(false) {
2574                            crossterm::event::read().ok()
2575                        } else {
2576                            None
2577                        }
2578                    });
2579                    pending_event = stashed;
2580                    let clipboard = if !more_queued && windows_paste_run.burst {
2581                        read_clipboard_text()
2582                    } else {
2583                        None
2584                    };
2585                    if windows_enter_in_paste(&windows_paste_run, more_queued, clipboard.as_deref())
2586                    {
2587                        windows_paste_run.feed('\n', std::time::Instant::now());
2588                        crate::key_trace::note("windows paste run -> newline");
2589                        continue;
2590                    }
2591                    crate::key_trace::note("windows paste run -> flush + submit");
2592                    windows_paste_run.flush(&editor_for_key);
2593                } else {
2594                    windows_paste_run.flush(&editor_for_key);
2595                }
2596            }
2597
2598            // 6. Otherwise forward to the editor + refresh autocomplete. The
2599            //    editor maps unmodified Enter and the encodings a remote client
2600            //    may send for it (`Char('\n')`/`Char('\r')`, and the raw LF
2601            //    crossterm reports as `Ctrl+J`) to submit, so a remote Enter
2602            //    sends instead of inserting a newline.
2603            editor_for_key.handle_key(key);
2604            refresh_autocomplete(&state_for_key, &editor_for_key);
2605            tui_for_key.request_render_reusing_scroll_content();
2606        }
2607    });
2608
2609    // ---- Session lifecycle (P1): SessionStart ----
2610    // The TUI + key worker are up and the session is ready to accept input.
2611    // Notify subscribed extensions now so they can initialize session-scoped
2612    // state. A veto here is **advisory** (the session is already up) — warn and
2613    // continue. No-op when no extension subscribes.
2614    if let Some(reason) = crate::session::dispatch_session_event_async(
2615        reload_context,
2616        rpi_plugin_sdk::EventTag::SessionStart,
2617    )
2618    .await
2619    {
2620        tracing::warn!("[rpi] extension vetoed SessionStart (advisory): {reason}");
2621    }
2622
2623    // ---- Initial prompts (run before reading from the channel) ----
2624    let mut prompts: Vec<String> = Vec::new();
2625    if let Some(init) = initial {
2626        prompts.push(init);
2627    }
2628    for m in extra_messages {
2629        prompts.push(m.clone());
2630    }
2631    // ---- Continue a run that recovery repaired, the way upstream does ----
2632    // This happens before any user input, and only when nothing was passed on the
2633    // command line: an explicit `-p` means the user has already said what they
2634    // want next. Driven here rather than inside the harness so the run's output
2635    // goes through the same streaming/render path as any other run, and so
2636    // startup is never blocked by a run the user cannot see.
2637    if prompts.is_empty() && lane.has_pending_resume().await {
2638        run_prompt_streaming(
2639            &lane,
2640            "",
2641            true,
2642            &tui,
2643            &state,
2644            drain_handle.is_some(),
2645            Vec::new(),
2646        )
2647        .await;
2648    }
2649
2650    let mut images = initial_images;
2651    for prompt in prompts {
2652        if !*running.lock().unwrap() {
2653            break;
2654        }
2655        // The harness emits no user `message_start` for a directly-sent prompt
2656        // (it drives the loop with an empty prompts vec), so the initial
2657        // `-p` / `--prompt` bubbles are rendered here.
2658        add_user_message(&chat_container, &prompt);
2659        add_image_previews(&chat_container, &images, show_images);
2660        tui.request_render(false);
2661        run_prompt_streaming(
2662            &lane,
2663            &prompt,
2664            false,
2665            &tui,
2666            &state,
2667            drain_handle.is_some(),
2668            std::mem::take(&mut images),
2669        )
2670        .await;
2671    }
2672
2673    // ---- Main loop: process submitted input + lifecycle messages ----
2674    loop {
2675        if !*running.lock().unwrap() {
2676            break;
2677        }
2678        match rx.recv().await {
2679            Some(TuiMessage::UserInput(prompt, prompt_images)) => {
2680                // Clear the editor so the next prompt starts fresh (the submit
2681                // handler runs on the blocking key thread and can't mutate the
2682                // editor state safely there; clearing here, on the async loop,
2683                // keeps it on one thread). Marked programmatic: this is the host
2684                // tidying up after a submit, not the user typing — reporting it
2685                // as a user edit made a hands-free voice session switch itself
2686                // off the moment it was started.
2687                state.clear_editor_programmatically();
2688                add_image_previews(&chat_container, &prompt_images, state.images_visible());
2689                if !prompt_images.is_empty() {
2690                    add_note_message(
2691                        &chat_container,
2692                        &format!("Attached {} image(s) to this prompt.", prompt_images.len()),
2693                    );
2694                }
2695                run_prompt_streaming(
2696                    &lane,
2697                    &prompt,
2698                    false,
2699                    &tui,
2700                    &state,
2701                    drain_handle.is_some(),
2702                    prompt_images,
2703                )
2704                .await;
2705            }
2706            Some(TuiMessage::ExternalEditorResult(result)) => {
2707                match result {
2708                    Ok(text) => {
2709                        let cursor = text.chars().count();
2710                        editor.set_text(&text);
2711                        editor.set_cursor(0, cursor);
2712                        add_note_message(&chat_container, "Draft updated from external editor.");
2713                    }
2714                    Err(error) => add_error_message(&chat_container, &error),
2715                }
2716                tui.request_render(false);
2717            }
2718            Some(TuiMessage::UserBashFinished(report)) => {
2719                // Free the run slot first: the guard and the Esc router both
2720                // read it, so a finished command must never block the next one.
2721                state.finish_user_bash();
2722                let message = rpi_harness::messages::bash_execution_message(
2723                    report.command,
2724                    report.output,
2725                    report.exit_code,
2726                    report.cancelled,
2727                    report.truncated,
2728                    report.full_output_path,
2729                    Some(report.exclude_from_context),
2730                    now_ms(),
2731                );
2732                // While a run is in flight the message is deferred so it is not
2733                // spliced into the middle of a turn's tool sequence; it is
2734                // flushed at `AgentEnd` (upstream `_pendingBashMessages`).
2735                if *state.status.lock().unwrap() == RunStatus::Idle {
2736                    if let Err(error) = lane.append_message(message).await {
2737                        add_error_message(
2738                            &chat_container,
2739                            &format!("Could not record bash result: {error}"),
2740                        );
2741                        tui.request_render(false);
2742                    }
2743                } else {
2744                    state.pending_bash_messages.lock().unwrap().push(message);
2745                }
2746            }
2747            Some(TuiMessage::OpenTree) => {
2748                if *state.status.lock().unwrap() != RunStatus::Idle {
2749                    add_note_message(
2750                        &chat_container,
2751                        "Wait for the current run to finish before opening the tree.",
2752                    );
2753                    tui.request_render(false);
2754                } else {
2755                    open_tree_selector(
2756                        &harness,
2757                        &state,
2758                        &editor_container,
2759                        &editor,
2760                        &tui,
2761                        &chat_container,
2762                        &tx,
2763                    )
2764                    .await;
2765                }
2766            }
2767            Some(TuiMessage::NavigateTree(entry_id)) => {
2768                match lane.navigate_tree(Some(&entry_id), false, None, None).await {
2769                    Ok(result) => match result.outcome {
2770                        rpi_harness::agent_harness::NavigationOutcome::Completed { .. } => {
2771                            chat_container.clear();
2772                            add_welcome_message(&chat_container);
2773                            render_session_history(
2774                                &harness,
2775                                &chat_container,
2776                                state.markdown_transformer(),
2777                                Some(state.extension_session.clone()),
2778                                state.images_visible(),
2779                            )
2780                            .await;
2781                            add_note_message(
2782                                &chat_container,
2783                                "Moved to the selected session entry.",
2784                            );
2785                        }
2786                        rpi_harness::agent_harness::NavigationOutcome::Failed { error, .. } => {
2787                            add_error_message(&chat_container, &error.message);
2788                        }
2789                        _ => add_note_message(
2790                            &chat_container,
2791                            "The selected entry could not be opened.",
2792                        ),
2793                    },
2794                    Err(error) => add_error_message(
2795                        &chat_container,
2796                        &format!("Could not navigate session tree: {error}"),
2797                    ),
2798                }
2799                tui.request_render(false);
2800            }
2801            Some(TuiMessage::ClearChat) => {
2802                chat_container.clear();
2803                add_welcome_message(&chat_container);
2804                tui.request_render(false);
2805            }
2806            Some(TuiMessage::Compact) => {
2807                run_compact(&lane, &tui, &state).await;
2808            }
2809            Some(TuiMessage::Copy) => {
2810                copy_last_assistant(&state, &chat_container);
2811                tui.request_render(false);
2812            }
2813            Some(TuiMessage::Exit) => {
2814                *running.lock().unwrap() = false;
2815                break;
2816            }
2817            Some(TuiMessage::SwitchSession(id)) => {
2818                switch_to_session(
2819                    &harness,
2820                    &lane,
2821                    &id,
2822                    &cwd,
2823                    &chat_container,
2824                    &state,
2825                    &reload_context.tool_context,
2826                )
2827                .await;
2828                tui.request_render(false);
2829            }
2830            Some(TuiMessage::ImportSession(path)) => {
2831                import_session(
2832                    &harness,
2833                    &lane,
2834                    &path,
2835                    &cwd,
2836                    &chat_container,
2837                    &state,
2838                    &reload_context.tool_context,
2839                )
2840                .await;
2841                tui.request_render(false);
2842            }
2843            Some(TuiMessage::ShareSession) => {
2844                share_session(&harness, &chat_container).await;
2845                tui.request_render(false);
2846            }
2847            Some(TuiMessage::SetSessionName(name)) => {
2848                let outcome = harness.session().set_name(Some(&name)).await;
2849                match outcome {
2850                    Ok(_) => add_note_message(
2851                        &chat_container,
2852                        &format!("Session renamed to \"{name}\"."),
2853                    ),
2854                    Err(e) => add_error_message(
2855                        &chat_container,
2856                        &format!("Could not rename session: {e}"),
2857                    ),
2858                }
2859                tui.request_render(false);
2860            }
2861            Some(TuiMessage::ExportSession) => {
2862                let file_name = agent_session
2863                    .default_export_file_name(crate::export::ExportFormat::Markdown)
2864                    .await;
2865                let path = cwd.join(&file_name);
2866                match agent_session.export_to_markdown(&path).await {
2867                    Ok(_) => add_note_message(
2868                        &chat_container,
2869                        &format!("Exported session to {}", path.display()),
2870                    ),
2871                    Err(e) => {
2872                        add_error_message(&chat_container, &format!("Could not write export: {e}"))
2873                    }
2874                }
2875                tui.request_render(false);
2876            }
2877            Some(TuiMessage::ExportSessionWithFormat(format)) => {
2878                let file_name = agent_session.default_export_file_name(format.clone()).await;
2879                let path = cwd.join(&file_name);
2880                match agent_session.export(format, &path).await {
2881                    Ok(_) => add_note_message(
2882                        &chat_container,
2883                        &format!("Exported session to {}", path.display()),
2884                    ),
2885                    Err(e) => {
2886                        add_error_message(&chat_container, &format!("Could not write export: {e}"))
2887                    }
2888                }
2889                tui.request_render(false);
2890            }
2891            Some(TuiMessage::ShowUsage) => {
2892                let stats = agent_session.usage_stats().await.ok();
2893                let total = agent_session.total_usage().await.ok();
2894                let snapshot = agent_session.snapshot().await.ok();
2895                match stats {
2896                    Some(stats) => {
2897                        let mut lines = vec![
2898                            "## Usage".to_string(),
2899                            String::new(),
2900                            format!("- messages: {}", stats.message_count),
2901                            format!("- total tokens: {}", stats.total_tokens),
2902                            format!("- cached tokens: {}", stats.cached_tokens),
2903                            format!("- uncached tokens: {}", stats.uncached_tokens),
2904                            format!("- cost: ${:.4}", stats.cost_total),
2905                        ];
2906                        match stats.cache_hit_ratio() {
2907                            Some(ratio) => {
2908                                lines.push(format!("- cache hit ratio: {:.1}%", ratio * 100.0))
2909                            }
2910                            None => lines.push("- cache hit ratio: n/a (no input yet)".to_string()),
2911                        }
2912                        if let Some(total) = total {
2913                            lines.push(String::new());
2914                            lines.push(format!(
2915                                "- last cumulative input/output: {} / {}",
2916                                total.input, total.output
2917                            ));
2918                        }
2919                        if let Some(snapshot) = snapshot {
2920                            lines.push(String::new());
2921                            lines.push(format!("- lane: `{}`", snapshot.lane));
2922                            lines.push(format!(
2923                                "- leaf: `{}`",
2924                                snapshot.leaf_id.clone().unwrap_or_else(|| "(empty)".into())
2925                            ));
2926                            if let Some(active) = &snapshot.active {
2927                                lines.push(format!(
2928                                    "- active operation: {} (`{}`)",
2929                                    active.kind.as_str(),
2930                                    active.run_id
2931                                ));
2932                            }
2933                        }
2934                        add_note_message(&chat_container, &lines.join("\n"));
2935                    }
2936                    None => {
2937                        add_error_message(&chat_container, "Could not read session usage stats.")
2938                    }
2939                }
2940                tui.request_render(false);
2941            }
2942            Some(TuiMessage::ForkSession) => {
2943                fork_session(
2944                    &harness,
2945                    &cwd,
2946                    &chat_container,
2947                    &state,
2948                    &reload_context.tool_context,
2949                )
2950                .await;
2951                tui.request_render(false);
2952            }
2953            Some(TuiMessage::ReloadExtensions) => {
2954                // B5d: drive the shared reload routine on the async runtime,
2955                // then surface the outcome. `reload_context` was passed into
2956                // `interactive_tui` and is the same `Arc<ReloadContext>` the
2957                // `ReloadCommand` + the plugin mailbox both route through —
2958                // clone the `Arc` out so the borrow of `harness` (the main
2959                // loop's `&AgentHarness`) lives across the await.
2960                let reload_ctx = ctx.reload_context.clone();
2961                add_note_message(&chat_container, "Reloading extensions + resources…");
2962                tui.request_render(false);
2963                let outcome =
2964                    crate::session::reload_extension_resources(&harness, &reload_ctx).await;
2965                // B5e: the reload swapped a fresh `ExtensionSession` into the
2966                // context's cell. Rebuild the markdown transformer from that
2967                // fresh snapshot and install it on the in-flight streaming
2968                // component (so a reloaded plugin's transformer takes effect on
2969                // the visible message immediately) + future components (they
2970                // read `state.markdown_transformer()` at construction). The old
2971                // closure no-ops once its snapshot's `active` flag flips false
2972                // (reload already did that before the swap).
2973                let fresh_transformer = build_markdown_transformer(
2974                    reload_ctx.extension_session.lock().unwrap().snapshot_arc(),
2975                );
2976                state.set_markdown_transformer_with_reinstall(fresh_transformer);
2977                if outcome.had_errors {
2978                    // Hard failure: the summary itself carries the error detail
2979                    // (e.g. "Settings reload failed: …"), so render it as an
2980                    // error without an extra stderr pointer.
2981                    add_error_message(&chat_container, &outcome.summary);
2982                } else if outcome.had_warnings {
2983                    // Reload succeeded but produced soft diagnostics (skill
2984                    // shadowing, name validation, …). The details are printed
2985                    // to stderr; keep this as an informational note so a
2986                    // successful reload isn't shown as a red ✗ error.
2987                    add_note_message(
2988                        &chat_container,
2989                        &format!(
2990                            "{} (with warnings — see stderr for details).",
2991                            outcome.summary
2992                        ),
2993                    );
2994                } else {
2995                    add_note_message(&chat_container, &outcome.summary);
2996                }
2997                tui.request_render(false);
2998            }
2999            None => break,
3000        }
3001    }
3002
3003    // ---- Shutdown ----
3004    ask_user_bridge.shutdown();
3005    *running.lock().unwrap() = false;
3006    for handle in update_check_handles {
3007        handle.abort();
3008        let _ = handle.await;
3009    }
3010    // The input worker checks `running` at least every 50ms. Join it before
3011    // restoring cooked mode so no late event read races terminal cleanup.
3012    let _ = key_handle.await;
3013    tick_handle.abort();
3014    if let Some(handle) = drain_handle {
3015        handle.abort();
3016    }
3017    // Drop the reload bridge: clearing the mailbox closes the signal channel,
3018    // the drain task's `recv` returns `None`, and the task exits. (Aborting is
3019    // redundant — the recv terminates — but cheap + makes shutdown explicit.)
3020    reload_context.mailbox.clear();
3021    reload_bridge_handle.abort();
3022    tui.stop(Default::default());
3023
3024    // upstream prints how to resume the session after an interactive exit so
3025    // a terminal that scrolled away can be recovered. Mirrors
3026    // `formatResumeCommand` (id + `--session-dir` only when non-default).
3027    let session_id = harness.session().storage().metadata().id;
3028    if let Some(command) = format_resume_command(&session_id, &cwd, args.session_dir.as_deref()) {
3029        println!("\x1b[2mTo resume this session:\x1b[0m {command}");
3030    }
3031    println!("\nGoodbye!");
3032    let _ = args;
3033
3034    0
3035}
3036
3037// ===========================================================================
3038// TUI support + entry detection
3039// ===========================================================================
3040
3041/// Check if the terminal supports TUI mode.
3042pub fn is_tui_supported() -> bool {
3043    std::io::stdout().is_terminal()
3044}
3045
3046// Keep the `Color` import used (theme accent rendering in autocomplete).
3047#[allow(unused_imports)]
3048use rpi_tui::Color as _Color;