trusty_code_tui/app/mod.rs
1//! The engine-agnostic render/reducer model: [`ReplApp`].
2//!
3//! Why: DOC-50 §3.2/§5 Slice 4 generalizes tagent's `ReplApp`
4//! (`crates/trusty-agents/src/repl/tui/types.rs`/`app.rs`) into the shape
5//! both `AgentEngine` (tagent) and `CodeEngine` (tcode) can render against
6//! without either product's semantics leaking into the shared crate. The
7//! original interleaves ~15 tagent-specific fields (OpenRouter cost
8//! tracking, TM/claude-mpm session counts, model/provider pickers, agent
9//! scope) with the genuinely generic chat/input/history/scroll state DOC-50
10//! §3.2 calls out for extraction — this module keeps only the latter.
11//! Product-specific data (statusline content, picker items, the
12//! slash-command table) flows in through the Slice-1/1.5 seam
13//! ([`crate::event::ReplEvent::StatuslineUpdate`], [`crate::model`]) instead
14//! of being hardcoded here, per the generalization mandate.
15//!
16//! What: [`ReplApp`] is the `M` the shared [`crate::run::event_loop`] drives
17//! (it implements [`crate::run::TuiModel`]). [`reduce::apply`] is the
18//! `apply: FnMut(&mut M, ReplEvent)` reducer half of that contract; this
19//! module owns the state and its primitive mutators (`insert_char`,
20//! `backspace`, `push_user`, `scroll`, …). Most are direct ports; a few
21//! (`Up`/`Down`/Ctrl-E key handling) are ports of tagent's REAL production
22//! behavior rather than its dead-code helpers — see the disclosure list
23//! below, which spells out every point (not just those) where this module's
24//! behavior differs from tagent's, since Slice 10's cutover plans against
25//! exactly this list. A product wiring `run()` (Slice 5+, tagent's eventual
26//! `AgentEngine`/tcode's `CodeEngine`) supplies its own product-specific
27//! fields (splash art, banner title, command table) via the public setters
28//! below rather than this crate special-casing either product.
29//!
30//! ## Disclosed behavioral differences from tagent (DOC-50 §5 Slice 4)
31//!
32//! Ported **faithfully** (same production behavior, verified against
33//! tagent's actual `keys.rs`/`app.rs`, not just its doc comments — one round
34//! of review on this slice caught a doc/reality drift in tagent itself, see
35//! history below):
36//! - Up-arrow recalls `Self::last_prompt` (the single most recent
37//! submission) and, when `Self::busy`, ALSO sets
38//! `Self::pending_cancel` — mirrors
39//! `crates/trusty-agents/src/repl/tui/keys.rs`'s real `KeyCode::Up` arm,
40//! not the multi-level `history_prev`/`history_next` `#[allow(dead_code)]`
41//! helpers tagent's own doc comment (misleadingly) attributes to
42//! production Up-handling.
43//! - Down-arrow calls `Self::history_next` — tagent's real `KeyCode::Down`
44//! arm does exactly this, even though nothing (including this crate's Up
45//! handler) ever sets `history_idx`, making it a functional no-op today in
46//! both tagent and here. Ported for fidelity, not because it currently
47//! does anything.
48//! - Ctrl-E, with an empty input buffer and a non-`None`
49//! `Self::last_bash_block`, pastes only that block's first non-blank
50//! line (not the whole block) — matches
51//! `crates/trusty-agents/src/repl/tui/keys.rs`'s `KeyCode::Char('e')` arm
52//! exactly (the REPL input is single-line; pasting a multi-line block
53//! would silently truncate at the first `\n` on submit).
54//! - The input composer's right-aligned `[thinking...]` label renders
55//! whenever `Self::busy` is true, REGARDLESS of whether the input
56//! buffer is empty — mirrors
57//! `crates/trusty-agents/src/repl/tui/chat.rs::draw_input`. `busy` is set
58//! `true` at submit time (not on the first streamed chunk), so the
59//! pre-first-token latency window after Enter also shows the indicator.
60//!
61//! Deliberately **NOT** ported (Phase 2 / later-slice / no-shared-crate-
62//! formula scope — not oversights):
63//! - The three-row animated activity panel (spinner cycling, elapsed timer,
64//! rust-rainbow shimmer, latest thinking-step echo —
65//! `repl/tui/layout.rs::draw_activity`, `repl/tui/status.rs`'s
66//! `SPINNER_FRAMES`/`rainbow_spans`/`hsl_to_rgb`). `busy: bool` is this
67//! crate's entire generalization of tagent's two-field
68//! `thinking: bool` + `busy_since: Option<Instant>` — there is no elapsed-
69//! time derivation available here (no stored start `Instant`).
70//! - Inline token counters in the input row and ALL cost/usage tracking
71//! (`tokens_in`/`tokens_out`, `daily_cost_start`, usage-file persistence,
72//! the OpenRouter pricing formula) — DOC-50 Q9: no cost formula belongs in
73//! the shared crate; cost is engine-supplied, pre-formatted, via
74//! [`crate::model::StatuslineSegment::Cost`].
75//! - Model/provider pickers (`PickerState`/`PickerKind`) and the inline
76//! LLM-offered/slash-completion choice list (`choices`/`choices_context`/
77//! `update_slash_completions`) — Phase 2 (DOC-50 §5 Slice 7 and later);
78//! [`crate::model::PickerItem`]/[`crate::model::PickerRequest`] exist
79//! (Slice 1.5) but no widget consumes them yet.
80//! - `AgentScope`'s User/Project cyan/yellow semantic — replaced by a plain
81//! `Self::accent_color` field with no "scope" concept; the engine
82//! decides what it means and when to change it.
83//! - The shared `trusty_common::banner` splash art, tagent's hardcoded
84//! banner title/identity text, and its fixed `/help`/`/connect`/`/clear`/
85//! `/status` command list — all now engine-supplied fields
86//! (`Self::banner_art`, `Self::banner_title`, [`Self::commands`](crate::commands),
87//! `Self::recent_activity`) rather than constants (this crate must not
88//! depend on `trusty_common`, see DOC-50 §2.2's dependency direction).
89//! - The literal `"[trusty-agents] "` status prefix and its exact idle-hint
90//! copy (`"Ask ctrl anything, or /connect <path> for project work"`) —
91//! generalized to `Self::status_prefix` (defaulted from `label`) and a
92//! generic [`crate::widgets::input_composer`] hint string respectively.
93//!
94//! Deliberately **DIVERGES** from tagent (Slice 5, DOC-50 §5 — an intentional
95//! improvement per spec, not an oversight or a parity gap):
96//! - **Ctrl-C cancels the in-flight request** (see `reduce::apply_key`'s
97//! `'c'` arm, staging `Self::pending_cancel` for `crate::run::run`'s
98//! dispatch step to relay as a real `TuiEngine::cancel_session` RPC).
99//! Tagent's actual Ctrl-c (`crates/trusty-agents/src/repl/tui/keys.rs`)
100//! only clears the input buffer — tagent's cancel trigger is Up-arrow
101//! while `thinking`. DOC-50 §5 Slice 5 specifies Ctrl-C as the cancel key
102//! (the conventional terminal interrupt), which this crate implements as
103//! written; Up-arrow-while-busy ALSO still signals cancel here (ported
104//! faithfully from tagent, see above), so both triggers work.
105//!
106//! # Spec References
107//! - [`SPEC-TTUI-03~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-03~draft) — §3.2, the generalization layer.
108//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 4 deliverable (§5, Slice 4): `ReplApp` state.
109
110mod reduce;
111
112pub use reduce::apply;
113
114use std::sync::Arc;
115use std::sync::atomic::AtomicUsize;
116
117use ratatui::style::Color;
118use ratatui::text::Line;
119
120use crate::event::WorkstreamSummary;
121use crate::model::{CommandDescriptor, PickerRequest, StatuslineSegment};
122use crate::run::TuiModel;
123use crate::text::{strip_interior_blank_lines, trim_surrounding_blank_lines};
124
125/// One rendered chat entry in the scrollback.
126///
127/// Why: a direct, unmodified port of tagent's `ChatLine`
128/// (`crates/trusty-agents/src/repl/tui/types.rs`) — already fully
129/// engine-agnostic (a role + a string), so no generalization was needed.
130#[derive(Debug, Clone)]
131pub struct ChatLine {
132 pub role: ChatRole,
133 pub text: String,
134}
135
136/// Source/role of a chat line — drives the leader glyph and color chosen by
137/// [`crate::widgets::scrollback::build_chat_lines`].
138///
139/// Why: a direct port of tagent's `ChatRole` — the four roles (who's
140/// speaking, or a system status line) are universal to any chat-shaped TUI,
141/// not specific to tagent's personas.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum ChatRole {
144 /// User input.
145 User,
146 /// Assistant/agent response.
147 Assistant,
148 /// An error response (rendered in the scrollback's error color).
149 Error,
150 /// An informational status line (e.g. "Connection lost", a tool
151 /// invocation notice).
152 Status,
153}
154
155/// All mutable state the shared render/event loop needs to draw one frame.
156///
157/// Why: kept separate from the render/event-loop machinery (mirroring
158/// tagent's original rationale) so unit tests can drive state transitions
159/// without a `Terminal`. See the module doc comment for what was
160/// deliberately left out of the generalized port.
161/// What: every field is `pub` (matching tagent's style — this is a plain
162/// data/mutator struct, not an encapsulated type) so a product binary can
163/// seed banner/branding fields at construction without a builder API.
164#[derive(Debug, Clone)]
165pub struct ReplApp {
166 /// Scrollback history of user/assistant/status exchanges.
167 pub chat: Vec<ChatLine>,
168 /// Current input line being edited.
169 pub input_buf: String,
170 /// Byte offset within `input_buf`.
171 pub cursor_pos: usize,
172 /// Number of lines scrolled up from the bottom (0 = pinned to newest).
173 pub scroll_offset: usize,
174 /// Last-rendered maximum scroll offset (published by the scrollback
175 /// widget each frame; `scroll()` clamps against it). `Arc` so a render
176 /// snapshot and the authoritative instance behind a caller's mutex (if
177 /// any) share the same cell — mirrors tagent's `last_max_scroll`.
178 pub last_max_scroll: Arc<AtomicUsize>,
179 /// In-memory input history (Up-arrow recall).
180 pub history: Vec<String>,
181 /// Index into `history` while navigating. `None` when not navigating.
182 pub history_idx: Option<usize>,
183 /// Saved current input while navigating history.
184 pub saved_input: Option<String>,
185 /// Whether to show the welcome banner in the scrollback.
186 pub show_banner: bool,
187 /// The name shown in the chat leader (`⏺ <label> · `) and the input
188 /// prompt (`<label>> `). Generic replacement for tagent's
189 /// `project_name` — any single display label a product wants there.
190 pub label: String,
191 /// The user's display name, shown in the banner's identity line.
192 pub user_label: String,
193 /// Accent color for the chat leader glyph and label. Generic replacement
194 /// for tagent's `AgentScope`-driven cyan/yellow — a product sets this to
195 /// whatever distinguishes its own contexts (or leaves the default).
196 pub accent_color: Color,
197 /// Prefix rendered before every [`ChatRole::Status`] line (e.g.
198 /// `"[tagent] "`). Defaults to `"[{label}] "` in [`ReplApp::new`];
199 /// override if a product wants different bracketed text than its
200 /// `label`.
201 pub status_prefix: String,
202 /// Banner title text (defaults to `label`).
203 pub banner_title: String,
204 /// Version string shown in the banner (defaults to this crate's own
205 /// version — a product should override with its own).
206 pub version: String,
207 /// Recent-activity lines shown in the banner's right column. Generic
208 /// replacement for tagent's `git_commits` — a product decides what
209 /// "recent activity" means for it (or supplies none).
210 pub recent_activity: Vec<String>,
211 /// Optional pre-rendered left-column art (e.g. a splash logo). Empty by
212 /// default — this crate has no branding assets of its own (see the
213 /// dependency-direction constraint in the crate-level doc comment: this
214 /// crate must not depend on a product-specific art asset).
215 pub banner_art: Vec<Line<'static>>,
216 /// Slash commands shown in the banner's "Commands" section, sourced from
217 /// [`crate::engine::TuiEngine::commands`] plus any client-side built-ins.
218 pub commands: Vec<CommandDescriptor>,
219 /// An inline picker currently open for selection (DOC-50 §3.2/§6 Q6),
220 /// staged by [`crate::commands::dispatch_forward`] when a bare `/name`
221 /// submission matches `TuiEngine::picker(name)`. `None` when no picker
222 /// is open. The picker WIDGET itself (navigation/rendering) is a
223 /// follow-up slice's concern (DOC-50 §5 Slice 7's deliverable scopes
224 /// "routing correctness", not the visual overlay); this field is the
225 /// data half of that contract.
226 pub active_picker: Option<PickerRequest>,
227 /// Whether a response is currently streaming in. Drives the input
228 /// composer's placeholder text.
229 pub busy: bool,
230 /// Index into `chat` of the in-progress streaming assistant entry, if
231 /// any. `None` when idle.
232 pub streaming_idx: Option<usize>,
233 /// Engine-supplied statusline segments, most recently pushed via
234 /// [`crate::event::ReplEvent::StatuslineUpdate`].
235 pub statusline: Vec<StatuslineSegment>,
236 /// The active workstream, most recently pushed via
237 /// [`crate::event::ReplEvent::WorkstreamUpdated`].
238 pub active_workstream: Option<WorkstreamSummary>,
239 /// Quit signal — set on Ctrl-D. Backs [`TuiModel::should_quit`].
240 pub quit: bool,
241 /// A line the user just submitted (typed Enter, or a synthesized
242 /// `ReplEvent::Submit`), staged for the outer driver to forward to
243 /// `TuiEngine::handle_input`. `apply` cannot reach the engine or the
244 /// event channel itself (see [`reduce`]'s doc comment), so — mirroring
245 /// tagent's `pending_picker_selection`/`pending_submit` pattern — it
246 /// stashes the line here instead. Drained (`Option::take`) by the
247 /// caller after each `apply` call.
248 pub pending_submit: Option<String>,
249 /// Set when the user pressed Ctrl-C. Drained by the caller, which should
250 /// call `TuiEngine::cancel_session` (thin-client axiom C-2 — cancellation
251 /// is the backend's job, not just clearing local UI state).
252 pub pending_cancel: bool,
253 /// The most recently submitted line, restored to `input_buf` on
254 /// Up-arrow. Direct port of tagent's `last_prompt` (single-level recall,
255 /// not the multi-level `history`/`history_idx` browser — see the module
256 /// doc comment's disclosure list for why Up uses this field and not
257 /// `history_prev`).
258 pub last_prompt: String,
259 /// The most recently seen executable-shell (bash/sh/zsh/fish) fenced
260 /// code block across all assistant messages, updated by
261 /// [`Self::update_last_bash_block`]. Ctrl-E pastes this block's first
262 /// non-blank line into an empty input buffer — direct port of tagent's
263 /// `last_bash_block` (`crates/trusty-agents/src/repl/tui/types.rs`).
264 pub last_bash_block: Option<String>,
265 /// The generation number of the turn currently considered "live" —
266 /// mirrors `crate::run::dispatch_pending`'s `AtomicU64` counter, updated
267 /// via [`TuiModel::set_current_generation`] on the SAME serial
268 /// event-loop task that owns that counter (never from a spawned task).
269 /// A `ReplEvent::TurnFinished { generation }` whose `generation` no
270 /// longer matches this field is a stale signal from a superseded turn
271 /// and is ignored — see that variant's doc comment for the TOCTOU race
272 /// this by-construction design closes (the comparison happens here, in
273 /// the reducer, serially — never as a spawned task's load-then-branch
274 /// against the shared counter).
275 pub current_generation: u64,
276}
277
278impl ReplApp {
279 /// Construct a fresh app with sensible generic defaults.
280 ///
281 /// Why: every field needs *some* value; the defaults chosen here (empty
282 /// scrollback, banner visible, cyan accent, no commands/art yet) mirror
283 /// tagent's `ReplApp::new` starting state minus the fields that didn't
284 /// survive generalization.
285 /// What: `label`/`user_label` seed both the derived `status_prefix` and
286 /// `banner_title` — override those two afterward if a product wants
287 /// different text than a straight derivation from `label`.
288 pub fn new(label: impl Into<String>, user_label: impl Into<String>) -> Self {
289 let label = label.into();
290 let status_prefix = format!("[{label}] ");
291 let banner_title = label.clone();
292 Self {
293 chat: Vec::new(),
294 input_buf: String::new(),
295 cursor_pos: 0,
296 scroll_offset: 0,
297 last_max_scroll: Arc::new(AtomicUsize::new(0)),
298 history: Vec::new(),
299 history_idx: None,
300 saved_input: None,
301 show_banner: true,
302 label,
303 user_label: user_label.into(),
304 accent_color: Color::Cyan,
305 status_prefix,
306 banner_title,
307 version: env!("CARGO_PKG_VERSION").to_string(),
308 recent_activity: Vec::new(),
309 banner_art: Vec::new(),
310 commands: Vec::new(),
311 active_picker: None,
312 busy: false,
313 streaming_idx: None,
314 statusline: Vec::new(),
315 active_workstream: None,
316 quit: false,
317 pending_submit: None,
318 pending_cancel: false,
319 last_prompt: String::new(),
320 last_bash_block: None,
321 current_generation: 0,
322 }
323 }
324
325 /// Append a user prompt line to the chat scrollback.
326 pub fn push_user(&mut self, text: impl Into<String>) {
327 self.chat.push(ChatLine {
328 role: ChatRole::User,
329 text: text.into(),
330 });
331 self.scroll_offset = 0;
332 }
333
334 /// Append an assistant response to the chat scrollback, trimming
335 /// surrounding and interior blank lines first.
336 ///
337 /// Why: assistant/agent responses regularly arrive with leading/trailing
338 /// blank lines and markdown-style `\n\n` paragraph breaks; rendering
339 /// them verbatim leaves visible dead space. See [`crate::text`] for the
340 /// two trimming passes.
341 /// Test: `reduce::tests::push_assistant_trims_surrounding_blanks`.
342 pub fn push_assistant(&mut self, text: impl Into<String>, is_error: bool) {
343 let role = if is_error {
344 ChatRole::Error
345 } else {
346 ChatRole::Assistant
347 };
348 let raw: String = text.into();
349 let trimmed = trim_surrounding_blank_lines(&raw);
350 let collapsed = strip_interior_blank_lines(&trimmed);
351 self.chat.push(ChatLine {
352 role,
353 text: collapsed,
354 });
355 self.scroll_offset = 0;
356 self.update_last_bash_block();
357 }
358
359 /// Rescan `self.chat` and refresh [`Self::last_bash_block`] with the
360 /// last executable-shell fenced block seen across all assistant
361 /// messages, newest-first. Direct port of tagent's
362 /// `ReplApp::update_last_bash_block`
363 /// (`crates/trusty-agents/src/repl/tui/app.rs`).
364 ///
365 /// Why: called after every chat mutation that could introduce or
366 /// obsolete a shell block ([`Self::push_assistant`], and the streaming
367 /// finalize path in [`reduce`]) so Ctrl-E's paste buffer never goes
368 /// stale relative to `chat`.
369 /// What: walks `chat` newest-to-oldest; the first [`ChatRole::Assistant`]
370 /// entry containing an executable shell fence wins (errors and user/
371 /// status entries are skipped — an error entry is never a paste source).
372 /// `None` when no assistant entry has one.
373 /// Test: `reduce::tests::push_assistant_updates_last_bash_block`,
374 /// `reduce::tests::push_assistant_skips_error_entries_for_bash_block`.
375 pub fn update_last_bash_block(&mut self) {
376 for entry in self.chat.iter().rev() {
377 if entry.role != ChatRole::Assistant {
378 continue;
379 }
380 if let Some(block) = crate::render::markdown::extract_last_shell_block(&entry.text) {
381 self.last_bash_block = Some(block);
382 return;
383 }
384 }
385 self.last_bash_block = None;
386 }
387
388 /// Append a status line (rendered with [`Self::status_prefix`]).
389 pub fn push_status(&mut self, text: impl Into<String>) {
390 self.chat.push(ChatLine {
391 role: ChatRole::Status,
392 text: text.into(),
393 });
394 self.scroll_offset = 0;
395 }
396
397 /// Clear the scrollback (backs `ReplEvent::ClearScrollback`, the shared
398 /// `/clear` built-in per DOC-50 §5 Slice 7).
399 pub fn clear_scrollback(&mut self) {
400 self.chat.clear();
401 self.streaming_idx = None;
402 self.scroll_offset = 0;
403 }
404
405 /// Open an inline picker (DOC-50 §3.2/§6 Q6), staged by
406 /// [`crate::commands::dispatch_forward`] for a bare command matching
407 /// `TuiEngine::picker(name)`.
408 pub fn open_picker(&mut self, request: PickerRequest) {
409 self.active_picker = Some(request);
410 }
411
412 /// Close the active picker without a selection (e.g. Esc). No-op if
413 /// none is open.
414 pub fn close_picker(&mut self) {
415 self.active_picker = None;
416 }
417
418 /// Confirm the picker item at `index`, closing the picker and returning
419 /// the composed `"{dispatch_command} {selected.id}"` line
420 /// ([`crate::commands::compose_selection`]) to resubmit — mirrors
421 /// [`crate::model::PickerRequest`]'s documented contract. Returns `None`
422 /// (leaving the picker untouched) when no picker is open or `index` is
423 /// out of range, so a stale/invalid confirmation is a no-op rather than
424 /// a panic.
425 /// Test: `crate::commands::tests::confirm_picker_selection_composes_and_closes`,
426 /// `crate::commands::tests::confirm_picker_selection_out_of_range_is_noop`.
427 pub fn confirm_picker_selection(&mut self, index: usize) -> Option<String> {
428 let request = self.active_picker.as_ref()?;
429 let selected = request.items.get(index)?;
430 let composed = crate::commands::compose_selection(request, selected);
431 self.active_picker = None;
432 Some(composed)
433 }
434
435 /// Push the current input onto history (with adjacent-duplicate dedup),
436 /// record it as [`Self::last_prompt`] (Up-arrow recall), echo it to the
437 /// scrollback, then route it (DOC-50 §5 Slice 7, §6 Q4): a recognized
438 /// built-in command ([`crate::commands::route`]) is applied inline and
439 /// never reaches an engine; anything else marks the app [`Self::busy`]
440 /// and stages it in [`Self::pending_submit`] for the caller to forward.
441 ///
442 /// Why: shared by the Enter-key path and a synthesized
443 /// `ReplEvent::Submit` (e.g. a picker confirmation, DOC-50 §3.2/§6 Q6)
444 /// so both go through one echo+route code path rather than duplicating
445 /// it — see [`reduce`]. Routing lives here rather than in `reduce`'s
446 /// `apply` because [`crate::commands::route`] is pure and needs no
447 /// `TuiEngine` handle (`apply` has none — see that module's doc
448 /// comment), so both submission paths get built-in short-circuiting for
449 /// free. `busy`/`pending_submit` are set ONLY for the non-built-in
450 /// (`Route::Forward`) case — a built-in never calls
451 /// `TuiEngine::handle_input`, so there is nothing to wait on and no
452 /// `AssistantOutput` will ever arrive to clear `busy` again. Setting
453 /// `busy` before any streamed chunk arrives (not on the first
454 /// `AssistantOutput` chunk) closes the pre-first-token latency window —
455 /// see the module doc comment's disclosure list.
456 ///
457 /// **A second turn cannot start while one is in flight**: if
458 /// [`Self::busy`] is already `true`, this whole function (routing
459 /// included) is a no-op — DOC-50 §5 Slice 5's "blocks user input until
460 /// cancel completes" requirement, made literal rather than reasoned
461 /// away. This is the authoritative guard (not just a UI nicety at the
462 /// call site): without it, a second `handle_input` task starts while the
463 /// first is still streaming, and with `streaming_idx` shared per-app
464 /// rather than per-task, the second task's chunks splice into the first
465 /// task's (now orphaned) chat entry — a real corruption bug this guard
466 /// closes at the source. Callers that want to preserve the user's typed
467 /// text when busy (the Enter-key path, [`reduce::apply_key`]) must check
468 /// `!app.busy` themselves BEFORE consuming the input buffer, since by
469 /// the time this function is reached the line is already taken out of
470 /// `input_buf` and would otherwise be silently lost, not just silently
471 /// ignored.
472 /// What: [`crate::commands::BuiltIn::Clear`] reuses
473 /// [`Self::clear_scrollback`] (the same effect
474 /// `ReplEvent::ClearScrollback` produces); [`crate::commands::BuiltIn::Quit`]
475 /// sets [`Self::quit`]; [`crate::commands::BuiltIn::Help`] renders
476 /// [`crate::commands::render_help`] (built-ins + [`Self::commands`]) as
477 /// a status line.
478 /// Test: [`crate::commands::tests::submit_line_builtin_clear_clears_scrollback`],
479 /// [`crate::commands::tests::submit_line_builtin_quit_sets_quit`],
480 /// [`crate::commands::tests::submit_line_builtin_help_lists_commands`],
481 /// [`crate::commands::tests::submit_line_forwards_non_builtin_and_marks_busy`],
482 /// [`reduce::tests::apply_enter_is_noop_while_busy_and_preserves_buffer`],
483 /// [`reduce::tests::apply_submit_event_is_noop_while_busy`].
484 pub(crate) fn submit_line(&mut self, line: String) {
485 if self.busy {
486 return;
487 }
488 self.remember_input(&line);
489 self.last_prompt = line.clone();
490 self.push_user(line.clone());
491 match crate::commands::route(&line) {
492 crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Clear) => {
493 self.clear_scrollback();
494 }
495 crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Quit) => {
496 self.quit = true;
497 }
498 crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Help) => {
499 self.push_status(crate::commands::render_help(&self.commands));
500 }
501 crate::commands::Route::Forward(forwarded) => {
502 self.busy = true;
503 self.pending_submit = Some(forwarded);
504 }
505 }
506 }
507
508 /// Push a line onto `history`, deduping an immediate repeat.
509 pub fn remember_input(&mut self, line: &str) {
510 if line.trim().is_empty() {
511 return;
512 }
513 if self.history.last().map(|s| s.as_str()) == Some(line) {
514 return;
515 }
516 self.history.push(line.to_string());
517 }
518
519 /// Set the input buffer + cursor in one shot (cursor moves to the end).
520 pub fn set_input(&mut self, s: String) {
521 self.cursor_pos = s.len();
522 self.input_buf = s;
523 }
524
525 /// Insert a single character at the cursor.
526 pub fn insert_char(&mut self, c: char) {
527 self.input_buf.insert(self.cursor_pos, c);
528 self.cursor_pos += c.len_utf8();
529 self.history_idx = None;
530 }
531
532 /// Backspace: delete the char before the cursor.
533 pub fn backspace(&mut self) {
534 if self.cursor_pos == 0 {
535 return;
536 }
537 let mut prev = self.cursor_pos - 1;
538 while prev > 0 && !self.input_buf.is_char_boundary(prev) {
539 prev -= 1;
540 }
541 self.input_buf.replace_range(prev..self.cursor_pos, "");
542 self.cursor_pos = prev;
543 }
544
545 /// Move the cursor left one char-boundary.
546 pub fn cursor_left(&mut self) {
547 if self.cursor_pos == 0 {
548 return;
549 }
550 let mut prev = self.cursor_pos - 1;
551 while prev > 0 && !self.input_buf.is_char_boundary(prev) {
552 prev -= 1;
553 }
554 self.cursor_pos = prev;
555 }
556
557 /// Move the cursor right one char-boundary.
558 pub fn cursor_right(&mut self) {
559 if self.cursor_pos >= self.input_buf.len() {
560 return;
561 }
562 let mut next = self.cursor_pos + 1;
563 while next < self.input_buf.len() && !self.input_buf.is_char_boundary(next) {
564 next += 1;
565 }
566 self.cursor_pos = next;
567 }
568
569 /// Up-arrow history navigation.
570 pub fn history_prev(&mut self) {
571 if self.history.is_empty() {
572 return;
573 }
574 let new_idx = match self.history_idx {
575 None => {
576 self.saved_input = Some(self.input_buf.clone());
577 self.history.len() - 1
578 }
579 Some(i) => i.saturating_sub(1),
580 };
581 self.history_idx = Some(new_idx);
582 let entry = self.history[new_idx].clone();
583 self.set_input(entry);
584 }
585
586 /// Down-arrow history navigation.
587 pub fn history_next(&mut self) {
588 let Some(i) = self.history_idx else { return };
589 if i + 1 >= self.history.len() {
590 let restore = self.saved_input.take().unwrap_or_default();
591 self.history_idx = None;
592 self.set_input(restore);
593 } else {
594 self.history_idx = Some(i + 1);
595 let entry = self.history[i + 1].clone();
596 self.set_input(entry);
597 }
598 }
599
600 /// Take the current input buffer and reset the editor state. Returns
601 /// `None` if the trimmed buffer was empty (nothing to submit).
602 pub fn take_input(&mut self) -> Option<String> {
603 let trimmed = self.input_buf.trim();
604 if trimmed.is_empty() {
605 return None;
606 }
607 let out = std::mem::take(&mut self.input_buf);
608 self.cursor_pos = 0;
609 self.history_idx = None;
610 self.saved_input = None;
611 Some(out)
612 }
613
614 /// Apply a scroll delta. Negative = older (up), positive = newer (down).
615 /// Clamps to `[0, last_max_scroll]` so mouse-wheel scroll-up can't
616 /// accumulate past the actual scrollback height.
617 pub fn scroll(&mut self, delta: isize) {
618 if delta < 0 {
619 self.scroll_offset = self.scroll_offset.saturating_add((-delta) as usize);
620 } else {
621 self.scroll_offset = self.scroll_offset.saturating_sub(delta as usize);
622 }
623 let cap = self
624 .last_max_scroll
625 .load(std::sync::atomic::Ordering::Relaxed);
626 if self.scroll_offset > cap {
627 self.scroll_offset = cap;
628 }
629 }
630}
631
632impl TuiModel for ReplApp {
633 fn should_quit(&self) -> bool {
634 self.quit
635 }
636
637 /// Drain [`Self::pending_submit`] — see `crate::run::dispatch_pending`
638 /// (private to `crate::run`, called from [`crate::run::run`]) for the
639 /// caller that reads this after every `apply` call.
640 fn take_pending_submit(&mut self) -> Option<String> {
641 self.pending_submit.take()
642 }
643
644 /// Drain-and-clear [`Self::pending_cancel`].
645 fn take_pending_cancel(&mut self) -> bool {
646 std::mem::replace(&mut self.pending_cancel, false)
647 }
648
649 /// Reset the in-flight-request UI state the moment a cancel is
650 /// dispatched (before the `TuiEngine::cancel_session` RPC even starts) —
651 /// direct parity with tagent's real cancel path, which resets
652 /// `thinking`/`busy_since` synchronously ahead of `h.abort()`
653 /// (`crates/trusty-agents/src/repl/tui/events.rs::process_event`). See
654 /// [`crate::run::TuiModel::on_cancelled`]'s doc comment for why this is
655 /// synchronous rather than waiting on the RPC.
656 /// What: clears [`Self::busy`] and abandons the in-progress streaming
657 /// entry index (a future response starts a fresh chat entry rather than
658 /// appending to one no more chunks will ever arrive for), then pushes a
659 /// "cancelled" status line.
660 /// Test: `reduce::tests::apply_ctrl_c_signals_pending_cancel` covers
661 /// the reducer half; `crate::run::tests` covers this method being
662 /// invoked from the dispatch step.
663 fn on_cancelled(&mut self) {
664 self.busy = false;
665 self.streaming_idx = None;
666 self.push_status("cancelled");
667 }
668
669 /// Record `generation` into [`Self::current_generation`] — see
670 /// [`crate::run::TuiModel::set_current_generation`]'s doc comment for
671 /// why this is called only from `dispatch_pending` on the serial
672 /// event-loop task, and [`ReplEvent::TurnFinished`](crate::ReplEvent::TurnFinished)'s doc comment for
673 /// the race this by-construction design closes.
674 /// Test: `reduce::tests::apply_turn_finished_with_stale_generation_is_ignored`,
675 /// `reduce::tests::apply_turn_finished_clears_busy_and_streaming_idx_without_touching_chat`.
676 fn set_current_generation(&mut self, generation: u64) {
677 self.current_generation = generation;
678 }
679}