Skip to main content

rpi_cli/
interactive_tui.rs

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