trusty_code_tui/layout.rs
1//! The top-level frame composition — generalized port of tagent's
2//! `repl/tui/layout.rs::draw`.
3//!
4//! Why: DOC-50 §5 Slice 4 migrates the vertical split that arranges the
5//! scrollback, input row, and statusline into one frame. Generalization
6//! dropped two tagent-only rows this crate has no generic equivalent for
7//! yet: the three-row "activity panel" (animated spinner + elapsed timer +
8//! latest thinking step, `repl/tui/layout.rs::draw_activity` /
9//! `status.rs`'s spinner helpers) and the inline choice-picker row (model/
10//! provider/persona pickers, `repl/tui/pickers.rs`) — both are Phase 2/
11//! later-slice concerns per DOC-50 §4.2/§5 Slice 7-9, not part of the MVP
12//! scrollback+input+statusline widget set this slice delivers.
13//!
14//! What: [`draw`] splits the frame into chat (sized to content height, per
15//! [`crate::widgets::scrollback::chat_line_count`]), a separator, the input
16//! row, another separator, and the statusline, with a trailing blank spacer.
17//!
18//! # Spec References
19//! - [`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 `layout.rs`.
20
21use ratatui::layout::{Constraint, Direction, Layout, Rect};
22use ratatui::style::{Modifier, Style};
23use ratatui::widgets::Paragraph;
24
25use crate::app::ReplApp;
26use crate::widgets::input_composer::draw_input;
27use crate::widgets::permission_prompt::{draw_permission_prompt, prompt_height};
28use crate::widgets::scrollback::{chat_line_count, draw_chat};
29use crate::widgets::status_line::draw_statusline;
30
31/// Render a dim horizontal rule across `area` — the visual divider above and
32/// below the input row.
33///
34/// Why: a single `─`-repeated row gives the borderless input a clear
35/// top/bottom demarcation without the vertical cost of a bordered `Block`.
36pub fn draw_separator(f: &mut ratatui::Frame, area: Rect) {
37 if area.height == 0 || area.width == 0 {
38 return;
39 }
40 let rule: String = "─".repeat(area.width as usize);
41 let p = Paragraph::new(rule).style(Style::default().add_modifier(Modifier::DIM));
42 f.render_widget(p, area);
43}
44
45/// Top-level draw: banner (in-scrollback) + chat (sized to content) +
46/// separator + input + separator + statusline + trailing spacer.
47///
48/// Why: sizing the chat pane to its actual content height (rather than
49/// `Constraint::Min`, which expands to fill the screen) lets the input row
50/// float up directly beneath the last message instead of always being
51/// pinned to the bottom of the terminal — matches tagent's `layout.rs`
52/// rationale (issue #337 upstream).
53/// What: reserves fixed 1-row constraints for both separators, the input
54/// row, and the statusline, then gives the chat pane `min(content_height,
55/// available_height)`. A trailing `Constraint::Min(1)` spacer absorbs
56/// leftover space so nothing gets stretched to fill the terminal.
57/// Test: pure geometry is covered by
58/// [`crate::widgets::scrollback::chat_line_count`]'s own tests; the full
59/// `Frame` composition is exercised via `ratatui::backend::TestBackend` in
60/// `tests::draw_renders_without_panicking`, which is a smoke test (no
61/// TTY, no assertions on cell contents — see that test's doc comment), and
62/// the banner branch's own sizing in
63/// `wrapped_row_geometry::the_banner_renders_whole_below_its_build_width`.
64pub fn draw(f: &mut ratatui::Frame, app: &ReplApp) {
65 let area = f.area();
66
67 // #8205: one measurement for every branch, and it measures exactly what
68 // `draw_chat` will draw. The banner used to be sized by
69 // `banner_lines(..).len()`, which is wrong twice: `banner_lines` builds at
70 // `width.max(40)`, so below 40 columns every row wraps and the count is
71 // half what the banner needs, and it omits the blank row `build_chat_lines`
72 // appends after the banner, which cost the pane its top rule to a one-row
73 // scroll.
74 let content_h = if app.chat.is_empty() && !app.show_banner {
75 0
76 } else {
77 chat_line_count(app, area.width as usize).max(1)
78 };
79
80 // #3422: the prompt sits directly above the input row, and costs its rows
81 // only while a request is actually pending. Given to the chat pane
82 // otherwise, so an idle frame looks exactly as it did before. The height
83 // is asked for rather than assumed, because a reopened prompt carries one
84 // extra retry row — see `prompt_height`.
85 let prompt_h = prompt_height(app);
86
87 // Reserved rows below chat: prompt + top_sep(1) + input(1) + bot_sep(1) +
88 // statusline(1) + bottom spacer minimum(1).
89 let reserved: u16 = 5 + prompt_h;
90 let available_h = area.height.saturating_sub(reserved) as usize;
91 let chat_h = content_h
92 .min(available_h)
93 .max(if content_h == 0 { 0 } else { 1 });
94
95 let chunks = Layout::default()
96 .direction(Direction::Vertical)
97 .constraints([
98 Constraint::Length(chat_h as u16),
99 Constraint::Length(prompt_h), // permission prompt (0 when none)
100 Constraint::Length(1), // separator above input
101 Constraint::Length(1), // input
102 Constraint::Length(1), // separator below input
103 Constraint::Length(1), // statusline
104 Constraint::Min(1), // trailing spacer
105 ])
106 .split(area);
107
108 draw_chat(f, app, chunks[0]);
109 draw_permission_prompt(f, app, chunks[1]);
110 draw_separator(f, chunks[2]);
111 draw_input(f, app, chunks[3]);
112 draw_separator(f, chunks[4]);
113 draw_statusline(f, app, chunks[5]);
114 f.render_widget(Paragraph::new(""), chunks[6]);
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120 use ratatui::Terminal;
121 use ratatui::backend::TestBackend;
122
123 /// Smoke test: `draw` must not panic across the shapes that matter most
124 /// — empty app (banner only), populated chat, and a tiny terminal where
125 /// every `Constraint::Length` competes for the same few rows. This does
126 /// NOT assert on cell contents (that's the pure-function tests' job in
127 /// each widget module); it exists purely to catch a layout arithmetic
128 /// panic (e.g. an unchecked subtraction) before it reaches a real TTY.
129 #[test]
130 fn draw_renders_without_panicking() {
131 for (w, h) in [(80u16, 24u16), (120, 40), (10, 3)] {
132 let backend = TestBackend::new(w, h);
133 let mut terminal = Terminal::new(backend).expect("construct terminal");
134 let mut app = ReplApp::new("demo", "bob");
135 terminal.draw(|f| draw(f, &app)).expect("draw empty app");
136
137 app.push_user("hello");
138 app.push_assistant("hi there", false);
139 terminal
140 .draw(|f| draw(f, &app))
141 .expect("draw populated app");
142
143 // #3422: the prompt steals four rows, so the tiny-terminal case
144 // above is where an unchecked subtraction would surface.
145 app.pending_permission = Some(crate::model::PendingPermission {
146 request_id: "req-1".to_string(),
147 agent: "python-engineer".to_string(),
148 agent_id: "spawn-1".to_string(),
149 tool: "bash".to_string(),
150 subject: "rm -rf build".to_string(),
151 rule: "bash[rm *]".to_string(),
152 });
153 terminal
154 .draw(|f| draw(f, &app))
155 .expect("draw app with a pending permission prompt");
156 }
157 }
158
159 /// Every row of the rendered frame, as plain text.
160 fn rendered_rows(app: &ReplApp, width: u16, height: u16) -> Vec<String> {
161 let backend = TestBackend::new(width, height);
162 let mut terminal = Terminal::new(backend).expect("construct terminal");
163 terminal.draw(|f| draw(f, app)).expect("draw");
164 let buffer = terminal.backend().buffer().clone();
165 (0..height)
166 .map(|y| {
167 (0..width)
168 .map(|x| buffer[(x, y)].symbol().to_string())
169 .collect::<String>()
170 })
171 .collect()
172 }
173
174 /// #8205 regression, at the 80x24 the defect was reported on: the connect
175 /// line's `home <path>` must be RENDERED, not merely assembled. The chat
176 /// pane used to be sized by logical line count while the pane wraps, so
177 /// the status line's continuation row fell outside the pane and the home
178 /// path — the fact the owner ruled must be named — never reached a cell.
179 ///
180 /// The three shapes are the ones `tui_client::splash::connect_line`
181 /// produces: a short bound path, a long worktree path (pre-elided at that
182 /// function's 60-column path budget), and projectless with a workstream.
183 #[test]
184 fn draw_keeps_the_connect_line_home_segment_at_80_columns() {
185 // A neutral home directory of the same length as the reported one, so
186 // the wrap arithmetic this test exists for is unchanged (#8205).
187 let socket = "/Users/dev0/Library/Application Support/tcode/tcode.sock";
188 let worktree = crate::text::elide_middle(
189 "/private/tmp/q8230/deep/trusty-tools-demo/.claude/worktrees/agent-0123456789abcdef",
190 60,
191 );
192 let cases: [(&str, &str); 3] = [
193 ("/private/tmp/q8230/repoA", ""),
194 (&worktree, ""),
195 (
196 "projectless",
197 ", workstream bobmatnyc/bakeoff-l1 (548f2143)",
198 ),
199 ];
200
201 for (home, workstream) in cases {
202 let mut app = ReplApp::new("demo", "bob");
203 app.show_banner = false;
204 app.push_status(format!(
205 "connected to tcode daemon at {socket} — home {home}{workstream}, \
206 solo agent (no delegation)"
207 ));
208 let rows = rendered_rows(&app, 80, 24);
209
210 assert!(
211 rows.iter().any(|r| r.contains(home)),
212 "the home segment must reach a cell: {home:?} missing from {rows:#?}"
213 );
214 assert!(
215 rows.iter().any(|r| r.contains("home")),
216 "the `home` label must render: {rows:#?}"
217 );
218 if !workstream.is_empty() {
219 assert!(
220 rows.iter().any(|r| r.contains("bobmatnyc/bakeoff-l1")),
221 "a bound workstream must render: {rows:#?}"
222 );
223 }
224 }
225 }
226
227 /// #8205: the repository name is what the banner's `project` row is read
228 /// for, and it used to be the first thing elided away at 80 columns.
229 #[test]
230 fn draw_keeps_the_repository_name_on_the_banner_project_row() {
231 let mut app = ReplApp::new("demo", "bob");
232 app.splash = vec![
233 "🤖🤖🤖 tcode v0.7.0".to_string(),
234 "project /private/tmp/q8230/deep/trusty-tools-demo/.claude/worktrees/agent-0123456789abcdef"
235 .to_string(),
236 ];
237 let rows = rendered_rows(&app, 80, 24);
238 assert!(
239 rows.iter().any(|r| r.contains("trusty-tools-demo")),
240 "the repository name must render: {rows:#?}"
241 );
242 assert!(
243 rows.iter().any(|r| r.contains("agent-0123456789abcdef")),
244 "the worktree name must render: {rows:#?}"
245 );
246 }
247}