返回 CodeWhale
help.rs
根目录 / crates / tui / src / tui / views / help.rs
1 //! Searchable help overlay for `Alt+?`, `F1`, and `Ctrl+/`.
2 //!
3 //! Renders two stacked sections — *Slash commands* and *Keybindings* — with
4 //! a live substring filter applied as the user types in the search box. The
5 //! entry point decides which section comes first: `/help` and context-menu
6 //! Help lead with commands, while keyboard shortcuts lead with the key
7 //! reference that the footer promises. The command list is sourced from
8 //! [`crate::commands::command_infos()`] and the keybinding list from
9 //! [`codewhale_engine::keybinding_table::KEYBINDINGS`] so neither can drift from the
10 //! wired-up handlers.
11 //!
12 //! Keys: any printable character extends the filter, `Backspace` (or `Ctrl+H`)
13 //! shrinks it,
14 //! `↑`/`↓` (or `Ctrl+P`/`Ctrl+N`) move the selection, `PgUp`/`PgDn` jump by
15 //! ten rows, `Home`/`End` jump to ends, and `Esc` closes. Pressing `?` again
16 //! at the call-site (`tui::ui`) also toggles the overlay closed.
17
18 use std::borrow::Cow;
19 use std::cell::RefCell;
20 use std::collections::HashSet;
21 use std::time::Instant;
22
23 #[cfg(test)]
24 use std::path::Path;
25
26 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
27 use ratatui::{
28 buffer::Buffer,
29 layout::Rect,
30 style::{Modifier, Style},
31 text::{Line, Span},
32 widgets::{Paragraph, Widget},
33 };
34 use unicode_width::UnicodeWidthStr;
35
36 use crate::commands;
37 use crate::tui::views::rounded::{
38 pad_selected_line, render_rounded_footer, render_rounded_surface,
39 };
40 use crate::tui::views::{ActionHint, ModalKind, ModalView, ViewAction, render_panel_scroll_rail};
41 use codewhale_engine::keybinding_table::KEYBINDINGS;
42 use codewhale_localization::{Locale, MessageId, tr};
43 use codewhale_palette as palette;
44 use codewhale_tui_kit::menu_style;
45
46 mod keycaps;
47
48 /// Two top-level sections rendered in the overlay.
49 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
50 enum HelpSection {
51 Command,
52 UserCommand,
53 Skill,
54 Keybinding,
55 }
56
57 impl HelpSection {
58 fn label(self, locale: Locale) -> Cow<'static, str> {
59 match self {
60 Self::Command => tr(locale, MessageId::HelpSlashCommands),
61 Self::UserCommand => tr(locale, MessageId::HelpUserCommands),
62 Self::Skill => tr(locale, MessageId::HelpSkills),
63 Self::Keybinding => tr(locale, MessageId::HelpKeybindings),
64 }
65 }
66 }
67
68 /// Which reference surface owns the first visible section when Help opens.
69 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
70 pub enum HelpOrdering {
71 /// `/help` and context-menu Help are command discovery surfaces.
72 CommandsFirst,
73 /// F1 and its Ctrl+/ and Alt+? fallbacks open the keyboard reference.
74 KeybindingsFirst,
75 }
76
77 impl HelpOrdering {
78 fn section_rank(self, section: HelpSection) -> u8 {
79 // User commands and skills sit with the built-in commands: they are
80 // the same kind of thing to the user (#3912), so a keyboard-reference
81 // open still sorts every command surface below the chords.
82 match (self, section) {
83 (Self::CommandsFirst, HelpSection::Command) => 0,
84 (Self::CommandsFirst, HelpSection::UserCommand) => 1,
85 (Self::CommandsFirst, HelpSection::Skill) => 2,
86 (Self::CommandsFirst, HelpSection::Keybinding) => 3,
87 (Self::KeybindingsFirst, HelpSection::Keybinding) => 0,
88 (Self::KeybindingsFirst, HelpSection::Command) => 1,
89 (Self::KeybindingsFirst, HelpSection::UserCommand) => 2,
90 (Self::KeybindingsFirst, HelpSection::Skill) => 3,
91 }
92 }
93 }
94
95 #[derive(Debug, Clone)]
96 struct HelpEntry {
97 binding: Option<MessageId>,
98 section: HelpSection,
99 /// Sort-within-section key — keybinding entries reuse their declared
100 /// section's rank so the help overlay groups Navigation, Editing, … in
101 /// the same order as `keybinding_table`.
102 sub_rank: u8,
103 label: String,
104 description: String,
105 /// The command's argument shape, when it has one worth stating — the
106 /// registry `usage` string for built-ins, the front-matter usage for
107 /// workspace commands. `None` for rows that are already the whole shape
108 /// (`/copy`, `$skill`, a keybinding chord).
109 usage: Option<String>,
110 /// Lowercased haystack used for substring matching; pre-built so each
111 /// keystroke does not re-allocate per entry.
112 haystack: String,
113 }
114
115 #[derive(Debug, Clone, PartialEq, Eq)]
116 enum HelpRenderRow {
117 Group {
118 key: String,
119 label: String,
120 count: usize,
121 collapsed: bool,
122 },
123 Entry {
124 slot: usize,
125 entry_idx: usize,
126 },
127 }
128
129 #[derive(Debug, Clone, PartialEq, Eq)]
130 enum HelpHit {
131 Group(String),
132 Entry(usize),
133 }
134
135 pub struct HelpView {
136 locale: Locale,
137 ordering: HelpOrdering,
138 entries: Vec<HelpEntry>,
139 /// Indices into `entries`, in display order, after filtering.
140 filtered: Vec<usize>,
141 query: String,
142 /// Keyboard focus covers both group headers and entry rows. `selected`
143 /// remains the last focused entry slot so entry-oriented actions and
144 /// tests keep a stable target while a header owns focus.
145 focus: Option<HelpHit>,
146 selected: usize,
147 collapsed: HashSet<String>,
148 row_hitboxes: RefCell<Vec<(Rect, HelpHit)>>,
149 theme: palette::UiTheme,
150 animate_keys: bool,
151 key_pressed: Option<Instant>,
152 }
153
154 impl Default for HelpView {
155 fn default() -> Self {
156 Self::new()
157 }
158 }
159
160 impl HelpView {
161 pub fn new() -> Self {
162 Self::new_for_locale(Locale::En)
163 }
164
165 pub fn new_for_locale(locale: Locale) -> Self {
166 Self::new_with_ordering(locale, HelpOrdering::CommandsFirst)
167 }
168
169 /// Discoverability index over every user-invocable surface (#3912):
170 /// built-ins, workspace commands, and discovered skills. `skills` comes
171 /// from `App::cached_skills`; pass `&[]` only where none are discovered.
172 #[cfg(test)]
173 pub fn new_for_workspace(
174 locale: Locale,
175 workspace: &Path,
176 skills: &[(String, String)],
177 ) -> Self {
178 commands::user_registry::with_registry_for_workspace(Some(workspace), |registry| {
179 Self::new_with_registry(locale, HelpOrdering::CommandsFirst, registry, skills, false)
180 })
181 }
182
183 pub fn new_for_app(app: &crate::tui::app::App, shortcuts: bool) -> Self {
184 let mut view = commands::user_registry::with_registry_for_app(app, |registry| {
185 Self::new_with_registry(
186 app.ui_locale,
187 if shortcuts {
188 HelpOrdering::KeybindingsFirst
189 } else {
190 HelpOrdering::CommandsFirst
191 },
192 registry,
193 &app.cached_skills,
194 app.composer_multiline_mode,
195 )
196 });
197 view.theme = app.ui_theme;
198 view.animate_keys = app.motion_policy().allows_decorative()
199 && !crate::tui::color_compat::ascii_safe_enabled()
200 && palette::resolvable_rgb(view.theme.elevated_bg).is_some()
201 && app.viewport.ocean_caps.is_some_and(|caps| {
202 matches!(
203 caps.depth,
204 codewhale_ratatui::color::ColorDepth::TrueColor
205 | codewhale_ratatui::color::ColorDepth::Ansi256
206 )
207 });
208 if shortcuts && app.focus() == crate::tui::shell_key_routing::Focus::Composer {
209 let binding = if !app.viewport.transcript_scroll.is_at_tail() {
210 MessageId::KbJumpTopBottom
211 } else if app.is_loading || app.queued_message_count() > 0 {
212 MessageId::KbSendDraft
213 } else {
214 MessageId::KbScrollTranscriptAlt
215 };
216 if let Some(slot) = view
217 .filtered
218 .iter()
219 .position(|&i| view.entries[i].binding == Some(binding))
220 {
221 view.collapsed
222 .remove(&group_key(&view.entries[view.filtered[slot]]));
223 view.set_focus(HelpHit::Entry(slot));
224 }
225 }
226 view
227 }
228 fn new_with_ordering(locale: Locale, ordering: HelpOrdering) -> Self {
229 let registry = commands::user_registry::UserCommandRegistry::new();
230 Self::new_with_registry(locale, ordering, &registry, &[], false)
231 }
232
233 fn new_with_registry(
234 locale: Locale,
235 ordering: HelpOrdering,
236 registry: &commands::user_registry::UserCommandRegistry,
237 skills: &[(String, String)],
238 multiline_mode: bool,
239 ) -> Self {
240 let entries = build_entries(locale, registry, skills, multiline_mode);
241 let mut view = Self {
242 locale,
243 ordering,
244 entries,
245 filtered: Vec::new(),
246 query: String::new(),
247 focus: None,
248 selected: 0,
249 collapsed: default_collapsed(ordering),
250 row_hitboxes: RefCell::new(Vec::new()),
251 theme: palette::UI_THEME,
252 animate_keys: false,
253 key_pressed: None,
254 };
255 view.refilter();
256 view
257 }
258
259 /// Start with every Help/shortcuts group expanded. Default is the
260 /// Grok-like folded long tail; `/config help_expand_groups true` opts in.
261 #[must_use]
262 pub fn with_groups_expanded(mut self, expand: bool) -> Self {
263 if expand {
264 self.collapsed.clear();
265 self.clamp_focus_to_visible();
266 }
267 self
268 }
269
270 fn tr(&self, id: MessageId) -> Cow<'static, str> {
271 tr(self.locale, id)
272 }
273
274 fn refilter(&mut self) {
275 // Substring matching is intentional — fuzzy matchers can hide the
276 // exact-prefix hit a user is typing toward, which is the wrong
277 // failure mode for a *help* surface. We split on whitespace so
278 // multi-term queries (`apply mode`) act as an AND.
279 let query = self.query.trim().to_ascii_lowercase();
280 let terms: Vec<&str> = query
281 .split_whitespace()
282 .filter(|term| !term.is_empty())
283 .collect();
284
285 let mut filtered: Vec<usize> = self
286 .entries
287 .iter()
288 .enumerate()
289 .filter(|(_, entry)| terms.iter().all(|term| entry.haystack.contains(term)))
290 .map(|(idx, _)| idx)
291 .collect();
292
293 filtered.sort_by_key(|idx| {
294 let entry = &self.entries[*idx];
295 (
296 self.ordering.section_rank(entry.section),
297 entry.sub_rank,
298 entry.label.clone(),
299 )
300 });
301 let previous = self.selected_shortcut().and_then(|entry| entry.binding);
302 self.filtered = filtered;
303 self.clamp_focus_to_visible();
304 if previous != self.selected_shortcut().and_then(|entry| entry.binding) {
305 self.start_key_pulse(Instant::now());
306 }
307 }
308
309 fn clamp_focus_to_visible(&mut self) {
310 let visible = self.visible_entry_slots();
311 if !visible.is_empty() && !visible.contains(&self.selected) {
312 self.selected = visible[0];
313 }
314 let focusable = self.focusable_rows();
315 if !self
316 .focus
317 .as_ref()
318 .is_some_and(|focus| focusable.contains(focus))
319 {
320 // Prefer the first entry over the group header above it. A header
321 // has no description, and the detail row under the filter reads
322 // the focused entry — so falling back to a header left that row
323 // blank exactly when Help opens and while a query is being typed.
324 self.focus = focusable
325 .iter()
326 .find(|hit| matches!(hit, HelpHit::Entry(_)))
327 .or_else(|| focusable.first())
328 .cloned();
329 }
330 }
331
332 fn visible_entry_slots(&self) -> Vec<usize> {
333 self.filtered
334 .iter()
335 .copied()
336 .enumerate()
337 .filter_map(|(slot, entry_idx)| {
338 let key = group_key(&self.entries[entry_idx]);
339 if self.group_is_collapsed(&key) {
340 None
341 } else {
342 Some(slot)
343 }
344 })
345 .collect()
346 }
347
348 fn group_is_collapsed(&self, key: &str) -> bool {
349 self.query.trim().is_empty() && self.collapsed.contains(key)
350 }
351
352 fn toggle_group(&mut self, key: &str) {
353 if !self.collapsed.remove(key) {
354 self.collapsed.insert(key.to_string());
355 }
356 self.focus = Some(HelpHit::Group(key.to_string()));
357 self.clamp_focus_to_visible();
358 }
359
360 fn move_selection(&mut self, delta: isize) {
361 // #4755: help list wraps at both ends (same as other modal lists).
362 // Group headers participate so a keyboard user can open the same
363 // default-collapsed rows as a mouse user.
364 let focusable = self.focusable_rows();
365 if focusable.is_empty() {
366 return;
367 }
368 let pos = focusable
369 .iter()
370 .position(|candidate| self.focus.as_ref() == Some(candidate))
371 .unwrap_or(0);
372 let next = codewhale_tui_kit::list_nav::wrap_index(pos, focusable.len(), delta);
373 self.set_focus(focusable[next].clone());
374 }
375
376 fn move_selection_wrapping(&mut self, delta: isize) {
377 self.move_selection(delta);
378 }
379
380 fn render_rows(&self) -> Vec<HelpRenderRow> {
381 let mut rows = Vec::new();
382 let mut active_group: Option<String> = None;
383
384 for (slot, entry_idx) in self.filtered.iter().copied().enumerate() {
385 let entry = &self.entries[entry_idx];
386 let key = group_key(entry);
387 if active_group.as_deref() != Some(key.as_str()) {
388 let count = self
389 .filtered
390 .iter()
391 .filter(|idx| group_key(&self.entries[**idx]) == key)
392 .count();
393 let collapsed = self.group_is_collapsed(&key);
394 rows.push(HelpRenderRow::Group {
395 key: key.clone(),
396 label: group_label(entry, self.locale),
397 count,
398 collapsed,
399 });
400 active_group = Some(key.clone());
401 }
402 if self.group_is_collapsed(&key) {
403 continue;
404 }
405 rows.push(HelpRenderRow::Entry { slot, entry_idx });
406 }
407
408 rows
409 }
410
411 /// Width of the label column for each group, measured from the labels
412 /// that group actually contains.
413 ///
414 /// The column used to be a flat 28 columns at every terminal size. At 60
415 /// columns that spent 28 of ~53 on a gutter — `/advisor` is eight cells
416 /// wide, so twenty blank columns sat between every command and a
417 /// description that had been cut to 21. Sizing per group keeps the block
418 /// under each header reading as one table while handing the slack back to
419 /// the descriptions; it is stable while scrolling because it does not
420 /// depend on which rows are on screen.
421 fn label_widths(&self, cap: usize) -> std::collections::HashMap<String, usize> {
422 let mut widths: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
423 for entry_idx in self.filtered.iter().copied() {
424 let entry = &self.entries[entry_idx];
425 let width = entry.label.width().min(cap);
426 let slot = widths.entry(group_key(entry)).or_default();
427 *slot = (*slot).max(width);
428 }
429 widths
430 }
431
432 /// What the focused row could not say for itself: the command's argument
433 /// shape, and its description when the row had to shed one.
434 ///
435 /// `/help` used to show `label + description` and keep `usage` in the
436 /// search haystack alone, so `/workspace [path|worktrees]` read as
437 /// `/workspace` and the worktree manager behind it was invisible (#5952).
438 /// The usage line is new information, so it is printed whenever the
439 /// registry has one; the description is only repeated when the row shed
440 /// it, because printing the same sentence twice on one screen is the
441 /// duplication this slot was built to avoid. The row stays reserved
442 /// either way so the list does not jump as focus moves.
443 fn focused_entry_detail(
444 &self,
445 inner_width: usize,
446 label_cap: usize,
447 label_widths: &std::collections::HashMap<String, usize>,
448 ) -> Option<String> {
449 let HelpHit::Entry(slot) = self.focus.as_ref()? else {
450 return None;
451 };
452 let entry_idx = *self.filtered.get(*slot)?;
453 let entry = &self.entries[entry_idx];
454 let label_width = label_widths
455 .get(&group_key(entry))
456 .copied()
457 .unwrap_or(label_cap);
458 let inline_capacity = inner_width.saturating_sub(label_width + 4);
459 let inline = shed_to_width(&entry.description, inline_capacity, self.locale);
460 let full = shed_to_width(&entry.description, inner_width, self.locale);
461 let repaired = (full != inline && !full.is_empty()).then(|| full.to_string());
462 match (entry.usage.as_deref(), repaired) {
463 (None, repaired) => repaired,
464 (Some(usage), None) => Some(shed_to_width(usage, inner_width, self.locale).to_string()),
465 (Some(usage), Some(description)) => {
466 // They join at a joint `shed_to_width` already sheds on, and
467 // the description leads: repairing the shed is what this slot
468 // was built for, and a panel too narrow to hold both must not
469 // spend itself on the argument shape and drop the sentence
470 // the row could not print.
471 let joined = format!("{description} — {usage}");
472 Some(shed_to_width(&joined, inner_width, self.locale).to_string())
473 }
474 }
475 }
476
477 fn focusable_rows(&self) -> Vec<HelpHit> {
478 self.render_rows()
479 .into_iter()
480 .map(|row| match row {
481 HelpRenderRow::Group { key, .. } => HelpHit::Group(key),
482 HelpRenderRow::Entry { slot, .. } => HelpHit::Entry(slot),
483 })
484 .collect()
485 }
486
487 fn set_focus(&mut self, focus: HelpHit) {
488 let changed = self.focus.as_ref() != Some(&focus);
489 if let HelpHit::Entry(slot) = &focus {
490 self.selected = *slot;
491 }
492 self.focus = Some(focus);
493 if changed {
494 self.start_key_pulse(Instant::now());
495 }
496 }
497
498 fn selected_shortcut(&self) -> Option<&HelpEntry> {
499 let HelpHit::Entry(slot) = self.focus.as_ref()? else {
500 return None;
501 };
502 let entry = &self.entries[*self.filtered.get(*slot)?];
503 (entry.binding.is_some()
504 && entry.sub_rank
505 != codewhale_engine::keybinding_table::KeybindingSection::Pointer.rank()
506 && entry.label.split(" / ").any(keycaps::is_shortcut))
507 .then_some(entry)
508 }
509
510 fn start_key_pulse(&mut self, at: Instant) {
511 self.key_pressed = (self.animate_keys && self.selected_shortcut().is_some()).then_some(at);
512 }
513
514 fn focused_group_key(&self) -> Option<String> {
515 match self.focus.as_ref()? {
516 HelpHit::Group(key) => Some(key.clone()),
517 HelpHit::Entry(slot) => self
518 .filtered
519 .get(*slot)
520 .map(|entry_idx| group_key(&self.entries[*entry_idx])),
521 }
522 }
523
524 fn selected_render_row(rows: &[HelpRenderRow], focus: Option<&HelpHit>) -> usize {
525 rows.iter()
526 .position(|row| match (row, focus) {
527 (HelpRenderRow::Group { key, .. }, Some(HelpHit::Group(focused))) => key == focused,
528 (HelpRenderRow::Entry { slot, .. }, Some(HelpHit::Entry(focused))) => {
529 slot == focused
530 }
531 _ => false,
532 })
533 .unwrap_or(0)
534 }
535
536 fn visible_row_start(
537 rows: &[HelpRenderRow],
538 focus: Option<&HelpHit>,
539 visible_budget: usize,
540 ) -> usize {
541 if rows.len() <= visible_budget {
542 return 0;
543 }
544
545 let selected_row = Self::selected_render_row(rows, focus);
546 let half = visible_budget / 2;
547 if selected_row <= half {
548 0
549 } else if selected_row + half >= rows.len() {
550 rows.len().saturating_sub(visible_budget)
551 } else {
552 selected_row.saturating_sub(half)
553 }
554 }
555 }
556
557 fn build_entries(
558 locale: Locale,
559 registry: &commands::user_registry::UserCommandRegistry,
560 skills: &[(String, String)],
561 multiline_mode: bool,
562 ) -> Vec<HelpEntry> {
563 let mut entries = Vec::new();
564
565 for command in commands::command_infos() {
566 if registry.get(command.name).is_some() {
567 continue;
568 }
569 let label = format!("/{}", command.name);
570 let localized = command.description_for(locale);
571 let visible_aliases = command
572 .aliases
573 .iter()
574 .copied()
575 .filter(|alias| registry.get(alias).is_none())
576 .filter(|alias| alias_is_listed_for(locale, alias))
577 .collect::<Vec<_>>();
578 // Every alias stays findable by typing it, listed or not.
579 let alias_terms = command
580 .aliases
581 .iter()
582 .map(|alias| format!("/{alias}"))
583 .collect::<Vec<_>>()
584 .join(" ");
585 let description = if visible_aliases.is_empty() {
586 localized.to_string()
587 } else {
588 format!(
589 "{} {}",
590 localized,
591 tr(locale, MessageId::HelpAliasesSuffix).replace(
592 "{aliases}",
593 &visible_aliases
594 .iter()
595 .map(|a| format!("/{a}"))
596 .collect::<Vec<_>>()
597 .join(&tr(locale, MessageId::ListSeparator))
598 )
599 )
600 };
601 let haystack = format!(
602 "{} {} {} {}",
603 label.to_ascii_lowercase(),
604 description.to_ascii_lowercase(),
605 command.usage.to_ascii_lowercase(),
606 alias_terms.to_lowercase()
607 );
608 entries.push(HelpEntry {
609 binding: None,
610 section: HelpSection::Command,
611 // Curated commands first, then the catalog; alphabetical within
612 // each by leaning on `label.clone()` in the final sort_by_key tuple.
613 sub_rank: command_sub_rank(&label),
614 usage: stated_usage(command.usage, &label),
615 label,
616 description,
617 haystack,
618 });
619 }
620
621 // Workspace commands (#3912). The registry was already consulted above to
622 // suppress shadowed built-ins; until now it never contributed a row of its
623 // own, so `.codewhale/commands/*.md` authors could not find their own work
624 // in the surface that teaches the product. `hidden` entries stay out.
625 for command in registry.iter().filter(|command| !command.hidden) {
626 let label = format!("/{}", command.name);
627 let description = command
628 .description
629 .as_deref()
630 .map(str::trim)
631 .filter(|description| !description.is_empty())
632 .unwrap_or_default()
633 .to_string();
634 let usage = command
635 .display_usage()
636 .map(str::to_owned)
637 .unwrap_or_else(|| label.clone());
638 let haystack = format!(
639 "{} {} {}",
640 label.to_ascii_lowercase(),
641 description.to_ascii_lowercase(),
642 usage.to_ascii_lowercase()
643 );
644 entries.push(HelpEntry {
645 binding: None,
646 section: HelpSection::UserCommand,
647 sub_rank: 0,
648 usage: stated_usage(&usage, &label),
649 label,
650 description,
651 haystack,
652 });
653 }
654
655 // Skills dispatch as `$name` or `/skill name`; advertise the shape the
656 // user actually types.
657 for (name, description) in skills {
658 let label = format!("${name}");
659 let description = description.trim().to_string();
660 let haystack = format!(
661 "{} {} /skill {}",
662 label.to_ascii_lowercase(),
663 description.to_ascii_lowercase(),
664 name.to_ascii_lowercase()
665 );
666 entries.push(HelpEntry {
667 binding: None,
668 section: HelpSection::Skill,
669 sub_rank: 0,
670 usage: None,
671 label,
672 description,
673 haystack,
674 });
675 }
676
677 for binding in KEYBINDINGS {
678 // macOS renders Alt chords with the Option glyph (`⌥V`), never
679 // `Alt`/`Cmd` (TUI-DOG-002 acceptance).
680 let chord = match (multiline_mode, binding.description_id) {
681 (true, MessageId::KbInsertNewline) => "Enter / Ctrl+J",
682 (true, MessageId::KbSendDraft) => "Alt+Enter / Shift+Enter (enhanced terminals)",
683 _ => binding.chord,
684 };
685 let mut label = crate::tui::shell_key_routing::display_chord(chord).into_owned();
686 // Shift+Enter depends on the startup capability receipt; Help never
687 // reads the terminal while the input pump owns it.
688 if label.contains("Shift+Enter")
689 && !crate::tui::composer_ui::terminal_can_report_shift_enter()
690 {
691 label = label.replace(" / Shift+Enter (enhanced terminals)", "");
692 }
693 let description = tr(locale, binding.description_id).into_owned();
694 let haystack = format!(
695 "{} {}",
696 label.to_ascii_lowercase(),
697 description.to_ascii_lowercase()
698 );
699 entries.push(HelpEntry {
700 binding: Some(binding.description_id),
701 section: HelpSection::Keybinding,
702 sub_rank: binding.section.rank(),
703 usage: None,
704 label,
705 description,
706 haystack,
707 });
708 }
709
710 entries
711 }
712
713 /// Romanized Chinese (pinyin) command aliases. They dispatch in every locale,
714 /// but only the Chinese packs list them: an English reader sees `/clear`, not
715 /// `/clear (aliases: /qingping)`.
716 const ROMANIZED_ALIASES: &[&str] = &[
717 "bangzhu",
718 "chongmingming",
719 "chongshi",
720 "daili",
721 "dangan",
722 "daochu",
723 "digui",
724 "fujian",
725 "gaiming",
726 "gouzi",
727 "jiazai",
728 "jihua",
729 "jineng",
730 "jinengliebiao",
731 "lianjie",
732 "maodian",
733 "moxing",
734 "moxingliebiao",
735 "qingchu",
736 "qingping",
737 "shencha",
738 "shouye",
739 "tuichu",
740 "xinren",
741 "xitong",
742 "yasuo",
743 "yuyin",
744 "yuyincontrol",
745 "yuyinsend",
746 "zhinengti",
747 "zhuye",
748 "zidong",
749 "zuoye",
750 ];
751
752 /// Whether `/help` lists `alias` beside its command for `locale`. Chinese
753 /// aliases (Han script or pinyin) are listed only in the Chinese packs.
754 fn alias_is_listed_for(locale: Locale, alias: &str) -> bool {
755 if matches!(locale, Locale::ZhHans | Locale::ZhHant) {
756 return true;
757 }
758 let han = alias
759 .chars()
760 .any(|ch| ('\u{4e00}'..='\u{9fff}').contains(&ch));
761 !han && !ROMANIZED_ALIASES.contains(&alias)
762 }
763
764 /// The usage line worth printing beside a row, or `None` when it only
765 /// restates the label.
766 ///
767 /// `/copy`'s usage is `/copy`; showing it teaches nothing and costs the row
768 /// that `/queue [list|send <n>|…]` needs. Workspace commands declare the
769 /// argument shape alone (`<environment>`), so the label is prepended to make
770 /// the same whole line a built-in already carries.
771 fn stated_usage(usage: &str, label: &str) -> Option<String> {
772 let usage = usage.trim();
773 if usage.is_empty() || usage == label {
774 return None;
775 }
776 Some(if usage.starts_with('/') {
777 usage.to_string()
778 } else {
779 format!("{label} {usage}")
780 })
781 }
782
783 /// The commands Help opens on. Everything else stays one keystroke away under
784 /// *All commands* — 103 rows sorted alphabetically is a catalog, not an answer,
785 /// and it buried the handful of commands people actually reach for.
786 ///
787 /// Membership is a product judgement, not a usage metric: these are the ones a
788 /// session needs to steer itself. The first five agree with the composer's own
789 /// curated slash menu on purpose, so the two surfaces teach the same thing.
790 const COMMON_COMMANDS: [&str; 12] = [
791 "/setup",
792 "/model",
793 "/settings",
794 "/resume",
795 "/clear",
796 "/compact",
797 "/context",
798 "/cost",
799 "/diff",
800 "/mcp",
801 "/theme",
802 "/exit",
803 ];
804
805 /// Sort rank that also selects the group: curated commands sort and group ahead
806 /// of the full catalog, because `filtered` is ordered by
807 /// `(section_rank, sub_rank, label)` and `group_key` reads the same field.
808 const COMMAND_RANK_COMMON: u8 = 0;
809 const COMMAND_RANK_ALL: u8 = 1;
810
811 fn command_sub_rank(label: &str) -> u8 {
812 if COMMON_COMMANDS.contains(&label) {
813 COMMAND_RANK_COMMON
814 } else {
815 COMMAND_RANK_ALL
816 }
817 }
818
819 fn group_key(entry: &HelpEntry) -> String {
820 match entry.section {
821 HelpSection::Command if entry.sub_rank == COMMAND_RANK_COMMON => "cmd:common".into(),
822 HelpSection::Command => "cmd:all".into(),
823 HelpSection::UserCommand => "usercmd".into(),
824 HelpSection::Skill => "skill".into(),
825 HelpSection::Keybinding => format!("kb:{}", entry.sub_rank),
826 }
827 }
828
829 fn group_label(entry: &HelpEntry, locale: Locale) -> String {
830 match entry.section {
831 HelpSection::Command if entry.sub_rank == COMMAND_RANK_COMMON => {
832 tr(locale, MessageId::HelpGroupCommonCommands).into_owned()
833 }
834 HelpSection::Command => tr(locale, MessageId::HelpGroupAllCommands).into_owned(),
835 HelpSection::Keybinding => keybinding_section_for_rank(entry.sub_rank)
836 .map(|section| section.label(locale).into_owned())
837 .unwrap_or_else(|| entry.section.label(locale).into_owned()),
838 other => other.label(locale).into_owned(),
839 }
840 }
841
842 fn keybinding_section_for_rank(
843 rank: u8,
844 ) -> Option<codewhale_engine::keybinding_table::KeybindingSection> {
845 codewhale_engine::keybinding_table::KeybindingSection::ALL
846 .into_iter()
847 .find(|section| section.rank() == rank)
848 }
849
850 fn default_collapsed(ordering: HelpOrdering) -> HashSet<String> {
851 use codewhale_engine::keybinding_table::KeybindingSection;
852 let kb_keys = KeybindingSection::ALL
853 .into_iter()
854 .map(|section| format!("kb:{}", section.rank()));
855
856 match ordering {
857 HelpOrdering::KeybindingsFirst => {
858 // Show Navigation only — the rest is a long tail the user
859 // expands or searches. Slash/skill catalogs stay folded.
860 let mut set: HashSet<String> = ["cmd:common", "cmd:all", "usercmd", "skill"]
861 .into_iter()
862 .map(str::to_string)
863 .collect();
864 set.extend(kb_keys.filter(|key| key != "kb:0"));
865 set
866 }
867 HelpOrdering::CommandsFirst => {
868 // Open on the curated commands with everything else folded. The
869 // catalogs are still one keystroke — or one keystroke of typing,
870 // since a query ignores collapse entirely — away.
871 let mut set: HashSet<String> = ["cmd:all", "usercmd", "skill"]
872 .into_iter()
873 .map(str::to_string)
874 .collect();
875 set.extend(kb_keys);
876 set
877 }
878 }
879 }
880
881 /// Joints a one-line description may shed at, longest-binding first. These
882 /// are the marks the descriptions already use: a trailing parenthetical (the
883 /// alias list), a semicolon or em-dash clause, then ordinary sentence and
884 /// comma boundaries.
885 const FIELD_JOINTS: [&str; 7] = [" (", " (", "; ", " — ", ". ", ": ", ", "];
886
887 /// Fit a description into `max_width` by shedding whole fields, never by
888 /// cutting one.
889 ///
890 /// The overlay used to hand every label and description to a
891 /// `truncate_to_width` that appended `…`. In a list of two hundred rows an
892 /// ellipsis is the worst possible mark: it promises text the row has no way
893 /// to reveal, and it lands mid-token — `(aliases: /qin…` leaves an unclosed
894 /// parenthesis, and `deepseek-v4-…` names no model, because these strings
895 /// share prefixes. So the description sheds its alias parenthetical first,
896 /// then trailing clauses at its own joints, and finally itself. The label is
897 /// never shed at all: it is the string the user has to type.
898 fn shed_to_width(text: &str, max_width: usize, locale: Locale) -> Cow<'_, str> {
899 let trimmed = text.trim_end();
900 if max_width == 0 {
901 return Cow::Borrowed("");
902 }
903 if trimmed.width() <= max_width {
904 return Cow::Borrowed(trimmed);
905 }
906 let mut best = "";
907 let mut oversize_clause = "";
908 let mut depth = 0usize;
909 for (idx, ch) in trimmed.char_indices() {
910 match ch {
911 '(' | '(' => depth += 1,
912 ')' | ')' => depth = depth.saturating_sub(1),
913 _ => {}
914 }
915 // Only cut where the parentheses balance. `(aliases: /image, /media)`
916 // holds a `: ` and a `, ` that are joints of the alias list, not of
917 // the sentence; cutting there left `(aliases: /image, /media` with the
918 // parenthesis hanging open — no ellipsis, and still a broken row.
919 if depth > 0 {
920 continue;
921 }
922 let rest = &trimmed[idx..];
923 if !FIELD_JOINTS.iter().any(|joint| rest.starts_with(joint)) {
924 continue;
925 }
926 let head = trimmed[..idx].trim_end_matches([' ', ',', ';', ':', '—', '-']);
927 if head.is_empty() {
928 continue;
929 }
930 let width = head.width();
931 if width <= max_width {
932 if width > best.width() {
933 best = head;
934 }
935 } else if oversize_clause.is_empty() {
936 // The main clause was one column over, so the joint itself did
937 // not fire. Word-shed that clause rather than the alias list
938 // hanging off it — otherwise `/automation` keeps the adjectives
939 // and loses `automations`. Heads grow left to right, so the first
940 // oversize one is the main clause; a later, wider head is that
941 // clause plus everything trailing it, which is the text this
942 // branch exists to shed.
943 oversize_clause = head;
944 }
945 }
946 if best.is_empty() {
947 // Roughly half of these descriptions are a single clause with no
948 // joint at all — "Toggle background advisor watcher on/off for this
949 // session". Shedding the whole field there left a bare `/advisor`
950 // beside rows that still had text, which reads as a broken renderer
951 // rather than as a decision. So the last resort is the sentence's
952 // own short form: whole words, no mark, and the same text restated
953 // at panel width one row up in the detail slot. What is never done
954 // is append `…`, which
955 // would claim text this overlay has no way to reveal.
956 let source = if oversize_clause.is_empty() {
957 trimmed
958 } else {
959 oversize_clause
960 };
961 shed_to_words(source, max_width, locale)
962 } else {
963 Cow::Borrowed(best)
964 }
965 }
966
967 /// Longest prefix of `text` that fits `max_width` display columns, cut on a
968 /// character boundary. Used when there is no word boundary to cut on.
969 fn widest_char_prefix(text: &str, max_width: usize) -> &str {
970 let mut fitted = 0usize;
971 for (idx, ch) in text.char_indices() {
972 let next = idx + ch.len_utf8();
973 if text[..next].width() > max_width {
974 break;
975 }
976 fitted = next;
977 }
978 &text[..fitted]
979 }
980
981 /// Longest whole-word prefix of `text` that fits, with trailing short
982 /// function words dropped so the phrase does not end on `to an`.
983 ///
984 /// The scan used to stop on a space, so the last word was never included
985 /// even when it fitted, and the two-pass short-word trim then left a simple
986 /// verb + modifier + noun phrase without the noun — `/automation` read
987 /// `Manage durable scheduled`. In English, if that prefix lost the head noun,
988 /// intervening modifiers are dropped so the noun survives.
989 fn shed_to_words(text: &str, max_width: usize, locale: Locale) -> Cow<'_, str> {
990 let mut end = 0usize;
991 for (idx, ch) in text.char_indices() {
992 if ch == ' ' && text[..idx].width() <= max_width {
993 end = idx;
994 }
995 }
996 // Include the last word when the whole phrase fits. The loop above only
997 // fires on spaces, so without this the head noun was always eaten.
998 if text.width() <= max_width {
999 end = text.len();
1000 }
1001 if end == 0 {
1002 // No usable space boundary. That is the normal case for Japanese,
1003 // Chinese and Thai, which do not delimit words with spaces at all —
1004 // the loop above can never fire, so this used to return "" and every
1005 // description in those locales rendered blank. It also happens in
1006 // English whenever the first space falls beyond `max_width`.
1007 // Fall back to the widest whole-character prefix that fits.
1008 return Cow::Borrowed(
1009 widest_char_prefix(text, max_width).trim_end_matches([' ', ',', ';', ':', '—', '-']),
1010 );
1011 }
1012 let mut head = &text[..end];
1013 // Two passes at most: enough for `to an`, not enough to eat a real word.
1014 for _ in 0..2 {
1015 let Some(cut) = head.rfind(' ') else { break };
1016 if head.len() - cut - 1 > 3 {
1017 break;
1018 }
1019 head = &head[..cut];
1020 }
1021 let head = head.trim_end_matches([' ', ',', ';', ':', '—', '-']);
1022 if locale == Locale::En
1023 && let Some(kept) = keep_simple_head_noun(text, head, max_width)
1024 {
1025 return kept;
1026 }
1027 Cow::Borrowed(head)
1028 }
1029
1030 fn is_short_function_word(word: &str) -> bool {
1031 !word.is_empty() && word.len() <= 3
1032 }
1033
1034 fn is_plain_content_word(word: &str) -> bool {
1035 !word.is_empty()
1036 && word
1037 .chars()
1038 .all(|ch| ch.is_ascii_alphabetic() || matches!(ch, '-' | '/'))
1039 }
1040
1041 /// Restore the head noun of a simple `verb modifier* noun` phrase when the
1042 /// prefix trim dropped it. Phrases with a short function word after the verb
1043 /// (`Toggle the background advisor for this session`) stay prefix-trimmed,
1044 /// as do rows that carry punctuation (`(aliases: /image, /media)`).
1045 fn keep_simple_head_noun<'a>(
1046 text: &'a str,
1047 prefix: &'a str,
1048 max_width: usize,
1049 ) -> Option<Cow<'a, str>> {
1050 let words: Vec<&str> = text.split(' ').filter(|word| !word.is_empty()).collect();
1051 if words.len() < 2 {
1052 return None;
1053 }
1054 let noun = *words.last()?;
1055 if is_short_function_word(noun) || prefix.ends_with(noun) {
1056 return None;
1057 }
1058 if !words.iter().all(|word| is_plain_content_word(word)) {
1059 return None;
1060 }
1061 if words[1..words.len() - 1]
1062 .iter()
1063 .any(|word| is_short_function_word(word))
1064 {
1065 return None;
1066 }
1067 if noun.width() > max_width {
1068 return None;
1069 }
1070 let verb = words[0];
1071 let modifiers = &words[1..words.len() - 1];
1072 for skip in 0..=modifiers.len() {
1073 let mut candidate = String::from(verb);
1074 for modifier in &modifiers[skip..] {
1075 candidate.push(' ');
1076 candidate.push_str(modifier);
1077 }
1078 candidate.push(' ');
1079 candidate.push_str(noun);
1080 if candidate.width() <= max_width {
1081 if text.starts_with(&candidate)
1082 && text
1083 .as_bytes()
1084 .get(candidate.len())
1085 .is_none_or(|byte| *byte == b' ')
1086 {
1087 return Some(Cow::Borrowed(&text[..candidate.len()]));
1088 }
1089 return Some(Cow::Owned(candidate));
1090 }
1091 }
1092 Some(Cow::Borrowed(noun))
1093 }
1094
1095 impl ModalView for HelpView {
1096 fn kind(&self) -> ModalKind {
1097 ModalKind::Help
1098 }
1099
1100 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
1101 self
1102 }
1103
1104 fn on_became_top(&mut self, at: Instant) {
1105 self.start_key_pulse(at);
1106 }
1107
1108 fn tick(&mut self) -> ViewAction {
1109 if let Some(at) = self.key_pressed {
1110 if at.elapsed() >= keycaps::PULSE {
1111 self.key_pressed = None;
1112 }
1113 return ViewAction::Redraw;
1114 }
1115 ViewAction::None
1116 }
1117
1118 fn handle_paste(&mut self, text: &str) -> bool {
1119 self.query.push_str(
1120 &text
1121 .trim_end_matches(['\r', '\n'])
1122 .replace("\r\n", "\n")
1123 .replace(char::is_control, " "),
1124 );
1125 self.refilter();
1126 true
1127 }
1128
1129 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
1130 // Scroll clamps at the ends (keyboard Up/Down wrap); wheel-wrapping
1131 // reads as disorienting.
1132 match mouse.kind {
1133 MouseEventKind::ScrollUp => self.move_selection(-1),
1134 MouseEventKind::ScrollDown => self.move_selection(1),
1135 MouseEventKind::Down(MouseButton::Left) => {
1136 let hit = self.row_hitboxes.borrow().iter().find_map(|(rect, hit)| {
1137 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
1138 .then_some(hit.clone())
1139 });
1140 if let Some(hit) = hit {
1141 match hit {
1142 HelpHit::Group(key) => self.toggle_group(&key),
1143 HelpHit::Entry(slot) => self.set_focus(HelpHit::Entry(slot)),
1144 }
1145 }
1146 }
1147 _ => {}
1148 }
1149 ViewAction::None
1150 }
1151
1152 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
1153 match key.code {
1154 KeyCode::Esc => ViewAction::Close,
1155 KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1156 ViewAction::Close
1157 }
1158 KeyCode::Up => {
1159 self.move_selection_wrapping(-1);
1160 ViewAction::None
1161 }
1162 KeyCode::Down => {
1163 self.move_selection_wrapping(1);
1164 ViewAction::None
1165 }
1166 KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1167 self.move_selection_wrapping(-1);
1168 ViewAction::None
1169 }
1170 KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1171 self.move_selection_wrapping(1);
1172 ViewAction::None
1173 }
1174 KeyCode::PageUp => {
1175 self.move_selection(-10);
1176 ViewAction::None
1177 }
1178 KeyCode::PageDown => {
1179 self.move_selection(10);
1180 ViewAction::None
1181 }
1182 KeyCode::Home => {
1183 if let Some(first) = self.focusable_rows().first().cloned() {
1184 self.set_focus(first);
1185 }
1186 ViewAction::None
1187 }
1188 KeyCode::End => {
1189 if let Some(last) = self.focusable_rows().last().cloned() {
1190 self.set_focus(last);
1191 }
1192 ViewAction::None
1193 }
1194 KeyCode::Enter => {
1195 if let Some(HelpHit::Group(key)) = self.focus.clone() {
1196 self.toggle_group(&key);
1197 }
1198 ViewAction::None
1199 }
1200 KeyCode::Right => {
1201 if let Some(HelpHit::Group(key)) = self.focus.clone()
1202 && self.group_is_collapsed(&key)
1203 {
1204 self.toggle_group(&key);
1205 }
1206 ViewAction::None
1207 }
1208 KeyCode::Left => {
1209 if let Some(key) = self.focused_group_key() {
1210 match self.focus.as_ref() {
1211 Some(HelpHit::Entry(_)) => self.set_focus(HelpHit::Group(key)),
1212 Some(HelpHit::Group(_)) if !self.group_is_collapsed(&key) => {
1213 self.collapsed.insert(key.clone());
1214 self.set_focus(HelpHit::Group(key));
1215 self.clamp_focus_to_visible();
1216 }
1217 _ => {}
1218 }
1219 }
1220 ViewAction::None
1221 }
1222 KeyCode::Backspace => {
1223 self.query.pop();
1224 self.refilter();
1225 ViewAction::None
1226 }
1227 // Terminals where stty erase == ^H send Ctrl+H instead of
1228 // Backspace (DEL). Treat it identically so the filter input
1229 // works across all platforms (#958).
1230 KeyCode::Char('h') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1231 self.query.pop();
1232 self.refilter();
1233 ViewAction::None
1234 }
1235 KeyCode::Char(c)
1236 if !c.is_control()
1237 && (key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT) =>
1238 {
1239 self.query.push(c);
1240 self.refilter();
1241 ViewAction::None
1242 }
1243 _ => ViewAction::None,
1244 }
1245 }
1246
1247 fn render(&self, area: Rect, buf: &mut Buffer) {
1248 self.row_hitboxes.borrow_mut().clear();
1249 let inner = render_rounded_surface(
1250 area,
1251 buf,
1252 format!(
1253 "{} — {}",
1254 self.tr(MessageId::HelpTitle),
1255 self.tr(MessageId::HelpSubtitle)
1256 ),
1257 None,
1258 !self.query.is_empty(),
1259 );
1260
1261 let content = render_rounded_footer(
1262 inner,
1263 buf,
1264 &[
1265 ActionHint::new("", self.tr(MessageId::HelpFooterMove)),
1266 ActionHint::new("", self.tr(MessageId::HelpFooterJump)),
1267 ActionHint::new("", self.tr(MessageId::HelpFooterClose)),
1268 ],
1269 );
1270
1271 let mut lines: Vec<Line<'static>> = Vec::new();
1272
1273 let query_label = if self.query.is_empty() {
1274 self.tr(MessageId::HelpFilterPlaceholder).to_string()
1275 } else {
1276 format!("{}{}", self.tr(MessageId::HelpFilterPrefix), self.query)
1277 };
1278 let match_count = if self.query.is_empty() {
1279 self.tr(MessageId::HelpEntryCount)
1280 .replace("{count}", &self.entries.len().to_string())
1281 } else {
1282 self.tr(MessageId::HelpMatchCount)
1283 .replace("{shown}", &self.filtered.len().to_string())
1284 .replace("{total}", &self.entries.len().to_string())
1285 };
1286 let rows = self.render_rows();
1287 let keycap_row = self.ordering == HelpOrdering::KeybindingsFirst && content.height >= 6;
1288 let visible_rows = content.height.saturating_sub(2 + u16::from(keycap_row)) as usize;
1289 let row_start = Self::visible_row_start(&rows, self.focus.as_ref(), visible_rows.max(1));
1290 let content = render_panel_scroll_rail(
1291 content,
1292 buf,
1293 rows.len(),
1294 row_start,
1295 visible_rows.max(1),
1296 true,
1297 );
1298
1299 let inner_width = content.width as usize;
1300 let label_cap = 28.min(inner_width.saturating_sub(8));
1301 let label_widths = self.label_widths(label_cap);
1302
1303 let gap = (content.width as usize)
1304 .saturating_sub(query_label.width() + match_count.width())
1305 .max(2);
1306 lines.push(Line::from(vec![
1307 Span::styled(
1308 query_label,
1309 Style::default()
1310 .fg(palette::WHALE_ACTION)
1311 .add_modifier(Modifier::BOLD),
1312 ),
1313 Span::raw(" ".repeat(gap)),
1314 Span::styled(match_count, Style::default().fg(palette::TEXT_MUTED)),
1315 ]));
1316
1317 if keycap_row {
1318 lines.push(Line::default());
1319 }
1320 let detail = self
1321 .focused_entry_detail(inner_width, label_cap, &label_widths)
1322 .unwrap_or_default();
1323 let detail_used = detail.width();
1324 lines.push(Line::from(Span::styled(
1325 detail,
1326 Style::default().fg(palette::TEXT_SOFT),
1327 )));
1328
1329 if self.filtered.is_empty() {
1330 lines.push(Line::from(Span::styled(
1331 self.tr(MessageId::HelpNoMatches),
1332 Style::default()
1333 .fg(palette::TEXT_MUTED)
1334 .add_modifier(Modifier::ITALIC),
1335 )));
1336 } else {
1337 let header_lines = lines.len();
1338 let visible_budget = (content.height as usize)
1339 .saturating_sub(header_lines)
1340 .max(1);
1341
1342 for row in rows.iter().skip(row_start).take(visible_budget) {
1343 match *row {
1344 HelpRenderRow::Group {
1345 ref key,
1346 ref label,
1347 count,
1348 collapsed,
1349 } => {
1350 let row_y = content.y.saturating_add(lines.len() as u16);
1351 self.row_hitboxes.borrow_mut().push((
1352 Rect::new(content.x, row_y, content.width, 1),
1353 HelpHit::Group(key.clone()),
1354 ));
1355 let ascii = crate::tui::color_compat::ascii_safe_enabled();
1356 let marker = if collapsed {
1357 if ascii { ">" } else { "▸" }
1358 } else if ascii {
1359 "v"
1360 } else {
1361 "▾"
1362 };
1363 let is_focused = self.focus.as_ref() == Some(&HelpHit::Group(key.clone()));
1364 if is_focused {
1365 let sel = menu_style::selected_row_style();
1366 lines.push(pad_selected_line(
1367 Line::from(Span::styled(
1368 format!("{marker} {label} ({count})"),
1369 sel,
1370 )),
1371 inner_width,
1372 sel,
1373 ));
1374 } else {
1375 lines.push(Line::from(vec![
1376 Span::styled(
1377 format!("{marker} {label} "),
1378 Style::default()
1379 .fg(palette::WHALE_ACTION)
1380 .add_modifier(Modifier::BOLD),
1381 ),
1382 Span::styled(
1383 format!("({count})"),
1384 Style::default().fg(palette::TEXT_MUTED),
1385 ),
1386 ]));
1387 }
1388 }
1389 HelpRenderRow::Entry { slot, entry_idx } => {
1390 let row_y = content.y.saturating_add(lines.len() as u16);
1391 self.row_hitboxes.borrow_mut().push((
1392 Rect::new(content.x, row_y, content.width, 1),
1393 HelpHit::Entry(slot),
1394 ));
1395 let entry = &self.entries[entry_idx];
1396 let is_selected = self.focus.as_ref() == Some(&HelpHit::Entry(slot));
1397 let cursor = format!(
1398 "{} ",
1399 codewhale_tui_kit::glyphs::selection_marker(is_selected)
1400 );
1401 let label_width = label_widths
1402 .get(&group_key(entry))
1403 .copied()
1404 .unwrap_or(label_cap);
1405 let pad = label_width.saturating_sub(entry.label.width());
1406 let desc_capacity =
1407 inner_width.saturating_sub(cursor.width() + label_width + 2);
1408 let desc = shed_to_width(&entry.description, desc_capacity, self.locale);
1409 let (label_style, desc_style) = if is_selected {
1410 (
1411 menu_style::selected_row_style(),
1412 menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT),
1413 )
1414 } else {
1415 (
1416 Style::default().fg(palette::TEXT_PRIMARY),
1417 Style::default().fg(palette::TEXT_MUTED),
1418 )
1419 };
1420 let mut spans = vec![
1421 Span::styled(format!("{cursor}{}", entry.label), label_style),
1422 Span::styled(" ".repeat(pad + 2), label_style),
1423 ];
1424 if !desc.is_empty() {
1425 spans.push(Span::styled(desc.to_string(), desc_style));
1426 }
1427 let line = Line::from(spans);
1428 if is_selected {
1429 lines.push(pad_selected_line(line, inner_width, desc_style));
1430 } else {
1431 lines.push(line);
1432 }
1433 }
1434 }
1435 }
1436 }
1437
1438 Paragraph::new(lines).render(content, buf);
1439 if let Some(entry) = self.selected_shortcut()
1440 && content.height >= 3
1441 {
1442 let offset = if keycap_row || detail_used == 0 {
1443 0
1444 } else {
1445 detail_used.saturating_add(2)
1446 };
1447 let offset = offset.min(usize::from(content.width)) as u16;
1448 let band = Rect::new(content.x + offset, content.y + 1, content.width - offset, 1);
1449 keycaps::paint(
1450 &entry.label,
1451 band,
1452 buf,
1453 &self.theme,
1454 self.key_pressed.map(|at| at.elapsed()),
1455 crate::tui::color_compat::ascii_safe_enabled(),
1456 );
1457 }
1458 }
1459 }
1460
1461 #[cfg(test)]
1462 mod tests {
1463 use super::*;
1464 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
1465
1466 fn key(code: KeyCode) -> KeyEvent {
1467 KeyEvent::new(code, KeyModifiers::NONE)
1468 }
1469
1470 fn type_filter(view: &mut HelpView, text: &str) {
1471 for ch in text.chars() {
1472 view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
1473 }
1474 }
1475
1476 fn first_filtered_section(view: &HelpView) -> HelpSection {
1477 view.entries[*view
1478 .filtered
1479 .first()
1480 .expect("help should contain at least one entry")]
1481 .section
1482 }
1483
1484 #[test]
1485 fn composer_help_selects_the_active_binding_without_delaying_input() {
1486 use crate::tui::app::{App, OnboardingState};
1487 let workspace = tempfile::TempDir::new().unwrap();
1488 let mut app = App::new(
1489 crate::tui::test_support::test_tui_options(workspace.path()),
1490 &codewhale_runtime::config::Config::default(),
1491 );
1492 app.onboarding = OnboardingState::None;
1493 app.launch.visible = false;
1494 app.redaction_gate = false;
1495 app.work_surface.focused = false;
1496 let selected = |app: &App| {
1497 let view = HelpView::new_for_app(app, true);
1498 view.selected_shortcut().and_then(|entry| entry.binding)
1499 };
1500 assert_eq!(selected(&app), Some(MessageId::KbScrollTranscriptAlt));
1501 app.is_loading = true;
1502 assert_eq!(selected(&app), Some(MessageId::KbSendDraft));
1503 app.scroll_to_transcript_line(1);
1504 assert_eq!(selected(&app), Some(MessageId::KbJumpTopBottom));
1505
1506 let mut view = HelpView::new_for_app(&app, true);
1507 view.animate_keys = true;
1508 view.on_became_top(Instant::now());
1509 assert!(matches!(view.tick(), ViewAction::Redraw));
1510 assert!(matches!(
1511 view.handle_key(key(KeyCode::Esc)),
1512 ViewAction::Close
1513 ));
1514 view.on_became_top(Instant::now() - keycaps::PULSE);
1515 assert!(matches!(view.tick(), ViewAction::Redraw));
1516 assert!(matches!(view.tick(), ViewAction::None));
1517 view.animate_keys = false;
1518 view.on_became_top(Instant::now());
1519 assert!(matches!(view.tick(), ViewAction::None));
1520 }
1521
1522 #[test]
1523 fn empty_filter_lists_all_entries() {
1524 let view = HelpView::new();
1525 // Total = registered slash commands + catalogued keybindings.
1526 let expected = commands::command_infos().len() + KEYBINDINGS.len();
1527 assert_eq!(view.filtered.len(), expected);
1528 assert_eq!(view.entries.len(), expected);
1529 }
1530
1531 #[test]
1532 fn entry_points_choose_the_section_they_promise() {
1533 let commands = HelpView::new_for_locale(Locale::En);
1534 assert_eq!(commands.ordering, HelpOrdering::CommandsFirst);
1535 assert_eq!(first_filtered_section(&commands), HelpSection::Command);
1536
1537 let shortcuts = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst);
1538 assert_eq!(shortcuts.ordering, HelpOrdering::KeybindingsFirst);
1539 assert_eq!(first_filtered_section(&shortcuts), HelpSection::Keybinding);
1540 let registry = commands::user_registry::UserCommandRegistry::new();
1541 let multiline = HelpView::new_with_registry(
1542 Locale::En,
1543 HelpOrdering::KeybindingsFirst,
1544 &registry,
1545 &[],
1546 true,
1547 );
1548 assert!(multiline.entries.iter().any(|entry| {
1549 entry.label == "Enter / Ctrl+J"
1550 && entry.description == tr(Locale::En, MessageId::KbInsertNewline)
1551 }));
1552 assert!(multiline.entries.iter().any(|entry| {
1553 !entry.label.contains("Shift+Enter")
1554 && entry.description == tr(Locale::En, MessageId::KbSendDraft)
1555 && entry.label == crate::tui::shell_key_routing::display_chord("Alt+Enter")
1556 }));
1557 }
1558
1559 #[test]
1560 fn workspace_commands_and_skills_are_findable_with_provenance() {
1561 // #3912: both surfaces executed and autocompleted but were absent
1562 // from the surface that teaches the product.
1563 let tmp = tempfile::TempDir::new().unwrap();
1564 crate::test_support::trust_workspace(tmp.path());
1565 let commands_dir = tmp.path().join(".codewhale").join("commands");
1566 std::fs::create_dir_all(&commands_dir).unwrap();
1567 std::fs::write(
1568 commands_dir.join("shipit.md"),
1569 "---\ndescription: Cut a release candidate\n---\nbody",
1570 )
1571 .unwrap();
1572 std::fs::write(
1573 commands_dir.join("secret.md"),
1574 "---\ndescription: Internal only\nhidden: true\n---\nbody",
1575 )
1576 .unwrap();
1577
1578 let skills = vec![(
1579 "codereview".to_string(),
1580 "Review a diff for defects".to_string(),
1581 )];
1582 let mut view = HelpView::new_for_workspace(Locale::En, tmp.path(), &skills);
1583
1584 let user = view
1585 .entries
1586 .iter()
1587 .find(|entry| entry.label == "/shipit")
1588 .expect("workspace command should be listed");
1589 assert_eq!(user.section, HelpSection::UserCommand);
1590 assert!(user.description.contains("Cut a release candidate"));
1591
1592 let skill = view
1593 .entries
1594 .iter()
1595 .find(|entry| entry.label == "$codereview")
1596 .expect("discovered skill should be listed");
1597 assert_eq!(skill.section, HelpSection::Skill);
1598
1599 assert!(
1600 !view.entries.iter().any(|entry| entry.label == "/secret"),
1601 "hidden workspace commands stay out of the overlay"
1602 );
1603
1604 // Both are reachable through the existing substring filter.
1605 type_filter(&mut view, "shipit");
1606 assert!(
1607 view.filtered
1608 .iter()
1609 .any(|idx| view.entries[*idx].label == "/shipit")
1610 );
1611
1612 let mut view = HelpView::new_for_workspace(Locale::En, tmp.path(), &skills);
1613 type_filter(&mut view, "review a diff");
1614 assert!(
1615 view.filtered
1616 .iter()
1617 .any(|idx| view.entries[*idx].label == "$codereview"),
1618 "skills are findable by their description"
1619 );
1620 }
1621
1622 #[test]
1623 fn skill_rows_advertise_the_slash_skill_shape_too() {
1624 let tmp = tempfile::TempDir::new().unwrap();
1625 let skills = vec![("audit".to_string(), "Audit the tree".to_string())];
1626 let mut view = HelpView::new_for_workspace(Locale::En, tmp.path(), &skills);
1627 type_filter(&mut view, "/skill audit");
1628 assert!(
1629 view.filtered
1630 .iter()
1631 .any(|idx| view.entries[*idx].label == "$audit"),
1632 "searching the /skill form finds the skill"
1633 );
1634 }
1635
1636 #[test]
1637 fn help_hides_builtins_with_shadowed_canonical_names() {
1638 let registry = commands::user_registry::UserCommandRegistry::from_loaded(vec![(
1639 "help".to_string(),
1640 "---\ndescription: Custom help workflow\n---\ncustom help".to_string(),
1641 )]);
1642 let entries = build_entries(Locale::En, &registry, &[], false);
1643
1644 // The built-in row is suppressed so the name is not advertised twice.
1645 assert!(
1646 !entries
1647 .iter()
1648 .any(|entry| entry.label == "/help" && entry.section == HelpSection::Command),
1649 "the shadowed built-in must not keep its own row"
1650 );
1651 // Since #3912 the shadowing workspace command supplies the row instead
1652 // of the name vanishing from help entirely.
1653 let user = entries
1654 .iter()
1655 .find(|entry| entry.label == "/help")
1656 .expect("the user command that shadows /help should be listed");
1657 assert_eq!(user.section, HelpSection::UserCommand);
1658 assert!(user.description.contains("Custom help workflow"));
1659 }
1660
1661 #[test]
1662 fn substring_filter_narrows_to_command() {
1663 let mut view = HelpView::new();
1664 type_filter(&mut view, "mode [work");
1665 assert!(!view.filtered.is_empty());
1666 // Every filtered entry should genuinely contain the query in its
1667 // searchable haystack — no false positives slipped past.
1668 for idx in &view.filtered {
1669 assert!(
1670 view.entries[*idx].haystack.contains("mode [work"),
1671 "entry {:?} leaked through `mode [work` filter",
1672 view.entries[*idx]
1673 );
1674 }
1675 // The unified `/mode` command must surface when filtering for a
1676 // concrete mode value from the visible vocabulary.
1677 assert!(
1678 view.filtered
1679 .iter()
1680 .any(|idx| view.entries[*idx].label == "/mode"),
1681 "/mode should match the `mode [work` filter"
1682 );
1683 }
1684
1685 #[test]
1686 fn help_filter_consumes_bracketed_paste() {
1687 let mut stack = crate::tui::views::ViewStack::new();
1688 stack.push(HelpView::new());
1689 stack.handle_key(key(KeyCode::Char('r')));
1690 assert!(stack.handle_paste("esume\r\n"));
1691
1692 let mut modal = stack.pop().unwrap();
1693 let view = modal.as_any_mut().downcast_mut::<HelpView>().unwrap();
1694 assert_eq!(view.query, "resume");
1695 assert!(
1696 view.filtered
1697 .iter()
1698 .any(|idx| view.entries[*idx].label == "/resume")
1699 );
1700 }
1701
1702 #[test]
1703 fn substring_filter_finds_keybinding_by_chord() {
1704 let mut view = HelpView::new();
1705 type_filter(&mut view, "ctrl+r");
1706 assert!(!view.filtered.is_empty(), "Ctrl+R should match");
1707 assert!(
1708 view.filtered
1709 .iter()
1710 .any(|idx| view.entries[*idx].label.eq_ignore_ascii_case("ctrl+r")),
1711 "Ctrl+R chord must surface in the filtered set"
1712 );
1713 }
1714
1715 #[test]
1716 fn multiple_terms_act_as_and() {
1717 let mut view = HelpView::new();
1718 type_filter(&mut view, "session picker");
1719 assert!(
1720 !view.filtered.is_empty(),
1721 "expected at least one entry mentioning both `session` and `picker`"
1722 );
1723 for idx in &view.filtered {
1724 let haystack = &view.entries[*idx].haystack;
1725 assert!(
1726 haystack.contains("session") && haystack.contains("picker"),
1727 "entry {:?} leaked through `session picker` AND filter",
1728 view.entries[*idx]
1729 );
1730 }
1731 }
1732
1733 #[test]
1734 fn unknown_filter_yields_empty_set() {
1735 let mut view = HelpView::new();
1736 type_filter(&mut view, "zzzqqxxnope");
1737 assert!(view.filtered.is_empty());
1738 assert_eq!(view.selected, 0);
1739 }
1740
1741 #[test]
1742 fn backspace_widens_match_set() {
1743 let mut view = HelpView::new();
1744 // Near-miss against the still-visible mode vocabulary so the last
1745 // character removes a unique miss and broadens the match set.
1746 type_filter(&mut view, "modez");
1747 let narrow = view.filtered.len();
1748 view.handle_key(key(KeyCode::Backspace));
1749 let wider = view.filtered.len();
1750 assert!(
1751 wider > narrow,
1752 "backspace must broaden the matching set (was {narrow}, now {wider})"
1753 );
1754 }
1755
1756 #[test]
1757 fn ctrl_h_widens_match_set() {
1758 let mut view = HelpView::new();
1759 type_filter(&mut view, "modez");
1760 let narrow = view.filtered.len();
1761 view.handle_key(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL));
1762 let wider = view.filtered.len();
1763 assert!(
1764 wider > narrow,
1765 "Ctrl+H must behave as Backspace, broadening the matching set (was {narrow}, now {wider})"
1766 );
1767 }
1768
1769 #[test]
1770 fn esc_closes_overlay() {
1771 let mut view = HelpView::new();
1772 let action = view.handle_key(key(KeyCode::Esc));
1773 assert!(matches!(action, ViewAction::Close));
1774 }
1775
1776 #[test]
1777 fn ctrl_c_closes_overlay() {
1778 let mut view = HelpView::new();
1779 let action = view.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
1780 assert!(matches!(action, ViewAction::Close));
1781 }
1782
1783 #[test]
1784 fn help_search_owns_initial_q() {
1785 for query in ["queue", "Queue", "q 队列é"] {
1786 let mut stack = crate::tui::views::ViewStack::new();
1787 stack.push(HelpView::new());
1788 for ch in query.chars() {
1789 let modifiers = if ch.is_uppercase() {
1790 KeyModifiers::SHIFT
1791 } else {
1792 KeyModifiers::NONE
1793 };
1794 assert!(
1795 stack
1796 .handle_key(KeyEvent::new(KeyCode::Char(ch), modifiers))
1797 .is_empty()
1798 );
1799 assert_eq!(stack.top_kind(), Some(ModalKind::Help), "{query:?}");
1800 }
1801 let mut modal = stack.pop().unwrap();
1802 let view = modal.as_any_mut().downcast_mut::<HelpView>().unwrap();
1803 assert_eq!(view.query, query);
1804 if query.eq_ignore_ascii_case("queue") {
1805 assert!(
1806 view.filtered
1807 .iter()
1808 .any(|&i| view.entries[i].label == "/queue")
1809 );
1810 }
1811 view.handle_key(key(KeyCode::Backspace));
1812 assert_eq!(
1813 view.query,
1814 query
1815 .chars()
1816 .take(query.chars().count() - 1)
1817 .collect::<String>()
1818 );
1819 assert!(matches!(
1820 view.handle_key(key(KeyCode::Esc)),
1821 ViewAction::Close
1822 ));
1823 }
1824 }
1825
1826 #[test]
1827 fn arrow_keys_move_selection_and_wrap_edges() {
1828 let mut view = HelpView::new();
1829 let focusable = view.focusable_rows();
1830 assert!(
1831 focusable.len() >= 3,
1832 "need at least three visible help rows"
1833 );
1834 // Help opens on the first entry, not the header above it: the detail
1835 // row under the filter reads the focused entry, and a header has no
1836 // description to put there.
1837 assert_eq!(view.focus.as_ref(), Some(&focusable[1]));
1838 // Up returns to its group; another Up wraps to the final visible row.
1839 view.handle_key(key(KeyCode::Up));
1840 assert_eq!(view.focus.as_ref(), focusable.first());
1841 view.handle_key(key(KeyCode::Up));
1842 assert_eq!(view.focus.as_ref(), focusable.last());
1843 // Down from last wraps to first; End still jumps to the last visible row.
1844 view.handle_key(key(KeyCode::Down));
1845 assert_eq!(view.focus.as_ref(), focusable.first());
1846 view.handle_key(key(KeyCode::Down));
1847 assert_eq!(view.focus.as_ref(), Some(&focusable[1]));
1848 view.handle_key(key(KeyCode::End));
1849 assert_eq!(view.focus.as_ref(), focusable.last());
1850 }
1851
1852 #[test]
1853 fn mouse_click_selects_visible_help_row() {
1854 let mut view = HelpView::new();
1855 let area = Rect::new(0, 0, 100, 30);
1856 let mut buf = Buffer::empty(area);
1857 view.render(area, &mut buf);
1858 let (rect, slot) = view
1859 .row_hitboxes
1860 .borrow()
1861 .iter()
1862 .find_map(|(rect, hit)| match hit {
1863 HelpHit::Entry(slot) => Some((*rect, *slot)),
1864 HelpHit::Group(_) => None,
1865 })
1866 .expect("at least one entry hitbox");
1867
1868 view.handle_mouse(MouseEvent {
1869 kind: MouseEventKind::Down(MouseButton::Left),
1870 column: rect.x,
1871 row: rect.y,
1872 modifiers: KeyModifiers::NONE,
1873 });
1874
1875 assert_eq!(view.selected, slot);
1876 assert_eq!(view.focus, Some(HelpHit::Entry(slot)));
1877 }
1878
1879 /// `/help` used to open on all 103 slash commands sorted alphabetically —
1880 /// a catalog, not an answer, and it buried the handful of commands a
1881 /// session actually steers itself with. It opens on the curated group now,
1882 /// with the catalog one keystroke below it.
1883 #[test]
1884 fn help_opens_on_the_curated_commands_with_the_catalog_folded() {
1885 let view = HelpView::new();
1886 assert!(
1887 !view.group_is_collapsed("cmd:common"),
1888 "the curated commands are the point of opening Help"
1889 );
1890 assert!(
1891 view.group_is_collapsed("cmd:all"),
1892 "the full catalog stays folded until asked for"
1893 );
1894
1895 let rows = view.render_rows();
1896 let entries = rows
1897 .iter()
1898 .filter(|row| matches!(row, HelpRenderRow::Entry { .. }))
1899 .count();
1900 assert!(
1901 entries <= COMMON_COMMANDS.len(),
1902 "Help opened with {entries} rows; only the curated set should be expanded: {:?}",
1903 rows.iter()
1904 .filter_map(|row| match row {
1905 HelpRenderRow::Entry { entry_idx, .. } =>
1906 Some(view.entries[*entry_idx].label.clone()),
1907 _ => None,
1908 })
1909 .collect::<Vec<_>>()
1910 );
1911
1912 // Every curated command is a real registered command, and each is on
1913 // screen. A typo here would silently shrink the opening view.
1914 // Distinct labels: a workspace command may share a built-in's name,
1915 // and that is a naming collision, not a missing curated entry.
1916 let shown: std::collections::BTreeSet<&str> = view
1917 .filtered
1918 .iter()
1919 .map(|idx| view.entries[*idx].label.as_str())
1920 .filter(|label| COMMON_COMMANDS.contains(label))
1921 .collect();
1922 assert_eq!(
1923 shown.len(),
1924 COMMON_COMMANDS.len(),
1925 "curated commands missing from the registry: {:?}",
1926 COMMON_COMMANDS
1927 .iter()
1928 .filter(|name| !shown.contains(*name))
1929 .collect::<Vec<_>>()
1930 );
1931
1932 // Typing reaches the folded catalog without expanding anything by hand.
1933 let mut view = view;
1934 type_filter(&mut view, "/advisor");
1935 assert!(
1936 view.filtered
1937 .iter()
1938 .any(|idx| view.entries[*idx].label == "/advisor"),
1939 "a query must reach commands inside the folded catalog"
1940 );
1941 }
1942
1943 /// Help opens with the full command catalog folded. Tests about layout,
1944 /// scrolling or a specific catalog command open it first — what they
1945 /// exercise is the rendering of those rows, not the default fold state,
1946 /// which `help_opens_on_the_curated_commands` covers on its own.
1947 fn view_with_catalog_open() -> HelpView {
1948 let mut view = HelpView::new();
1949 view.toggle_group("cmd:all");
1950 view.focus = None;
1951 view
1952 }
1953
1954 #[test]
1955 fn visible_window_keeps_selected_entry_visible_after_scroll() {
1956 let mut view = view_with_catalog_open();
1957 let selected = view
1958 .filtered
1959 .iter()
1960 .position(|idx| view.entries[*idx].label == "/home")
1961 .expect("/home command should be present");
1962 view.selected = selected;
1963 view.focus = Some(HelpHit::Entry(selected));
1964
1965 let rows = view.render_rows();
1966 let row_start = HelpView::visible_row_start(&rows, view.focus.as_ref(), 12);
1967 let visible = &rows[row_start..(row_start + 12).min(rows.len())];
1968
1969 assert!(
1970 visible
1971 .iter()
1972 .any(|row| matches!(row, HelpRenderRow::Entry { slot, .. } if *slot == selected)),
1973 "selected help entry should stay in the visible render window"
1974 );
1975 }
1976
1977 fn rows_at(view: &HelpView, width: u16, height: u16) -> Vec<String> {
1978 let area = Rect::new(0, 0, width, height);
1979 let mut buf = Buffer::empty(area);
1980 view.render(area, &mut buf);
1981 (area.top()..area.bottom())
1982 .map(|y| {
1983 (area.left()..area.right())
1984 .map(|x| buf[(x, y)].symbol())
1985 .collect::<String>()
1986 })
1987 .collect()
1988 }
1989
1990 /// House rule, and the thing the overlay broke worst. A trailing `…` in a
1991 /// list of two hundred rows promises text no keystroke can reveal, and it
1992 /// lands mid-token: `(aliases: /qin…` and `deepseek-v4-…` name nothing,
1993 /// because these strings share prefixes.
1994 #[test]
1995 fn no_row_advertises_truncation_at_any_width() {
1996 for width in [60u16, 80, 96, 120] {
1997 let view = HelpView::new();
1998 for row in rows_at(&view, width, 24) {
1999 assert!(
2000 !row.contains('…'),
2001 "help must shed, not truncate, at {width} columns: {row:?}"
2002 );
2003 }
2004 }
2005 }
2006
2007 /// A cut inside `(aliases: /image, /media)` leaves the parenthesis hanging
2008 /// open — no ellipsis, and still a broken row. Joints only count where the
2009 /// parentheses balance.
2010 #[test]
2011 fn shedding_never_leaves_a_parenthesis_open() {
2012 let text = "Attach media (aliases: /image, /media)";
2013 for width in 4..text.len() {
2014 let shed = shed_to_width(text, width, Locale::En);
2015 let opens = shed.matches('(').count();
2016 let closes = shed.matches(')').count();
2017 assert_eq!(opens, closes, "unbalanced at width {width}: {shed:?}");
2018 }
2019 }
2020
2021 #[test]
2022 fn zh_hans_help_localizes_the_alias_list_and_the_entry_count() {
2023 let view = HelpView::new_for_locale(Locale::ZhHans);
2024 let clear = view
2025 .entries
2026 .iter()
2027 .find(|entry| entry.label == "/clear")
2028 .expect("/clear entry");
2029 assert!(
2030 clear.description.ends_with(" (别名:/qingping)"),
2031 "{}",
2032 clear.description
2033 );
2034 let attach = view
2035 .entries
2036 .iter()
2037 .find(|entry| entry.label == "/attach")
2038 .expect("/attach entry");
2039 assert!(
2040 attach.description.contains("/image、/media"),
2041 "{}",
2042 attach.description
2043 );
2044 for width in 4..attach.description.width() {
2045 let shed = shed_to_width(&attach.description, width, Locale::ZhHans);
2046 assert_eq!(
2047 shed.matches('(').count(),
2048 shed.matches(')').count(),
2049 "unbalanced at width {width}: {shed:?}"
2050 );
2051 }
2052 let area = Rect::new(0, 0, 100, 30);
2053 let mut buf = Buffer::empty(area);
2054 view.render(area, &mut buf);
2055 let dump = buffer_text(&buf, area).replace(' ', "");
2056 assert!(
2057 dump.contains(&format!("{}个条目", view.entries.len())),
2058 "{dump}"
2059 );
2060 assert!(!dump.contains("entries"), "{dump}");
2061 }
2062
2063 /// A single-clause description has no joint to shed at. Shedding the whole
2064 /// field left a bare label beside rows that still had text, which reads as
2065 /// a broken renderer; the short form stops on a whole word instead, and
2066 /// does not end on a dangling `to an`.
2067 #[test]
2068 fn a_jointless_description_sheds_to_whole_words() {
2069 let text = "Move the active branch to an existing session entry";
2070 let shed = shed_to_width(text, 26, Locale::En);
2071 assert!(text.starts_with(&*shed), "{shed:?}");
2072 assert!(!shed.is_empty());
2073 assert!(!shed.ends_with(" an"), "{shed:?}");
2074 assert!(!shed.ends_with(" to"), "{shed:?}");
2075 assert!(!shed.ends_with('…'), "{shed:?}");
2076 }
2077
2078 /// The label column was a flat 28 columns at every terminal size, so at 60
2079 /// columns twenty blank cells sat between `/advisor` and a description cut
2080 /// to 21. It is measured from the labels each group holds instead — and
2081 /// measured in the rendered row, not just in the helper, because a helper
2082 /// the renderer ignores proves nothing.
2083 #[test]
2084 fn label_column_is_measured_from_the_group_not_fixed() {
2085 let view = view_with_catalog_open();
2086 let widest = view
2087 .entries
2088 .iter()
2089 .filter(|entry| {
2090 entry.section == HelpSection::Command && entry.sub_rank == COMMAND_RANK_ALL
2091 })
2092 .map(|entry| entry.label.width())
2093 .max()
2094 .expect("commands exist");
2095 assert!(
2096 widest < 28,
2097 "slash command labels are short; the fixture assumes it"
2098 );
2099 assert_eq!(view.label_widths(28).get("cmd:all").copied(), Some(widest));
2100
2101 // Tall enough to reach past the curated group into the catalog.
2102 let rows = rows_at(&view, 60, 60);
2103 let row = rows
2104 .iter()
2105 .find(|row| row.contains("/advisor"))
2106 .expect("advisor row");
2107 let label_at = row.find("/advisor").expect("label");
2108 let description_at = row[label_at..]
2109 .find("Toggle")
2110 .map(|offset| label_at + offset)
2111 .expect("description follows the label on the same row");
2112 assert!(
2113 description_at - label_at <= widest + 2,
2114 "description must start right after the widest label in the group, \
2115 not after a flat 28-column gutter: {row:?}"
2116 );
2117 }
2118
2119 /// At 60x20 the description slot is 35 columns. `/automation`'s
2120 /// "Manage durable scheduled automations" is 36, so the last-resort
2121 /// word shed printed "Manage durable scheduled" — the adjectives
2122 /// without the noun that says what is being managed.
2123 #[test]
2124 fn sixty_column_help_keeps_the_automation_noun() {
2125 let view = view_with_catalog_open();
2126 let rows = rows_at(&view, 60, 60);
2127 let row = rows
2128 .iter()
2129 .find(|row| row.contains("/automation"))
2130 .expect("/automation is a registered command");
2131 assert!(
2132 row.contains("automations"),
2133 "/automation lost the noun it manages: {row:?}"
2134 );
2135 }
2136
2137 /// The selection cursor and the collapsed chevron are both `▸`. Printed
2138 /// side by side, a focused collapsed group read `▸ ▸ Slash commands (97)`
2139 /// — one glyph, twice, for two different facts.
2140 #[test]
2141 fn a_group_header_spends_one_glyph_on_one_meaning() {
2142 let mut view = view_with_catalog_open();
2143 view.toggle_group("cmd:all");
2144 assert_eq!(view.focus, Some(HelpHit::Group("cmd:all".to_string())));
2145 let rows = rows_at(&view, 96, 60);
2146 let header = rows
2147 .iter()
2148 .find(|row| row.contains("All commands"))
2149 .expect("group header row");
2150 assert!(!header.contains("▸ ▸"), "{header:?}");
2151 assert!(
2152 header.contains('▸'),
2153 "collapsed state still shown: {header:?}"
2154 );
2155 }
2156
2157 /// The detail row repairs a shed; it never repeats one. On a wide terminal
2158 /// the inline description already fits, so the slot carries the usage
2159 /// line alone rather than printing the same sentence twice on one screen.
2160 #[test]
2161 fn the_detail_row_repairs_a_shed_and_never_repeats_one() {
2162 let mut view = view_with_catalog_open();
2163 let slot = view
2164 .filtered
2165 .iter()
2166 .position(|idx| view.entries[*idx].label == "/advisor")
2167 .expect("/advisor is a registered command");
2168 view.set_focus(HelpHit::Entry(slot));
2169 let entry = &view.entries[view.filtered[slot]];
2170 let description = entry.description.clone();
2171
2172 let wide = rows_at(&view, 140, 24);
2173 let occurrences = wide
2174 .iter()
2175 .filter(|row| row.contains(description.trim()))
2176 .count();
2177 assert_eq!(
2178 occurrences, 1,
2179 "wide terminal must not say it twice: {wide:#?}"
2180 );
2181
2182 let narrow = rows_at(&view, 60, 20);
2183 let detail_row = narrow
2184 .iter()
2185 .position(|row| row.contains("Type to filter"))
2186 .expect("filter row")
2187 + 1;
2188 // The scroll rail paints the last column of every row.
2189 let strip_rail = |row: &str| row.trim_matches(['█', '│', '┃', ' ']).to_string();
2190 let detail = strip_rail(narrow.get(detail_row).expect("detail row"));
2191 assert!(
2192 !detail.is_empty(),
2193 "narrow terminal must repair the shed: {narrow:#?}"
2194 );
2195 assert!(description.starts_with(&detail), "{detail:?}");
2196 let inline = strip_rail(
2197 narrow
2198 .iter()
2199 .find(|row| row.contains("/advisor"))
2200 .expect("advisor row"),
2201 );
2202 let inline_description = inline
2203 .split_once("/advisor")
2204 .map(|(_, rest)| rest.trim().to_string())
2205 .unwrap_or_default();
2206 assert!(
2207 detail.len() > inline_description.len(),
2208 "the detail row must carry more than the row could: {inline_description:?} / {detail:?}"
2209 );
2210 }
2211
2212 /// #5952: the usage string lived in the search haystack alone, so
2213 /// `/workspace [path|worktrees]` rendered as `/workspace` and the
2214 /// worktree manager behind it had no way of being seen.
2215 #[test]
2216 fn the_focused_command_states_its_usage() {
2217 let mut view = HelpView::new();
2218 let slot = view
2219 .filtered
2220 .iter()
2221 .position(|idx| view.entries[*idx].label == "/workspace")
2222 .expect("/workspace is a registered command");
2223 view.set_focus(HelpHit::Entry(slot));
2224
2225 let rows = rows_at(&view, 140, 24);
2226 assert!(
2227 rows.iter()
2228 .any(|row| row.contains("/workspace [path|worktrees]")),
2229 "the usage line must be on screen: {rows:#?}"
2230 );
2231 }
2232
2233 /// A row whose usage only restates its label spends no columns saying so.
2234 #[test]
2235 fn a_command_without_arguments_states_no_usage() {
2236 let view = HelpView::new();
2237 let entry = view
2238 .entries
2239 .iter()
2240 .find(|entry| entry.label == "/copy")
2241 .expect("/copy is a registered command");
2242 assert_eq!(entry.usage, None);
2243
2244 let workspace = view
2245 .entries
2246 .iter()
2247 .find(|entry| entry.label == "/workspace")
2248 .expect("/workspace is a registered command");
2249 assert_eq!(
2250 workspace.usage.as_deref(),
2251 Some("/workspace [path|worktrees]")
2252 );
2253 }
2254
2255 /// At 60 columns the detail slot cannot hold both, and the description it
2256 /// exists to repair wins — the usage sheds at its own joint rather than
2257 /// pushing the sentence off the panel.
2258 #[test]
2259 fn a_narrow_panel_keeps_the_repaired_description_over_the_usage() {
2260 let mut view = HelpView::new();
2261 let slot = view
2262 .filtered
2263 .iter()
2264 .position(|idx| view.entries[*idx].label == "/advisor")
2265 .expect("/advisor is a registered command");
2266 view.set_focus(HelpHit::Entry(slot));
2267 let description = view.entries[view.filtered[slot]].description.clone();
2268
2269 let narrow = rows_at(&view, 60, 20);
2270 let detail_row = narrow
2271 .iter()
2272 .position(|row| row.contains("Type to filter"))
2273 .expect("filter row")
2274 + 1;
2275 let detail = narrow
2276 .get(detail_row)
2277 .expect("detail row")
2278 .trim_matches(['█', '│', '┃', ' '])
2279 .to_string();
2280 assert!(
2281 description.starts_with(&detail) && !detail.is_empty(),
2282 "the narrow detail row must still be the description: {detail:?}"
2283 );
2284 }
2285
2286 /// Workspace commands declare their own usage in front matter; the row
2287 /// reads it from the same place the built-ins read theirs.
2288 #[test]
2289 fn a_workspace_command_states_its_declared_usage() {
2290 let tmp = tempfile::TempDir::new().unwrap();
2291 crate::test_support::trust_workspace(tmp.path());
2292 let commands_dir = tmp.path().join(".codewhale").join("commands");
2293 std::fs::create_dir_all(&commands_dir).unwrap();
2294 std::fs::write(
2295 commands_dir.join("shipit.md"),
2296 "---\ndescription: Ship the branch\nargument-hint: <environment>\n---\nbody",
2297 )
2298 .unwrap();
2299
2300 let view = HelpView::new_for_workspace(Locale::En, tmp.path(), &[]);
2301 let entry = view
2302 .entries
2303 .iter()
2304 .find(|entry| entry.label == "/shipit")
2305 .expect("workspace command row");
2306 assert_eq!(entry.usage.as_deref(), Some("/shipit <environment>"));
2307 }
2308
2309 #[test]
2310 fn render_keeps_next_row_after_help_visible() {
2311 let mut view = HelpView::new();
2312 let help_slot = view
2313 .filtered
2314 .iter()
2315 .position(|idx| view.entries[*idx].label == "/help")
2316 .expect("/help command should be present");
2317 view.selected = help_slot;
2318 view.focus = Some(HelpHit::Entry(help_slot));
2319 view.handle_key(key(KeyCode::Down));
2320 let selected_slot = match view.focus {
2321 Some(HelpHit::Entry(slot)) => slot,
2322 ref other => panic!("expected entry focus after /help, got {other:?}"),
2323 };
2324 let selected_idx = view.filtered[selected_slot];
2325 let selected_label = view.entries[selected_idx].label.clone();
2326
2327 let area = Rect::new(0, 0, 96, 32);
2328 let mut buf = Buffer::empty(area);
2329 view.render(area, &mut buf);
2330
2331 let mut highlighted_label = false;
2332 for y in area.top()..area.bottom() {
2333 let mut row = String::new();
2334 let mut row_has_highlight = false;
2335 for x in area.left()..area.right() {
2336 let cell = &buf[(x, y)];
2337 row.push_str(cell.symbol());
2338 row_has_highlight |=
2339 cell.bg == palette::SELECTION_BG && cell.fg == palette::SELECTION_TEXT;
2340 }
2341 if row_has_highlight && row.contains(&selected_label) {
2342 highlighted_label = true;
2343 break;
2344 }
2345 }
2346
2347 assert!(
2348 highlighted_label,
2349 "selected row after /help should stay visibly highlighted"
2350 );
2351 }
2352
2353 #[test]
2354 fn selected_help_row_uses_selection_highlight() {
2355 let view = HelpView::new();
2356 let area = Rect::new(0, 0, 96, 32);
2357 let mut buf = Buffer::empty(area);
2358 view.render(area, &mut buf);
2359
2360 let mut found_highlight = false;
2361 for y in area.top()..area.bottom() {
2362 for x in area.left()..area.right() {
2363 let cell = &buf[(x, y)];
2364 if cell.bg == palette::SELECTION_BG && cell.fg == palette::SELECTION_TEXT {
2365 found_highlight = true;
2366 break;
2367 }
2368 }
2369 }
2370
2371 assert!(
2372 found_highlight,
2373 "selected row should use the semantic selection highlight"
2374 );
2375 }
2376
2377 #[test]
2378 fn render_includes_help_chrome_for_empty_filter() {
2379 let view = view_with_catalog_open();
2380 let area = Rect::new(0, 0, 96, 32);
2381 let mut buf = Buffer::empty(area);
2382 view.render(area, &mut buf);
2383
2384 let dump = buffer_text(&buf, area);
2385 // Title border + section headings should always render.
2386 assert!(dump.contains("Help"), "missing help title:\n{dump}");
2387 assert!(
2388 dump.contains("Type to filter"),
2389 "missing filter prompt:\n{dump}"
2390 );
2391 // Help opens on the curated set with the catalog folded beneath it,
2392 // so both group headings are part of the chrome a user always sees.
2393 assert!(
2394 dump.contains("Common commands"),
2395 "missing curated-command heading:\n{dump}"
2396 );
2397 assert!(
2398 dump.contains("All commands"),
2399 "missing command-catalog heading:\n{dump}"
2400 );
2401 // Footer hint should advertise close key on the bottom border.
2402 assert!(
2403 dump.contains("Esc close"),
2404 "missing Esc close footer hint:\n{dump}"
2405 );
2406 }
2407
2408 #[test]
2409 fn render_with_filter_shows_only_matching_section_and_status() {
2410 let mut view = HelpView::new();
2411 type_filter(&mut view, "mode [work");
2412 let area = Rect::new(0, 0, 96, 24);
2413 let mut buf = Buffer::empty(area);
2414 view.render(area, &mut buf);
2415
2416 let dump = buffer_text(&buf, area);
2417 assert!(
2418 dump.contains("Filter: mode [work"),
2419 "filter echo missing:\n{dump}"
2420 );
2421 assert!(
2422 dump.contains("matches"),
2423 "match counter missing in dump:\n{dump}"
2424 );
2425 assert!(
2426 dump.contains("/mode"),
2427 "expected /mode command in filtered render:\n{dump}"
2428 );
2429 assert!(
2430 !dump.contains("/model"),
2431 "non-matching commands should not render under a `mode [work` filter:\n{dump}"
2432 );
2433 }
2434
2435 #[test]
2436 fn localized_help_chrome_renders_without_missing_markers() {
2437 let view = HelpView::new_for_locale(Locale::ZhHans);
2438 let area = Rect::new(0, 0, 48, 18);
2439 let mut buf = Buffer::empty(area);
2440 view.render(area, &mut buf);
2441
2442 let dump = buffer_text(&buf, area);
2443 assert!(
2444 dump.contains('帮') && dump.contains('助'),
2445 "missing localized title:\n{dump}"
2446 );
2447 assert!(
2448 !dump.contains("MISSING"),
2449 "missing-key marker leaked:\n{dump}"
2450 );
2451 }
2452
2453 #[test]
2454 fn localized_help_keybinding_descriptions_use_zh_hans() {
2455 let registry = commands::user_registry::UserCommandRegistry::new();
2456 let entries = build_entries(Locale::ZhHans, &registry, &[], false);
2457 let kb_entries: Vec<_> = entries
2458 .iter()
2459 .filter(|e| e.section == HelpSection::Keybinding)
2460 .collect();
2461 assert!(!kb_entries.is_empty(), "no keybinding entries found");
2462
2463 for entry in &kb_entries {
2464 let group = group_label(entry, Locale::ZhHans);
2465 assert!(
2466 group
2467 .chars()
2468 .any(|c| { ('\u{4e00}'..='\u{9fff}').contains(&c) }),
2469 "keybinding group not localized: {group} ({})",
2470 entry.description
2471 );
2472 }
2473 }
2474
2475 /// The four terminal sizes the v0.8.66 modal blocker (#3732) requires
2476 /// every overlay to remain readable and fully operable at.
2477 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
2478
2479 const SHORTCUT_HELP_SIZES: [(u16, u16); 5] =
2480 [(40, 12), (60, 16), (80, 24), (100, 32), (140, 40)];
2481
2482 #[test]
2483 fn shortcut_help_leads_with_keys_at_responsive_sizes() {
2484 use crate::tui::views::ViewStack;
2485
2486 let keybindings_heading = tr(Locale::En, MessageId::HelpSectionNavigation);
2487 let commands_heading = tr(Locale::En, MessageId::HelpSlashCommands);
2488
2489 for (w, h) in SHORTCUT_HELP_SIZES {
2490 let area = Rect::new(0, 0, w, h);
2491 let mut buf = Buffer::empty(area);
2492 for y in 0..h {
2493 for x in 0..w {
2494 buf[(x, y)].set_symbol("§");
2495 }
2496 }
2497
2498 let mut stack = ViewStack::new();
2499 stack.push(HelpView::new_with_ordering(
2500 Locale::En,
2501 HelpOrdering::KeybindingsFirst,
2502 ));
2503 stack.render(area, &mut buf);
2504
2505 let rows: Vec<String> = (0..h)
2506 .map(|y| {
2507 (0..w)
2508 .map(|x| buf[(x, y)].symbol().to_string())
2509 .collect::<String>()
2510 })
2511 .collect();
2512 let text = rows.join("\n");
2513 let keys_at = text.find(keybindings_heading.as_ref()).unwrap_or_else(|| {
2514 panic!("{w}x{h}: shortcut Help hid the keybindings heading:\n{text}")
2515 });
2516 if let Some(commands_at) = text.find(commands_heading.as_ref()) {
2517 assert!(
2518 keys_at < commands_at,
2519 "{w}x{h}: shortcut Help rendered commands before keybindings:\n{text}"
2520 );
2521 }
2522 assert!(
2523 !text.contains('§'),
2524 "{w}x{h}: background bleed-through into shortcut Help"
2525 );
2526 assert!(
2527 (0..h).any(|y| {
2528 (0..w).any(|x| {
2529 let cell = &buf[(x, y)];
2530 cell.bg == palette::SELECTION_BG && cell.fg == palette::SELECTION_TEXT
2531 })
2532 }),
2533 "{w}x{h}: first keybinding row lost its selection highlight"
2534 );
2535 for (y, row) in rows.iter().enumerate() {
2536 assert!(
2537 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
2538 "{w}x{h}: row {y} overflows width: {row:?}"
2539 );
2540 }
2541 }
2542 }
2543
2544 #[test]
2545 fn help_is_usable_and_opaque_at_blocker_sizes() {
2546 use crate::tui::views::ViewStack;
2547 for (w, h) in BLOCKER_SIZES {
2548 let area = Rect::new(0, 0, w, h);
2549 let mut buf = Buffer::empty(area);
2550 for y in 0..h {
2551 for x in 0..w {
2552 buf[(x, y)].set_symbol("X");
2553 }
2554 }
2555 let mut stack = ViewStack::new();
2556 stack.push(HelpView::new_for_locale(Locale::En));
2557 stack.render(area, &mut buf);
2558
2559 let rows: Vec<String> = (0..h)
2560 .map(|y| {
2561 (0..w)
2562 .map(|x| buf[(x, y)].symbol().to_string())
2563 .collect::<String>()
2564 })
2565 .collect();
2566 let text = rows.join("\n");
2567
2568 // `type to filter` is deliberately absent: the filter row prints
2569 // `Type to filter` two lines above, and at 60 columns saying it
2570 // twice pushed the footer onto a second row.
2571 for label in [
2572 "Type to filter",
2573 "Up/Down move",
2574 "PgUp/PgDn jump",
2575 "Esc close",
2576 ] {
2577 assert!(text.contains(label), "{w}x{h}: missing footer '{label}'");
2578 }
2579 assert!(
2580 !text.contains('X'),
2581 "{w}x{h}: background bleed-through into modal surface"
2582 );
2583 assert_eq!(
2584 buf[(w / 2, h / 2)].bg,
2585 palette::COMPOSER_BG,
2586 "{w}x{h}: modal interior must be opaque"
2587 );
2588 for (y, row) in rows.iter().enumerate() {
2589 assert!(
2590 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
2591 "{w}x{h}: row {y} overflows width: {row:?}"
2592 );
2593 }
2594 }
2595 }
2596
2597 #[test]
2598 fn shortcuts_open_folds_the_long_tail() {
2599 let view = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst);
2600 let rows = view.render_rows();
2601 let groups: Vec<&str> = rows
2602 .iter()
2603 .filter_map(|row| match row {
2604 HelpRenderRow::Group {
2605 label, collapsed, ..
2606 } => Some((*collapsed, label.as_str())),
2607 _ => None,
2608 })
2609 .map(|(collapsed, label)| {
2610 if collapsed {
2611 label
2612 } else {
2613 // keep expanded groups in a second pass
2614 label
2615 }
2616 })
2617 .collect();
2618 assert!(
2619 groups.contains(&"Navigation"),
2620 "shortcuts should surface Navigation: {groups:?}"
2621 );
2622 assert!(
2623 rows.iter().any(|row| matches!(
2624 row,
2625 HelpRenderRow::Group {
2626 collapsed: false,
2627 ..
2628 }
2629 )),
2630 "at least one group stays open"
2631 );
2632 assert!(
2633 rows.iter().any(|row| matches!(
2634 row,
2635 HelpRenderRow::Group {
2636 collapsed: true,
2637 ..
2638 }
2639 )),
2640 "the long tail should start collapsed"
2641 );
2642 assert!(
2643 !rows.iter().any(|row| matches!(
2644 row,
2645 HelpRenderRow::Entry { entry_idx, .. }
2646 if view.entries[*entry_idx].section == HelpSection::Command
2647 )),
2648 "slash commands stay folded until the user expands or searches"
2649 );
2650 }
2651
2652 #[test]
2653 fn enter_toggles_the_selected_group() {
2654 let mut view = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst);
2655 // Focus opens on the first entry, so step up onto its header first.
2656 view.handle_key(key(KeyCode::Up));
2657 assert!(matches!(view.focus, Some(HelpHit::Group(_))));
2658 let before = view.visible_entry_slots().len();
2659 view.handle_key(key(KeyCode::Enter));
2660 let after = view.visible_entry_slots().len();
2661 assert_ne!(
2662 before, after,
2663 "Enter should fold or unfold the selected group's members"
2664 );
2665 view.handle_key(key(KeyCode::Enter));
2666 assert_eq!(
2667 view.visible_entry_slots().len(),
2668 before,
2669 "a second Enter restores the previous fold"
2670 );
2671 }
2672
2673 #[test]
2674 fn right_expands_and_left_collapses_a_focused_header() {
2675 let mut view = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst);
2676 let group_key = "cmd:all".to_string();
2677 assert!(view.group_is_collapsed(&group_key));
2678 view.focus = Some(HelpHit::Group(group_key.clone()));
2679
2680 view.handle_key(key(KeyCode::Right));
2681 assert!(!view.group_is_collapsed(&group_key));
2682 assert_eq!(view.focus, Some(HelpHit::Group(group_key.clone())));
2683
2684 view.handle_key(key(KeyCode::Left));
2685 assert!(view.group_is_collapsed(&group_key));
2686 assert_eq!(view.focus, Some(HelpHit::Group(group_key)));
2687 }
2688
2689 #[test]
2690 fn mouse_click_on_group_header_matches_enter_toggle() {
2691 let mut view = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst);
2692 let area = Rect::new(0, 0, 100, 120);
2693 let mut buf = Buffer::empty(area);
2694 view.render(area, &mut buf);
2695 let (rect, group) = view
2696 .row_hitboxes
2697 .borrow()
2698 .iter()
2699 .find_map(|(rect, hit)| match hit {
2700 HelpHit::Group(key) if view.group_is_collapsed(key) => Some((*rect, key.clone())),
2701 _ => None,
2702 })
2703 .expect("at least one collapsed group header is visible");
2704
2705 view.handle_mouse(MouseEvent {
2706 kind: MouseEventKind::Down(MouseButton::Left),
2707 column: rect.x,
2708 row: rect.y,
2709 modifiers: KeyModifiers::NONE,
2710 });
2711
2712 assert!(!view.group_is_collapsed(&group));
2713 assert_eq!(view.focus, Some(HelpHit::Group(group)));
2714 }
2715
2716 #[test]
2717 fn search_unfolds_collapsed_groups() {
2718 let mut view = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst);
2719 assert!(
2720 view.group_is_collapsed("cmd:all"),
2721 "slash commands start collapsed on the shortcuts surface"
2722 );
2723 type_filter(&mut view, "/mode");
2724 assert!(
2725 !view.group_is_collapsed("cmd:all"),
2726 "a search query must reveal matching groups"
2727 );
2728 assert!(
2729 view.filtered
2730 .iter()
2731 .any(|idx| view.entries[*idx].label == "/mode")
2732 );
2733 }
2734
2735 #[test]
2736 fn help_expand_groups_starts_unfolded() {
2737 let view = HelpView::new_with_ordering(Locale::En, HelpOrdering::KeybindingsFirst)
2738 .with_groups_expanded(true);
2739 assert!(
2740 !view.group_is_collapsed("cmd:all"),
2741 "help_expand_groups must start with slash commands visible"
2742 );
2743 assert!(
2744 view.render_rows().iter().any(|row| matches!(
2745 row,
2746 HelpRenderRow::Entry { entry_idx, .. }
2747 if view.entries[*entry_idx].section == HelpSection::Command
2748 )),
2749 "expanded shortcuts include slash command rows"
2750 );
2751 }
2752
2753 fn buffer_text(buf: &Buffer, area: Rect) -> String {
2754 let mut out = String::new();
2755 for y in area.top()..area.bottom() {
2756 for x in area.left()..area.right() {
2757 out.push_str(buf[(x, y)].symbol());
2758 }
2759 out.push('\n');
2760 }
2761 out
2762 }
2763 }
2764
2765 #[cfg(test)]
2766 mod shed_to_words_script_tests {
2767 use super::{Locale, shed_to_words, widest_char_prefix};
2768 use unicode_width::UnicodeWidthStr;
2769
2770 /// Japanese, Chinese and Thai do not put spaces between words, so a
2771 /// word-boundary scan finds nothing and used to yield an empty string —
2772 /// every help description rendered blank in those locales.
2773 #[test]
2774 fn a_script_without_spaces_still_gets_a_description() {
2775 for text in [
2776 "バックグラウンドのアドバイザーを切り替える",
2777 "切换后台顾问",
2778 "切換背景顧問",
2779 ] {
2780 for width in [8usize, 12, 20, 30] {
2781 let shed = shed_to_words(text, width, Locale::En);
2782 assert!(
2783 !shed.is_empty(),
2784 "{text:?} at {width}: description rendered blank",
2785 );
2786 assert!(
2787 shed.width() <= width,
2788 "{text:?} at {width}: {shed:?} overflows ({} cols)",
2789 shed.width(),
2790 );
2791 assert!(
2792 text.starts_with(&*shed),
2793 "{shed:?} is not a prefix of {text:?}"
2794 );
2795 }
2796 }
2797 }
2798
2799 /// The same hole opens in English whenever the first space sits past the
2800 /// budget: the scan never fires and the row goes blank.
2801 #[test]
2802 fn an_overlong_first_word_sheds_to_characters_rather_than_nothing() {
2803 let text = "Internationalisation settings";
2804 let shed = shed_to_words(text, 10, Locale::En);
2805 assert!(!shed.is_empty(), "long first word rendered blank");
2806 assert!(shed.width() <= 10, "{shed:?}");
2807 }
2808
2809 /// Ordinary English is unchanged: still cut on a word boundary, still
2810 /// drops a trailing short function word.
2811 #[test]
2812 fn english_still_sheds_on_word_boundaries() {
2813 let text = "Toggle the background advisor for this session";
2814 let shed = shed_to_words(text, 24, Locale::En);
2815 assert!(shed.width() <= 24, "{shed:?}");
2816 assert!(!shed.ends_with(' '), "{shed:?}");
2817 assert!(
2818 shed.split(' ').count() > 1 && text.starts_with(&*shed),
2819 "{shed:?} should be a whole-word prefix",
2820 );
2821 }
2822
2823 #[test]
2824 fn widest_char_prefix_never_splits_a_character() {
2825 let text = "日本語テキスト";
2826 for width in 0..=14 {
2827 let prefix = widest_char_prefix(text, width);
2828 assert!(text.starts_with(prefix));
2829 assert!(prefix.width() <= width);
2830 }
2831 }
2832
2833 /// The last-resort word shed always ended on a space, so the last word
2834 /// of a simple verb + modifier + noun phrase was dropped even when it
2835 /// fitted, and when it overflowed by one column the two-pass short-word
2836 /// trim left the adjectives without the noun they qualify.
2837 #[test]
2838 fn a_simple_noun_phrase_keeps_the_head_noun() {
2839 let text = "Manage durable scheduled automations";
2840 // 24 fits "Manage durable scheduled" exactly and not the noun.
2841 // 35 is the description slot at 60 columns (measured).
2842 // 36 is the full phrase.
2843 for width in [24usize, 28, 32, 35, 36] {
2844 let shed = shed_to_words(text, width, Locale::En);
2845 assert!(
2846 shed.contains("automations"),
2847 "width {width} dropped the head noun: {shed:?}"
2848 );
2849 assert!(
2850 shed.width() <= width,
2851 "width {width} overflowed: {shed:?} ({} cols)",
2852 shed.width()
2853 );
2854 }
2855
2856 // Help appends ` (aliases: …)` onto the same row. The joint head is
2857 // one column over the 35-column slot, so last-resort word shed must
2858 // run on that clause, not on the alias list.
2859 let aliased = "Manage durable scheduled automations (aliases: /automations, /scheduled)";
2860 let shed = super::shed_to_width(aliased, 35, Locale::En);
2861 assert!(
2862 shed.contains("automations"),
2863 "aliased row dropped the head noun: {shed:?}"
2864 );
2865 assert!(
2866 !shed.contains("aliases"),
2867 "aliased row kept the alias list instead of the clause: {shed:?}"
2868 );
2869 assert!(shed.width() <= 35, "{shed:?}");
2870 }
2871 }
2872
2872 lines RUST