Skip to main content

trusty_code_tui/widgets/
input_composer.rs

1//! The input composer row — generalized port of tagent's `chat.rs::draw_input`.
2//!
3//! Why: DOC-50 §5 Slice 4 migrates the borderless, Claude-Code-style prompt
4//! row. Generalization dropped tagent's inline token counters (`↑{in}
5//! ↓{out}`) — the same product-specific usage-tracking DOC-50 Q9 keeps out
6//! of the shared crate (no cost/usage formula here). Everything else —
7//! prompt label, the empty-buffer placeholder swapping busy/idle text, AND
8//! the right-aligned `[thinking...]` decoration — is a direct,
9//! width-aware port: tagent renders that decoration whenever `app.thinking`
10//! is true, REGARDLESS of whether the input buffer is empty (a user typing
11//! ahead while the agent is still responding still sees it). An earlier
12//! revision of this module only surfaced busy state through the empty-
13//! buffer placeholder, which silently dropped that case — see
14//! `crate::app`'s module doc comment for the full disclosure list.
15//!
16//! What: [`draw_input`] renders `"{label}> {input_or_placeholder}"` with the
17//! `[thinking...]` label right-aligned when `app.busy` and space allows, and
18//! positions the terminal cursor at the true edit position within the typed
19//! text.
20//!
21//! # Spec References
22//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 4 deliverable (§5, Slice 4): migrate the input composer.
23
24use ratatui::layout::Rect;
25use ratatui::style::{Modifier, Style};
26use ratatui::text::{Line, Span};
27use ratatui::widgets::Paragraph;
28
29use crate::app::ReplApp;
30
31/// Placeholder shown while idle with an empty input buffer.
32const IDLE_HINT: &str = "Ask anything, or /help for commands";
33
34/// Placeholder shown while busy with an empty input buffer.
35const BUSY_HINT: &str = "↑ to cancel";
36
37/// Right-aligned decoration shown whenever `app.busy`, independent of
38/// buffer contents — matches tagent's `thinking_label`.
39const BUSY_LABEL: &str = "[thinking...]";
40
41/// Right-aligned decoration that REPLACES [`BUSY_LABEL`] while a dispatched
42/// cancel is unconfirmed (#8207).
43///
44/// Why: the run is no longer thinking on the operator's behalf, it is being
45/// stopped, and the row is the only always-visible place that says so — the
46/// scrollback line scrolls away. Same bracket shape and width class as
47/// `[thinking...]`, so the padding math needs no special case.
48/// Test: `tests::draw_input_shows_cancelling_label_instead_of_thinking`.
49const CANCELLING_LABEL: &str = "[cancelling...]";
50
51/// Stand-in glyph for a newline queued into `input_buf` (#8240).
52///
53/// Why: a raw `\n` inside one ratatui `Span` renders as nothing, so
54/// type-ahead queued across an Enter would LOOK glued (`echo twoecho three`)
55/// even though the buffer holds the separator. Exactly one char wide, so
56/// [`compose_line`]'s cursor-column arithmetic stays a plain char count.
57const NEWLINE_GLYPH: char = '⏎';
58
59/// Render the input composer row into `area` and position the terminal
60/// cursor at the true edit position.
61///
62/// Why: a borderless single row (Claude Code style) — the `<label>> ` prompt
63/// is sufficient demarcation without spending a row on a border.
64/// What: empty input shows a dim italic placeholder (busy vs. idle hint);
65/// non-empty input renders the buffer with each queued newline shown as
66/// [`NEWLINE_GLYPH`] (#8240) and everything else verbatim; either way, a busy
67/// state additionally right-aligns `[thinking...]` — or `[cancelling...]` while
68/// a dispatched cancel is unconfirmed (#8207) — if the row is wide enough.
69/// The cursor is positioned by counting chars up to `app.cursor_pos`, not
70/// bytes, so multi-byte input doesn't desync the visual cursor from the true
71/// edit point — the glyph is one char for one `\n`, so that count is
72/// unaffected by the substitution.
73/// Test: `tests::draw_input_shows_idle_placeholder_when_empty`,
74/// `tests::draw_input_shows_queued_newlines_as_a_glyph` and
75/// friends exercise the pure text composition via [`compose_line`]; the
76/// `Frame`/cursor-position side effects are integration-level and covered by
77/// [`crate::layout::draw`]'s manual/visual verification.
78pub fn draw_input(f: &mut ratatui::Frame, app: &ReplApp, area: Rect) {
79    let (line, cursor_col_offset) = compose_line(app, area.width as usize);
80    let p = Paragraph::new(line);
81    f.render_widget(p, area);
82
83    let cursor_col = area.x + cursor_col_offset as u16;
84    let cursor_row = area.y;
85    f.set_cursor_position((cursor_col, cursor_row));
86}
87
88/// Pure composition of the input row's `Line` plus the cursor's column
89/// offset within it — split out from [`draw_input`] so the text/placeholder/
90/// busy-label logic is unit-testable without a `Frame`.
91///
92/// Why: `width` is needed (not just `app`) to replicate tagent's exact
93/// right-alignment math for `[thinking...]` — `crate::layout::draw` reserves
94/// a fixed 1-row height for this widget, so unlike the scrollback pane there
95/// is no pre-layout content-height query; `width` alone is what the padding
96/// calculation needs.
97fn compose_line(app: &ReplApp, width: usize) -> (Line<'static>, usize) {
98    let prompt = format!("{}> ", app.label);
99    let prompt_width = prompt.chars().count();
100
101    let mut spans: Vec<Span<'static>> = vec![Span::raw(prompt.clone())];
102    if app.input_buf.is_empty() {
103        // #8207: the cancel window is a held-input state too — `↑ to cancel`
104        // still reads correctly there, since a repeat gesture re-asks.
105        let placeholder = if app.accepts_submit() {
106            IDLE_HINT
107        } else {
108            BUSY_HINT
109        };
110        spans.push(Span::styled(
111            placeholder.to_string(),
112            Style::default()
113                .add_modifier(Modifier::DIM)
114                .add_modifier(Modifier::ITALIC),
115        ));
116    } else {
117        // #8240: display-only substitution — `input_buf` itself keeps the real
118        // `\n` so the submitted text stays byte-identical to what was typed.
119        spans.push(Span::raw(
120            app.input_buf.replace('\n', &NEWLINE_GLYPH.to_string()),
121        ));
122    }
123
124    let cursor_col = prompt_width + app.input_buf[..app.cursor_pos].chars().count();
125
126    // Right-aligned busy decoration — independent of whether the buffer is
127    // empty (matches tagent's `chat.rs::draw_input`: `used` is computed from
128    // `input_buf`'s real length, not the placeholder text, so both the
129    // empty-buffer placeholder AND this label can render together).
130    // #8207: an unconfirmed cancel outranks `busy` here — both are true during
131    // the cancel window, and "cancelling" is the state the operator needs.
132    if app.cancelling || app.busy {
133        let label = if app.cancelling {
134            CANCELLING_LABEL
135        } else {
136            BUSY_LABEL
137        };
138        let used = prompt_width + app.input_buf.chars().count();
139        let label_w = label.chars().count();
140        if width > used + label_w + 1 {
141            let pad = width - used - label_w;
142            spans.push(Span::raw(" ".repeat(pad)));
143            spans.push(Span::styled(
144                label,
145                Style::default().add_modifier(Modifier::DIM),
146            ));
147        }
148    }
149
150    (Line::from(spans), cursor_col)
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use crate::app::ReplApp;
157
158    /// Wide enough that the busy label's padding math never truncates it
159    /// away in tests that aren't specifically exercising the narrow-width
160    /// case.
161    const WIDE: usize = 120;
162
163    fn line_text(line: &Line<'_>) -> String {
164        line.spans.iter().map(|s| s.content.as_ref()).collect()
165    }
166
167    #[test]
168    fn draw_input_shows_idle_placeholder_when_empty() {
169        let app = ReplApp::new("demo", "u");
170        let (line, cursor) = compose_line(&app, WIDE);
171        assert!(line_text(&line).contains(IDLE_HINT));
172        assert_eq!(cursor, "demo> ".chars().count());
173    }
174
175    #[test]
176    fn draw_input_shows_busy_placeholder_when_empty_and_busy() {
177        let mut app = ReplApp::new("demo", "u");
178        app.busy = true;
179        let (line, _) = compose_line(&app, WIDE);
180        assert!(line_text(&line).contains(BUSY_HINT));
181    }
182
183    #[test]
184    fn draw_input_renders_typed_buffer_verbatim() {
185        let mut app = ReplApp::new("demo", "u");
186        app.set_input("hello".to_string());
187        let (line, cursor) = compose_line(&app, WIDE);
188        assert!(line_text(&line).contains("hello"));
189        assert_eq!(cursor, "demo> hello".chars().count());
190    }
191
192    /// #8240: a newline queued while a turn is in flight must be VISIBLE.
193    /// A raw `\n` inside a `Span` renders as nothing, so pre-fix this row
194    /// read `echo oneecho two` — the same glued text the bug reported. The
195    /// glyph is one char, so the cursor column stays a plain char count.
196    #[test]
197    fn draw_input_shows_queued_newlines_as_a_glyph() {
198        let mut app = ReplApp::new("demo", "u");
199        app.busy = true;
200        app.set_input("echo one\necho two".to_string());
201        let (line, cursor) = compose_line(&app, WIDE);
202        let text = line_text(&line);
203        assert!(!text.contains('\n'), "the composer is one row: {text:?}");
204        assert!(
205            text.contains("echo one⏎echo two"),
206            "the line break must render as a glyph: {text:?}"
207        );
208        assert_eq!(
209            app.input_buf, "echo one\necho two",
210            "rendering must not mutate the buffer"
211        );
212        assert_eq!(cursor, "demo> echo one\necho two".chars().count());
213    }
214
215    #[test]
216    fn draw_input_cursor_offset_respects_multibyte_chars() {
217        let mut app = ReplApp::new("demo", "u");
218        app.set_input("héllo".to_string());
219        app.cursor_pos = "h".len() + "é".len(); // after the é (byte offset)
220        let (_, cursor) = compose_line(&app, WIDE);
221        // "demo> " (6 chars) + "h" + "é" = 8 chars, not a byte count.
222        assert_eq!(cursor, 8);
223    }
224
225    /// The HIGH-severity regression this module exists to fix: a user
226    /// typing ahead (non-empty buffer) while the agent is still responding
227    /// must still see a busy indicator — not just when the buffer happens
228    /// to be empty.
229    #[test]
230    fn draw_input_shows_busy_label_while_typing_with_nonempty_buffer() {
231        let mut app = ReplApp::new("demo", "u");
232        app.busy = true;
233        app.set_input("still typing".to_string());
234        let (line, _) = compose_line(&app, WIDE);
235        let text = line_text(&line);
236        assert!(
237            text.contains("still typing"),
238            "typed text must survive: {text}"
239        );
240        assert!(
241            text.contains(BUSY_LABEL),
242            "busy label must render even with a non-empty buffer: {text}"
243        );
244    }
245
246    /// #8207: during the unconfirmed-cancel window the row must say the run is
247    /// being stopped, not that it is still thinking — the always-visible half of
248    /// the cancelling state (the scrollback line scrolls away).
249    #[test]
250    fn draw_input_shows_cancelling_label_instead_of_thinking() {
251        let mut app = ReplApp::new("demo", "u");
252        app.busy = true;
253        app.cancelling = true;
254        let (line, _) = compose_line(&app, WIDE);
255        let text = line_text(&line);
256        assert!(text.contains(CANCELLING_LABEL), "{text}");
257        assert!(
258            !text.contains(BUSY_LABEL),
259            "a cancelling run is not thinking: {text}"
260        );
261    }
262
263    #[test]
264    fn draw_input_omits_busy_label_when_idle() {
265        let mut app = ReplApp::new("demo", "u");
266        app.set_input("hello".to_string());
267        app.busy = false;
268        let (line, _) = compose_line(&app, WIDE);
269        assert!(!line_text(&line).contains(BUSY_LABEL));
270    }
271
272    /// When the row is too narrow to fit the label without colliding with
273    /// the prompt/typed text, it must be omitted rather than overlapping —
274    /// matches tagent's `total_width > used + label_w + 1` guard.
275    #[test]
276    fn draw_input_omits_busy_label_when_too_narrow() {
277        let mut app = ReplApp::new("demo", "u");
278        app.busy = true;
279        app.set_input("hello".to_string());
280        let (line, _) = compose_line(&app, 10);
281        assert!(!line_text(&line).contains(BUSY_LABEL));
282    }
283}