Skip to main content

rpi_cli/
interactive_tui.rs

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