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