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