Skip to main content

rpi_cli/
interactive_tui.rs

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