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