Skip to main content

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, when `Self::busy`, sets `Self::pending_cancel` — mirrors
37//!   `crates/trusty-agents/src/repl/tui/keys.rs`'s real `KeyCode::Up` arm.
38//!   What Up RECALLS diverges (#8181, see the divergence list below).
39//! - Ctrl-E, with an empty input buffer and a non-`None`
40//!   `Self::last_bash_block`, pastes only that block's first non-blank
41//!   line (not the whole block) — matches
42//!   `crates/trusty-agents/src/repl/tui/keys.rs`'s `KeyCode::Char('e')` arm
43//!   exactly (the REPL input is single-line; pasting a multi-line block
44//!   would silently truncate at the first `\n` on submit).
45//! - The input composer's right-aligned `[thinking...]` label renders
46//!   whenever `Self::busy` is true, REGARDLESS of whether the input
47//!   buffer is empty — mirrors
48//!   `crates/trusty-agents/src/repl/tui/chat.rs::draw_input`. `busy` is set
49//!   `true` at submit time (not on the first streamed chunk), so the
50//!   pre-first-token latency window after Enter also shows the indicator.
51//!
52//! Deliberately **NOT** ported (Phase 2 / later-slice / no-shared-crate-
53//! formula scope — not oversights):
54//! - The three-row animated activity panel (spinner cycling, elapsed timer,
55//!   rust-rainbow shimmer, latest thinking-step echo —
56//!   `repl/tui/layout.rs::draw_activity`, `repl/tui/status.rs`'s
57//!   `SPINNER_FRAMES`/`rainbow_spans`/`hsl_to_rgb`). `busy: bool` is this
58//!   crate's entire generalization of tagent's two-field
59//!   `thinking: bool` + `busy_since: Option<Instant>` — there is no elapsed-
60//!   time derivation available here (no stored start `Instant`).
61//! - Inline token counters in the input row and ALL cost/usage tracking
62//!   (`tokens_in`/`tokens_out`, `daily_cost_start`, usage-file persistence,
63//!   the OpenRouter pricing formula) — DOC-50 Q9: no cost formula belongs in
64//!   the shared crate; cost is engine-supplied, pre-formatted, via
65//!   [`crate::model::StatuslineSegment::Cost`].
66//! - Model/provider pickers (`PickerState`/`PickerKind`) and the inline
67//!   LLM-offered/slash-completion choice list (`choices`/`choices_context`/
68//!   `update_slash_completions`) — Phase 2 (DOC-50 §5 Slice 7 and later);
69//!   [`crate::model::PickerItem`]/[`crate::model::PickerRequest`] exist
70//!   (Slice 1.5) but no widget consumes them yet.
71//! - `AgentScope`'s User/Project cyan/yellow semantic — replaced by a plain
72//!   `Self::accent_color` field with no "scope" concept; the engine
73//!   decides what it means and when to change it.
74//! - The shared `trusty_common::banner` splash art, tagent's hardcoded
75//!   banner title/identity text, and its fixed `/help`/`/connect`/`/clear`/
76//!   `/status` command list — all now engine-supplied fields
77//!   (`Self::banner_art`, `Self::banner_title`, [`Self::commands`](crate::commands),
78//!   `Self::recent_activity`) rather than constants (this crate must not
79//!   depend on `trusty_common`, see DOC-50 §2.2's dependency direction).
80//! - The literal `"[trusty-agents] "` status prefix and its exact idle-hint
81//!   copy (`"Ask ctrl anything, or /connect <path> for project work"`) —
82//!   generalized to `Self::status_prefix` (defaulted from `label`) and a
83//!   generic [`crate::widgets::input_composer`] hint string respectively.
84//!
85//! Deliberately **DIVERGES** from tagent (Slice 5, DOC-50 §5 — an intentional
86//! improvement per spec, not an oversight or a parity gap):
87//! - **Ctrl-C cancels the in-flight request** (see `reduce::apply_key`'s
88//!   `'c'` arm, staging `Self::pending_cancel` for `crate::run::run`'s
89//!   dispatch step to relay as a real `TuiEngine::cancel_session` RPC).
90//!   Tagent's actual Ctrl-c (`crates/trusty-agents/src/repl/tui/keys.rs`)
91//!   only clears the input buffer — tagent's cancel trigger is Up-arrow
92//!   while `thinking`. DOC-50 §5 Slice 5 specifies Ctrl-C as the cancel key
93//!   (the conventional terminal interrupt), which this crate implements as
94//!   written; Up-arrow-while-busy ALSO still signals cancel here (ported
95//!   faithfully from tagent, see above), so both triggers work.
96//! - **Up/Down walk the whole session's prompt history** (#8181). Tagent's
97//!   real `KeyCode::Up` arm recalls only `last_prompt` — one snapshot,
98//!   overwritten every submit — and its `KeyCode::Down` arm calls
99//!   `history_next` against a `history_idx` nothing ever sets, so Down is a
100//!   no-op there. This crate wires Up to `Self::history_prev` instead, which
101//!   makes both arms live: Up steps older through `Self::history`, Down
102//!   steps newer and restores the in-progress draft at the end. The
103//!   busy-cancel half of Up is unchanged.
104//!
105//! # Spec References
106//! - [`SPEC-TTUI-03~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-03~draft) — §3.2, the generalization layer.
107//! - [`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.
108
109mod reduce;
110
111pub use reduce::apply;
112
113use std::collections::HashMap;
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::{
122    CommandDescriptor, PendingPermission, PermissionAnswer, PermissionResponse, PickerRequest,
123    StatuslineSegment,
124};
125use crate::run::TuiModel;
126use crate::text::{strip_interior_blank_lines, trim_surrounding_blank_lines};
127
128/// The scrollback line a dispatched, not-yet-confirmed cancel shows (#8207).
129///
130/// Why: kept next to [`CANCELLED_STATUS`] so the one word that claims the run
131/// actually stopped is visibly separate from the one that only claims it was
132/// asked to.
133pub(crate) const CANCELLING_STATUS: &str = "cancelling…";
134
135/// The scrollback line a CONFIRMED stop shows (#8207) — the only cancel line
136/// in this crate that says the run is over.
137pub(crate) const CANCELLED_STATUS: &str = "cancelled";
138
139/// One rendered chat entry in the scrollback.
140///
141/// Why: a direct, unmodified port of tagent's `ChatLine`
142/// (`crates/trusty-agents/src/repl/tui/types.rs`) — already fully
143/// engine-agnostic (a role + a string), so no generalization was needed.
144#[derive(Debug, Clone)]
145pub struct ChatLine {
146    pub role: ChatRole,
147    pub text: String,
148    /// The tool call this entry renders as a card, if any (#4596). When
149    /// `Some`, the scrollback draws the card and ignores `text`; `role` still
150    /// places it — [`ChatRole::Status`] at top level, [`ChatRole::Delegated`]
151    /// inside a delegation block.
152    pub tool: Option<ToolCard>,
153}
154
155/// One tool call and its result, rendered as a single scrollback card
156/// (#4596).
157///
158/// Why: [`crate::event::ReplEvent::ToolInvocation`] arrives twice per call
159/// (start, then completion) sharing an `id`. Holding both halves in one value
160/// lets the reducer fill in one card instead of pushing two entries.
161/// What: `result` is `None` while the call is in flight. `args` keeps the
162/// start event's payload, because a completion event may carry `Null` args.
163/// Test: `reduce::tests::tool_invocation_result_merges_into_its_call_card`.
164#[derive(Debug, Clone, PartialEq)]
165pub struct ToolCard {
166    /// The engine-minted call id shared by the start and completion events.
167    pub id: String,
168    /// The invoked tool's name.
169    pub tool_name: String,
170    /// The call's arguments, as the start event carried them.
171    pub args: serde_json::Value,
172    /// The tool's output; `None` while the call is still running.
173    pub result: Option<String>,
174    /// The backend's own verdict that this call failed (#4596), copied from
175    /// [`crate::event::ReplEvent::ToolInvocation`]'s `failed`. `false` while
176    /// the call is still running.
177    pub failed: bool,
178    /// Whether the card draws as a one-line summary rather than its full
179    /// result body (#4596).
180    ///
181    /// Why: a successful `read_file` or `cargo test` buries the conversation
182    /// under dozens of rows nobody asked to re-read. A collapsed card keeps
183    /// the call visible and costs one row.
184    /// What: `false` while the call is in flight (the body is a single
185    /// `running…` row anyway); set by the reducer when the result lands —
186    /// `true` on success, `false` on an error, so a failure is never hidden.
187    /// Ctrl-O toggles it (`reduce::apply_key`).
188    pub collapsed: bool,
189}
190
191impl ToolCard {
192    /// Whether this call failed (#4596).
193    ///
194    /// Why: an error must be impossible to hide. An earlier revision read
195    /// the `FAILED:` / `ERROR:` prefix trusty-code writes into the result
196    /// text, which made a producer reword silently render a failed call as
197    /// a collapsed green `· ok` card. The verdict now travels as data —
198    /// [`crate::event::ReplEvent::ToolInvocation`]'s `failed` — and the
199    /// prefix is display text only.
200    /// What: [`Self::failed`], AND a result having arrived. A producer is
201    /// contracted to leave `failed` false on a start event; requiring the
202    /// result too means a slip there cannot paint an in-flight card red.
203    /// Test: `widgets::tool_card::tests::errored_card_renders_expanded_by_default`,
204    /// `widgets::tool_card::tests::failure_flag_alone_drives_the_error_render`,
205    /// `reduce::tests::tool_card_is_error_reads_the_event_failure_flag`.
206    pub fn is_error(&self) -> bool {
207        self.failed && self.result.is_some()
208    }
209}
210
211/// Source/role of a chat line — drives the leader glyph and color chosen by
212/// [`crate::widgets::scrollback::build_chat_lines`].
213///
214/// Why: a direct port of tagent's `ChatRole` — the four roles (who's
215/// speaking, or a system status line) are universal to any chat-shaped TUI,
216/// not specific to tagent's personas.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum ChatRole {
219    /// User input.
220    User,
221    /// Assistant/agent response.
222    Assistant,
223    /// An error response (rendered in the scrollback's error color).
224    Error,
225    /// An informational status line (e.g. "Connection lost"), or a
226    /// top-level tool card when the entry carries [`ChatLine::tool`].
227    Status,
228    /// The header or footer line framing one delegated sub-agent's block
229    /// (#7940). Rendered flush-left with its own glyph so the block's start
230    /// and end are scannable.
231    Delegation,
232    /// Output or a tool notice produced by a delegated sub-agent (#7940).
233    /// Rendered indented inside the [`ChatRole::Delegation`] frame above it.
234    Delegated,
235}
236
237/// One delegated sub-agent whose block is currently open in the scrollback
238/// (#7940).
239///
240/// Why: the reducer needs two things after a delegation starts — whether an
241/// arriving `(agent_id, turn_id)` stream belongs inside a delegation block,
242/// and which agent name the status line should show. Both are answered by
243/// this pair, kept in a `Vec` so the first-seen order is the display order.
244/// What: `agent_id` is the seam's opaque id (empty only for a producer that
245/// announced the delegation before the sub-agent existed — see
246/// [`crate::event::ReplEvent::DelegationStarted`]); `agent` is the display
247/// name.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct Delegation {
250    /// The opaque per-spawn agent id this block is keyed on.
251    pub agent_id: String,
252    /// The delegated agent's display name.
253    pub agent: String,
254}
255
256/// All mutable state the shared render/event loop needs to draw one frame.
257///
258/// Why: kept separate from the render/event-loop machinery (mirroring
259/// tagent's original rationale) so unit tests can drive state transitions
260/// without a `Terminal`. See the module doc comment for what was
261/// deliberately left out of the generalized port.
262/// What: every field is `pub` (matching tagent's style — this is a plain
263/// data/mutator struct, not an encapsulated type) so a product binary can
264/// seed banner/branding fields at construction without a builder API.
265#[derive(Debug, Clone)]
266pub struct ReplApp {
267    /// Scrollback history of user/assistant/status exchanges.
268    pub chat: Vec<ChatLine>,
269    /// Current input line being edited.
270    pub input_buf: String,
271    /// Byte offset within `input_buf`.
272    pub cursor_pos: usize,
273    /// Number of lines scrolled up from the bottom (0 = pinned to newest).
274    pub scroll_offset: usize,
275    /// Last-rendered maximum scroll offset (published by the scrollback
276    /// widget each frame; `scroll()` clamps against it). `Arc` so a render
277    /// snapshot and the authoritative instance behind a caller's mutex (if
278    /// any) share the same cell — mirrors tagent's `last_max_scroll`.
279    pub last_max_scroll: Arc<AtomicUsize>,
280    /// Every prompt submitted this session, oldest first, with adjacent
281    /// duplicates collapsed ([`Self::remember_input`]). Up/Down walk it
282    /// (#8181).
283    ///
284    /// Why: scoped to one TUI process deliberately. Persisting across
285    /// launches would need a store this crate cannot reach — it must not
286    /// depend on `trusty_common` (see the crate-level doc comment's
287    /// dependency-direction constraint) and has no product-specific state
288    /// directory of its own — so cross-launch history stays with whichever
289    /// product wants it, seeding this field at construction.
290    pub history: Vec<String>,
291    /// Index into `history` while navigating. `None` when not navigating.
292    pub history_idx: Option<usize>,
293    /// The in-progress draft stashed by [`Self::history_prev`]'s first step
294    /// and restored by [`Self::history_next`] at the newest end (#8181).
295    /// `None` when not navigating.
296    pub saved_input: Option<String>,
297    /// Whether to show the welcome banner in the scrollback.
298    pub show_banner: bool,
299    /// The name shown in the chat leader (`⏺ <label> · `) and the input
300    /// prompt (`<label>> `). Generic replacement for tagent's
301    /// `project_name` — any single display label a product wants there.
302    pub label: String,
303    /// The user's display name, shown in the banner's identity line.
304    pub user_label: String,
305    /// Accent color for the chat leader glyph and label. Generic replacement
306    /// for tagent's `AgentScope`-driven cyan/yellow — a product sets this to
307    /// whatever distinguishes its own contexts (or leaves the default).
308    pub accent_color: Color,
309    /// Prefix rendered before every [`ChatRole::Status`] line (e.g.
310    /// `"[tagent] "`). Defaults to `"[{label}] "` in [`ReplApp::new`];
311    /// override if a product wants different bracketed text than its
312    /// `label`.
313    pub status_prefix: String,
314    /// Banner title text (defaults to `label`).
315    pub banner_title: String,
316    /// Version string shown in the banner (defaults to this crate's own
317    /// version — a product should override with its own).
318    pub version: String,
319    /// Engine-supplied startup splash lines (#8164). Empty by default; when
320    /// non-empty they REPLACE the banner's generic `{banner_title}
321    /// v{version}` identity row rather than stacking above or below it, so a
322    /// product that knows its own launch facts states them once. Set from
323    /// [`crate::event::ReplEvent::SplashUpdated`], which is also where the
324    /// content contract lives.
325    pub splash: Vec<String>,
326    /// Recent-activity lines shown in the banner's right column. Generic
327    /// replacement for tagent's `git_commits` — a product decides what
328    /// "recent activity" means for it (or supplies none).
329    pub recent_activity: Vec<String>,
330    /// Optional pre-rendered left-column art (e.g. a splash logo). Empty by
331    /// default — this crate has no branding assets of its own (see the
332    /// dependency-direction constraint in the crate-level doc comment: this
333    /// crate must not depend on a product-specific art asset).
334    pub banner_art: Vec<Line<'static>>,
335    /// Slash commands shown in the banner's "Commands" section, sourced from
336    /// [`crate::engine::TuiEngine::commands`] plus any client-side built-ins.
337    pub commands: Vec<CommandDescriptor>,
338    /// An inline picker currently open for selection (DOC-50 §3.2/§6 Q6),
339    /// staged by [`crate::commands::dispatch_forward`] when a bare `/name`
340    /// submission matches `TuiEngine::picker(name)`. `None` when no picker
341    /// is open. The picker WIDGET itself (navigation/rendering) is a
342    /// follow-up slice's concern (DOC-50 §5 Slice 7's deliverable scopes
343    /// "routing correctness", not the visual overlay); this field is the
344    /// data half of that contract.
345    pub active_picker: Option<PickerRequest>,
346    /// The permission request currently blocking the turn (#3422), or `None`
347    /// when nothing is pending.
348    ///
349    /// Why: a suspended tool call is a second, independent reason input must
350    /// not be accepted — [`Self::busy`] cannot express it, because the
351    /// backend is stopped rather than working. `Self::submit_line` refuses
352    /// while this is `Some`, exactly as it refuses while `busy`, and
353    /// `reduce::apply_key` routes every key to the decision bindings.
354    /// What: set by [`crate::event::ReplEvent::PermissionRequested`], cleared
355    /// by a matching `PermissionResolved` or by the user answering.
356    pub pending_permission: Option<PendingPermission>,
357    /// An answer staged for the outer driver to relay to
358    /// [`crate::engine::TuiEngine::respond_permission`] (#3422). Drained by
359    /// [`TuiModel::take_pending_permission_response`], same as
360    /// [`Self::pending_submit`].
361    pub pending_permission_response: Option<PermissionResponse>,
362    /// Why the last answer to [`Self::pending_permission`] never reached the
363    /// backend (#3422), rendered as an inline retry line on the reopened
364    /// prompt; `None` on a prompt that has not been answered yet.
365    ///
366    /// Why: reopening the prompt alone would look like the backend asked
367    /// twice. The operator needs to know their answer was lost, not
368    /// re-asked, before choosing again.
369    /// What: set by [`crate::event::ReplEvent::PermissionAnswerFailed`],
370    /// cleared whenever the prompt is opened, answered, or resolved.
371    pub permission_error: Option<String>,
372    /// Whether a response is currently streaming in. Drives the input
373    /// composer's placeholder text.
374    pub busy: bool,
375    /// Whether a dispatched cancel is still unconfirmed (#8207).
376    ///
377    /// Why: the daemon's `session.cancel` only returns once the run has
378    /// actually stopped, and can answer "not stopped yet". Between the Ctrl-C
379    /// and that answer the turn may still be running, so the TUI shows a
380    /// cancelling state and accepts no new prompt — printing "cancelled" and
381    /// reopening input on request is what earned the next prompt a
382    /// `-32003 already has a task running` refusal in #8207's transcript.
383    /// What: set by [`TuiModel::on_cancel_requested`] when the cancel is
384    /// dispatched, cleared by [`crate::event::ReplEvent::CancelSettled`] on
385    /// every arm except [`crate::model::CancelReply::StillCancelling`], which
386    /// keeps it set because the run genuinely has not stopped. Read by
387    /// [`Self::accepts_submit`] and by
388    /// [`crate::widgets::input_composer`]'s label.
389    pub cancelling: bool,
390    /// Index into `chat` of the in-progress streaming assistant entry, if
391    /// any. `None` when idle.
392    pub streaming_idx: Option<usize>,
393    /// Delegated sub-agents whose scrollback block is currently open, in
394    /// first-seen order (#7940). Pushed by
395    /// [`crate::event::ReplEvent::DelegationStarted`], removed by
396    /// `DelegationFinished`. The last entry names the agent the status line
397    /// shows — see [`Self::active_agent`].
398    pub delegations: Vec<Delegation>,
399    /// Index into `chat` of the in-progress bubble for one `(agent_id,
400    /// turn_id)` stream (#7940). Separate from [`Self::streaming_idx`] —
401    /// which is the single unkeyed slot
402    /// [`crate::event::ReplEvent::AssistantOutput`] uses — precisely so two
403    /// agents streaming at once cannot land in one bubble.
404    pub agent_streams: HashMap<(String, String), usize>,
405    /// Index into `chat` of the card for each in-flight tool call, keyed by
406    /// the call's `id` (#4596). Inserted when a call starts; removed when its
407    /// result lands in that card.
408    pub tool_cards: HashMap<String, usize>,
409    /// Engine-supplied statusline segments, most recently pushed via
410    /// [`crate::event::ReplEvent::StatuslineUpdate`].
411    pub statusline: Vec<StatuslineSegment>,
412    /// The active workstream, most recently pushed via
413    /// [`crate::event::ReplEvent::WorkstreamUpdated`].
414    pub active_workstream: Option<WorkstreamSummary>,
415    /// Quit signal — set on Ctrl-D. Backs [`TuiModel::should_quit`].
416    pub quit: bool,
417    /// A line the user just submitted (typed Enter, or a synthesized
418    /// `ReplEvent::Submit`), staged for the outer driver to forward to
419    /// `TuiEngine::handle_input`. `apply` cannot reach the engine or the
420    /// event channel itself (see [`reduce`]'s doc comment), so — mirroring
421    /// tagent's `pending_picker_selection`/`pending_submit` pattern — it
422    /// stashes the line here instead. Drained (`Option::take`) by the
423    /// caller after each `apply` call.
424    pub pending_submit: Option<String>,
425    /// Set when the user pressed Ctrl-C. Drained by the caller, which should
426    /// call `TuiEngine::cancel_session` (thin-client axiom C-2 — cancellation
427    /// is the backend's job, not just clearing local UI state).
428    pub pending_cancel: bool,
429    /// The most recently submitted line. Direct port of tagent's
430    /// `last_prompt`, kept as a plain snapshot a product can read.
431    ///
432    /// Why: Up-arrow no longer reads it (#8181 moved recall to
433    /// [`Self::history`]/[`Self::history_idx`]); the field stays because it
434    /// is published API and costs one `String` clone per submit.
435    pub last_prompt: String,
436    /// The most recently seen executable-shell (bash/sh/zsh/fish) fenced
437    /// code block across all assistant messages, updated by
438    /// [`Self::update_last_bash_block`]. Ctrl-E pastes this block's first
439    /// non-blank line into an empty input buffer — direct port of tagent's
440    /// `last_bash_block` (`crates/trusty-agents/src/repl/tui/types.rs`).
441    pub last_bash_block: Option<String>,
442    /// The generation number of the turn currently considered "live" —
443    /// mirrors `crate::run::dispatch_pending`'s `AtomicU64` counter, updated
444    /// via [`TuiModel::set_current_generation`] on the SAME serial
445    /// event-loop task that owns that counter (never from a spawned task).
446    /// A `ReplEvent::TurnFinished { generation }` whose `generation` no
447    /// longer matches this field is a stale signal from a superseded turn
448    /// and is ignored — see that variant's doc comment for the TOCTOU race
449    /// this by-construction design closes (the comparison happens here, in
450    /// the reducer, serially — never as a spawned task's load-then-branch
451    /// against the shared counter).
452    pub current_generation: u64,
453}
454
455impl ReplApp {
456    /// Construct a fresh app with sensible generic defaults.
457    ///
458    /// Why: every field needs *some* value; the defaults chosen here (empty
459    /// scrollback, banner visible, cyan accent, no commands/art yet) mirror
460    /// tagent's `ReplApp::new` starting state minus the fields that didn't
461    /// survive generalization.
462    /// What: `label`/`user_label` seed both the derived `status_prefix` and
463    /// `banner_title` — override those two afterward if a product wants
464    /// different text than a straight derivation from `label`.
465    pub fn new(label: impl Into<String>, user_label: impl Into<String>) -> Self {
466        let label = label.into();
467        let status_prefix = format!("[{label}] ");
468        let banner_title = label.clone();
469        Self {
470            chat: Vec::new(),
471            input_buf: String::new(),
472            cursor_pos: 0,
473            scroll_offset: 0,
474            last_max_scroll: Arc::new(AtomicUsize::new(0)),
475            history: Vec::new(),
476            history_idx: None,
477            saved_input: None,
478            show_banner: true,
479            label,
480            user_label: user_label.into(),
481            accent_color: Color::Cyan,
482            status_prefix,
483            banner_title,
484            version: env!("CARGO_PKG_VERSION").to_string(),
485            splash: Vec::new(),
486            recent_activity: Vec::new(),
487            banner_art: Vec::new(),
488            commands: Vec::new(),
489            active_picker: None,
490            pending_permission: None,
491            pending_permission_response: None,
492            permission_error: None,
493            busy: false,
494            cancelling: false,
495            streaming_idx: None,
496            delegations: Vec::new(),
497            agent_streams: HashMap::new(),
498            tool_cards: HashMap::new(),
499            statusline: Vec::new(),
500            active_workstream: None,
501            quit: false,
502            pending_submit: None,
503            pending_cancel: false,
504            last_prompt: String::new(),
505            last_bash_block: None,
506            current_generation: 0,
507        }
508    }
509
510    /// Append a user prompt line to the chat scrollback.
511    pub fn push_user(&mut self, text: impl Into<String>) {
512        self.chat.push(ChatLine {
513            role: ChatRole::User,
514            text: text.into(),
515            tool: None,
516        });
517        self.scroll_offset = 0;
518    }
519
520    /// Append an assistant response to the chat scrollback, trimming
521    /// surrounding and interior blank lines first.
522    ///
523    /// Why: assistant/agent responses regularly arrive with leading/trailing
524    /// blank lines and markdown-style `\n\n` paragraph breaks; rendering
525    /// them verbatim leaves visible dead space. See [`crate::text`] for the
526    /// two trimming passes.
527    /// Test: `reduce::tests::push_assistant_trims_surrounding_blanks`.
528    pub fn push_assistant(&mut self, text: impl Into<String>, is_error: bool) {
529        let role = if is_error {
530            ChatRole::Error
531        } else {
532            ChatRole::Assistant
533        };
534        let raw: String = text.into();
535        let trimmed = trim_surrounding_blank_lines(&raw);
536        let collapsed = strip_interior_blank_lines(&trimmed);
537        self.chat.push(ChatLine {
538            role,
539            text: collapsed,
540            tool: None,
541        });
542        self.scroll_offset = 0;
543        self.update_last_bash_block();
544    }
545
546    /// Rescan `self.chat` and refresh [`Self::last_bash_block`] with the
547    /// last executable-shell fenced block seen across all assistant
548    /// messages, newest-first. Direct port of tagent's
549    /// `ReplApp::update_last_bash_block`
550    /// (`crates/trusty-agents/src/repl/tui/app.rs`).
551    ///
552    /// Why: called after every chat mutation that could introduce or
553    /// obsolete a shell block ([`Self::push_assistant`], and the streaming
554    /// finalize path in [`reduce`]) so Ctrl-E's paste buffer never goes
555    /// stale relative to `chat`.
556    /// What: walks `chat` newest-to-oldest; the first [`ChatRole::Assistant`]
557    /// entry containing an executable shell fence wins (errors and user/
558    /// status entries are skipped — an error entry is never a paste source).
559    /// `None` when no assistant entry has one.
560    /// Test: `reduce::tests::push_assistant_updates_last_bash_block`,
561    /// `reduce::tests::push_assistant_skips_error_entries_for_bash_block`.
562    pub fn update_last_bash_block(&mut self) {
563        for entry in self.chat.iter().rev() {
564            if entry.role != ChatRole::Assistant {
565                continue;
566            }
567            if let Some(block) = crate::render::markdown::extract_last_shell_block(&entry.text) {
568                self.last_bash_block = Some(block);
569                return;
570            }
571        }
572        self.last_bash_block = None;
573    }
574
575    /// Append a status line (rendered with [`Self::status_prefix`]).
576    pub fn push_status(&mut self, text: impl Into<String>) {
577        self.chat.push(ChatLine {
578            role: ChatRole::Status,
579            text: text.into(),
580            tool: None,
581        });
582        self.scroll_offset = 0;
583    }
584
585    /// Clear the scrollback (backs `ReplEvent::ClearScrollback`, the shared
586    /// `/clear` built-in per DOC-50 §5 Slice 7).
587    pub fn clear_scrollback(&mut self) {
588        self.chat.clear();
589        self.streaming_idx = None;
590        // #7940: both keyed-stream maps index INTO `chat`, so clearing it
591        // without clearing them would leave every key pointing at a stale
592        // (or out-of-range) row.
593        self.agent_streams.clear();
594        self.delegations.clear();
595        // #4596: same for the tool-call index map.
596        self.tool_cards.clear();
597        self.scroll_offset = 0;
598    }
599
600    /// The delegated agent whose work is currently in flight, if any
601    /// (#7940).
602    ///
603    /// Why: the status line shows "who is working right now"; that is the
604    /// most recently opened, not-yet-closed delegation, and it must revert
605    /// on its own when the block closes rather than needing the engine to
606    /// push a statusline update.
607    /// What: the last entry of [`Self::delegations`]; `None` when no
608    /// delegation is open.
609    /// Test: `delegation_started_pushes_header_and_sets_active_agent`,
610    /// `delegation_finished_pushes_footer_and_clears_active_agent`,
611    /// `build_statusline_appends_active_agent_while_delegating`.
612    pub fn active_agent(&self) -> Option<&str> {
613        self.delegations.last().map(|d| d.agent.as_str())
614    }
615
616    /// Expand or collapse the newest tool-call card in the scrollback
617    /// (#4596).
618    ///
619    /// Why: this TUI has no card-focus concept — nothing moves a selection
620    /// between scrollback entries — so "the focused card" is the most recent
621    /// one, which is also the one the user just watched arrive and the only
622    /// one still on screen at scroll offset 0. A focus ring would be a
623    /// bigger surface than the toggle it serves.
624    /// What: walks `chat` newest-first for the first entry carrying a
625    /// [`ChatLine::tool`] and flips its [`ToolCard::collapsed`]. No-op when
626    /// no card exists. Returns `true` when a card was toggled, so a caller
627    /// can tell "nothing to toggle" from "toggled".
628    /// Test: `reduce::tests::ctrl_o_toggles_the_newest_tool_card_round_trip`,
629    /// `reduce::tests::ctrl_o_is_a_noop_when_no_tool_card_exists`.
630    pub fn toggle_last_tool_card(&mut self) -> bool {
631        for entry in self.chat.iter_mut().rev() {
632            if let Some(card) = entry.tool.as_mut() {
633                card.collapsed = !card.collapsed;
634                return true;
635            }
636        }
637        false
638    }
639
640    /// Open an inline picker (DOC-50 §3.2/§6 Q6), staged by
641    /// [`crate::commands::dispatch_forward`] for a bare command matching
642    /// `TuiEngine::picker(name)`.
643    pub fn open_picker(&mut self, request: PickerRequest) {
644        self.active_picker = Some(request);
645    }
646
647    /// Close the active picker without a selection (e.g. Esc). No-op if
648    /// none is open.
649    pub fn close_picker(&mut self) {
650        self.active_picker = None;
651    }
652
653    /// Confirm the picker item at `index`, closing the picker and returning
654    /// the composed `"{dispatch_command} {selected.id}"` line
655    /// ([`crate::commands::compose_selection`]) to resubmit — mirrors
656    /// [`crate::model::PickerRequest`]'s documented contract. Returns `None`
657    /// (leaving the picker untouched) when no picker is open or `index` is
658    /// out of range, so a stale/invalid confirmation is a no-op rather than
659    /// a panic.
660    /// Test: `crate::commands::tests::confirm_picker_selection_composes_and_closes`,
661    /// `crate::commands::tests::confirm_picker_selection_out_of_range_is_noop`.
662    pub fn confirm_picker_selection(&mut self, index: usize) -> Option<String> {
663        let request = self.active_picker.as_ref()?;
664        let selected = request.items.get(index)?;
665        let composed = crate::commands::compose_selection(request, selected);
666        self.active_picker = None;
667        Some(composed)
668    }
669
670    /// Push the current input onto history (with adjacent-duplicate dedup),
671    /// record it as [`Self::last_prompt`] (Up-arrow recall), echo it to the
672    /// scrollback, then route it (DOC-50 §5 Slice 7, §6 Q4): a recognized
673    /// built-in command ([`crate::commands::route`]) is applied inline and
674    /// never reaches an engine; anything else marks the app [`Self::busy`]
675    /// and stages it in [`Self::pending_submit`] for the caller to forward.
676    ///
677    /// Why: shared by the Enter-key path and a synthesized
678    /// `ReplEvent::Submit` (e.g. a picker confirmation, DOC-50 §3.2/§6 Q6)
679    /// so both go through one echo+route code path rather than duplicating
680    /// it — see [`reduce`]. Routing lives here rather than in `reduce`'s
681    /// `apply` because [`crate::commands::route`] is pure and needs no
682    /// `TuiEngine` handle (`apply` has none — see that module's doc
683    /// comment), so both submission paths get built-in short-circuiting for
684    /// free. `busy`/`pending_submit` are set ONLY for the non-built-in
685    /// (`Route::Forward`) case — a built-in never calls
686    /// `TuiEngine::handle_input`, so there is nothing to wait on and no
687    /// `AssistantOutput` will ever arrive to clear `busy` again. Setting
688    /// `busy` before any streamed chunk arrives (not on the first
689    /// `AssistantOutput` chunk) closes the pre-first-token latency window —
690    /// see the module doc comment's disclosure list.
691    ///
692    /// **A second turn cannot start while one is in flight**: if
693    /// [`Self::busy`] is already `true`, this whole function (routing
694    /// included) is a no-op — DOC-50 §5 Slice 5's "blocks user input until
695    /// cancel completes" requirement, made literal rather than reasoned
696    /// away. This is the authoritative guard (not just a UI nicety at the
697    /// call site): without it, a second `handle_input` task starts while the
698    /// first is still streaming, and with `streaming_idx` shared per-app
699    /// rather than per-task, the second task's chunks splice into the first
700    /// task's (now orphaned) chat entry — a real corruption bug this guard
701    /// closes at the source. Callers that want to preserve the user's typed
702    /// text when busy (the Enter-key path, [`reduce::apply_key`]) must check
703    /// `!app.busy` themselves BEFORE consuming the input buffer, since by
704    /// the time this function is reached the line is already taken out of
705    /// `input_buf` and would otherwise be silently lost, not just silently
706    /// ignored.
707    /// What: [`crate::commands::BuiltIn::Clear`] reuses
708    /// [`Self::clear_scrollback`] (the same effect
709    /// `ReplEvent::ClearScrollback` produces); [`crate::commands::BuiltIn::Quit`]
710    /// sets [`Self::quit`]; [`crate::commands::BuiltIn::Help`] renders
711    /// [`crate::commands::render_help`] (built-ins + [`Self::commands`]) as
712    /// a status line.
713    /// Test: [`crate::commands::tests::submit_line_builtin_clear_clears_scrollback`],
714    /// [`crate::commands::tests::submit_line_builtin_quit_sets_quit`],
715    /// [`crate::commands::tests::submit_line_builtin_help_lists_commands`],
716    /// [`crate::commands::tests::submit_line_forwards_non_builtin_and_marks_busy`],
717    /// [`reduce::tests::apply_enter_while_busy_inserts_a_newline_instead_of_submitting`],
718    /// [`reduce::tests::queued_multi_line_type_ahead_submits_byte_identical_text`],
719    /// [`reduce::tests::apply_submit_event_is_noop_while_busy`],
720    /// [`reduce::tests::submit_line_is_noop_while_a_permission_prompt_is_pending`].
721    pub(crate) fn submit_line(&mut self, line: String) {
722        // #3422/#8207: a suspended permission request and an unconfirmed cancel
723        // block the turn for the same reason `busy` does — the backend will not
724        // accept new work — so all three live behind one predicate, and it is
725        // authoritative here rather than only at the key-handling call site.
726        if !self.accepts_submit() {
727            return;
728        }
729        self.remember_input(&line);
730        self.last_prompt = line.clone();
731        self.push_user(line.clone());
732        match crate::commands::route(&line) {
733            crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Clear) => {
734                self.clear_scrollback();
735            }
736            crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Quit) => {
737                self.quit = true;
738            }
739            crate::commands::Route::BuiltIn(crate::commands::BuiltIn::Help) => {
740                self.push_status(crate::commands::render_help(&self.commands));
741            }
742            crate::commands::Route::Forward(forwarded) => {
743                self.busy = true;
744                self.pending_submit = Some(forwarded);
745            }
746        }
747    }
748
749    /// Whether the backend can be handed a new turn right now (#8207).
750    ///
751    /// Why: three independent conditions mean "the backend will refuse new
752    /// work" — a turn in flight ([`Self::busy`]), a suspended permission
753    /// request ([`Self::pending_permission`]), and a dispatched cancel the
754    /// backend has not confirmed yet ([`Self::cancelling`]). They were checked
755    /// ad hoc in two places, so the cancel window was easy to add to one and
756    /// miss in the other; one predicate makes both call sites ask the same
757    /// question. The Enter key must consult it BEFORE taking the input buffer,
758    /// or the typed line is consumed and then dropped by
759    /// [`Self::submit_line`]'s own guard.
760    /// What: pure read, no mutation. `false` does not mean the keystroke is
761    /// lost — `reduce::apply_key` queues the typed text in the composer
762    /// instead (#8240). Not a link: it is a private free function in a private
763    /// module, which rustdoc cannot resolve at all under
764    /// `deny(rustdoc::broken_intra_doc_links)`.
765    /// Test: `reduce::tests::a_prompt_submitted_while_cancelling_is_not_dispatched`,
766    /// `reduce::tests::an_unsettled_cancel_keeps_input_closed_after_the_turn_finished_on_its_own`
767    /// (the only case where [`Self::cancelling`] is the deciding term — `busy`
768    /// closes the gate in the others),
769    /// `reduce::tests::apply_cancel_settled_stopped_reopens_input`.
770    pub fn accepts_submit(&self) -> bool {
771        !self.busy && !self.cancelling && self.pending_permission.is_none()
772    }
773
774    /// Answer the open permission prompt (#3422), staging the answer for the
775    /// outer driver and releasing the input block.
776    ///
777    /// Why: the prompt is modal, so it must close the moment the user
778    /// answers rather than waiting on the RPC — the same reasoning
779    /// [`TuiModel::on_cancel_requested`] documents for entering the cancelling
780    /// state ahead of the cancel RPC. A backend that is slow to confirm must
781    /// not leave the keyboard dead. The backend's own
782    /// [`crate::event::ReplEvent::PermissionResolved`] is what records the
783    /// outcome in the scrollback; this method records nothing, because the
784    /// TUI's belief about the decision is not evidence that it was applied.
785    /// What: no-op when no prompt is open. Otherwise takes the prompt and
786    /// stages [`Self::pending_permission_response`] carrying it whole, so a
787    /// relay that fails can hand the same request back (#3422 — see
788    /// [`crate::event::ReplEvent::PermissionAnswerFailed`]). Also clears
789    /// [`Self::permission_error`]: this attempt has not failed yet, and a
790    /// stale retry line must not survive onto it.
791    /// Test: `reduce::tests::permission_key_y_answers_allow_once`,
792    /// `reduce::tests::permission_key_a_answers_allow_for_session`,
793    /// `reduce::tests::permission_key_n_answers_deny`,
794    /// `reduce::tests::permission_unbound_key_leaves_the_prompt_pending`,
795    /// `crate::run::tests::dispatch_pending_permission_answer_failure_reopens_the_prompt`.
796    pub fn answer_permission(&mut self, answer: PermissionAnswer) {
797        let Some(pending) = self.pending_permission.take() else {
798            return;
799        };
800        self.permission_error = None;
801        self.pending_permission_response = Some(PermissionResponse { pending, answer });
802    }
803
804    /// Push a line onto [`Self::history`], deduping an immediate repeat
805    /// (readline's `ignoredups` convention, #8181).
806    ///
807    /// Why: submitting the same prompt twice in a row should cost one Up
808    /// press to recall, not two.
809    /// What: blank/whitespace-only lines are never recorded; a line equal to
810    /// the current newest entry is dropped. A repeat that is NOT adjacent is
811    /// kept, so the walk order still reflects what was actually run.
812    /// Test: `reduce::tests::consecutive_duplicate_submissions_are_stored_once`,
813    /// `reduce::tests::submitting_appends_to_history_and_resets_the_cursor`.
814    pub fn remember_input(&mut self, line: &str) {
815        if line.trim().is_empty() {
816            return;
817        }
818        if self.history.last().map(|s| s.as_str()) == Some(line) {
819            return;
820        }
821        self.history.push(line.to_string());
822    }
823
824    /// Set the input buffer + cursor in one shot (cursor moves to the end).
825    pub fn set_input(&mut self, s: String) {
826        self.cursor_pos = s.len();
827        self.input_buf = s;
828    }
829
830    /// Insert a single character at the cursor.
831    ///
832    /// Why: editing does NOT end history navigation (#8181). It used to
833    /// clear [`Self::history_idx`] while leaving [`Self::saved_input`] set,
834    /// so Up-then-type stranded the draft with no way back — and Backspace
835    /// and Ctrl-U never cleared it at all, making the same gesture behave
836    /// three ways. Readline's rule is the consistent one: the draft is
837    /// yours until you submit, and Down always walks back to it. Editing a
838    /// RECALLED entry still discards that edit when you navigate away;
839    /// per-entry edit buffers are not worth the state.
840    pub fn insert_char(&mut self, c: char) {
841        self.input_buf.insert(self.cursor_pos, c);
842        self.cursor_pos += c.len_utf8();
843    }
844
845    /// Backspace: delete the char before the cursor.
846    pub fn backspace(&mut self) {
847        if self.cursor_pos == 0 {
848            return;
849        }
850        let mut prev = self.cursor_pos - 1;
851        while prev > 0 && !self.input_buf.is_char_boundary(prev) {
852            prev -= 1;
853        }
854        self.input_buf.replace_range(prev..self.cursor_pos, "");
855        self.cursor_pos = prev;
856    }
857
858    /// Move the cursor left one char-boundary.
859    pub fn cursor_left(&mut self) {
860        if self.cursor_pos == 0 {
861            return;
862        }
863        let mut prev = self.cursor_pos - 1;
864        while prev > 0 && !self.input_buf.is_char_boundary(prev) {
865            prev -= 1;
866        }
867        self.cursor_pos = prev;
868    }
869
870    /// Move the cursor right one char-boundary.
871    pub fn cursor_right(&mut self) {
872        if self.cursor_pos >= self.input_buf.len() {
873            return;
874        }
875        let mut next = self.cursor_pos + 1;
876        while next < self.input_buf.len() && !self.input_buf.is_char_boundary(next) {
877            next += 1;
878        }
879        self.cursor_pos = next;
880    }
881
882    /// Up-arrow history navigation: step one entry older, saving the
883    /// in-progress draft on the first step (#8181).
884    ///
885    /// Why: the draft the user was typing must survive a walk through
886    /// history and come back when they walk forward past the newest entry —
887    /// losing it is the failure readline's `saved_input` slot exists to
888    /// prevent.
889    /// What: no-op on an empty history. The first step (`history_idx ==
890    /// None`) stashes `input_buf` into [`Self::saved_input`] and lands on the
891    /// newest entry; later steps move one older. At the oldest entry the key
892    /// does NOTHING rather than re-reading `history[0]` into the buffer —
893    /// since #8181 made editing keep you in history, a clamp that still
894    /// called `set_input` silently destroyed an in-place edit of the oldest
895    /// entry. The cursor moves to the end of a recalled line
896    /// ([`Self::set_input`]).
897    /// Test: `reduce::tests::apply_up_walks_back_through_submitted_prompts`,
898    /// `reduce::tests::apply_down_walks_forward_and_restores_the_draft`,
899    /// `reduce::tests::apply_up_clamps_at_the_oldest_entry`,
900    /// `reduce::tests::apply_up_at_the_oldest_entry_keeps_an_in_place_edit`.
901    pub fn history_prev(&mut self) {
902        if self.history.is_empty() {
903            return;
904        }
905        let new_idx = match self.history_idx {
906            None => {
907                self.saved_input = Some(self.input_buf.clone());
908                self.history.len() - 1
909            }
910            // #8181: the floor is a true no-op, not a re-recall.
911            Some(0) => return,
912            Some(i) => i - 1,
913        };
914        self.history_idx = Some(new_idx);
915        let entry = self.history[new_idx].clone();
916        self.set_input(entry);
917    }
918
919    /// Down-arrow history navigation: step one entry newer, restoring the
920    /// saved draft once past the newest entry (#8181).
921    ///
922    /// Why: the other half of [`Self::history_prev`]'s contract — walking
923    /// forward off the newest entry returns the user to what they were
924    /// typing, not to an empty line.
925    /// What: no-op when not navigating (`history_idx == None`), so Down on a
926    /// freshly typed line never clobbers it. Stepping past the newest entry
927    /// clears `history_idx` and restores [`Self::saved_input`] (empty string
928    /// when the draft was empty). Editing while navigating does not end
929    /// navigation — see [`Self::insert_char`] — so the draft survives
930    /// typing, Backspace and Ctrl-U alike.
931    /// Test: `reduce::tests::apply_down_walks_forward_and_restores_the_draft`,
932    /// `reduce::tests::apply_down_is_noop_when_not_navigating_history`,
933    /// `reduce::tests::editing_a_recalled_entry_still_leaves_down_the_draft`.
934    pub fn history_next(&mut self) {
935        let Some(i) = self.history_idx else { return };
936        if i + 1 >= self.history.len() {
937            let restore = self.saved_input.take().unwrap_or_default();
938            self.history_idx = None;
939            self.set_input(restore);
940        } else {
941            self.history_idx = Some(i + 1);
942            let entry = self.history[i + 1].clone();
943            self.set_input(entry);
944        }
945    }
946
947    /// Take the current input buffer and reset the editor state. Returns
948    /// `None` if the trimmed buffer was empty (nothing to submit).
949    pub fn take_input(&mut self) -> Option<String> {
950        let trimmed = self.input_buf.trim();
951        if trimmed.is_empty() {
952            return None;
953        }
954        let out = std::mem::take(&mut self.input_buf);
955        self.cursor_pos = 0;
956        self.history_idx = None;
957        self.saved_input = None;
958        Some(out)
959    }
960
961    /// Apply a scroll delta. Negative = older (up), positive = newer (down).
962    /// Clamps to `[0, last_max_scroll]` so mouse-wheel scroll-up can't
963    /// accumulate past the actual scrollback height.
964    pub fn scroll(&mut self, delta: isize) {
965        if delta < 0 {
966            self.scroll_offset = self.scroll_offset.saturating_add((-delta) as usize);
967        } else {
968            self.scroll_offset = self.scroll_offset.saturating_sub(delta as usize);
969        }
970        let cap = self
971            .last_max_scroll
972            .load(std::sync::atomic::Ordering::Relaxed);
973        if self.scroll_offset > cap {
974            self.scroll_offset = cap;
975        }
976    }
977}
978
979impl TuiModel for ReplApp {
980    fn should_quit(&self) -> bool {
981        self.quit
982    }
983
984    /// Drain [`Self::pending_submit`] — see `crate::run::dispatch_pending`
985    /// (private to `crate::run`, called from [`crate::run::run`]) for the
986    /// caller that reads this after every `apply` call.
987    fn take_pending_submit(&mut self) -> Option<String> {
988        self.pending_submit.take()
989    }
990
991    /// Drain-and-clear [`Self::pending_cancel`].
992    fn take_pending_cancel(&mut self) -> bool {
993        std::mem::replace(&mut self.pending_cancel, false)
994    }
995
996    /// Drain [`Self::pending_permission_response`] (#3422) — see
997    /// `crate::run::dispatch_pending` for the caller.
998    fn take_pending_permission_response(&mut self) -> Option<PermissionResponse> {
999        self.pending_permission_response.take()
1000    }
1001
1002    /// Enter the cancelling state the moment a cancel is dispatched (#8207).
1003    ///
1004    /// Why: this used to clear [`Self::busy`] and push "cancelled" here, ahead
1005    /// of the RPC — the bug in #8207. The daemon's cancel is cooperative, so
1006    /// on request the run may still be executing; saying "cancelled" and
1007    /// reopening input let the next prompt reach a daemon that still had a task
1008    /// running, and the user saw a raw
1009    /// `-32003 already has a task running` instead. `busy` therefore STAYS set
1010    /// until [`crate::event::ReplEvent::CancelSettled`] reports a confirmed
1011    /// stop, which is also what keeps #8240's queued-input behaviour covering
1012    /// the cancel window: keystrokes and Enter accumulate in the composer
1013    /// instead of starting a turn the backend would refuse.
1014    /// What: sets [`Self::cancelling`], abandons the in-progress streaming
1015    /// entry index (a later response starts a fresh chat entry rather than
1016    /// appending to one no more chunks will ever arrive for), and pushes a
1017    /// "cancelling…" status line. It deliberately reports no outcome — the
1018    /// TUI's belief about the cancel is not evidence the run stopped, the same
1019    /// reasoning [`Self::answer_permission`] records for a permission answer.
1020    /// Test: `reduce::tests::a_prompt_submitted_while_cancelling_is_not_dispatched`,
1021    /// `crate::run::tests::dispatch_pending_cancel_holds_input_until_the_reply_lands`.
1022    fn on_cancel_requested(&mut self) {
1023        self.cancelling = true;
1024        self.streaming_idx = None;
1025        self.push_status(CANCELLING_STATUS);
1026    }
1027
1028    /// Record `generation` into [`Self::current_generation`] — see
1029    /// [`crate::run::TuiModel::set_current_generation`]'s doc comment for
1030    /// why this is called only from `dispatch_pending` on the serial
1031    /// event-loop task, and [`ReplEvent::TurnFinished`](crate::ReplEvent::TurnFinished)'s doc comment for
1032    /// the race this by-construction design closes.
1033    /// Test: `reduce::tests::apply_turn_finished_with_stale_generation_is_ignored`,
1034    /// `reduce::tests::apply_turn_finished_clears_busy_and_streaming_idx_without_touching_chat`.
1035    fn set_current_generation(&mut self, generation: u64) {
1036        self.current_generation = generation;
1037    }
1038}