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