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