trusty_code_tui/text.rs
1//! Pure text-shaping helpers shared by [`crate::app`]'s chat mutators and
2//! [`crate::widgets::scrollback`]'s renderer.
3//!
4//! Why: LLM/agent responses routinely arrive with extra leading/trailing
5//! blank lines (a model's closing paragraph break) and interior `\n\n`
6//! paragraph gaps that read as wasted vertical space once rendered into a
7//! fixed-height terminal pane. Both problems are pure string transforms with
8//! no dependency on `ReplApp` or ratatui, so they live in their own module
9//! rather than being duplicated between the state mutator that trims stored
10//! text ([`crate::app::ReplApp::push_assistant`]) and any future consumer
11//! that needs the same shaping. Extracted verbatim (behavior-preserving) from
12//! `crates/trusty-agents/src/repl/tui/helpers.rs`'s `trim_surrounding_blank_lines`/
13//! `strip_interior_blank_lines` (DOC-50 §3.1/§5 Slice 4 migration).
14//!
15//! # Spec References
16//! - [`SPEC-TTUI-05~draft`](docs/specs/DOC-50-tcode-tui-claude-code-clone.md#SPEC-TTUI-05~draft) — Slice 4 deliverable (§5, Slice 4).
17
18/// Shorten `text` to `width` columns, preferring `/` boundaries (#8164).
19///
20/// Why: a splash or status line that names an absolute path routinely
21/// overflows its column, and clipping the tail removes the leaf — the one
22/// component a reader is checking. Eliding whole path components instead
23/// keeps the deepest directories intact, which is where a repository name
24/// and a worktree name live.
25///
26/// What it GUARANTEES, and nothing more: `text` that already fits `width` is
27/// returned unchanged, and the result never exceeds `width` — except at a
28/// `width` of 0 or 1, where the one-column `…` is kept rather than an empty
29/// string. For a path, the deepest components arrive WHOLE behind a leading
30/// `…/`, and the repository directory name survives alongside them: when the
31/// deepest contiguous run that fits does not reach back to the repository —
32/// a linked worktree under `<repo>/.claude/worktrees/<name>` is the
33/// motivating case (#8205) — that run is replaced by `…/<repo>/…/<tail>`, so
34/// the name a reader identifies the checkout by stays on the row. The two
35/// columns each `…/` costs are part of the budget.
36///
37/// Order of surrender, repository name LAST (owner ruling 2026-09-17): tail
38/// components go one at a time, then the tail entirely (`…/<repo>/…`), and
39/// only a repository name too wide for `width` itself is given up — that path
40/// falls back to the gapless `…/<tail>` run, keeping whole components even
41/// though the repository name is no longer among them. Character elision,
42/// which keeps both ends and replaces the middle with `…`, is the last resort:
43/// it takes a string with no `/`, and any path where not even the last two
44/// components fit. Widths count `char`s, never bytes.
45/// Test: `tests::elide_middle_keeps_whole_trailing_path_components`,
46/// `tests::elide_middle_keeps_the_repo_name_at_both_render_budgets`,
47/// `tests::elide_middle_keeps_a_repo_name_that_is_the_leaf`,
48/// `tests::elide_middle_drops_the_tail_before_the_repo_name`,
49/// `tests::elide_middle_keeps_a_fitting_path_unchanged`,
50/// `tests::elide_middle_falls_back_to_character_elision`,
51/// `tests::elide_middle_handles_degenerate_widths`.
52pub fn elide_middle(text: &str, width: usize) -> String {
53 if text.chars().count() <= width {
54 return text.to_string();
55 }
56 if text.contains('/')
57 && let Some(elided) = elide_path_components(text, width)
58 {
59 return elided;
60 }
61 elide_chars(text, width)
62}
63
64/// Directory names whose PARENT component names a git repository.
65///
66/// Why (#8205): a bare path is the only input `elide_middle` gets, so the
67/// repository has to be recognised from shape. Both worktree layouts put the
68/// repository directly above an administrative directory —
69/// `<repo>/.claude/worktrees/<name>` (this workspace's own) and
70/// `<repo>/.git/worktrees/<name>` (git's) — which makes the component above
71/// one of these names the repository. Nothing here touches the filesystem.
72const REPO_MARKERS: [&str; 2] = [".claude", ".git"];
73
74/// Index of the component naming the repository, per [`REPO_MARKERS`].
75///
76/// What: the component immediately above the LAST marker, so the nearest
77/// enclosing repository wins on a path that nests two. Returns an index, not
78/// the name, because the caller also has to ask whether a tail it already
79/// kept covers it. A marker at index 0 has no parent and yields `None`.
80/// Test: `tests::elide_middle_keeps_the_repo_name_at_both_render_budgets`,
81/// `tests::elide_middle_keeps_a_repo_name_that_is_the_leaf`.
82fn repo_anchor(components: &[&str]) -> Option<usize> {
83 components
84 .iter()
85 .rposition(|c| REPO_MARKERS.contains(c))
86 .filter(|&marker| marker > 0)
87 .map(|marker| marker - 1)
88}
89
90/// [`elide_middle`]'s path arm: the deepest components that fit, with the
91/// repository name kept alongside them.
92///
93/// Why kept separate: it can legitimately fail (a lone component wider than
94/// `width`), and `None` is what routes the caller to character elision rather
95/// than to a path rendering that does not fit.
96/// What: prefers [`deepest_contiguous`], which has no interior gap, and takes
97/// it whenever the path names no repository or the run already reaches the
98/// repository. Otherwise the repository name is spliced back in by
99/// [`anchored_on_repo`] — the #8205 defect was returning the gapless run even
100/// when it had elided the one name identifying the checkout.
101/// Test: `tests::elide_middle_keeps_the_repo_name_at_both_render_budgets`,
102/// `tests::elide_middle_keeps_whole_trailing_path_components`,
103/// `tests::elide_middle_falls_back_to_character_elision`.
104fn elide_path_components(text: &str, width: usize) -> Option<String> {
105 let components: Vec<&str> = text.split('/').filter(|c| !c.is_empty()).collect();
106 let anchor = repo_anchor(&components);
107 let contiguous = deepest_contiguous(&components, width);
108 let reaches_repo = |kept: usize| anchor.is_none_or(|a| a >= components.len() - kept);
109 if let Some((kept, rendered)) = &contiguous
110 && reaches_repo(*kept)
111 {
112 return Some(rendered.clone());
113 }
114 // #8205: the repository name outlives the tail, so an anchored rendering
115 // that fits beats the gapless run that dropped the name.
116 match anchor.and_then(|a| anchored_on_repo(&components, a, width)) {
117 Some(anchored) => Some(anchored),
118 None => contiguous.map(|(_, rendered)| rendered),
119 }
120}
121
122/// `…/<tail>`: the deepest run of whole components that fits `width`.
123///
124/// What: walks from the leaf backwards, accepting each component while
125/// `…/<tail>` stays within `width`, and reports how many it kept so the
126/// caller can tell whether the repository name is among them. `None` unless
127/// at least the last TWO were accepted — one lone directory name behind an
128/// ellipsis says less than head-and-tail character elision would.
129/// Test: `tests::elide_middle_keeps_a_repo_name_that_is_the_leaf`,
130/// `tests::elide_middle_falls_back_to_character_elision`.
131fn deepest_contiguous(components: &[&str], width: usize) -> Option<(usize, String)> {
132 let mut kept = 0usize;
133 let mut rendered = String::new();
134 for count in 1..=components.len() {
135 let tail = components[components.len() - count..].join("/");
136 let candidate = format!("…/{tail}");
137 if candidate.chars().count() > width {
138 break;
139 }
140 kept = count;
141 rendered = candidate;
142 }
143 (kept >= 2).then_some((kept, rendered))
144}
145
146/// `…/<repo>/…/<tail>`: the repository name, then the deepest tail that fits.
147///
148/// What: tries tails from as deep as the path allows down to the leaf alone,
149/// never reaching back into the repository component itself, and returns the
150/// longest that fits. When no tail fits, the bare `…/<repo>/…` keeps the name
151/// on its own — the repository name is the last thing surrendered (owner
152/// ruling 2026-09-17). `None` only when even that bare form overflows, which
153/// sends a repository name wider than `width` back to the caller's gapless
154/// [`deepest_contiguous`] run — and on to character elision only when there is
155/// no such run either.
156/// Test: `tests::elide_middle_keeps_the_repo_name_at_both_render_budgets`,
157/// `tests::elide_middle_drops_the_tail_before_the_repo_name`.
158fn anchored_on_repo(components: &[&str], anchor: usize, width: usize) -> Option<String> {
159 let repo = components[anchor];
160 let mut rendered: Option<String> = None;
161 for count in 1..components.len() - anchor {
162 let tail = components[components.len() - count..].join("/");
163 let candidate = format!("…/{repo}/…/{tail}");
164 if candidate.chars().count() > width {
165 break;
166 }
167 rendered = Some(candidate);
168 }
169 rendered.or_else(|| {
170 let bare = format!("…/{repo}/…");
171 (bare.chars().count() <= width).then_some(bare)
172 })
173}
174
175/// [`elide_middle`]'s fallback: keep both ends, replace the middle with `…`.
176///
177/// What: splits the `width - 1` remaining budget between the two ends, the
178/// odd character going to the head. Counts chars, not bytes. A `width` of 0
179/// or 1 returns the bare `…`, so a zero budget is overshot by one column
180/// rather than answered with an empty string.
181/// Test: `tests::elide_middle_falls_back_to_character_elision`,
182/// `tests::elide_middle_handles_degenerate_widths`.
183fn elide_chars(text: &str, width: usize) -> String {
184 let chars: Vec<char> = text.chars().collect();
185 if chars.len() <= width {
186 return text.to_string();
187 }
188 if width <= 1 {
189 return "…".to_string();
190 }
191 let keep = width - 1;
192 let head = keep.div_ceil(2);
193 let tail = keep - head;
194 let mut out: String = chars[..head].iter().collect();
195 out.push('…');
196 out.extend(&chars[chars.len() - tail..]);
197 out
198}
199
200/// Strip leading and trailing whitespace-only lines from a multi-line string.
201///
202/// Why: Assistant responses regularly include extra `\n\n` at the head or
203/// tail. Rendering them verbatim leaves visible blank rows in the chat
204/// scrollback, which reads as a UI bug. Trimming once at the boundary keeps
205/// interior blank lines (which carry paragraph-break meaning) intact.
206/// What: Trims trailing whitespace first, then drops leading whitespace-only
207/// lines one at a time. Interior blank lines are untouched.
208/// Test: `tests::trim_surrounding_blank_lines_strips_leading_and_trailing`,
209/// `tests::trim_surrounding_blank_lines_preserves_when_no_blanks`,
210/// `tests::trim_surrounding_blank_lines_empty_input`.
211pub fn trim_surrounding_blank_lines(s: &str) -> String {
212 let trimmed_end = s.trim_end();
213 let mut start = 0usize;
214 let bytes = trimmed_end.as_bytes();
215 while start < bytes.len() {
216 let nl = bytes[start..]
217 .iter()
218 .position(|&b| b == b'\n')
219 .map(|p| start + p);
220 let line_end = nl.unwrap_or(bytes.len());
221 let line = &trimmed_end[start..line_end];
222 if line.trim().is_empty() {
223 start = match nl {
224 Some(p) => p + 1,
225 None => bytes.len(),
226 };
227 } else {
228 break;
229 }
230 }
231 trimmed_end[start..].to_string()
232}
233
234/// Drop every whitespace-only line from within a response.
235///
236/// Why: Markdown-style double-newline paragraph breaks accumulate into
237/// wasted vertical space in a terminal chat panel — the user already reads
238/// consecutive paragraphs as one flowing thought, so the gap just pushes
239/// later content off-screen sooner. Removing every interior blank produces a
240/// tight, compact response block.
241/// What: Returns a string where every whitespace-only line is dropped;
242/// non-blank lines are preserved verbatim and rejoined with single `\n`s.
243/// Test: `tests::strip_interior_blank_lines_drops_all_blanks`,
244/// `tests::strip_interior_blank_lines_drops_single_blank`,
245/// `tests::strip_interior_blank_lines_treats_whitespace_only_as_blank`.
246pub fn strip_interior_blank_lines(s: &str) -> String {
247 let mut out = String::with_capacity(s.len());
248 let mut first = true;
249 for line in s.split('\n') {
250 if line.trim().is_empty() {
251 continue;
252 }
253 if !first {
254 out.push('\n');
255 }
256 out.push_str(line);
257 first = false;
258 }
259 out
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 /// The motivating case (#8164): a worktree path on an 80-column banner
267 /// gets 54 columns. The deepest components must arrive WHOLE — a clipped
268 /// tail would name neither the worktree nor the directory holding it.
269 #[test]
270 fn elide_middle_keeps_whole_trailing_path_components() {
271 let path = "/Users/masa/trusty-mpm-projects/bobmatnyc/trusty-tools/.claude/worktrees/agent-af14d84dd34577cee";
272 let out = elide_middle(path, 54);
273 assert!(out.chars().count() <= 54, "{out}");
274 assert!(out.starts_with("…/"), "{out}");
275 assert!(
276 out.ends_with("/worktrees/agent-af14d84dd34577cee"),
277 "the last two components must survive whole: {out}"
278 );
279 // Nothing is clipped mid-component: every retained segment is either
280 // one of the original path's own components or the `…` standing in
281 // for the run #8205 replaced with the repository name.
282 for segment in out.trim_start_matches("…/").split('/') {
283 assert!(
284 segment == "…" || path.split('/').any(|c| c == segment),
285 "{segment:?} in {out}"
286 );
287 }
288 // #8205: the repository the worktree belongs to is named too.
289 assert!(out.contains("trusty-tools"), "{out}");
290 }
291
292 /// #8205, the owner-reported defect: at the banner's 54-column budget the
293 /// repository name vanished while columns went unused, and only the
294 /// connect line's roomier 60 kept it. Both budgets must name the repo.
295 #[test]
296 fn elide_middle_keeps_the_repo_name_at_both_render_budgets() {
297 let path =
298 "/private/tmp/q8230/deep/trusty-tools-demo/.claude/worktrees/agent-0123456789abcdef";
299 for width in [54usize, 60] {
300 let out = elide_middle(path, width);
301 assert!(
302 out.chars().count() <= width,
303 "must fit {width}: {out} ({})",
304 out.chars().count()
305 );
306 assert!(
307 out.contains("trusty-tools-demo"),
308 "the repository name must survive at {width}: {out}"
309 );
310 assert!(
311 out.ends_with("agent-0123456789abcdef"),
312 "the worktree's own name must survive at {width}: {out}"
313 );
314 }
315 }
316
317 /// Order of surrender (owner ruling 2026-09-17): squeezed hard enough,
318 /// the tail goes and the repository name stays — never the reverse.
319 #[test]
320 fn elide_middle_drops_the_tail_before_the_repo_name() {
321 let path =
322 "/private/tmp/q8230/deep/trusty-tools-demo/.claude/worktrees/agent-0123456789abcdef";
323 let out = elide_middle(path, 26);
324 assert!(out.chars().count() <= 26, "{out}");
325 assert!(
326 out.contains("trusty-tools-demo"),
327 "the repo name outlives the tail: {out}"
328 );
329 assert_eq!(out, "…/trusty-tools-demo/…", "{out}");
330 }
331
332 /// A path already inside its budget is handed back byte-for-byte — no
333 /// ellipsis, no reshaping.
334 #[test]
335 fn elide_middle_keeps_a_fitting_path_unchanged() {
336 let path = "/private/tmp/q8230/repoA";
337 assert_eq!(elide_middle(path, 60), path);
338 assert_eq!(elide_middle(path, path.chars().count()), path);
339 }
340
341 /// A plain repository root — the common case — carries its own name as
342 /// the leaf, so keeping the tail already keeps the repo name and no
343 /// anchoring is needed. True for a deep path with no repository marker
344 /// too: its final component is what survives.
345 #[test]
346 fn elide_middle_keeps_a_repo_name_that_is_the_leaf() {
347 let path = "/Users/masa/trusty-mpm-projects/bobmatnyc/trusty-tools";
348 let out = elide_middle(path, 30);
349 assert!(out.chars().count() <= 30, "{out}");
350 assert!(out.ends_with("/trusty-tools"), "{out}");
351 assert!(!out.contains("/…/"), "no anchor splice is needed: {out}");
352
353 let deep = "/private/var/folders/zz/T/very/deeply/nested/scratch/workspace/repoZ";
354 let out = elide_middle(deep, 40);
355 assert!(out.chars().count() <= 40, "{out}");
356 assert!(
357 out.ends_with("/repoZ"),
358 "the final component survives: {out}"
359 );
360 }
361
362 /// A string with no `/`, and a path whose last two components alone
363 /// overflow, both fall back to character elision — head and tail kept.
364 #[test]
365 fn elide_middle_falls_back_to_character_elision() {
366 let out = elide_middle("abcdefghijklmnopqrstuvwxyz", 11);
367 assert_eq!(out.chars().count(), 11, "{out}");
368 assert_eq!(out, "abcde…vwxyz", "head and tail both kept");
369 assert!(out.contains('…'), "{out}");
370
371 let deep = "/a/averyveryverylongdirectoryname/anotherverylongleafname";
372 let out = elide_middle(deep, 20);
373 assert_eq!(out.chars().count(), 20, "{out}");
374 assert!(out.starts_with("/a/"), "{out}");
375 assert!(out.ends_with("leafname"), "{out}");
376 }
377
378 /// Degenerate widths must not panic and must not exceed the budget.
379 #[test]
380 fn elide_middle_handles_degenerate_widths() {
381 assert_eq!(elide_middle("/a/b/c", 0), "…");
382 assert_eq!(elide_middle("/a/b/c", 1), "…");
383 assert_eq!(elide_middle("short", 99), "short");
384 }
385
386 #[test]
387 fn trim_surrounding_blank_lines_strips_leading_and_trailing() {
388 let input = "\n\n \nhello\n\nworld\n\n \n";
389 let out = trim_surrounding_blank_lines(input);
390 assert_eq!(out, "hello\n\nworld");
391 }
392
393 #[test]
394 fn trim_surrounding_blank_lines_preserves_when_no_blanks() {
395 assert_eq!(trim_surrounding_blank_lines("hi"), "hi");
396 assert_eq!(trim_surrounding_blank_lines("a\nb"), "a\nb");
397 }
398
399 #[test]
400 fn trim_surrounding_blank_lines_empty_input() {
401 assert_eq!(trim_surrounding_blank_lines(""), "");
402 assert_eq!(trim_surrounding_blank_lines("\n\n \n"), "");
403 }
404
405 #[test]
406 fn strip_interior_blank_lines_drops_all_blanks() {
407 let input = "para1\n\n\npara2\n\n\n\npara3";
408 let out = strip_interior_blank_lines(input);
409 assert_eq!(out, "para1\npara2\npara3");
410 }
411
412 #[test]
413 fn strip_interior_blank_lines_drops_single_blank() {
414 let input = "para1\n\npara2";
415 assert_eq!(strip_interior_blank_lines(input), "para1\npara2");
416 }
417
418 #[test]
419 fn strip_interior_blank_lines_treats_whitespace_only_as_blank() {
420 let input = "a\n \n\t\nb";
421 assert_eq!(strip_interior_blank_lines(input), "a\nb");
422 }
423}