Skip to main content

rpi_cli/
interactive_tui.rs

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