Skip to main content

rpi_cli/
interactive_tui.rs

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