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 ®istry.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, ®istry_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 let mut last_search_document = std::sync::Weak::new();
1966 // upstream's `handleCtrlC` "press twice to exit" window: the instant of
1967 // the last lone Ctrl+C. Shares the 500ms with Esc's double-escape.
1968 let mut last_sigint_time: Option<std::time::Instant> = None;
1969 // One event peeked at by the paste-burst probe (which must discard a
1970 // key's Release but never lose a meaningful event it read). Restored
1971 // at the top of the next loop iteration.
1972 let mut pending_event: Option<Event> = None;
1973 let mut windows_paste_run = WindowsPasteRun::default();
1974 if crate::key_trace::enabled() {
1975 crate::key_trace::note(&format!(
1976 "--- rpi TUI key trace start pid={} TERM={} raw_mode={} ---",
1977 std::process::id(),
1978 std::env::var("TERM").unwrap_or_else(|_| "(unset)".to_string()),
1979 crossterm::terminal::is_raw_mode_enabled().unwrap_or(false),
1980 ));
1981 }
1982 loop {
1983 if !*running_key.lock().unwrap() {
1984 break;
1985 }
1986 // Console releases, mouse motion and resize must not postpone
1987 // the last text character's idle deadline indefinitely.
1988 if cfg!(windows)
1989 && windows_paste_run
1990 .remaining_delay(std::time::Instant::now())
1991 .is_some_and(|left| left.is_zero())
1992 {
1993 windows_paste_run.flush_with_clipboard(
1994 &editor_for_key,
1995 std::time::Instant::now(),
1996 read_clipboard_text,
1997 );
1998 refresh_autocomplete(&state_for_key, &editor_for_key);
1999 tui_for_key.request_render_reusing_scroll_content();
2000 }
2001 if !state_for_key.selector_open() && !state_for_key.extension_dialog_open() {
2002 if let Some(request) = ask_user_for_key.take_pending_for_tui() {
2003 if cfg!(windows) {
2004 windows_paste_run.flush_with_clipboard(
2005 &editor_for_key,
2006 std::time::Instant::now(),
2007 read_clipboard_text,
2008 );
2009 windows_paste_run.end_paste_session();
2010 }
2011 open_ask_user_dialog(&ctx_for_key, ask_user_for_key.clone(), request);
2012 }
2013 }
2014 let ev = if let Some(ev) = pending_event.take() {
2015 ev
2016 } else {
2017 // `event::read()` blocks indefinitely. Poll first so shutdown can
2018 // stop and join this worker even when no further key arrives. A
2019 // paste run waits only for the remainder of its idle window,
2020 // not another full 120ms after each unrelated event.
2021 let idle = if cfg!(windows) {
2022 windows_paste_run.remaining_delay(std::time::Instant::now())
2023 } else {
2024 None
2025 }
2026 .unwrap_or(std::time::Duration::from_millis(50));
2027 match terminal_for_key.read(idle) {
2028 Ok(Some(TerminalInput::Event(event))) => {
2029 if !matches!(
2030 event,
2031 Event::Resize(..) | Event::FocusGained | Event::FocusLost
2032 ) {
2033 last_input = std::time::Instant::now();
2034 }
2035 event
2036 }
2037 #[cfg(unix)]
2038 Ok(Some(TerminalInput::Editor(result))) => {
2039 editing = false;
2040 last_input = std::time::Instant::now();
2041 tui_for_key.resume();
2042 let _ = tx_for_key.send(TuiMessage::ExternalEditorResult(result));
2043 continue;
2044 }
2045 Ok(None) => {
2046 if cfg!(windows)
2047 && windows_paste_run
2048 .remaining_delay(std::time::Instant::now())
2049 .is_some_and(|left| left.is_zero())
2050 {
2051 windows_paste_run.flush_with_clipboard(
2052 &editor_for_key,
2053 std::time::Instant::now(),
2054 read_clipboard_text,
2055 );
2056 refresh_autocomplete(&state_for_key, &editor_for_key);
2057 tui_for_key.request_render_reusing_scroll_content();
2058 }
2059 if editing
2060 || state_for_key.user_bash_running()
2061 || *state_for_key.status.lock().unwrap() != RunStatus::Idle
2062 {
2063 last_input = std::time::Instant::now();
2064 } else if idle_timeout.is_some_and(|limit| last_input.elapsed() >= limit) {
2065 idle_expired_for_key.store(true, std::sync::atomic::Ordering::Release);
2066 let _ = tx_for_key.send(TuiMessage::Exit);
2067 break;
2068 }
2069 continue;
2070 }
2071 Err(_) => {
2072 state_for_key.cancel_js_preparation();
2073 let _ = tx_for_key.send(TuiMessage::Exit);
2074 break;
2075 }
2076 }
2077 };
2078 // `Event::Resize` is delivered as its own event (not a Key). With
2079 // `start_readerless` there is no competing terminal-reader thread to
2080 // handle it: force one full-screen repaint. The renderer re-reads the
2081 // window size itself; the event's own columns/rows are not used (on
2082 // Windows they carry the console buffer size, not the window).
2083 if let Event::Resize(..) = ev {
2084 tui_for_key.note_resize();
2085 continue;
2086 }
2087 // Mouse wheel scrolls the transcript (pi supports wheel
2088 // scrolling). Previously every non-Key event was dropped, so a
2089 // wheel had zero effect
2090 if let Event::Mouse(m) = ev {
2091 if cfg!(windows) && m.kind != crossterm::event::MouseEventKind::Moved {
2092 if windows_paste_run.is_buffering() {
2093 windows_paste_run.flush_with_clipboard(
2094 &editor_for_key,
2095 std::time::Instant::now(),
2096 read_clipboard_text,
2097 );
2098 refresh_autocomplete(&state_for_key, &editor_for_key);
2099 tui_for_key.request_render_reusing_scroll_content();
2100 }
2101 windows_paste_run.end_paste_session();
2102 }
2103 if side_questions::input_allowed(&state_for_key)
2104 && side_for_key
2105 .lock()
2106 .unwrap()
2107 .mouse(&m, &tui_for_key, &scroll_for_key)
2108 {
2109 continue;
2110 }
2111 if tui_for_key.handle_scroll_to_end_indicator_mouse_event(&m) {
2112 tui_for_key.clear_selection();
2113 continue;
2114 }
2115 // A click on a thinking label/body row toggles THAT message's
2116 // thinking before the press can anchor a text selection. The
2117 // regions are frame-scoped: only rows the last painted frame
2118 // actually showed resolve, so a stale rectangle can never fire
2119 // after a scroll.
2120 if let Some(message_id) = tui_for_key.thinking_region_hit(&m) {
2121 state_for_key
2122 .transcript_view()
2123 .toggle_message_thinking(&message_id);
2124 tui_for_key.clear_selection();
2125 tui_for_key.request_render_reusing_scroll_content();
2126 continue;
2127 }
2128 use crossterm::event::MouseEventKind;
2129 match m.kind {
2130 MouseEventKind::ScrollUp => {
2131 let delta = -MOUSE_WHEEL_SCROLL_LINES;
2132 if scroll_for_key.scroll_by(delta) != delta {
2133 tui_for_key.request_render_reusing_scroll_content();
2134 }
2135 }
2136 MouseEventKind::ScrollDown => {
2137 let delta = MOUSE_WHEEL_SCROLL_LINES;
2138 if scroll_for_key.scroll_by(delta) != delta {
2139 tui_for_key.request_render_reusing_scroll_content();
2140 }
2141 }
2142 MouseEventKind::Down(crossterm::event::MouseButton::Right) if cfg!(windows) => {
2143 windows_paste_run.flush_with_clipboard(
2144 &editor_for_key,
2145 std::time::Instant::now(),
2146 read_clipboard_text,
2147 );
2148 windows_paste_run.end_paste_session();
2149 // upstream treats Windows right-click as a clipboard
2150 // paste, rather than letting the console deliver the
2151 // clipboard contents as individual key events. This is
2152 // what preserves the complete payload for
2153 // Editor::handle_paste and large-paste folding.
2154 if let Some(text) = read_clipboard_text() {
2155 if !text.is_empty() {
2156 editor_for_key.handle_paste(&text);
2157 refresh_autocomplete(&state_for_key, &editor_for_key);
2158 tui_for_key.request_render_reusing_scroll_content();
2159 }
2160 }
2161 }
2162 MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
2163 // Begin fullscreen text selection (anchor + highlight).
2164 // The TUI owns the anchor/focus state in content
2165 // coordinates; a plain click later collapses it and
2166 // never touches the clipboard.
2167 tui_for_key.handle_selection_mouse_event(&m);
2168 }
2169 MouseEventKind::Drag(crossterm::event::MouseButton::Left) => {
2170 // Extend the selection; the re-render paints the
2171 // reverse-video highlight as the pointer moves.
2172 tui_for_key.handle_selection_mouse_event(&m);
2173 }
2174 MouseEventKind::Up(crossterm::event::MouseButton::Left) => {
2175 // Finish the selection and auto-copy when enabled.
2176 tui_for_key.handle_selection_mouse_event(&m);
2177 if tui_for_key.selection_dragged() {
2178 let auto_copy = crate::settings::load_settings()
2179 .ok()
2180 .and_then(|s| s.fullscreen_copy_on_select)
2181 .unwrap_or(true);
2182 if auto_copy
2183 && copy_mouse_selection_with(&tui_for_key, copy_to_clipboard)
2184 == Some(false)
2185 {
2186 add_note_message(
2187 &state_for_key.notice_container(),
2188 "Clipboard unavailable. Selection kept; press Ctrl+X to retry.",
2189 );
2190 tui_for_key.request_render(false);
2191 }
2192 }
2193 }
2194 _ => {}
2195 }
2196 continue;
2197 }
2198 let Event::Key(key) = ev else {
2199 if let Event::Paste(text) = ev {
2200 if cfg!(windows) {
2201 windows_paste_run.flush_with_clipboard(
2202 &editor_for_key,
2203 std::time::Instant::now(),
2204 read_clipboard_text,
2205 );
2206 windows_paste_run.end_paste_session();
2207 }
2208 if side_questions::input_allowed(&state_for_key)
2209 && side_for_key.lock().unwrap().paste(&text, &tui_for_key)
2210 {
2211 continue;
2212 }
2213 crate::key_trace::note(&format!(
2214 "paste event ({} bytes, bracketed paste supported)",
2215 text.len()
2216 ));
2217 // A provider-form text step owns the input slot: paste into
2218 // its single-line input instead of the chat editor.
2219 if state_for_key.provider_form.lock().unwrap().is_some() {
2220 let active = state_for_key.active_provider_input.lock().unwrap().clone();
2221 if let Some(input) = active {
2222 input.handle_paste(&text);
2223 tui_for_key.request_render_reusing_scroll_content();
2224 continue;
2225 }
2226 }
2227 if let Some(input) = state_for_key.active_provider_input.lock().unwrap().clone()
2228 {
2229 input.handle_paste(&text);
2230 tui_for_key.request_render_reusing_scroll_content();
2231 continue;
2232 }
2233 if state_for_key
2234 .provider_auth_flow_id
2235 .load(std::sync::atomic::Ordering::Acquire)
2236 != 0
2237 {
2238 tui_for_key.request_render_reusing_scroll_content();
2239 continue;
2240 }
2241 if let Some(images) = images_from_pasted_paths(&text) {
2242 for image in images {
2243 state_for_key.queue_image(image);
2244 }
2245 add_note_message(
2246 &state_for_key.notice_container(),
2247 "Dropped images attached to the next prompt.",
2248 );
2249 tui_for_key.request_render(false);
2250 continue;
2251 }
2252 editor_for_key.handle_paste(&text);
2253 refresh_autocomplete(&state_for_key, &editor_for_key);
2254 tui_for_key.request_render_reusing_scroll_content();
2255 }
2256 continue;
2257 };
2258 let key = rpi_tui::terminal::normalize_key_event_with_protocol(
2259 key,
2260 tui_for_key.terminal().info().supports_kitty_keyboard,
2261 );
2262 if cfg!(windows) && windows_paste_key_barrier(&key) {
2263 if windows_paste_run.is_buffering() {
2264 windows_paste_run.flush_with_clipboard(
2265 &editor_for_key,
2266 std::time::Instant::now(),
2267 read_clipboard_text,
2268 );
2269 refresh_autocomplete(&state_for_key, &editor_for_key);
2270 tui_for_key.request_render_reusing_scroll_content();
2271 }
2272 windows_paste_run.end_paste_session();
2273 }
2274 // Diagnostic trace (off unless RPI_DEBUG_KEYS is set): records what
2275 // actually arrived before any routing decision, so a client that
2276 // sends LF for Enter is visible as `Char('j') mods=CONTROL`.
2277 crate::key_trace::key(&key, "");
2278 // Side input is independent of main-run abort/preparation and plugin
2279 // shortcuts. Modal/approval dialogs still own the input slot first.
2280 if side_questions::input_allowed(&state_for_key)
2281 && side_for_key.lock().unwrap().focused()
2282 {
2283 if !should_dispatch_key(key.kind) {
2284 continue;
2285 }
2286 if keybinding_matches(&keybindings_for_key, &key, rpi_tui::keybindings::keys::EXIT)
2287 && side_for_key.lock().unwrap().empty_draft()
2288 {
2289 if *state_for_key.status.lock().unwrap() == RunStatus::Idle {
2290 let _ = tx_for_key.send(TuiMessage::Exit);
2291 } else {
2292 terminal_for_key.exit_active(&tui_for_key, &tx_for_key);
2293 }
2294 continue;
2295 }
2296 if side_for_key.lock().unwrap().key(key, &tui_for_key) {
2297 continue;
2298 }
2299 }
2300 // A key press during a voice-draft auto-send countdown cancels the
2301 // countdown — the user wants to edit, not send. The key still falls
2302 // through to the editor, so it doubles as their first correction.
2303 if key.kind != KeyEventKind::Release && state_for_key.cancel_auto_send_on_key() {
2304 tui_for_key.request_render(false);
2305 }
2306 // Extension shortcuts see Press *and* Release (this is what lets a
2307 // push-to-talk extension time a hold). Checked before the
2308 // release-drop below; a claimed key with an empty editor is routed
2309 // to the plugin's `Input` handler instead of the editor.
2310 // Hidden, buffered text is still a draft. Do not let an
2311 // empty-editor shortcut (notably push-to-talk Space) steal a
2312 // printable key while that draft awaits its display deadline.
2313 // Releases owned by an extension must still reach that owner.
2314 let owned_release = key.kind == KeyEventKind::Release
2315 && state_for_key
2316 .extension_claimed_keys
2317 .lock()
2318 .unwrap()
2319 .contains(&key.code);
2320 let shortcut_allowed = !windows_paste_run.is_buffering()
2321 || matches!(key.code, KeyCode::F(_))
2322 || owned_release;
2323 if shortcut_allowed && dispatch_key_event(&state_for_key, &key, &editor_for_key) {
2324 continue;
2325 }
2326 // Drop releases but preserve Repeat so holding arrows, Backspace,
2327 // PageUp, etc. behaves naturally. Windows emits Press + Release
2328 // for a tap; terminals with keyboard enhancement may additionally
2329 // emit Repeat while a key is held.
2330 if !should_dispatch_key(key.kind) {
2331 continue;
2332 }
2333
2334 // Prompt preparation runs on a blocking worker before the agent
2335 // lane owns the turn. Cancel it directly: an abort queued only to
2336 // the lane cannot wake a JS factory or lifecycle hook that never
2337 // resolves. This check precedes custom/dialog routing because
2338 // those components may themselves have been opened by the hook.
2339 let prompt_abort = (key.modifiers == KeyModifiers::CONTROL
2340 && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')))
2341 || (key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Esc);
2342 if prompt_abort && state_for_key.cancel_js_preparation() {
2343 state_for_key.set_status(RunStatus::Aborting);
2344 if !run_extension_cancel(&state_for_key) && state_for_key.extension_dialog_open() {
2345 close_extension_editor(
2346 &state_for_key,
2347 &ctx_for_key.editor_container,
2348 &editor_for_key,
2349 &tui_for_key,
2350 );
2351 }
2352 tui_for_key.set_render_suspended(false);
2353 tui_for_key.request_render(false);
2354 continue;
2355 }
2356
2357 // Ctrl+C cancels an open selector before it reaches the global
2358 // abort/exit handler. Route through Esc so selector callbacks run.
2359 if key.modifiers == KeyModifiers::CONTROL
2360 && key.code == KeyCode::Char('c')
2361 && state_for_key.selector_open()
2362 {
2363 let selector = state_for_key
2364 .active_selector
2365 .lock()
2366 .unwrap()
2367 .clone()
2368 .expect("selector_open guaranteed Some")
2369 .0;
2370 selector.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
2371 tui_for_key.request_render_reusing_scroll_content();
2372 continue;
2373 }
2374
2375 // The interactive "Add provider" form owns the input slot while it
2376 // collects a field: route every key to its single-line input (Esc
2377 // and Enter are handled by the Input's own callbacks). Clone the
2378 // input OUTSIDE `if let` so the `active_provider_input` mutex guard
2379 // drops before `handle_key` — the submit path re-enters that mutex
2380 // to swap in the next step's input and would deadlock on it.
2381 if state_for_key.provider_form.lock().unwrap().is_some() {
2382 let active_input = state_for_key.active_provider_input.lock().unwrap().clone();
2383 let active_select = state_for_key.active_provider_select.lock().unwrap().clone();
2384 if let Some(input) = active_input {
2385 input.handle_key(key);
2386 } else if let Some(select) = active_select {
2387 select.handle_key(key);
2388 }
2389 tui_for_key.request_render_reusing_scroll_content();
2390 continue;
2391 }
2392
2393 // Provider login inputs use the same input slot without creating an
2394 // Add-provider form state. Route them before the normal editor so
2395 // masked API keys and OAuth exchange values actually receive keys.
2396 if handle_provider_login_key(&state_for_key, key) {
2397 tui_for_key.request_render_reusing_scroll_content();
2398 continue;
2399 }
2400
2401 // OAuth begin/exchange/revoke owns the input slot even while the
2402 // provider call is running. Do not let keys leak into the prompt.
2403 if state_for_key
2404 .provider_auth_flow_id
2405 .load(std::sync::atomic::Ordering::Acquire)
2406 != 0
2407 {
2408 // Only report a cancel that won the flow from a completing result.
2409 if key.code == KeyCode::Esc
2410 && key.modifiers == KeyModifiers::NONE
2411 && finish_provider_login(
2412 &state_for_key,
2413 &ctx_for_key.editor_container,
2414 &editor_for_key,
2415 &tui_for_key,
2416 )
2417 {
2418 add_note_message(&state_for_key.notice_container(), "OAuth flow cancelled.");
2419 }
2420 tui_for_key.request_render_reusing_scroll_content();
2421 continue;
2422 }
2423
2424 // Extension dialogs own the input slot while awaiting a result.
2425 // Esc and Ctrl+C both resolve the pending command with cancel;
2426 // all other keys go to the active native editor/input widget.
2427 if state_for_key.extension_dialog_open() {
2428 let cancel = key.code == KeyCode::Esc
2429 || (key.modifiers == KeyModifiers::CONTROL && key.code == KeyCode::Char('c'));
2430 if cancel {
2431 if !run_extension_cancel(&state_for_key) {
2432 close_extension_editor(
2433 &state_for_key,
2434 &ctx_for_key.editor_container,
2435 &editor_for_key,
2436 &tui_for_key,
2437 );
2438 }
2439 } else {
2440 handle_extension_dialog_key(&state_for_key, key);
2441 }
2442 tui_for_key.request_render_reusing_scroll_content();
2443 continue;
2444 }
2445
2446 // Pet Esc pauses audio; an active run still reaches normal abort
2447 // routing below. Dialogs and selectors retain their own Escape.
2448 if key.code == KeyCode::Esc
2449 && key.modifiers == KeyModifiers::NONE
2450 && !state_for_key.selector_open()
2451 && pet::active(&state_for_key.ext_status)
2452 {
2453 let _ = invoke_extension_command(&state_for_key.extension_session, "pet", "quiet");
2454 tui_for_key.request_render(false);
2455 if *state_for_key.status.lock().unwrap() == RunStatus::Idle
2456 && editor_for_key.get_text().is_empty()
2457 {
2458 continue;
2459 }
2460 }
2461
2462 // 0. Ctrl+C: upstream's `handleCtrlC`. A second press inside the
2463 // double-press window quits; any other press only clears the
2464 // editor (text *and* selection — native `clearEditor`). It never
2465 // aborts — `app.interrupt` (Esc) owns cancelling a run — so a
2466 // stray Ctrl+C while streaming can no longer kill the turn.
2467 // Open selectors and extension dialogs are handled above so
2468 // their cancellation callbacks get first chance.
2469 if keybinding_matches(
2470 &keybindings_for_key,
2471 &key,
2472 rpi_tui::keybindings::keys::CLEAR,
2473 ) {
2474 // A held key auto-repeats: only a fresh Press may arm or
2475 // consume the window, so holding Ctrl+C cannot turn one tap
2476 // into the quit.
2477 if key.kind != KeyEventKind::Repeat {
2478 let now = std::time::Instant::now();
2479 match ctrl_c_action(last_sigint_time, now) {
2480 CtrlCAction::Exit => {
2481 last_sigint_time = None;
2482 // The async loop parks inside
2483 // `run_prompt_streaming(..).await` for the whole run,
2484 // so a queued `Exit` would not be read until the run
2485 // returns — force the quit while one is active. Either
2486 // way the TUI stays quittable.
2487 if *state_for_key.status.lock().unwrap() == RunStatus::Idle {
2488 let _ = tx_for_key.send(TuiMessage::Exit);
2489 } else {
2490 terminal_for_key.exit_active(&tui_for_key, &tx_for_key);
2491 }
2492 }
2493 CtrlCAction::Clear => {
2494 editor_for_key.clear();
2495 state_for_key.take_pending_images();
2496 refresh_autocomplete(&state_for_key, &editor_for_key);
2497 last_sigint_time = Some(now);
2498 tui_for_key.request_render(false);
2499 }
2500 }
2501 }
2502 continue;
2503 }
2504
2505 // 0b. Ctrl+X: copy the mouse selection first, then the editor
2506 // selection, else the last assistant reply. Ctrl+C retains its
2507 // clear/exit semantics. A failed write must not change sources.
2508 if !state_for_key.selector_open()
2509 && keybinding_matches(
2510 &keybindings_for_key,
2511 &key,
2512 rpi_tui::keybindings::keys::MESSAGE_COPY,
2513 )
2514 {
2515 match copy_mouse_selection_with(&tui_for_key, copy_to_clipboard) {
2516 Some(copied) => add_note_message(
2517 &state_for_key.notice_container(),
2518 if copied {
2519 "Copied selection to the clipboard."
2520 } else {
2521 "Clipboard unavailable. Selection kept; press Ctrl+X to retry."
2522 },
2523 ),
2524 None => {
2525 if editor_for_key.has_selection() && editor_for_key.copy_selection() {
2526 add_note_message(&state_for_key.notice_container(), "Copied!");
2527 } else {
2528 copy_last_assistant(&state_for_key);
2529 }
2530 }
2531 }
2532 tui_for_key.request_render(false);
2533 continue;
2534 }
2535
2536 // 0c. Ctrl+Z (Unix only): upstream's `app.suspend` — hand the
2537 // terminal back to the shell and stop ourselves; `SIGTSTP`
2538 // returns when the user resumes with `fg`. Windows binds no key
2539 // here (native's `defaultKeys` is empty), so this never fires.
2540 if keybinding_matches(
2541 &keybindings_for_key,
2542 &key,
2543 rpi_tui::keybindings::keys::SUSPEND,
2544 ) {
2545 terminal_for_key.suspend(&tui_for_key);
2546 continue;
2547 }
2548
2549 // 1. A selector overlay is open → route to it first. Only Esc
2550 // (cancel) and Enter/Up/Down/Ctrl-K/J/P/N (navigate/select)
2551 // escape to the selector; on done/cancel the selector callbacks
2552 // restore the editor and clear `active_selector`.
2553 if state_for_key.selector_open() {
2554 // `/session` uses Tab to switch between this-project and all-
2555 // projects. Autocomplete is cleared while a selector is open,
2556 // so Tab is free here; consume it before the generic selector
2557 // routing (which would send it to the list as a no-op).
2558 if selector_owns_key(&state_for_key, &key) {
2559 tui_for_key.request_render_reusing_scroll_content();
2560 continue;
2561 }
2562 // Esc always cancels the selector (even with modifiers off).
2563 // Route through `SelectList::handle_key(Esc)` so the list's
2564 // `on_cancel` fires (the `/scoped-models` toggle selector saves
2565 // its edits there) — the old shortcut called `close_selector`
2566 // directly and skipped the callback.
2567 if key.code == KeyCode::Esc {
2568 let (selector, _kind) = state_for_key
2569 .active_selector
2570 .lock()
2571 .unwrap()
2572 .clone()
2573 .expect("selector_open guaranteed Some");
2574 selector.handle_key(key);
2575 continue;
2576 }
2577 let (selector, _kind) = state_for_key
2578 .active_selector
2579 .lock()
2580 .unwrap()
2581 .clone()
2582 .expect("selector_open guaranteed Some");
2583 selector.handle_key(key);
2584 tui_for_key.request_render_reusing_scroll_content();
2585 continue;
2586 }
2587
2588 // 2a. Ctrl+D: upstream's `app.exit`. `handleCtrlD` only fires when
2589 // the editor is empty; with text present the key falls through to
2590 // the editor's deleteCharForward (`tui.editor.deleteCharForward`).
2591 // It never aborts — that is `app.interrupt` (Esc)'s job.
2592 if keybinding_matches(&keybindings_for_key, &key, rpi_tui::keybindings::keys::EXIT) {
2593 if !editor_for_key.get_text().is_empty() {
2594 // Editor holds text — delete the char forward (pi parity).
2595 editor_for_key.handle_key(key);
2596 refresh_autocomplete(&state_for_key, &editor_for_key);
2597 tui_for_key.request_render_reusing_scroll_content();
2598 continue;
2599 }
2600 // Empty editor → quit. A parked run needs the forced path: a
2601 // queued `Exit` is unread until the run returns.
2602 if *state_for_key.status.lock().unwrap() == RunStatus::Idle {
2603 let _ = tx_for_key.send(TuiMessage::Exit);
2604 } else {
2605 terminal_for_key.exit_active(&tui_for_key, &tx_for_key);
2606 }
2607 continue;
2608 }
2609
2610 // 2b. Esc: interrupt an active run (mirrors Ctrl+C abort). When a
2611 // selector is open Esc already cancelled it above; when idle,
2612 // Esc falls through to the editor (no-op-ish). Only fire while
2613 // Working so an idle Esc doesn't abort a non-existent run.
2614 if keybinding_matches(
2615 &keybindings_for_key,
2616 &key,
2617 rpi_tui::keybindings::keys::INTERRUPT,
2618 ) {
2619 let status = *state_for_key.status.lock().unwrap();
2620 if status == RunStatus::Working {
2621 state_for_key.set_status(RunStatus::Aborting);
2622 ask_user_for_key.cancel_all();
2623 if !run_extension_cancel(&state_for_key)
2624 && state_for_key.extension_dialog_open()
2625 {
2626 close_extension_editor(
2627 &state_for_key,
2628 &ctx_for_key.editor_container,
2629 &editor_for_key,
2630 &tui_for_key,
2631 );
2632 }
2633 // upstream's `onEscape` restores the queue before it
2634 // aborts, so an interrupt hands the staged messages back.
2635 abort_run_restoring_queue(
2636 lane_for_key.clone(),
2637 editor_for_key.clone(),
2638 state_for_key.clone(),
2639 tui_for_key.clone(),
2640 );
2641 continue;
2642 }
2643 // A running `!command` takes Esc next (upstream's `onEscape`
2644 // precedence: streaming → bash → bash-mode editor →
2645 // double-escape). The run slot stays occupied until the capture
2646 // resolves, so a second Esc is a no-op rather than a
2647 // double-escape trigger.
2648 if state_for_key.user_bash_running() {
2649 state_for_key.cancel_user_bash();
2650 tui_for_key.request_render(false);
2651 continue;
2652 }
2653 if status == RunStatus::Idle
2654 && editor_for_key.get_text().trim().is_empty()
2655 && double_escape_action != "none"
2656 {
2657 let now = std::time::Instant::now();
2658 if double_escape_trigger(last_escape_time, now) {
2659 last_escape_time = None;
2660 match double_escape_action.as_str() {
2661 "tree" => {
2662 let _ = tx_for_key.send(TuiMessage::OpenTree);
2663 }
2664 "fork" => {
2665 let _ = tx_for_key.send(TuiMessage::ForkSession);
2666 }
2667 _ => {}
2668 }
2669 } else {
2670 last_escape_time = Some(now);
2671 }
2672 }
2673 continue;
2674 }
2675
2676 // 2c. Ctrl+G: edit the current draft in the user's external
2677 // editor, matching upstream's VISUAL/EDITOR fallback chain.
2678 if keybinding_matches(
2679 &keybindings_for_key,
2680 &key,
2681 rpi_tui::keybindings::keys::EXTERNAL_EDITOR,
2682 ) {
2683 editing = terminal_for_key.is_host();
2684 terminal_for_key.edit(
2685 &tui_for_key,
2686 editor_for_key.get_expanded_text(),
2687 &tx_for_key,
2688 );
2689 continue;
2690 }
2691
2692 // 2d. Ctrl+O: toggle all tool output panels between compact and
2693 // expanded rendering (upstream's global output toggle).
2694 if keybinding_matches(
2695 &keybindings_for_key,
2696 &key,
2697 rpi_tui::keybindings::keys::TOOLS_EXPAND,
2698 ) {
2699 let expanded = state_for_key.toggle_tool_outputs();
2700 // Persist per-session so a later `-c`/`-r` restores it.
2701 let session = ctx_for_key.session.clone();
2702 ctx_for_key.state.session_write_tasks.spawn(async move {
2703 let _ = session
2704 .set_value("display.tool_outputs_expanded", serde_json::json!(expanded))
2705 .await;
2706 });
2707 tui_for_key.request_render(false);
2708 continue;
2709 }
2710
2711 // 2e. Ctrl+T: toggle visibility of reasoning/thinking blocks.
2712 if keybinding_matches(
2713 &keybindings_for_key,
2714 &key,
2715 rpi_tui::keybindings::keys::THINKING_TOGGLE,
2716 ) {
2717 let hide = state_for_key.toggle_thinking();
2718 // Persist per-session so a later `-c`/`-r` restores it.
2719 let session = ctx_for_key.session.clone();
2720 ctx_for_key.state.session_write_tasks.spawn(async move {
2721 let _ = session
2722 .set_value("display.hide_thinking", serde_json::json!(hide))
2723 .await;
2724 });
2725 tui_for_key.request_render(false);
2726 continue;
2727 }
2728
2729 // Cycle the authenticated catalog, including other providers. Resolve
2730 // the anchor from the live lane so duplicate model ids stay distinct.
2731 let cycle_forward = keybinding_matches(
2732 &keybindings_for_key,
2733 &key,
2734 rpi_tui::keybindings::keys::MODEL_CYCLE_FORWARD,
2735 );
2736 let cycle_backward = keybinding_matches(
2737 &keybindings_for_key,
2738 &key,
2739 rpi_tui::keybindings::keys::MODEL_CYCLE_BACKWARD,
2740 );
2741 if cycle_forward || cycle_backward {
2742 let catalog = ctx_for_key
2743 .model_catalog
2744 .read()
2745 .unwrap_or_else(|error| error.into_inner())
2746 .clone();
2747 let lane = lane_for_key.clone();
2748 let state = state_for_key.clone();
2749 let tui = tui_for_key.clone();
2750 state.session_write_tasks.clone().spawn(async move {
2751 match cycle_model(&lane, &catalog, cycle_backward).await {
2752 Ok(Some(model)) => {
2753 report_model_selection(&lane, &state, &tui, model, false).await;
2754 }
2755 Ok(None) => {}
2756 Err(error) => {
2757 add_error_message(&state.notice_container(), &error);
2758 tui.request_render(false);
2759 }
2760 }
2761 });
2762 continue;
2763 }
2764
2765 // 2f. Shift+Tab / BackTab: cycle the current model's supported
2766 // thinking levels, matching upstream's thinking-level shortcut.
2767 if keybinding_matches(
2768 &keybindings_for_key,
2769 &key,
2770 rpi_tui::keybindings::keys::THINKING_CYCLE,
2771 ) {
2772 let lane = lane_for_key.clone();
2773 let catalog = model_catalog_for_key
2774 .read()
2775 .unwrap_or_else(|error| error.into_inner())
2776 .clone();
2777 let state = state_for_key.clone();
2778 state.session_write_tasks.clone().spawn(async move {
2779 let Ok(current_model) = lane.get_model().await else {
2780 return;
2781 };
2782 let levels = catalog
2783 .iter()
2784 .find(|model| {
2785 model.provider == current_model.provider && model.id == current_model.id
2786 })
2787 .map(|model| model.supported_thinking_levels())
2788 .unwrap_or_else(|| vec![rpi_ai::types::ThinkingLevel::Medium]);
2789 if levels.is_empty() {
2790 return;
2791 }
2792 let current = lane
2793 .get_thinking_level()
2794 .await
2795 .unwrap_or(rpi_ai::types::ThinkingLevel::Medium);
2796 let next = levels
2797 .iter()
2798 .position(|level| *level == current)
2799 .map(|index| levels[(index + 1) % levels.len()])
2800 .unwrap_or(levels[0]);
2801 if lane.set_thinking_level(next).await.is_ok() {
2802 state
2803 .footer
2804 .set_thinking_level(Some(thinking_level_name(next)));
2805 if let Some(tui) = state.tui.as_ref() {
2806 tui.request_render(false)
2807 }
2808 }
2809 });
2810 continue;
2811 }
2812
2813 // Ctrl+V (or a configured paste-image key): if the system
2814 // clipboard holds an image, queue it for the next prompt;
2815 // otherwise paste the clipboard TEXT into the editor. Previously
2816 // a text-only clipboard fell through to the editor's Ctrl+V,
2817 // which yanks from the internal KILL RING — not the system
2818 // clipboard. On platforms without bracketed-paste `Event::Paste`
2819 // (Windows console, some remote clients) that meant Ctrl+V pasted
2820 // stale/other content instead of the user's real clipboard
2821 // ("不是系统的粘贴的内容").
2822 if keybinding_matches(
2823 &keybindings_for_key,
2824 &key,
2825 rpi_tui::keybindings::keys::PASTE_IMAGE,
2826 ) {
2827 if cfg!(windows) {
2828 windows_paste_run.flush_with_clipboard(
2829 &editor_for_key,
2830 std::time::Instant::now(),
2831 read_clipboard_text,
2832 );
2833 windows_paste_run.end_paste_session();
2834 }
2835 if let Some(paths) = read_clipboard_file_paths() {
2836 let text = paths.join("\n");
2837 if let Some(images) = images_from_pasted_paths(&text) {
2838 for image in images {
2839 state_for_key.queue_image(image);
2840 }
2841 add_note_message(
2842 &state_for_key.notice_container(),
2843 "Clipboard images attached to the next prompt.",
2844 );
2845 } else {
2846 editor_for_key.handle_paste(&text);
2847 }
2848 tui_for_key.request_render(false);
2849 continue;
2850 }
2851 if let Ok(Some(image)) = read_clipboard_image() {
2852 state_for_key.queue_image(image);
2853 add_note_message(
2854 &state_for_key.notice_container(),
2855 "Clipboard image attached to the next prompt.",
2856 );
2857 tui_for_key.request_render(false);
2858 continue;
2859 }
2860 // Local Ctrl+V can paste clipboard text as Pi does. Under SSH,
2861 // text must arrive from the client via bracketed paste rather
2862 // than reading the remote host's unrelated clipboard.
2863 if cfg!(windows) || std::env::var_os("SSH_CONNECTION").is_none() {
2864 if let Some(text) = read_clipboard_text() {
2865 if !text.is_empty() {
2866 if !attach_pasted_images(&state_for_key, &text) {
2867 editor_for_key.handle_paste(&text);
2868 }
2869 refresh_autocomplete(&state_for_key, &editor_for_key);
2870 tui_for_key.request_render_reusing_scroll_content();
2871 continue;
2872 }
2873 }
2874 }
2875 }
2876
2877 // 3. Ctrl+Shift+F: open transcript search
2878 if key
2879 .modifiers
2880 .contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT)
2881 && key.code == KeyCode::Char('F')
2882 {
2883 state_for_key.search.activate();
2884 state_for_key.search_bar.set_visible(true);
2885 state_for_key.search_bar.set_query("");
2886 state_for_key.search_bar.set_match_info(0, 0);
2887 last_search_document = std::sync::Weak::new();
2888 tui_for_key.request_render_reusing_scroll_content();
2889 continue;
2890 }
2891
2892 // Handle search mode input
2893 if state_for_key.search.is_active() {
2894 let search = &state_for_key.search;
2895 let search_bar = &state_for_key.search_bar;
2896 match key.code {
2897 KeyCode::Esc => {
2898 search.deactivate();
2899 search_bar.set_visible(false);
2900 tui_for_key.request_render_reusing_scroll_content();
2901 continue;
2902 }
2903 KeyCode::Enter => {}
2904 KeyCode::Backspace => search.backspace(),
2905 KeyCode::Char(c) => search.append_char(c),
2906 _ => continue,
2907 }
2908
2909 let navigating = key.code == KeyCode::Enter;
2910 let document = scroll_for_key.rendered_document();
2911 if let Some(document) = &document {
2912 if !navigating || !last_search_document.ptr_eq(&Arc::downgrade(document)) {
2913 search.update_matches(
2914 (0..document.len()).filter_map(|row| document.line(row)),
2915 );
2916 last_search_document = Arc::downgrade(document);
2917 }
2918 } else if !navigating {
2919 let lines = state_for_key.chat_container.render(tui_for_key.width());
2920 search.update_matches(lines.iter().map(String::as_str));
2921 }
2922 if navigating {
2923 let matched = if key.modifiers.contains(KeyModifiers::SHIFT) {
2924 search.previous_match()
2925 } else {
2926 search.next_match()
2927 };
2928 if let (Some(matched), Some(_)) = (matched, &document) {
2929 let centered = matched
2930 .line
2931 .saturating_sub(scroll_for_key.viewport_height() / 2);
2932 scroll_for_key.scroll_to(centered);
2933 }
2934 } else {
2935 search_bar.set_query(&search.get_query());
2936 }
2937 search_bar.set_match_info(search.get_match_index(), search.get_match_count());
2938 tui_for_key.request_render_reusing_scroll_content();
2939 continue;
2940 }
2941
2942 // 3. Ctrl+L: open the model selector. Routed through the `/model`
2943 // command so the hotkey and the slash command share one path
2944 // (TS binds Ctrl+L to model-select).
2945 if keybinding_matches(
2946 &keybindings_for_key,
2947 &key,
2948 rpi_tui::keybindings::keys::MODEL_SELECT,
2949 ) {
2950 if let Some(cmd) = registry_for_key.find("/model") {
2951 cmd.execute(&ctx_for_key, "");
2952 }
2953 continue;
2954 }
2955
2956 // 4. Tab: accept the top autocomplete suggestion (if any).
2957 if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Tab {
2958 if accept_top_suggestion(&state_for_key, &editor_for_key) {
2959 tui_for_key.request_render_reusing_scroll_content();
2960 }
2961 continue;
2962 }
2963
2964 // 5. Global transcript scroll. PageUp/PageDown use the actual
2965 // viewport height with four rows of overlap (upstream behavior),
2966 // while Home/End jump to the transcript boundaries.
2967 if history::handle_key(&state_for_key, &tui_for_key, &keybindings_for_key, &key) {
2968 continue;
2969 }
2970 if editor_for_key.get_text().is_empty()
2971 && crate::transcript_navigation::handle_key(
2972 &tui_for_key,
2973 &keybindings_for_key,
2974 &key,
2975 )
2976 {
2977 continue;
2978 }
2979
2980 // 5a-bis. ↑/↓ (or Alt-P/Alt-N, the emacs bindings — Ctrl-P is
2981 // taken by user-configurable model select) navigate the
2982 // autocomplete list while it is open (typed `/` or `@`), then
2983 // Tab accepts the highlighted row.
2984 let navigate_direction =
2985 if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Up {
2986 Some(-1)
2987 } else if key.modifiers == KeyModifiers::NONE && key.code == KeyCode::Down {
2988 Some(1)
2989 } else if key.modifiers == KeyModifiers::ALT && key.code == KeyCode::Char('p') {
2990 Some(-1)
2991 } else if key.modifiers == KeyModifiers::ALT && key.code == KeyCode::Char('n') {
2992 Some(1)
2993 } else {
2994 None
2995 };
2996 if let Some(direction) = navigate_direction {
2997 if navigate_autocomplete(&state_for_key, &editor_for_key, direction) {
2998 tui_for_key.request_render_reusing_scroll_content();
2999 continue;
3000 }
3001 }
3002
3003 // 5b. ↑/↓ move the caret through a multi-line draft, and only
3004 // leave for prompt history once the caret cannot move any
3005 // further (first line for ↑, last line for ↓) — mirrors TS
3006 // historyPrevious/Next, which only fire at the editor's edge.
3007 // A fresh prompt (no caret row to move to) recalls
3008 // immediately. A single-line draft keeps the older contract
3009 // and never swaps itself for a history entry: that was
3010 // reported as "text disappeared", and one line has no second
3011 // row to move to — but once a browse session is active, ↑/↓
3012 // keep walking history (a one-line recall must not strand it).
3013 if key.modifiers == KeyModifiers::NONE
3014 && matches!(key.code, KeyCode::Up | KeyCode::Down)
3015 {
3016 let direction = if key.code == KeyCode::Up { -1 } else { 1 };
3017 if arrow_belongs_to_history(&state_for_key, &editor_for_key, direction) {
3018 navigate_history(&state_for_key, &editor_for_key, direction);
3019 tui_for_key.request_render_reusing_scroll_content();
3020 continue;
3021 }
3022 }
3023
3024 // `app.message.dequeue` (Alt+Q on Windows, Alt+Up elsewhere):
3025 // restore every queued steering/follow-up message into the editor
3026 // so it can be edited before resending. Mirrors upstream's
3027 // `handleDequeue`; the pending-messages display shows the hint.
3028 if keybinding_matches(
3029 &keybindings_for_key,
3030 &key,
3031 rpi_tui::keybindings::keys::DEQUEUE,
3032 ) {
3033 // Handled here, on the key worker — NOT via the mailbox. The
3034 // async main loop parks inside `run_prompt_streaming(..).await`
3035 // for the whole run, and a queue only exists *while* a run is
3036 // in flight, so a `TuiMessage::Dequeue` sat unread until the
3037 // run finished (after the lane had already consumed the queue).
3038 // Alt+Q therefore looked like a no-op while it was most needed.
3039 // Spawn the drain so it lands while the user is still looking at
3040 // the queue, exactly like the Alt+Enter `follow_up` path above.
3041 // Routed through `handle_dequeue` (not the raw restore) so the
3042 // `Restored N queued message(s)` status note fires, mirroring
3043 // upstream's `handleDequeue`.
3044 state_for_key.session_write_tasks.spawn(handle_dequeue(
3045 lane_for_key.clone(),
3046 editor_for_key.clone(),
3047 state_for_key.clone(),
3048 tui_for_key.clone(),
3049 ));
3050 continue;
3051 }
3052
3053 // `app.message.followUp` (Alt+Enter; Ctrl+Q and Alt+Enter on
3054 // Windows) queues a follow-up while a run is active. It is handled
3055 // here because Editor treats only a bare Enter as submit; when idle
3056 // the same key keeps the normal prompt behavior.
3057 if keybinding_matches(
3058 &keybindings_for_key,
3059 &key,
3060 rpi_tui::keybindings::keys::MESSAGE_FOLLOW_UP,
3061 ) {
3062 let prompt = editor_for_key.get_expanded_text().trim().to_string();
3063 if prompt.is_empty() && state_for_key.pending_images.lock().unwrap().is_empty() {
3064 continue;
3065 }
3066 editor_for_key.clear();
3067 let status = *state_for_key.status.lock().unwrap();
3068 if status == RunStatus::Idle {
3069 if state_for_key.try_start_working() {
3070 // Direct send: the harness emits no user `message_start`
3071 // for it, so render the bubble here (see the submit
3072 // handler in `interactive_tui`).
3073 add_user_message(&state_for_key.history_page.active, &prompt);
3074 push_history(&state_for_key, &prompt);
3075 let _ = tx_for_key.send(TuiMessage::UserInput(
3076 prompt,
3077 state_for_key.take_pending_images(),
3078 ));
3079 }
3080 } else {
3081 // Follow-ups are echoed by the loop's
3082 // `AgentEvent::MessageStart` once they are consumed; while
3083 // they wait, the pending-messages display shows them.
3084 let images = state_for_key.take_pending_images();
3085 let message = user_message_with_images(&prompt, images.clone());
3086 let lane = lane_for_key.clone();
3087 let chat = state_for_key.notice_container();
3088 let tui = tui_for_key.clone();
3089 let state = state_for_key.clone();
3090 state.session_write_tasks.clone().spawn(async move {
3091 if let Err(error) = lane.follow_up(message).await {
3092 state.restore_pending_images(images);
3093 add_error_message(&chat, &format!("Could not queue message: {error}"));
3094 tui.request_render(false);
3095 return;
3096 }
3097 refresh_pending_messages(&state, &lane).await;
3098 tui.request_render(false);
3099 });
3100 }
3101 tui_for_key.request_render(false);
3102 continue;
3103 }
3104
3105 // Windows' console backend has no Event::Paste. Assemble text keys
3106 // into one payload; only absorb Enter when another key is queued
3107 // or the clipboard confirms a trailing pasted newline. A standalone
3108 // Enter must reach Editor::handle_key so it submits normally.
3109 if cfg!(windows) {
3110 let text_key = match key.code {
3111 KeyCode::Char(c)
3112 if !key
3113 .modifiers
3114 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
3115 {
3116 Some(c)
3117 }
3118 _ => None,
3119 };
3120 if let Some(ch) = text_key {
3121 if ch == '\r' || ch == '\n' {
3122 // Treat these the same as KeyCode::Enter below.
3123 } else {
3124 let now = std::time::Instant::now();
3125 // Feed first: `feed` is what detects the burst, and the
3126 // fold threshold is what decides whether this run is an
3127 // established paste.
3128 windows_paste_run.feed(ch, now);
3129 // An established paste is drained straight out of the
3130 // console. Probing here would stash the next event, which
3131 // is what made that drain unreachable. `pending_event` is
3132 // `None` at this point (the loop took it above), so
3133 // reading the console cannot reorder input.
3134 if !windows_paste_run.probe_needed() {
3135 #[cfg(windows)]
3136 if should_drain_queued_text(
3137 &windows_paste_run,
3138 state_for_key
3139 .extension_claimed_keys
3140 .lock()
3141 .unwrap()
3142 .is_empty(),
3143 ) {
3144 windows_paste_run.read_queued_text();
3145 }
3146 continue;
3147 }
3148 // Queue-empty is not a paste boundary. Leave the run
3149 // buffered for its idle window; probe only to retain
3150 // newline evidence. Releases are not queued text.
3151 let (more_queued, stashed) =
3152 probe_paste_input(pending_event.take(), || {
3153 if crossterm::event::poll(std::time::Duration::ZERO)
3154 .unwrap_or(false)
3155 {
3156 crossterm::event::read().ok().map(normalize_decoded_event)
3157 } else {
3158 None
3159 }
3160 });
3161 pending_event = stashed;
3162 if more_queued {
3163 windows_paste_run.mark_collected();
3164 }
3165 continue;
3166 }
3167 }
3168 if key.modifiers.is_empty()
3169 && matches!(
3170 key.code,
3171 KeyCode::Enter | KeyCode::Char('\n') | KeyCode::Char('\r')
3172 )
3173 {
3174 let (more_queued, stashed) = probe_paste_input(pending_event.take(), || {
3175 if crossterm::event::poll(PASTE_PROBE).unwrap_or(false) {
3176 crossterm::event::read().ok().map(normalize_decoded_event)
3177 } else {
3178 None
3179 }
3180 });
3181 pending_event = stashed;
3182 let now = std::time::Instant::now();
3183 // Read the clipboard only when some text here could be a
3184 // paste still waiting for its trailing newline — the live
3185 // run or a batch flushed within `PASTE_CARRY_GAP`.
3186 let clipboard = if !more_queued && windows_paste_run.has_paste_evidence(now) {
3187 read_clipboard_text()
3188 } else {
3189 None
3190 };
3191 if windows_enter_in_paste(
3192 &windows_paste_run,
3193 more_queued,
3194 clipboard.as_deref(),
3195 now,
3196 ) {
3197 windows_paste_run.feed('\n', now);
3198 crate::key_trace::note("windows paste run -> newline");
3199 continue;
3200 }
3201 crate::key_trace::note("windows paste run -> flush + submit");
3202 windows_paste_run.flush_with_clipboard(
3203 &editor_for_key,
3204 now,
3205 read_clipboard_text,
3206 );
3207 windows_paste_run.end_paste_session();
3208 // Enter can beat the idle deadline: autocomplete must see
3209 // the newly delivered draft before its confirm/submit path.
3210 refresh_autocomplete(&state_for_key, &editor_for_key);
3211 } else {
3212 windows_paste_run.flush_with_clipboard(
3213 &editor_for_key,
3214 std::time::Instant::now(),
3215 read_clipboard_text,
3216 );
3217 windows_paste_run.end_paste_session();
3218 }
3219 }
3220
3221 // 5a-ter. A bare Enter in a completion context (`/` or `@`)
3222 // resolves the completion before submitting, mirroring the
3223 // TS editor's `tui.select.confirm` (`editor.ts:757-815`):
3224 // apply the highlighted item — the panel's first choice on a
3225 // fresh popup — then let a `/` completion fall through to
3226 // submit while an `@`-path one consumes the Enter (a path
3227 // popup therefore still needs a sole candidate or an explicit
3228 // ↑/↓). Unknown `/skill:name` has no popup and still reaches
3229 // the model untouched.
3230 //
3231 // Placement is load-bearing: this runs AFTER the Windows
3232 // paste classification and flush above, immediately before
3233 // the confirmed submit Enter is forwarded to the editor, so
3234 // an Enter that belongs to a paste never reaches it — the
3235 // paste paths have already `continue`d. At this point the
3236 // editor also holds any buffered typed prefix the Windows
3237 // handler just flushed, so the completion sees the full
3238 // token.
3239 if key.modifiers == KeyModifiers::NONE
3240 && (key.code == KeyCode::Enter
3241 || key.code == KeyCode::Char('\n')
3242 || key.code == KeyCode::Char('\r'))
3243 {
3244 // One resolution, one replacement: `route_enter_completion`
3245 // applies the same snapshot it decided on and reports whether
3246 // this Enter is consumed by an `@`-path completion.
3247 if route_enter_completion(&state_for_key, &editor_for_key) {
3248 refresh_autocomplete(&state_for_key, &editor_for_key);
3249 tui_for_key.request_render_reusing_scroll_content();
3250 continue;
3251 }
3252 }
3253
3254 // 6. Otherwise forward to the editor + refresh autocomplete. The
3255 // editor maps unmodified Enter and the encodings a remote client
3256 // may send for it (`Char('\n')`/`Char('\r')`, and the raw LF
3257 // crossterm reports as `Ctrl+J`) to submit, so a remote Enter
3258 // sends instead of inserting a newline.
3259 editor_for_key.handle_key(key);
3260 refresh_autocomplete(&state_for_key, &editor_for_key);
3261 tui_for_key.request_render_reusing_scroll_content();
3262 }
3263 });
3264
3265 // ---- Session lifecycle (P1): SessionStart ----
3266 // The TUI + key worker are up and the session is ready to accept input.
3267 // Notify subscribed extensions now so they can initialize session-scoped
3268 // state. A veto here is **advisory** (the session is already up) — warn and
3269 // continue. No-op when no extension subscribes.
3270 if let Some(reason) = crate::session::dispatch_session_event_async(
3271 reload_context,
3272 rpi_plugin_sdk::EventTag::SessionStart,
3273 )
3274 .await
3275 {
3276 tracing::warn!("[rpi] extension vetoed SessionStart (advisory): {reason}");
3277 }
3278
3279 // ---- Initial prompts (run before reading from the channel) ----
3280 let mut prompts: Vec<String> = Vec::new();
3281 if let Some(init) = initial {
3282 prompts.push(init);
3283 }
3284 for m in extra_messages {
3285 prompts.push(m.clone());
3286 }
3287 // ---- Continue a run that recovery repaired, the way upstream does ----
3288 // This happens before any user input, and only when nothing was passed on the
3289 // command line: an explicit `-p` means the user has already said what they
3290 // want next. Driven here rather than inside the harness so the run's output
3291 // goes through the same streaming/render path as any other run, and so
3292 // startup is never blocked by a run the user cannot see.
3293 if prompts.is_empty() && lane.has_pending_resume().await {
3294 run_prompt_streaming(
3295 &lane,
3296 "",
3297 true,
3298 &tui,
3299 &state,
3300 drain_handle.is_some(),
3301 Vec::new(),
3302 )
3303 .await;
3304 }
3305
3306 let mut images = initial_images;
3307 for prompt in prompts {
3308 if !*running.lock().unwrap() {
3309 break;
3310 }
3311 // The harness emits no user `message_start` for a directly-sent prompt
3312 // (it drives the loop with an empty prompts vec), so the initial
3313 // `-p` / `--prompt` bubbles are rendered here.
3314 add_user_message(&state.history_page.active, &prompt);
3315 add_image_previews(&state.history_page.active, &images, show_images);
3316 tui.request_render(false);
3317 run_prompt_streaming(
3318 &lane,
3319 &prompt,
3320 false,
3321 &tui,
3322 &state,
3323 drain_handle.is_some(),
3324 std::mem::take(&mut images),
3325 )
3326 .await;
3327 }
3328
3329 // ---- Main loop: process submitted input + lifecycle messages ----
3330 loop {
3331 if terminal.is_closing() || !*running.lock().unwrap() {
3332 break;
3333 }
3334 match rx.recv().await {
3335 Some(
3336 TuiMessage::SwitchSession(_)
3337 | TuiMessage::ImportSession(_)
3338 | TuiMessage::ForkSession
3339 | TuiMessage::ExportSession
3340 | TuiMessage::ExportSessionWithFormat(_),
3341 ) if args.mini => {
3342 add_error_message(
3343 &state.notice_container(),
3344 "--mini does not support saved sessions or session exports.",
3345 );
3346 tui.request_render(false);
3347 }
3348 Some(TuiMessage::OpenProviderSelector) => {
3349 let current = lane.get_model().await.ok();
3350 open_provider_selector(
3351 &state,
3352 &editor_container,
3353 &editor,
3354 &tui,
3355 &ctx.reload_context.extension_session,
3356 &ctx.tx,
3357 current.as_ref().map(|model| model.provider.as_str()),
3358 );
3359 }
3360 Some(TuiMessage::SwitchProvider(input)) => {
3361 let manifests = current_provider_manifests(&ctx.reload_context.extension_session);
3362 let available = ctx
3363 .model_catalog
3364 .read()
3365 .unwrap_or_else(|error| error.into_inner())
3366 .clone();
3367 match switch_provider(&input, &manifests, &available, &lane).await {
3368 Ok((model, note)) => {
3369 state.set_current_model(&model);
3370 add_note_message(&state.notice_container(), ¬e);
3371 }
3372 Err(error) => add_error_message(&state.notice_container(), &error),
3373 }
3374 tui.request_render(false);
3375 }
3376 Some(TuiMessage::UserInput(prompt, prompt_images)) => {
3377 // Clear the editor so the next prompt starts fresh (the submit
3378 // handler runs on the blocking key thread and can't mutate the
3379 // editor state safely there; clearing here, on the async loop,
3380 // keeps it on one thread). Marked programmatic: this is the host
3381 // tidying up after a submit, not the user typing — reporting it
3382 // as a user edit made a hands-free voice session switch itself
3383 // off the moment it was started.
3384 state.clear_editor_programmatically();
3385 add_image_previews(
3386 &state.history_page.active,
3387 &prompt_images,
3388 state.images_visible(),
3389 );
3390 if !prompt_images.is_empty() {
3391 add_note_message(
3392 &state.notice_container(),
3393 &format!("Attached {} image(s) to this prompt.", prompt_images.len()),
3394 );
3395 }
3396 run_prompt_streaming(
3397 &lane,
3398 &prompt,
3399 false,
3400 &tui,
3401 &state,
3402 drain_handle.is_some(),
3403 prompt_images,
3404 )
3405 .await;
3406 }
3407 Some(TuiMessage::ExternalEditorResult(result)) => {
3408 match result {
3409 Ok(text) => {
3410 let cursor = text.chars().count();
3411 editor.set_text(&text);
3412 editor.set_cursor(0, cursor);
3413 add_note_message(
3414 &state.notice_container(),
3415 "Draft updated from external editor.",
3416 );
3417 }
3418 Err(error) => add_error_message(&state.notice_container(), &error),
3419 }
3420 tui.request_render(false);
3421 }
3422 Some(TuiMessage::UserBashFinished(report)) => {
3423 // Free the run slot first: the guard and the Esc router both
3424 // read it, so a finished command must never block the next one.
3425 state.finish_user_bash();
3426 let message = rpi_harness::messages::bash_execution_message(
3427 report.command,
3428 report.output,
3429 report.exit_code,
3430 report.cancelled,
3431 report.truncated,
3432 report.full_output_path,
3433 Some(report.exclude_from_context),
3434 now_ms(),
3435 );
3436 // While a run is in flight the message is deferred so it is not
3437 // spliced into the middle of a turn's tool sequence; it is
3438 // flushed at `AgentEnd` (upstream `_pendingBashMessages`).
3439 if *state.status.lock().unwrap() == RunStatus::Idle {
3440 if let Err(error) = lane.append_message(message).await {
3441 state
3442 .history_page
3443 .unsaved
3444 .store(true, std::sync::atomic::Ordering::SeqCst);
3445 add_error_message(
3446 &state.notice_container(),
3447 &format!("Could not record bash result: {error}"),
3448 );
3449 tui.request_render(false);
3450 }
3451 history::settle(&state, &tui);
3452 } else {
3453 state.pending_bash_messages.lock().unwrap().push(message);
3454 }
3455 }
3456 Some(TuiMessage::OpenTree) => {
3457 if *state.status.lock().unwrap() != RunStatus::Idle {
3458 add_note_message(
3459 &state.notice_container(),
3460 "Wait for the current run to finish before opening the tree.",
3461 );
3462 tui.request_render(false);
3463 } else {
3464 open_tree_selector(harness, &state, &editor_container, &editor, &tui, &tx)
3465 .await;
3466 }
3467 }
3468 Some(TuiMessage::NavigateTree(entry_id)) => {
3469 state.history_page.invalidate();
3470 dispatch_observed_session_event(
3471 reload_context,
3472 rpi_plugin_sdk::EventTag::SessionBeforeTree,
3473 )
3474 .await;
3475 match lane.navigate_tree(Some(&entry_id), false, None, None).await {
3476 Ok(result) => match result.outcome {
3477 rpi_harness::agent_harness::NavigationOutcome::Completed { .. } => {
3478 state.reset_session_state();
3479 chat_container.clear();
3480 let (tools, skills, context_files) =
3481 current_capabilities(harness, &lane).await;
3482 add_welcome_message_with_capabilities(
3483 &state.history_page.header,
3484 &tools,
3485 &skills,
3486 &context_files,
3487 );
3488 history::restore(harness, &state, &chat_container).await;
3489 dispatch_observed_session_event(
3490 reload_context,
3491 rpi_plugin_sdk::EventTag::SessionTree,
3492 )
3493 .await;
3494 add_note_message(
3495 &state.notice_container(),
3496 "Moved to the selected session entry.",
3497 );
3498 }
3499 rpi_harness::agent_harness::NavigationOutcome::Failed { error, .. } => {
3500 add_error_message(&state.notice_container(), &error.message);
3501 }
3502 _ => add_note_message(
3503 &state.notice_container(),
3504 "The selected entry could not be opened.",
3505 ),
3506 },
3507 Err(error) => add_error_message(
3508 &state.notice_container(),
3509 &format!("Could not navigate session tree: {error}"),
3510 ),
3511 }
3512 tui.request_render(false);
3513 }
3514 Some(TuiMessage::ClearChat) => {
3515 // `/new` starts a genuinely new session instead of only wiping
3516 // the transcript: the harness swaps its JSONL backing, the
3517 // banner is rebuilt from the real capability snapshot, and the
3518 // footer counters are reset.
3519 dispatch_observed_session_event(
3520 reload_context,
3521 rpi_plugin_sdk::EventTag::SessionBeforeSwitch,
3522 )
3523 .await;
3524 start_new_session(
3525 harness,
3526 &lane,
3527 &cwd,
3528 &chat_container,
3529 &state,
3530 &reload_context.tool_context,
3531 )
3532 .await;
3533 tui.request_render(false);
3534 }
3535 Some(TuiMessage::Compact) => {
3536 dispatch_observed_session_event(
3537 reload_context,
3538 rpi_plugin_sdk::EventTag::SessionBeforeCompact,
3539 )
3540 .await;
3541 if run_compact(&lane, &tui, &state).await {
3542 dispatch_observed_session_event(
3543 reload_context,
3544 rpi_plugin_sdk::EventTag::SessionCompact,
3545 )
3546 .await;
3547 }
3548 }
3549 Some(TuiMessage::Copy) => {
3550 copy_last_assistant(&state);
3551 tui.request_render(false);
3552 }
3553 Some(TuiMessage::Exit) => {
3554 *running.lock().unwrap() = false;
3555 break;
3556 }
3557 Some(TuiMessage::SwitchSession(id)) => {
3558 dispatch_observed_session_event(
3559 reload_context,
3560 rpi_plugin_sdk::EventTag::SessionBeforeSwitch,
3561 )
3562 .await;
3563 switch_to_session(
3564 SessionLane {
3565 harness,
3566 lane: &lane,
3567 },
3568 &id,
3569 &cwd,
3570 &chat_container,
3571 &state,
3572 &reload_context.tool_context,
3573 &reload_context.catalog,
3574 )
3575 .await;
3576 tui.request_render(false);
3577 }
3578 Some(TuiMessage::ImportSession(path)) => {
3579 dispatch_observed_session_event(
3580 reload_context,
3581 rpi_plugin_sdk::EventTag::SessionBeforeSwitch,
3582 )
3583 .await;
3584 import_session(
3585 SessionLane {
3586 harness,
3587 lane: &lane,
3588 },
3589 &path,
3590 &cwd,
3591 &chat_container,
3592 &state,
3593 &reload_context.tool_context,
3594 &reload_context.catalog,
3595 )
3596 .await;
3597 tui.request_render(false);
3598 }
3599 Some(TuiMessage::ShareSession) => {
3600 share_session(harness, &state.notice_container()).await;
3601 tui.request_render(false);
3602 }
3603 Some(TuiMessage::SetSessionName(name)) => {
3604 let outcome = harness.session().set_name(Some(&name)).await;
3605 match outcome {
3606 Ok(_) => {
3607 // Line 1 of the footer renders `session_name`, but nothing
3608 // in production ever wrote it — the slot was always empty
3609 // and `/name` looked like a no-op on screen.
3610 state.footer.set_session_name(Some(&name));
3611 add_note_message(
3612 &state.notice_container(),
3613 &format!("Session renamed to \"{name}\"."),
3614 );
3615 }
3616 Err(e) => add_error_message(
3617 &state.notice_container(),
3618 &format!("Could not rename session: {e}"),
3619 ),
3620 }
3621 tui.request_render(false);
3622 }
3623 Some(TuiMessage::ExportSession) => {
3624 let file_name = agent_session
3625 .default_export_file_name(crate::export::ExportFormat::Markdown)
3626 .await;
3627 let path = cwd.join(&file_name);
3628 match agent_session.export_to_markdown(&path).await {
3629 Ok(_) => add_note_message(
3630 &state.notice_container(),
3631 &format!("Exported session to {}", path.display()),
3632 ),
3633 Err(e) => add_error_message(
3634 &state.notice_container(),
3635 &format!("Could not write export: {e}"),
3636 ),
3637 }
3638 tui.request_render(false);
3639 }
3640 Some(TuiMessage::ExportSessionWithFormat(format)) => {
3641 let file_name = agent_session.default_export_file_name(format.clone()).await;
3642 let path = cwd.join(&file_name);
3643 match agent_session.export(format, &path).await {
3644 Ok(_) => add_note_message(
3645 &state.notice_container(),
3646 &format!("Exported session to {}", path.display()),
3647 ),
3648 Err(e) => add_error_message(
3649 &state.notice_container(),
3650 &format!("Could not write export: {e}"),
3651 ),
3652 }
3653 tui.request_render(false);
3654 }
3655 Some(TuiMessage::NativeDurable(args)) => {
3656 match crate::native_durable::interactive_command(agent_session.harness(), &args)
3657 .await
3658 {
3659 Ok(text) => add_note_message(&state.notice_container(), &text),
3660 Err(text) => add_error_message(&state.notice_container(), &text),
3661 }
3662 tui.request_render(false);
3663 }
3664 Some(TuiMessage::ShowUsage) => {
3665 let stats = agent_session.usage_stats().await.ok();
3666 let total = agent_session.total_usage().await.ok();
3667 let snapshot = agent_session.snapshot().await.ok();
3668 match stats {
3669 Some(stats) => {
3670 let mut lines = vec![
3671 "## Usage".to_string(),
3672 String::new(),
3673 format!("- messages: {}", stats.message_count),
3674 format!("- total tokens: {}", stats.total_tokens),
3675 format!("- cached tokens: {}", stats.cached_tokens),
3676 format!("- uncached tokens: {}", stats.uncached_tokens),
3677 format!("- cost: ${:.4}", stats.cost_total),
3678 ];
3679 match stats.cache_hit_ratio() {
3680 Some(ratio) => {
3681 lines.push(format!("- cache hit ratio: {:.1}%", ratio * 100.0))
3682 }
3683 None => lines.push("- cache hit ratio: n/a (no input yet)".to_string()),
3684 }
3685 if let Some(total) = total {
3686 lines.push(String::new());
3687 lines.push(format!(
3688 "- last cumulative input/output: {} / {}",
3689 total.input, total.output
3690 ));
3691 }
3692 if let Some(snapshot) = snapshot {
3693 lines.push(String::new());
3694 lines.push(format!("- lane: `{}`", snapshot.lane));
3695 lines.push(format!(
3696 "- leaf: `{}`",
3697 snapshot.leaf_id.clone().unwrap_or_else(|| "(empty)".into())
3698 ));
3699 if let Some(active) = &snapshot.active {
3700 lines.push(format!(
3701 "- active operation: {} (`{}`)",
3702 active.kind.as_str(),
3703 active.run_id
3704 ));
3705 }
3706 }
3707 add_note_message(&state.notice_container(), &lines.join("\n"));
3708 }
3709 None => add_error_message(
3710 &state.notice_container(),
3711 "Could not read session usage stats.",
3712 ),
3713 }
3714 tui.request_render(false);
3715 }
3716 Some(TuiMessage::ForkSession) => {
3717 dispatch_observed_session_event(
3718 reload_context,
3719 rpi_plugin_sdk::EventTag::SessionBeforeFork,
3720 )
3721 .await;
3722 fork_session(
3723 harness,
3724 &cwd,
3725 &chat_container,
3726 &state,
3727 &reload_context.tool_context,
3728 )
3729 .await;
3730 tui.request_render(false);
3731 }
3732 Some(TuiMessage::ProviderOAuthAction {
3733 provider,
3734 action,
3735 input,
3736 purpose,
3737 flow_id,
3738 cancel,
3739 }) => {
3740 // The flow ended (Esc, or a newer flow) before its call started.
3741 if state
3742 .provider_auth_flow_id
3743 .load(std::sync::atomic::Ordering::Acquire)
3744 != flow_id
3745 {
3746 continue;
3747 }
3748 let (snapshot, keepalive) = {
3749 let session = ctx
3750 .reload_context
3751 .extension_session
3752 .lock()
3753 .unwrap_or_else(|error| error.into_inner());
3754 (session.snapshot_arc(), session.keepalive())
3755 };
3756 let tx = ctx.tx.clone();
3757 let provider_result = provider.clone();
3758 let action_result = action.clone();
3759 tokio::spawn(async move {
3760 let result = match snapshot {
3761 Some(snapshot) => {
3762 let provider_call = provider.clone();
3763 let action_call = action.clone();
3764 tokio::task::spawn_blocking(move || {
3765 let _keepalive = keepalive;
3766 rpi_extensions::request_oauth_with_cancel(
3767 &snapshot,
3768 &provider_call,
3769 &action_call,
3770 input,
3771 &cancel,
3772 )
3773 .map_err(|error| error.to_string())
3774 })
3775 .await
3776 .map_err(|error| format!("OAuth worker failed: {error}"))
3777 .and_then(|result| result)
3778 }
3779 None => Err("no OAuth extensions are loaded".to_string()),
3780 };
3781 let _ = tx.send(TuiMessage::ProviderOAuthResult {
3782 provider: provider_result,
3783 action: action_result,
3784 result,
3785 purpose,
3786 flow_id,
3787 });
3788 });
3789 }
3790 Some(TuiMessage::ProviderOAuthResult {
3791 provider,
3792 action,
3793 result,
3794 purpose,
3795 flow_id,
3796 }) => {
3797 handle_provider_oauth_result(
3798 EditorUi {
3799 state: &state,
3800 editor_container: &editor_container,
3801 editor: &editor,
3802 tui: &tui,
3803 },
3804 &ctx.tx,
3805 &provider,
3806 &action,
3807 result,
3808 purpose,
3809 flow_id,
3810 );
3811 }
3812 Some(TuiMessage::LogoutProvider(provider)) => {
3813 let auth = match crate::config::read_auth() {
3814 Ok(auth) => auth,
3815 Err(error) => {
3816 add_error_message(
3817 &state.notice_container(),
3818 &format!("Could not read saved credentials: {error}"),
3819 );
3820 tui.request_render(false);
3821 continue;
3822 }
3823 };
3824 let credential = auth.get(&provider).cloned();
3825 match credential {
3826 Some(crate::config::Credential::Oauth {
3827 access, refresh, ..
3828 }) => {
3829 begin_provider_oauth_logout(
3830 &state,
3831 &editor_container,
3832 &editor,
3833 &tui,
3834 &ctx.tx,
3835 &provider,
3836 access,
3837 refresh,
3838 );
3839 }
3840 Some(crate::config::Credential::ApiKey { .. }) => {
3841 match crate::config::delete_credential(&provider) {
3842 Ok(true) => {
3843 add_note_message(
3844 &state.notice_container(),
3845 &format!("Removed saved credentials for {provider}; reloading providers…"),
3846 );
3847 let _ = ctx.tx.send(TuiMessage::ReloadExtensions);
3848 }
3849 Ok(false) => add_note_message(
3850 &state.notice_container(),
3851 &format!("No saved credentials found for {provider}."),
3852 ),
3853 Err(error) => add_error_message(
3854 &state.notice_container(),
3855 &format!("Could not remove {provider} credentials: {error}"),
3856 ),
3857 }
3858 tui.request_render(false);
3859 }
3860 None => {
3861 add_note_message(
3862 &state.notice_container(),
3863 &format!("No saved credentials found for {provider}."),
3864 );
3865 tui.request_render(false);
3866 }
3867 }
3868 }
3869 Some(TuiMessage::ReloadExtensions) => {
3870 // B5d: drive the shared reload routine on the async runtime,
3871 // then surface the outcome. `reload_context` was passed into
3872 // `interactive_tui` and is the same `Arc<ReloadContext>` the
3873 // `ReloadCommand` + the plugin mailbox both route through —
3874 // clone the `Arc` out so the borrow of `harness` (the main
3875 // loop's `&AgentHarness`) lives across the await.
3876 let reload_ctx = ctx.reload_context.clone();
3877 add_note_message(
3878 &state.notice_container(),
3879 "Reloading extensions + resources…",
3880 );
3881 tui.request_render(false);
3882 let outcome =
3883 crate::session::reload_extension_resources(harness, &reload_ctx).await;
3884 if !outcome.had_errors {
3885 if let Ok(resources) = harness.get_resources().await {
3886 update_resource_listing(
3887 &ctx.resources,
3888 ctx.startup_context.as_ref(),
3889 resources,
3890 );
3891 }
3892 }
3893 // B5e: the reload swapped a fresh `ExtensionSession` into the
3894 // context's cell. Rebuild the markdown transformer from that
3895 // fresh snapshot and install it on the in-flight streaming
3896 // component (so a reloaded plugin's transformer takes effect on
3897 // the visible message immediately) + future components (they
3898 // read `state.markdown_transformer()` at construction). The old
3899 // closure no-ops once its snapshot's `active` flag flips false
3900 // (reload already did that before the swap).
3901 let fresh_transformer = build_markdown_transformer(
3902 reload_ctx.extension_session.lock().unwrap().snapshot_arc(),
3903 );
3904 state.set_markdown_transformer_with_reinstall(fresh_transformer);
3905 // Rebuild the custom-theme registry: extension reloads can
3906 // change project trust (`/trust` flow) and the session cwd is
3907 // fixed per TUI, so re-resolve both. Use the policy this
3908 // reload actually resolved (`resolve_project_trust` over the
3909 // effective args), not the immutable startup snapshot;
3910 // after a hard failure the previous resources were kept, so
3911 // the previous registry stays untouched too. A broken theme
3912 // dir surfaces as a warning, never a reload failure.
3913 if !reload_ctx.args.no_themes {
3914 let mut rebuilt = None;
3915 if let Some(reload_trusted) = outcome.project_trusted {
3916 let (mut registry, diagnostics) =
3917 crate::themes::ThemeRegistry::discover(&reload_ctx.cwd, reload_trusted);
3918 let discovered = reload_ctx
3919 .discovered_theme_paths
3920 .lock()
3921 .map(|paths| paths.clone())
3922 .unwrap_or_default();
3923 registry.merge_discovered(&discovered);
3924 for diagnostic in &diagnostics {
3925 terminal.report(&format!("warning: {diagnostic}"), true);
3926 }
3927 // A reload can remove the active file theme (its package
3928 // went away or no longer returns the path); fall back to
3929 // the default preset with a notice instead of rendering
3930 // with a palette nothing can re-resolve.
3931 let active = state.active_theme_spec.lock().ok().and_then(|g| g.clone());
3932 if let Ok(mut guard) = state.theme_registry.write() {
3933 *guard = registry.clone();
3934 }
3935 if let Some(notice) = crate::themes::reconcile_after_reload(
3936 active.as_deref(),
3937 ®istry,
3938 &state.theme_manager,
3939 ) {
3940 add_note_message(&state.notice_container(), ¬ice);
3941 state.set_active_theme_spec(Some("dark".to_string()));
3942 }
3943 rebuilt = Some(registry);
3944 }
3945 // The registry may now resolve a different file for the
3946 // active name; re-target the watcher either way (with the
3947 // rebuilt registry when the reload completed, the previous
3948 // one after a hard failure kept the old resources).
3949 let registry = rebuilt.unwrap_or_else(|| {
3950 state
3951 .theme_registry
3952 .read()
3953 .map(|guard| guard.clone())
3954 .unwrap_or_default()
3955 });
3956 crate::themes::restart_theme_watcher(
3957 &state.theme_watcher,
3958 state.active_theme_spec().as_deref(),
3959 ®istry,
3960 &state.theme_manager,
3961 theme_watch_notify(&state, tui.clone()),
3962 );
3963 }
3964 if outcome.had_errors {
3965 // Hard failure: the summary itself carries the error detail
3966 // (e.g. "Settings reload failed: …"), so render it as an
3967 // error without an extra stderr pointer.
3968 add_error_message(&state.notice_container(), &outcome.summary);
3969 } else if outcome.had_warnings {
3970 // Reload succeeded but produced soft diagnostics (skill
3971 // shadowing, name validation, …). The details are printed
3972 // to stderr; keep this as an informational note so a
3973 // successful reload isn't shown as a red ✗ error.
3974 add_note_message(
3975 &state.notice_container(),
3976 &format!(
3977 "{} (with warnings — see stderr for details).",
3978 outcome.summary
3979 ),
3980 );
3981 } else {
3982 add_note_message(&state.notice_container(), &outcome.summary);
3983 }
3984 tui.request_render(false);
3985 }
3986 None => break,
3987 }
3988 }
3989
3990 // ---- Shutdown ----
3991 state.history_page.invalidate();
3992 let mut key_handle = Some(key_handle);
3993 let mut exit_code = 0;
3994 if args.native_durable || terminal.is_host() {
3995 // Stop the input producer before sealing the writers it admitted. Dialog
3996 // cancellation can unblock key work, and the streaming event consumer stays live through producer settlement.
3997 *running.lock().unwrap() = false;
3998 ask_user_bridge.shutdown();
3999 if key_handle.take().unwrap().await.is_err() {
4000 exit_code = 1;
4001 }
4002 if terminal.is_host() {
4003 state.cancel_user_bash();
4004 state.end_provider_auth();
4005 }
4006 }
4007 if args.native_durable {
4008 let _ = lane.abort_and_reconcile().await;
4009 if !settlement::settle_native(harness, state.session_write_tasks.seal()).await {
4010 terminal.report("[rpi] native TUI settlement failed", true);
4011 exit_code = 1;
4012 }
4013 } else {
4014 // Wait for session writers while the event consumer is still alive.
4015 if terminal.is_host() && !state.session_write_tasks.seal().join().await {
4016 exit_code = 1;
4017 }
4018 let _ = lane.wait_for_idle().await;
4019 lane.drain_session().await;
4020 }
4021
4022 ask_user_bridge.shutdown();
4023 *running.lock().unwrap() = false;
4024 for handle in update_check_handles {
4025 handle.abort();
4026 let _ = handle.await;
4027 }
4028 // The input worker checks `running` at least every 50ms. Join it before
4029 // restoring cooked mode so no late event read races terminal cleanup.
4030 if let Some(key_handle) = key_handle {
4031 let _ = key_handle.await;
4032 }
4033 tick_handle.abort();
4034 let _ = tick_handle.await;
4035 if let Some(handle) = drain_handle {
4036 handle.abort();
4037 let _ = handle.await;
4038 }
4039 // Drop the reload bridge: clearing the mailbox closes the signal channel,
4040 // the drain task's `recv` returns `None`, and the task exits. (Aborting is
4041 // redundant — the recv terminates — but cheap + makes shutdown explicit.)
4042 reload_context.mailbox.clear();
4043 reload_bridge_handle.abort();
4044 let _ = reload_bridge_handle.await;
4045 tui.stop(Default::default());
4046
4047 // upstream prints how to resume the session after an interactive exit so
4048 // a terminal that scrolled away can be recovered. Mirrors
4049 // `formatResumeCommand` (id + `--session-dir` only when non-default).
4050 let session_id = harness.session().storage().metadata().id;
4051 if let Some(command) = format_resume_command(&session_id, &cwd, Some(&state.session_dir)) {
4052 terminal.report(
4053 &format!("\x1b[2mTo resume this session:\x1b[0m {command}"),
4054 false,
4055 );
4056 }
4057 terminal.report("\nGoodbye!", false);
4058 if idle_expired.load(std::sync::atomic::Ordering::Acquire) {
4059 if let Some(timeout) = idle_timeout {
4060 terminal.report(
4061 &format!(
4062 "Host session closed after {} seconds of inactivity",
4063 timeout.as_secs()
4064 ),
4065 true,
4066 );
4067 exit_code = 1;
4068 }
4069 }
4070
4071 exit_code
4072}
4073
4074// ===========================================================================
4075// TUI support + entry detection
4076// ===========================================================================
4077
4078/// Check if the terminal supports TUI mode.
4079pub fn is_tui_supported() -> bool {
4080 std::io::stdout().is_terminal()
4081}
4082
4083// Keep the `Color` import used (theme accent rendering in autocomplete).
4084#[allow(unused_imports)]
4085use rpi_tui::Color as _Color;
4086
4087#[cfg(test)]
4088#[path = "interactive_tui/shutdown/experimental_dialog_failed_attach_tests.rs"]
4089mod experimental_dialog_failed_attach_tests;
4090#[cfg(test)]
4091#[path = "interactive_tui/shutdown/experimental_dialog_generation_tests.rs"]
4092mod experimental_dialog_generation_tests;
4093#[cfg(test)]
4094#[path = "interactive_tui/shutdown/experimental_dialog_reattachment_tests.rs"]
4095mod experimental_dialog_reattachment_tests;
4096#[cfg(test)]
4097#[path = "interactive_tui/shutdown/experimental_dialog_retirement_tests.rs"]
4098mod experimental_dialog_retirement_tests;
4099#[cfg(test)]
4100#[path = "interactive_tui/shutdown/experimental_dialog_startup_tests.rs"]
4101mod experimental_dialog_startup_tests;
4102#[cfg(test)]
4103#[path = "interactive_tui/shutdown/experimental_durable_tests.rs"]
4104mod experimental_durable_shutdown_tests;
4105#[cfg(test)]
4106#[path = "interactive_tui/shutdown/experimental_event_retirement_tests.rs"]
4107mod experimental_event_retirement_tests;
4108#[cfg(test)]
4109#[path = "interactive_tui/shutdown/experimental_reload_bridge_tests.rs"]
4110mod experimental_reload_bridge_tests;