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