Skip to main content

rpi_cli/
interactive_tui.rs

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