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