trusty_code_tui/app/reduce.rs
1//! [`apply`] — the `ReplApp` half of [`crate::run::event_loop`]'s
2//! `apply: FnMut(&mut M, ReplEvent)` contract.
3//!
4//! Why: Slice 4 (already on main) needed *some* `apply` closure so the
5//! widgets could be demonstrated against real key input before DOC-50 §5
6//! Slice 5 ("Event dispatch and line editing") landed as its own slice — it
7//! shipped the generic core: character insertion/deletion, cursor movement,
8//! history recall, and scroll. Slice 5 (this revision) completes the keymap
9//! to full parity with tagent's actual `crates/trusty-agents/src/repl/tui/keys.rs`
10//! (not its doc comments, which in at least one case — Up-arrow —
11//! misattribute production behavior to a dead-code helper) and wires
12//! [`ReplApp::pending_submit`]/[`ReplApp::pending_cancel`] through to
13//! `TuiEngine::handle_input`/`cancel_session` in [`crate::run::run`]. See
14//! [`crate::app`]'s module doc comment for the full disclosed-differences
15//! list. Tagent-specific extras (pickers, slash-completion, cost/token
16//! tracking) stay behind per the generalization mandate; line-editing
17//! features tagent's own `keys.rs` never had either (Ctrl-w word-delete, a
18//! kill-ring, word-motion) are deliberately NOT invented here — full parity
19//! means matching tagent, not exceeding it.
20//!
21//! What: `apply` cannot reach the event channel or the engine — it only has
22//! `&mut ReplApp` — so anything that would normally need to call
23//! `TuiEngine::handle_input`/`cancel_session` instead stages a signal on
24//! `ReplApp` ([`ReplApp::pending_submit`], [`ReplApp::pending_cancel`]) for
25//! the caller to drain after `apply` returns, mirroring tagent's own
26//! `pending_picker_selection`/`pending_cancel` precedent
27//! (`crates/trusty-agents/src/repl/tui/types.rs`). [`crate::run::run`]'s
28//! dispatch step is the actual drain point — see that module for the
29//! `engine.handle_input`/`engine.cancel_session` wiring and the
30//! `ReplEvent::Quit` round-trip an engine's `Ok(false)` needs to reach
31//! `ReplApp::quit`, since a spawned task can't reach `&mut ReplApp` directly.
32//!
33//! # Spec References
34//! - [`SPEC-TTUI-05~draft`](../../../docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 5 deliverable (§5, Slice 5): line-editor keymap + Ctrl-C daemon cancel.
35
36use super::ReplApp;
37use crate::event::{KeyCode, KeyInput, ReplEvent};
38use crate::text::{strip_interior_blank_lines, trim_surrounding_blank_lines};
39
40/// How many lines a Page-Up/Page-Down key press scrolls.
41const PAGE_SCROLL: isize = 10;
42
43/// Apply one [`ReplEvent`] to `app`, mutating it in place.
44///
45/// Why: a free function (rather than an `ReplApp` method) so it matches
46/// `crate::run::event_loop`'s `apply: impl FnMut(&mut M, ReplEvent)` shape
47/// exactly — a caller passes `trusty_code_tui::app::apply` directly as that
48/// argument.
49/// What: dispatches on every [`ReplEvent`] variant (see the module doc
50/// comment for what's out of scope). `Key` events are further dispatched by
51/// [`apply_key`].
52/// Test: `tests` below cover every variant this function actually changes
53/// state for.
54pub fn apply(app: &mut ReplApp, ev: ReplEvent) {
55 match ev {
56 ReplEvent::Key(key) => apply_key(app, key),
57 ReplEvent::Resize(_, _) => {
58 // No-op: ratatui reads the real terminal size on every `draw`;
59 // nothing in `ReplApp` caches a stale width/height to refresh.
60 }
61 ReplEvent::Scroll(delta) => app.scroll(delta),
62 ReplEvent::Submit(line) => app.submit_line(line),
63 ReplEvent::Cancel => app.pending_cancel = true,
64 ReplEvent::Quit => app.quit = true,
65 // `crate::run::dispatch_pending`'s completion safety net (see
66 // `ReplEvent::TurnFinished`'s doc comment for the stuck-`busy`
67 // deadlock this closes). Applied ONLY if `generation` still matches
68 // `app.current_generation` — a stale signal from a turn that was
69 // since cancelled/superseded is a no-op, by construction (this
70 // compare runs serially in the reducer, never as a spawned task's
71 // load-then-branch against the shared counter — see that variant's
72 // doc comment for the TOCTOU race this closes). When applied, it
73 // touches ONLY these two fields, never `chat`, so it can never push
74 // a stray blank entry.
75 ReplEvent::TurnFinished { generation } => {
76 if generation == app.current_generation {
77 app.busy = false;
78 app.streaming_idx = None;
79 }
80 }
81 ReplEvent::AssistantOutput {
82 chunk,
83 done,
84 is_error,
85 } => apply_assistant_output(app, chunk, done, is_error),
86 ReplEvent::ToolInvocation {
87 id: _,
88 tool_name,
89 args,
90 result,
91 } => match result {
92 None => app.push_status(format!("[TOOL] {tool_name}: {args}")),
93 Some(r) => app.push_status(format!("[RESULT] {r}")),
94 },
95 ReplEvent::StatusMessage(msg) => app.push_status(msg),
96 ReplEvent::ClearScrollback => app.clear_scrollback(),
97 ReplEvent::StatuslineUpdate(segments) => app.statusline = segments,
98 ReplEvent::WorkstreamUpdated(ws) => app.active_workstream = Some(ws),
99 ReplEvent::WorkstreamActivationChanged { new_active_id, .. } => {
100 if new_active_id.is_none() {
101 // The workstream was deactivated with no replacement active
102 // (DOC-48 §4.2/§4.3, a real daemon-published state — see this
103 // variant's own doc comment). `WorkstreamUpdated`'s payload
104 // is a concrete `WorkstreamSummary`, so it structurally
105 // CANNOT represent "no active workstream" — there is no
106 // follow-up `WorkstreamUpdated` to wait for here, unlike the
107 // `Some(new_id)` case below. This is the only place the
108 // indicator gets cleared; skipping it (as a prior revision
109 // did, treating this whole variant as an unconditional
110 // no-op) left the status line showing a stale workstream
111 // name forever after a deactivation.
112 app.active_workstream = None;
113 }
114 // A `Some(new_id)` activation: per
115 // `TuiEngine::subscribe_workstream_events`'s contract, the
116 // engine follows this with a `WorkstreamUpdated` carrying the
117 // full re-fetched summary — that event, not this one, is what
118 // sets the displayed name (this event alone names an id with no
119 // display name to show yet).
120 }
121 ReplEvent::ConnectionLost { reason } => {
122 app.push_status(format!("Connection lost: {reason}"))
123 }
124 }
125}
126
127/// Accumulate one streamed assistant-output chunk into the in-progress chat
128/// entry, finalizing (trim + role) it on `done`.
129///
130/// Why: split out of [`apply`] so the streaming state machine — "append to
131/// the open entry, or open a new one" — reads as its own unit.
132/// What: mirrors [`ReplApp::push_assistant`]'s trim/collapse pass, but only
133/// on the *finished* text (trimming mid-stream would strip a blank line the
134/// next chunk was about to fill back in). Also refreshes
135/// [`ReplApp::last_bash_block`] on finalize, same as `push_assistant`
136/// (Ctrl-E's paste buffer must not go stale just because a response arrived
137/// via streaming instead of a single push).
138/// Test: [`tests::apply_assistant_output_streams_into_one_entry`],
139/// [`tests::apply_assistant_output_finalizes_as_error_role`],
140/// [`tests::apply_assistant_output_refreshes_last_bash_block_on_finalize`].
141fn apply_assistant_output(app: &mut ReplApp, chunk: String, done: bool, is_error: bool) {
142 use crate::app::ChatRole;
143
144 match app.streaming_idx {
145 Some(idx) => {
146 if let Some(entry) = app.chat.get_mut(idx) {
147 entry.text.push_str(&chunk);
148 }
149 }
150 None => {
151 app.chat.push(super::ChatLine {
152 role: ChatRole::Assistant,
153 text: chunk,
154 });
155 app.streaming_idx = Some(app.chat.len() - 1);
156 }
157 }
158 app.busy = !done;
159 app.scroll_offset = 0;
160
161 if done
162 && let Some(idx) = app.streaming_idx.take()
163 && let Some(entry) = app.chat.get_mut(idx)
164 {
165 let trimmed = trim_surrounding_blank_lines(&entry.text);
166 entry.text = strip_interior_blank_lines(&trimmed);
167 if is_error {
168 entry.role = ChatRole::Error;
169 }
170 app.update_last_bash_block();
171 }
172}
173
174/// Dispatch one translated key press to the appropriate `ReplApp` mutator.
175///
176/// Why: split out of [`apply`] so the (long, mechanical) key-by-key match
177/// reads as its own unit, matching tagent's `keys.rs::handle_key` precedent
178/// in spirit (though deliberately smaller — see the module doc comment for
179/// what's deferred to Slice 5).
180/// What: printable chars insert; Backspace/Left/Right/Home/End edit/move;
181/// PageUp/PageDown scroll a page; Enter submits; Ctrl-a/u/c/d match the
182/// readline bindings DOC-50 §5 Slice 5 specifies. Up, Down, and Ctrl-E are
183/// direct ports of tagent's real `keys.rs` bindings rather than a Slice-5
184/// invention — see [`apply_up`] and [`apply_ctrl_e`] for why they're pulled
185/// into their own functions. Any other key (Tab, Esc, Delete,
186/// `KeyCode::Other`) is a no-op — those are slash-completion/picker-
187/// navigation concerns this slice doesn't own.
188/// Test: [`tests`] below, one per binding.
189fn apply_key(app: &mut ReplApp, key: KeyInput) {
190 let ctrl = key.modifiers.ctrl;
191 match key.code {
192 KeyCode::Char(c) if ctrl => match c {
193 'a' => app.cursor_pos = 0,
194 'e' => apply_ctrl_e(app),
195 'u' => {
196 app.input_buf.clear();
197 app.cursor_pos = 0;
198 }
199 'c' => app.pending_cancel = true,
200 // Direct port of tagent's real `KeyCode::Char('d')` arm
201 // (`crates/trusty-agents/src/repl/tui/keys.rs`): Ctrl-D only
202 // quits on an EMPTY input buffer (the readline EOF convention);
203 // with text still in the buffer it's a no-op in tagent too (no
204 // forward-delete fallback), so this stays a plain guard rather
205 // than growing new behavior tagent doesn't have.
206 'd' if app.input_buf.is_empty() => app.quit = true,
207 _ => {}
208 },
209 KeyCode::Char(c) => app.insert_char(c),
210 KeyCode::Backspace => app.backspace(),
211 KeyCode::Left => app.cursor_left(),
212 KeyCode::Right => app.cursor_right(),
213 KeyCode::Home => app.cursor_pos = 0,
214 KeyCode::End => app.cursor_pos = app.input_buf.len(),
215 KeyCode::Up => apply_up(app),
216 // Direct port of tagent's real `KeyCode::Down` arm
217 // (`crates/trusty-agents/src/repl/tui/keys.rs`), which calls
218 // `history_next()` even though nothing (including `apply_up` below)
219 // ever sets `history_idx` — a functional no-op today in tagent too.
220 // Kept for fidelity per `crate::app`'s disclosure list, not because
221 // it currently does anything observable.
222 KeyCode::Down => app.history_next(),
223 KeyCode::PageUp => app.scroll(-PAGE_SCROLL),
224 KeyCode::PageDown => app.scroll(PAGE_SCROLL),
225 // Gated on `!app.busy` BEFORE `take_input()` runs (not just inside
226 // `submit_line`, which also guards): while a turn is in flight, the
227 // typed line stays in `input_buf` untouched rather than being taken
228 // out and then silently dropped by `submit_line`'s own guard — DOC-50
229 // §5 Slice 5's "blocks user input until cancel completes", made
230 // literal so a second turn genuinely cannot start (see
231 // `ReplApp::submit_line`'s doc comment for the corruption bug this
232 // closes).
233 KeyCode::Enter => {
234 if !app.busy
235 && let Some(line) = app.take_input()
236 {
237 app.submit_line(line);
238 }
239 }
240 KeyCode::Delete | KeyCode::Tab | KeyCode::Esc | KeyCode::Other => {}
241 }
242}
243
244/// Up-arrow: recall [`ReplApp::last_prompt`], and — while
245/// [`ReplApp::busy`] — ALSO signal [`ReplApp::pending_cancel`].
246///
247/// Why: direct port of tagent's real `KeyCode::Up` arm
248/// (`crates/trusty-agents/src/repl/tui/keys.rs`): a busy in-flight request
249/// gets cancelled so the user can edit and resubmit, and the cancel signal
250/// fires independent of whether `last_prompt` happens to be set (matching
251/// tagent's unconditional `if app.thinking { app.pending_cancel = true; }`
252/// ahead of the recall). This is NOT the multi-level `history_prev` browser
253/// — see `crate::app`'s module doc comment for why that helper stays
254/// unwired, exactly as it is in tagent.
255/// What: no-ops the recall half when `last_prompt` is empty (nothing to
256/// recall); the cancel signal is unconditional on `busy`.
257/// Test: [`tests::apply_up_recalls_last_prompt_when_idle`],
258/// [`tests::apply_up_signals_cancel_and_recalls_when_busy`],
259/// [`tests::apply_up_signals_cancel_even_with_no_last_prompt`],
260/// [`tests::apply_up_is_noop_when_idle_and_no_last_prompt`].
261fn apply_up(app: &mut ReplApp) {
262 if app.busy {
263 app.pending_cancel = true;
264 }
265 if !app.last_prompt.is_empty() {
266 let lp = app.last_prompt.clone();
267 app.set_input(lp);
268 }
269}
270
271/// Ctrl-E: with an empty input buffer and a cached
272/// [`ReplApp::last_bash_block`], paste that block's first non-blank line;
273/// otherwise (non-empty buffer, or no cached block) move the cursor to the
274/// end of the line.
275///
276/// Why: direct port of tagent's real `KeyCode::Char('e')` arm
277/// (`crates/trusty-agents/src/repl/tui/keys.rs`) — only the first line
278/// pastes because the REPL input is single-line; pasting a multi-line block
279/// verbatim would silently truncate at the first `\n` on submit.
280/// Test: [`tests::apply_ctrl_e_pastes_last_bash_block_when_input_empty`],
281/// [`tests::apply_ctrl_e_falls_back_to_end_of_line_when_input_nonempty`],
282/// [`tests::apply_ctrl_e_noop_when_no_block_and_input_empty`].
283fn apply_ctrl_e(app: &mut ReplApp) {
284 if app.input_buf.is_empty()
285 && let Some(block) = &app.last_bash_block
286 {
287 let first_line = block
288 .lines()
289 .find(|l| !l.trim().is_empty())
290 .unwrap_or("")
291 .to_string();
292 if !first_line.is_empty() {
293 app.input_buf = first_line;
294 app.cursor_pos = app.input_buf.len();
295 return;
296 }
297 }
298 app.cursor_pos = app.input_buf.len();
299}
300
301#[cfg(test)]
302mod tests;