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