返回 CodeWhale
setup.rs
根目录 / crates / tui / src / tui / hotbar / setup.rs
1 use std::collections::{BTreeMap, BTreeSet};
2
3 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
4 use ratatui::{
5 buffer::Buffer,
6 layout::Rect,
7 style::{Color, Modifier, Style},
8 text::{Line, Span},
9 widgets::{Block, Borders, Paragraph, Widget, Wrap},
10 };
11
12 use crate::tui::app::App;
13 use crate::tui::views::{
14 ActionHint, EmptyState, ListDetailLayout, ModalKind, ModalView, ViewAction, ViewEvent,
15 centered_modal_area, render_modal_footer, render_modal_surface,
16 };
17 use codewhale_localization::{Locale, MessageId, tr};
18 use codewhale_palette as palette;
19 use codewhale_runtime::config::Config;
20
21 #[cfg(test)]
22 use super::actions::HotbarRecommendation;
23 use super::actions::{
24 HotbarActionCategory, HotbarActionMetadata, HotbarArgsBehavior, HotbarRecommendationOptions,
25 HotbarSafetyClass, recommend_hotbar_actions,
26 };
27
28 #[derive(Debug, Clone, PartialEq, Eq)]
29 pub struct HotbarSetupActionRow {
30 pub metadata: HotbarActionMetadata,
31 pub disabled_reason: Option<String>,
32 }
33
34 impl HotbarSetupActionRow {
35 fn status_label(&self, locale: Locale) -> String {
36 tr(
37 locale,
38 if self.disabled_reason.is_some() {
39 MessageId::HotbarSetupStatusDisabled
40 } else if matches!(self.metadata.args, HotbarArgsBehavior::Required) {
41 MessageId::HotbarSetupStatusPrefill
42 } else {
43 MessageId::HotbarSetupStatusReady
44 },
45 )
46 .into_owned()
47 }
48 }
49
50 fn hotbar_setup_source_label(locale: Locale, source: HotbarActionCategory) -> String {
51 let id = match source {
52 HotbarActionCategory::App => MessageId::HotbarSetupSourceApp,
53 HotbarActionCategory::Slash => MessageId::HotbarSetupSourceSlash,
54 HotbarActionCategory::Mcp => MessageId::HotbarSetupSourceMcp,
55 HotbarActionCategory::Skill => MessageId::HotbarSetupSourceSkill,
56 HotbarActionCategory::Plugin => MessageId::HotbarSetupSourcePlugin,
57 // `Route` is a source category introduced after PR #3785; it has no
58 // dedicated localization key, so fall back to its canonical English label.
59 HotbarActionCategory::Route => return source.as_str().to_string(),
60 };
61 tr(locale, id).into_owned()
62 }
63
64 fn tr_hotbar_setup(locale: Locale, id: MessageId, replacements: &[(&str, String)]) -> String {
65 let mut message = tr(locale, id).into_owned();
66 for (placeholder, value) in replacements {
67 message = message.replace(placeholder, value);
68 }
69 message
70 }
71
72 fn hotbar_setup_dirty_label(locale: Locale, is_dirty: bool) -> String {
73 tr(
74 locale,
75 if is_dirty {
76 MessageId::HotbarSetupDirtyModified
77 } else {
78 MessageId::HotbarSetupDirtyClean
79 },
80 )
81 .into_owned()
82 }
83
84 #[derive(Debug, Clone, PartialEq, Eq)]
85 pub struct HotbarSetupView {
86 locale: Locale,
87 sources: Vec<HotbarActionCategory>,
88 actions: Vec<HotbarSetupActionRow>,
89 selected_source_idx: usize,
90 selected_action_idx_by_source: BTreeMap<HotbarActionCategory, usize>,
91 selected_slot: u8,
92 original_bindings: BTreeMap<u8, codewhale_config::HotbarBindingToml>,
93 draft_bindings: BTreeMap<u8, codewhale_config::HotbarBindingToml>,
94 recommended_action_ids: BTreeSet<String>,
95 validation_errors: Vec<String>,
96 query: String,
97 filter_focused: bool,
98 help_visible: bool,
99 /// `d` arms this instead of persisting `hotbar = []` straight away.
100 /// Disabling rewrites every slot binding on disk and the setup view invites
101 /// bare typing as its filter, so a stray keystroke must not be able to
102 /// destroy the bindings. Mirrors `SessionPickerView::confirm_delete`.
103 confirm_disable: bool,
104 }
105
106 impl HotbarSetupView {
107 #[must_use]
108 pub fn new(app: &App, config: &Config) -> Self {
109 let mut actions = app
110 .hotbar_actions
111 .iter()
112 .map(|action| {
113 let metadata = action.metadata(app.ui_locale);
114 let disabled_reason = action.disabled_reason(app);
115 HotbarSetupActionRow {
116 metadata,
117 disabled_reason,
118 }
119 })
120 .collect::<Vec<_>>();
121 actions.sort_by(|a, b| {
122 a.metadata
123 .category
124 .cmp(&b.metadata.category)
125 .then_with(|| {
126 a.metadata
127 .display_name
128 .to_ascii_lowercase()
129 .cmp(&b.metadata.display_name.to_ascii_lowercase())
130 })
131 .then_with(|| a.metadata.id.cmp(&b.metadata.id))
132 });
133
134 let sources = actions
135 .iter()
136 .map(|row| row.metadata.category)
137 .collect::<BTreeSet<_>>()
138 .into_iter()
139 .collect::<Vec<_>>();
140 let recommended_action_ids =
141 recommend_hotbar_actions(app, HotbarRecommendationOptions::for_setup_wizard())
142 .into_iter()
143 .map(|entry| entry.metadata.id)
144 .collect::<BTreeSet<_>>();
145
146 let known_action_ids = app
147 .hotbar_actions
148 .iter()
149 .map(|action| action.id())
150 .collect::<Vec<_>>();
151 let original_bindings = config
152 .resolve_hotbar_bindings(&known_action_ids)
153 .bindings
154 .into_iter()
155 .map(|binding| {
156 (
157 binding.slot,
158 codewhale_config::HotbarBindingToml {
159 slot: binding.slot,
160 action: binding.action,
161 label: binding.label,
162 },
163 )
164 })
165 .collect::<BTreeMap<_, _>>();
166
167 Self {
168 locale: app.ui_locale,
169 sources,
170 actions,
171 selected_source_idx: 0,
172 selected_action_idx_by_source: BTreeMap::new(),
173 selected_slot: 1,
174 draft_bindings: original_bindings.clone(),
175 original_bindings,
176 recommended_action_ids,
177 validation_errors: Vec::new(),
178 confirm_disable: false,
179 query: String::new(),
180 filter_focused: false,
181 help_visible: false,
182 }
183 }
184
185 #[must_use]
186 #[cfg(test)]
187 pub fn source_categories(&self) -> &[HotbarActionCategory] {
188 &self.sources
189 }
190
191 #[must_use]
192 pub fn selected_source(&self) -> Option<HotbarActionCategory> {
193 self.sources.get(self.selected_source_idx).copied()
194 }
195
196 #[must_use]
197 #[cfg(test)]
198 pub fn selected_slot(&self) -> u8 {
199 self.selected_slot
200 }
201
202 #[must_use]
203 pub fn selected_action(&self) -> Option<&HotbarSetupActionRow> {
204 let source = self.selected_source()?;
205 self.actions_for_source(source)
206 .get(self.selected_action_idx(source))
207 .copied()
208 }
209
210 #[must_use]
211 #[cfg(test)]
212 pub fn binding_for_slot(&self, slot: u8) -> Option<&codewhale_config::HotbarBindingToml> {
213 self.draft_bindings.get(&slot)
214 }
215
216 #[must_use]
217 #[cfg(test)]
218 pub fn checked_action_ids(&self) -> BTreeSet<String> {
219 self.draft_bindings
220 .values()
221 .map(|binding| binding.action.clone())
222 .collect()
223 }
224
225 #[must_use]
226 #[cfg(test)]
227 pub fn recommended_action_ids(&self) -> &BTreeSet<String> {
228 &self.recommended_action_ids
229 }
230
231 #[must_use]
232 pub fn is_dirty(&self) -> bool {
233 self.draft_bindings != self.original_bindings
234 }
235
236 #[must_use]
237 #[cfg(test)]
238 pub fn validation_errors(&self) -> &[String] {
239 &self.validation_errors
240 }
241
242 #[must_use]
243 #[cfg(test)]
244 pub fn query(&self) -> &str {
245 &self.query
246 }
247
248 /// The status row, styled. An armed disable confirmation outranks every
249 /// other status because it is the only one asking for an answer.
250 fn status_line(&self) -> Line<'static> {
251 if self.confirm_disable {
252 return Line::from(Span::styled(
253 tr(self.locale, MessageId::HotbarSetupConfirmDisable).into_owned(),
254 Style::default()
255 .fg(palette::STATUS_WARNING)
256 .add_modifier(Modifier::BOLD),
257 ));
258 }
259 Line::from(self.status_text())
260 }
261
262 #[must_use]
263 pub fn status_text(&self) -> String {
264 if self.confirm_disable {
265 return tr(self.locale, MessageId::HotbarSetupConfirmDisable).into_owned();
266 }
267 if let Some(error) = self.validation_errors.last() {
268 return error.clone();
269 }
270 let dirty = hotbar_setup_dirty_label(self.locale, self.is_dirty());
271 let action = self
272 .selected_action()
273 .map(|row| {
274 format!(
275 "{} ({})",
276 row.metadata.display_name,
277 row.status_label(self.locale)
278 )
279 })
280 .unwrap_or_else(|| tr(self.locale, MessageId::HotbarSetupNoAction).into_owned());
281 tr_hotbar_setup(
282 self.locale,
283 MessageId::HotbarSetupStatusLine,
284 &[
285 ("{slot}", self.selected_slot.to_string()),
286 ("{action}", action),
287 ("{dirty}", dirty),
288 ],
289 )
290 }
291
292 #[cfg(test)]
293 pub fn select_action_by_id(&mut self, action_id: &str) -> bool {
294 self.query.clear();
295 self.filter_focused = false;
296 let Some(row) = self
297 .actions
298 .iter()
299 .find(|row| row.metadata.id == action_id)
300 .cloned()
301 else {
302 return false;
303 };
304 let Some(source_idx) = self
305 .sources
306 .iter()
307 .position(|source| *source == row.metadata.category)
308 else {
309 return false;
310 };
311 self.selected_source_idx = source_idx;
312 let index = self
313 .actions_for_source(row.metadata.category)
314 .iter()
315 .position(|candidate| candidate.metadata.id == action_id)
316 .unwrap_or(0);
317 self.selected_action_idx_by_source
318 .insert(row.metadata.category, index);
319 self.validation_errors.clear();
320 true
321 }
322
323 pub fn select_slot(&mut self, slot: u8) -> bool {
324 if !(1..=codewhale_config::HOTBAR_SLOT_COUNT).contains(&slot) {
325 self.validation_errors = vec![tr_hotbar_setup(
326 self.locale,
327 MessageId::HotbarSetupSlotOutOfRange,
328 &[
329 ("{slot}", slot.to_string()),
330 ("{max}", codewhale_config::HOTBAR_SLOT_COUNT.to_string()),
331 ],
332 )];
333 return false;
334 }
335 self.selected_slot = slot;
336 self.validation_errors.clear();
337 true
338 }
339
340 pub fn assign_selected_action(&mut self) -> bool {
341 let Some(row) = self.selected_action().cloned() else {
342 self.validation_errors =
343 vec![tr(self.locale, MessageId::HotbarSetupNoActionSelected).into_owned()];
344 return false;
345 };
346 if let Some(reason) = row.disabled_reason {
347 self.validation_errors = vec![tr_hotbar_setup(
348 self.locale,
349 MessageId::HotbarSetupCannotAssign,
350 &[
351 ("{action}", row.metadata.display_name),
352 ("{reason}", reason),
353 ],
354 )];
355 return false;
356 }
357 self.draft_bindings.insert(
358 self.selected_slot,
359 codewhale_config::HotbarBindingToml {
360 slot: self.selected_slot,
361 action: row.metadata.id,
362 label: None,
363 },
364 );
365 self.validation_errors.clear();
366 true
367 }
368
369 pub fn toggle_selected_action(&mut self) -> bool {
370 let selected_id = self
371 .selected_action()
372 .map(|row| row.metadata.id.clone())
373 .unwrap_or_default();
374 if self
375 .draft_bindings
376 .get(&self.selected_slot)
377 .is_some_and(|binding| binding.action == selected_id)
378 {
379 self.clear_selected_slot();
380 true
381 } else {
382 self.assign_selected_action()
383 }
384 }
385
386 pub fn clear_selected_slot(&mut self) {
387 self.draft_bindings.remove(&self.selected_slot);
388 self.validation_errors.clear();
389 }
390
391 #[must_use]
392 pub fn save_bindings(&self) -> Vec<codewhale_config::HotbarBindingToml> {
393 self.draft_bindings.values().cloned().collect()
394 }
395
396 fn actions_for_source(&self, source: HotbarActionCategory) -> Vec<&HotbarSetupActionRow> {
397 let query = self.query.trim().to_ascii_lowercase();
398 self.actions
399 .iter()
400 .filter(|row| {
401 row.metadata.category == source
402 && (query.is_empty() || action_matches_query(row, self.locale, &query))
403 })
404 .collect()
405 }
406
407 fn unfiltered_actions_for_source(
408 &self,
409 source: HotbarActionCategory,
410 ) -> Vec<&HotbarSetupActionRow> {
411 self.actions
412 .iter()
413 .filter(|row| row.metadata.category == source)
414 .collect()
415 }
416
417 fn selected_action_idx(&self, source: HotbarActionCategory) -> usize {
418 let len = self.actions_for_source(source).len();
419 if len == 0 {
420 return 0;
421 }
422 self.selected_action_idx_by_source
423 .get(&source)
424 .copied()
425 .unwrap_or(0)
426 .min(len.saturating_sub(1))
427 }
428
429 fn set_selected_action_idx(&mut self, source: HotbarActionCategory, idx: usize) {
430 let len = self.actions_for_source(source).len();
431 if len == 0 {
432 self.selected_action_idx_by_source.insert(source, 0);
433 } else {
434 self.selected_action_idx_by_source
435 .insert(source, idx.min(len.saturating_sub(1)));
436 }
437 }
438
439 fn move_source(&mut self, delta: isize) {
440 if self.sources.is_empty() {
441 return;
442 }
443 self.selected_source_idx = wrap_index(self.selected_source_idx, self.sources.len(), delta);
444 self.validation_errors.clear();
445 }
446
447 fn move_action(&mut self, delta: isize) {
448 let Some(source) = self.selected_source() else {
449 return;
450 };
451 let len = self.actions_for_source(source).len();
452 if len == 0 {
453 return;
454 }
455 let next = wrap_index(self.selected_action_idx(source), len, delta);
456 self.set_selected_action_idx(source, next);
457 self.validation_errors.clear();
458 }
459
460 fn move_slot(&mut self, delta: isize) {
461 let len = usize::from(codewhale_config::HOTBAR_SLOT_COUNT);
462 let next = wrap_index(usize::from(self.selected_slot - 1), len, delta) + 1;
463 self.selected_slot = u8::try_from(next).expect("hotbar slot fits in u8");
464 self.validation_errors.clear();
465 }
466
467 fn save_action(&self) -> ViewAction {
468 ViewAction::EmitAndClose(ViewEvent::HotbarSetupSaved {
469 bindings: self.save_bindings(),
470 })
471 }
472
473 #[cfg(test)]
474 fn render_lines(&self) -> Vec<Line<'static>> {
475 let mut lines = Vec::new();
476 lines.extend(self.header_lines());
477
478 let Some(source) = self.selected_source() else {
479 lines.push(Line::from(
480 tr(self.locale, MessageId::HotbarSetupNoActions).into_owned(),
481 ));
482 return lines;
483 };
484
485 for (idx, row) in self.actions_for_source(source).iter().enumerate() {
486 lines.push(self.action_row_line(source, idx, row, 80, true));
487 }
488
489 lines.push(Line::from(""));
490 lines.push(self.slots_line());
491 lines.push(self.status_line());
492 lines
493 }
494
495 fn header_lines(&self) -> Vec<Line<'static>> {
496 // The header is painted into `content.height.min(5)` rows with
497 // `Wrap { trim: true }`, and the intro wraps to two rows at ordinary
498 // widths — which is the whole budget once the slots, tabs and filter
499 // rows follow. An armed confirmation must never be the line that falls
500 // off the bottom, so it takes the intro's place instead of queueing
501 // behind it. Chrome yields to the question; the question is the content.
502 if self.confirm_disable {
503 return vec![
504 self.status_line(),
505 self.slots_line(),
506 self.source_tabs_line(),
507 self.filter_line(),
508 ];
509 }
510 let alt_prefix = crate::tui::widgets::key_hint::alt_prefix();
511 vec![
512 Line::from(Span::styled(
513 format!(
514 "Hotbar gives you {alt_prefix}1-8 shortcuts. Assign actions below; \
515 press 'd' or run `/hotbar off` to hide it."
516 ),
517 Style::default()
518 .fg(palette::TEXT_PRIMARY)
519 .add_modifier(Modifier::DIM),
520 )),
521 self.slots_line(),
522 self.source_tabs_line(),
523 self.filter_line(),
524 self.status_line(),
525 ]
526 }
527
528 fn source_tabs_line(&self) -> Line<'static> {
529 let mut spans = Vec::new();
530 for (idx, source) in self.sources.iter().enumerate() {
531 if idx > 0 {
532 spans.push(Span::raw(" "));
533 }
534 let count = self.unfiltered_actions_for_source(*source).len();
535 let name = hotbar_setup_source_label(self.locale, *source);
536 let label = if Some(*source) == self.selected_source() {
537 format!("[{name} {count}]")
538 } else {
539 format!("{name} {count}")
540 };
541 spans.push(Span::styled(
542 label,
543 Style::default()
544 .fg(if Some(*source) == self.selected_source() {
545 Color::Cyan
546 } else {
547 palette::TEXT_MUTED
548 })
549 .add_modifier(if Some(*source) == self.selected_source() {
550 Modifier::BOLD
551 } else {
552 Modifier::empty()
553 }),
554 ));
555 }
556 Line::from(spans)
557 }
558
559 fn filter_line(&self) -> Line<'static> {
560 let value = if self.query.is_empty() {
561 if self.filter_focused {
562 "type to filter".to_string()
563 } else {
564 "press / or type to filter".to_string()
565 }
566 } else {
567 self.query.clone()
568 };
569 Line::from(vec![
570 Span::styled("Filter ", Style::default().fg(palette::TEXT_MUTED)),
571 Span::styled(
572 value,
573 Style::default().fg(if self.filter_focused {
574 palette::WHALE_ACTION
575 } else {
576 palette::TEXT_PRIMARY
577 }),
578 ),
579 ])
580 }
581
582 fn slots_line(&self) -> Line<'static> {
583 let slots = (1..=codewhale_config::HOTBAR_SLOT_COUNT)
584 .map(|slot| {
585 let label = self
586 .draft_bindings
587 .get(&slot)
588 .map(|binding| compact_action_id(&binding.action))
589 .unwrap_or_else(|| {
590 tr(self.locale, MessageId::HotbarSetupEmptySlot).into_owned()
591 });
592 if slot == self.selected_slot {
593 format!("[{slot}:{label}]")
594 } else {
595 format!("{slot}:{label}")
596 }
597 })
598 .collect::<Vec<_>>()
599 .join(" ");
600 Line::from(slots)
601 }
602
603 fn action_row_line(
604 &self,
605 source: HotbarActionCategory,
606 idx: usize,
607 row: &HotbarSetupActionRow,
608 max_width: u16,
609 show_description: bool,
610 ) -> Line<'static> {
611 let selected = idx == self.selected_action_idx(source);
612 let marker = codewhale_tui_kit::glyphs::selection_marker(selected);
613 let checked = if self
614 .draft_bindings
615 .values()
616 .any(|binding| binding.action == row.metadata.id)
617 {
618 "*"
619 } else {
620 " "
621 };
622 let recommended = if self.recommended_action_ids.contains(&row.metadata.id) {
623 tr(self.locale, MessageId::HotbarSetupRecommended).into_owned()
624 } else {
625 String::new()
626 };
627 let pad = codewhale_tui_kit::ui_text::pad_to_display_width;
628 let prefix = format!(
629 "{marker}{checked} {} {} {} ",
630 pad(&recommended, 3),
631 pad(&row.metadata.display_name, 22),
632 pad(&row.status_label(self.locale), 8)
633 );
634 let suffix = if let Some(reason) = row.disabled_reason.as_deref() {
635 format!(" ({reason})")
636 } else {
637 String::new()
638 };
639 let (prefix, description) = if show_description {
640 (prefix.as_str(), row.metadata.description.as_str())
641 } else {
642 (prefix.trim_end(), "")
643 };
644 let text = codewhale_tui_kit::ui_text::semantic_truncate_with_affixes(
645 prefix,
646 description,
647 &suffix,
648 usize::from(max_width),
649 );
650 Line::from(Span::styled(
651 text,
652 Style::default()
653 .fg(if selected {
654 palette::WHALE_ACTION
655 } else {
656 palette::TEXT_PRIMARY
657 })
658 .add_modifier(if selected {
659 Modifier::BOLD
660 } else {
661 Modifier::empty()
662 }),
663 ))
664 }
665
666 fn render_header(&self, area: Rect, buf: &mut Buffer) {
667 Paragraph::new(self.header_lines())
668 .style(Style::default().fg(palette::TEXT_PRIMARY))
669 .wrap(Wrap { trim: true })
670 .render(area, buf);
671 }
672
673 fn render_action_list(&self, area: Rect, buf: &mut Buffer, show_descriptions: bool) {
674 let Some(source) = self.selected_source() else {
675 EmptyState::new("No actions", "No hotbar action sources are available.")
676 .render(area, buf);
677 return;
678 };
679 let rows = self.actions_for_source(source);
680 if rows.is_empty() {
681 EmptyState::new(
682 "No matching actions",
683 "Clear the filter or switch categories to find another bindable action.",
684 )
685 .primary_action("/", "filter")
686 .secondary_action("Esc", "clear filter")
687 .render(area, buf);
688 return;
689 }
690 let mut lines = vec![Line::from(Span::styled(
691 format!("{} actions", source.as_str()),
692 Style::default()
693 .fg(palette::TEXT_MUTED)
694 .add_modifier(Modifier::BOLD),
695 ))];
696 // Keep the focused row inside the rendered viewport. The list used to
697 // render only its first rows, so keyboard selection could advance past
698 // `/export` while the highlight stayed behind (#4418).
699 let visible_rows = usize::from(area.height.saturating_sub(1));
700 let visible_range =
701 action_list_visible_range(self.selected_action_idx(source), rows.len(), visible_rows);
702 for idx in visible_range {
703 lines.push(self.action_row_line(source, idx, rows[idx], area.width, show_descriptions));
704 }
705 Paragraph::new(lines)
706 .style(Style::default().fg(palette::TEXT_PRIMARY))
707 .render(area, buf);
708 }
709
710 fn render_action_detail(&self, area: Rect, buf: &mut Buffer) {
711 let Some(row) = self.selected_action() else {
712 EmptyState::new(
713 "Select an action",
714 "Move through the catalog to preview the selected slot binding.",
715 )
716 .primary_action("Tab", "category")
717 .secondary_action("/", "filter")
718 .render(area, buf);
719 return;
720 };
721 Paragraph::new(self.detail_lines(row))
722 .style(Style::default().fg(palette::TEXT_PRIMARY))
723 .wrap(Wrap { trim: true })
724 .render(area, buf);
725 }
726
727 fn detail_lines(&self, row: &HotbarSetupActionRow) -> Vec<Line<'static>> {
728 let mut lines = vec![
729 Line::from(Span::styled(
730 row.metadata.display_name.clone(),
731 Style::default()
732 .fg(palette::TEXT_PRIMARY)
733 .add_modifier(Modifier::BOLD),
734 )),
735 Line::from(Span::styled(
736 row.metadata.id.clone(),
737 Style::default().fg(palette::TEXT_MUTED),
738 )),
739 Line::from(""),
740 Line::from(format!("Category: {}", row.metadata.category.as_str())),
741 Line::from(format!("Status: {}", row.status_label(self.locale))),
742 Line::from(format!("Safety: {}", safety_label(row.metadata.safety))),
743 Line::from(format!("Arguments: {}", args_label(row.metadata.args))),
744 Line::from(format!(
745 "Slot {}: {}",
746 self.selected_slot,
747 self.selected_slot_binding_label()
748 )),
749 Line::from(""),
750 Line::from(row.metadata.description.clone()),
751 Line::from(""),
752 Line::from(preview_line(row)),
753 ];
754 if let Some(reason) = row.disabled_reason.as_deref() {
755 lines.push(Line::from(Span::styled(
756 format!("Unavailable: {reason}"),
757 Style::default().fg(palette::STATUS_WARNING),
758 )));
759 }
760 if self.help_visible {
761 lines.push(Line::from(""));
762 lines.push(Line::from(
763 "Save writes staged slots; Esc cancels staged changes unless a filter is active.",
764 ));
765 lines.push(Line::from(
766 "After save: Alt+1 through Alt+8 dispatch Hotbar slots. Bare 1-8 stay composer text outside setup.",
767 ));
768 }
769 lines
770 }
771
772 fn selected_slot_binding_label(&self) -> String {
773 let Some(binding) = self.draft_bindings.get(&self.selected_slot) else {
774 return tr(self.locale, MessageId::HotbarSetupEmptySlot).into_owned();
775 };
776 self.actions
777 .iter()
778 .find(|row| row.metadata.id == binding.action)
779 .map(|row| row.metadata.display_name.clone())
780 .unwrap_or_else(|| binding.action.clone())
781 }
782 }
783
784 impl ModalView for HotbarSetupView {
785 fn kind(&self) -> ModalKind {
786 ModalKind::HotbarSetup
787 }
788
789 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
790 // The disable confirmation owns every key while it is armed, so the
791 // filter cannot swallow the answer and no other action can fire under it.
792 if self.confirm_disable {
793 return match key.code {
794 KeyCode::Char('y') | KeyCode::Char('Y') => {
795 self.confirm_disable = false;
796 ViewAction::EmitAndClose(ViewEvent::HotbarDisableRequested)
797 }
798 _ => {
799 self.confirm_disable = false;
800 ViewAction::None
801 }
802 };
803 }
804
805 match key.code {
806 KeyCode::Esc if self.filter_focused || !self.query.is_empty() => {
807 self.query.clear();
808 self.filter_focused = false;
809 self.validation_errors.clear();
810 ViewAction::None
811 }
812 KeyCode::Esc => ViewAction::Close,
813 KeyCode::Char('q') | KeyCode::Char('Q')
814 if key.modifiers.is_empty() && !self.filter_focused =>
815 {
816 ViewAction::Close
817 }
818 KeyCode::Tab => {
819 self.move_source(1);
820 ViewAction::None
821 }
822 KeyCode::BackTab => {
823 self.move_source(-1);
824 ViewAction::None
825 }
826 KeyCode::Left if key.modifiers.contains(KeyModifiers::ALT) => {
827 self.move_source(-1);
828 ViewAction::None
829 }
830 KeyCode::Right if key.modifiers.contains(KeyModifiers::ALT) => {
831 self.move_source(1);
832 ViewAction::None
833 }
834 KeyCode::Left => {
835 self.move_slot(-1);
836 ViewAction::None
837 }
838 KeyCode::Right => {
839 self.move_slot(1);
840 ViewAction::None
841 }
842 KeyCode::Up => {
843 self.move_action(-1);
844 ViewAction::None
845 }
846 KeyCode::Char('k') | KeyCode::Char('K')
847 if key.modifiers.is_empty() && !self.filter_focused =>
848 {
849 self.move_action(-1);
850 ViewAction::None
851 }
852 KeyCode::Down => {
853 self.move_action(1);
854 ViewAction::None
855 }
856 KeyCode::Char('j') | KeyCode::Char('J')
857 if key.modifiers.is_empty() && !self.filter_focused =>
858 {
859 self.move_action(1);
860 ViewAction::None
861 }
862 KeyCode::Enter => {
863 self.assign_selected_action();
864 ViewAction::None
865 }
866 KeyCode::Char('a') | KeyCode::Char('A')
867 if key.modifiers.is_empty() && !self.filter_focused =>
868 {
869 self.assign_selected_action();
870 ViewAction::None
871 }
872 KeyCode::Char(' ') if !self.filter_focused => {
873 self.toggle_selected_action();
874 ViewAction::None
875 }
876 KeyCode::Backspace if self.filter_focused || !self.query.is_empty() => {
877 self.query.pop();
878 if self.query.is_empty() {
879 self.filter_focused = false;
880 }
881 self.validation_errors.clear();
882 ViewAction::None
883 }
884 KeyCode::Backspace | KeyCode::Delete => {
885 self.clear_selected_slot();
886 ViewAction::None
887 }
888 KeyCode::Char('c') | KeyCode::Char('C')
889 if key.modifiers.is_empty() && !self.filter_focused =>
890 {
891 self.clear_selected_slot();
892 ViewAction::None
893 }
894 KeyCode::Char(ch) if ('1'..='8').contains(&ch) => {
895 let slot = ch.to_digit(10).expect("digit") as u8;
896 self.select_slot(slot);
897 ViewAction::None
898 }
899 KeyCode::Char('s') | KeyCode::Char('S')
900 if key.modifiers.is_empty() && !self.filter_focused =>
901 {
902 self.save_action()
903 }
904 KeyCode::Char('d') | KeyCode::Char('D')
905 if key.modifiers.is_empty() && !self.filter_focused =>
906 {
907 // "Disable Hotbar" from inside the setup flow: hide it and
908 // persist `hotbar = []`. Mirrors `/hotbar off`. Arm the
909 // confirmation rather than writing; `y` commits.
910 self.confirm_disable = true;
911 ViewAction::None
912 }
913 KeyCode::Char('/') if key.modifiers.is_empty() => {
914 self.filter_focused = true;
915 self.validation_errors.clear();
916 ViewAction::None
917 }
918 KeyCode::Char('?') => {
919 self.help_visible = !self.help_visible;
920 ViewAction::None
921 }
922 KeyCode::Char(ch) if key.modifiers.is_empty() => {
923 self.filter_focused = true;
924 self.query.push(ch);
925 self.validation_errors.clear();
926 if let Some(source) = self.selected_source() {
927 self.set_selected_action_idx(source, 0);
928 }
929 ViewAction::None
930 }
931 _ => ViewAction::None,
932 }
933 }
934
935 fn handle_paste(&mut self, text: &str) -> bool {
936 if self.confirm_disable {
937 return true;
938 }
939 let sanitized = text
940 .trim_end_matches(['\r', '\n'])
941 .replace("\r\n", "\n")
942 .replace(char::is_control, " ");
943 if !sanitized.is_empty() {
944 self.filter_focused = true;
945 self.query.push_str(&sanitized);
946 self.validation_errors.clear();
947 if let Some(source) = self.selected_source() {
948 self.set_selected_action_idx(source, 0);
949 }
950 }
951 true
952 }
953
954 fn render(&self, area: Rect, buf: &mut Buffer) {
955 let popup_area = centered_modal_area(area, 118, 28, 72, 12);
956 render_modal_surface(area, popup_area, buf);
957 let block = Block::default()
958 .title(Line::from(Span::styled(
959 tr(self.locale, MessageId::HotbarSetupTitle),
960 Style::default()
961 .fg(palette::WHALE_ACTION)
962 .add_modifier(Modifier::BOLD),
963 )))
964 .borders(Borders::ALL)
965 .border_style(Style::default().fg(palette::BORDER_COLOR))
966 .style(Style::default().bg(palette::WHALE_BG));
967 let inner = block.inner(popup_area);
968 block.render(popup_area, buf);
969
970 let content = render_modal_footer(
971 inner,
972 buf,
973 &[
974 ActionHint::new("Tab/Shift+Tab", "source"),
975 ActionHint::new("↑/↓", "action"),
976 ActionHint::new("1-8", "slot"),
977 ActionHint::new("/", "filter"),
978 ActionHint::new("Enter/A", "assign"),
979 ActionHint::new("Space", "toggle"),
980 ActionHint::new("C/Delete", "clear"),
981 ActionHint::new("s", "save"),
982 ActionHint::new("d", "disable"),
983 ActionHint::new("Esc", "cancel"),
984 ],
985 );
986 let header_height = content.height.min(5);
987 let header = Rect {
988 x: content.x,
989 y: content.y,
990 width: content.width,
991 height: header_height,
992 };
993 self.render_header(header, buf);
994 let body = Rect {
995 x: content.x,
996 y: content.y + header_height,
997 width: content.width,
998 height: content.height.saturating_sub(header_height),
999 };
1000 let layout = ListDetailLayout::split(body, 34);
1001 self.render_action_list(layout.list, buf, layout.stacked);
1002 self.render_action_detail(layout.detail, buf);
1003 }
1004
1005 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
1006 self
1007 }
1008 }
1009
1010 fn wrap_index(current: usize, len: usize, delta: isize) -> usize {
1011 if len == 0 {
1012 return 0;
1013 }
1014 let len = isize::try_from(len).expect("len fits in isize");
1015 let current = isize::try_from(current).expect("current fits in isize");
1016 usize::try_from((current + delta).rem_euclid(len)).expect("wrapped index fits")
1017 }
1018
1019 fn action_list_visible_range(
1020 selected_idx: usize,
1021 row_count: usize,
1022 visible_rows: usize,
1023 ) -> std::ops::Range<usize> {
1024 if row_count == 0 || visible_rows == 0 {
1025 return 0..0;
1026 }
1027 let selected_idx = selected_idx.min(row_count.saturating_sub(1));
1028 let start = selected_idx.saturating_add(1).saturating_sub(visible_rows);
1029 let end = start.saturating_add(visible_rows).min(row_count);
1030 start..end
1031 }
1032
1033 fn action_matches_query(row: &HotbarSetupActionRow, locale: Locale, query: &str) -> bool {
1034 let status = row.status_label(locale);
1035 [
1036 row.metadata.id.as_str(),
1037 row.metadata.display_name.as_str(),
1038 row.metadata.description.as_str(),
1039 row.metadata.category.as_str(),
1040 status.as_str(),
1041 row.disabled_reason.as_deref().unwrap_or_default(),
1042 ]
1043 .into_iter()
1044 .any(|value| value.to_ascii_lowercase().contains(query))
1045 }
1046
1047 fn safety_label(safety: HotbarSafetyClass) -> &'static str {
1048 match safety {
1049 HotbarSafetyClass::LocalUi => "safe UI",
1050 HotbarSafetyClass::LocalState => "local state",
1051 HotbarSafetyClass::ConfigChange => "config change",
1052 HotbarSafetyClass::ExternalInput => "external input",
1053 HotbarSafetyClass::ExistingCommand => "existing command",
1054 HotbarSafetyClass::RequiresApproval => "approval gated",
1055 }
1056 }
1057
1058 fn args_label(args: HotbarArgsBehavior) -> &'static str {
1059 match args {
1060 HotbarArgsBehavior::None => "none",
1061 HotbarArgsBehavior::Optional => "optional",
1062 HotbarArgsBehavior::Required => "prefill required arguments",
1063 }
1064 }
1065
1066 fn preview_line(row: &HotbarSetupActionRow) -> String {
1067 match (row.metadata.category, row.metadata.args) {
1068 (HotbarActionCategory::Route, _) => {
1069 "Preview: switches provider/model through /model route logic.".to_string()
1070 }
1071 (_, HotbarArgsBehavior::Required) => {
1072 "Preview: pre-fills the composer instead of running blindly.".to_string()
1073 }
1074 _ => "Preview: dispatches through the existing Hotbar action path.".to_string(),
1075 }
1076 }
1077
1078 fn compact_action_id(action_id: &str) -> String {
1079 let suffix = action_id.rsplit('.').next().unwrap_or(action_id);
1080 codewhale_tui_kit::ui_text::truncate_line_to_width(suffix, 7)
1081 }
1082
1083 #[cfg(test)]
1084 mod tests {
1085 use super::*;
1086 use crate::tui::app::TuiOptions;
1087 use crate::tui::hotbar::HotbarActionRegistry;
1088 use codewhale_config::ProviderKind;
1089 use codewhale_localization::{Locale, MessageId, tr};
1090 use codewhale_runtime::config::Config;
1091 use crossterm::event::KeyModifiers;
1092 use std::path::PathBuf;
1093
1094 fn test_app_with_config(config: &Config) -> App {
1095 let options = TuiOptions {
1096 start_in_agent_mode: true,
1097 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
1098 };
1099 let mut app = App::new(options, config);
1100 app.ui_locale = Locale::En;
1101 app
1102 }
1103
1104 fn test_app_with_locale(locale: Locale) -> App {
1105 let mut app = test_app();
1106 app.ui_locale = locale;
1107 app
1108 }
1109
1110 fn test_app() -> App {
1111 test_app_with_config(&Config::default())
1112 }
1113
1114 fn key(code: KeyCode) -> KeyEvent {
1115 KeyEvent::new(code, KeyModifiers::NONE)
1116 }
1117
1118 fn rendered_text_at(view: &HotbarSetupView, width: u16, height: u16) -> String {
1119 let area = Rect::new(0, 0, width, height);
1120 let mut buf = Buffer::empty(area);
1121 view.render(area, &mut buf);
1122
1123 let mut out = String::new();
1124 for y in area.top()..area.bottom() {
1125 for x in area.left()..area.right() {
1126 out.push_str(buf[(x, y)].symbol());
1127 }
1128 out.push('\n');
1129 }
1130 out
1131 }
1132
1133 fn rendered_text(view: &HotbarSetupView) -> String {
1134 rendered_text_at(view, 140, 36)
1135 }
1136
1137 #[test]
1138 fn wizard_sources_follow_registered_action_categories() {
1139 let app = test_app();
1140 let view = HotbarSetupView::new(&app, &Config::default());
1141
1142 // Skills are registered from whatever the startup skill cache
1143 // discovered, so only the always-present categories are asserted
1144 // in order here (see wizard_lists_skill_and_mcp_sources_when_registered
1145 // for the injected-source coverage).
1146 assert!(
1147 view.source_categories().starts_with(&[
1148 HotbarActionCategory::App,
1149 HotbarActionCategory::Route,
1150 HotbarActionCategory::Slash,
1151 ]),
1152 "unexpected wizard sources: {:?}",
1153 view.source_categories()
1154 );
1155 // MCP tools only appear after a live discovery snapshot lands, and
1156 // plugins stay a deferred source.
1157 assert!(
1158 !view
1159 .source_categories()
1160 .contains(&HotbarActionCategory::Mcp)
1161 );
1162 assert!(
1163 !view
1164 .source_categories()
1165 .contains(&HotbarActionCategory::Plugin)
1166 );
1167 assert_eq!(view.selected_source(), Some(HotbarActionCategory::App));
1168 assert!(view.recommended_action_ids().contains("mode.agent"));
1169 // #3807: a fresh config seeds no bindings, so the wizard opens with
1170 // nothing checked until the user opts in.
1171 assert!(view.checked_action_ids().is_empty());
1172 }
1173
1174 #[test]
1175 fn wizard_lists_skill_and_mcp_sources_when_registered() {
1176 let mut app = test_app();
1177 let mut registry = HotbarActionRegistry::with_builtins();
1178 registry.register_skills(&[("demo".to_string(), "Demo skill".to_string())]);
1179 registry.replace_mcp_tools(Some(&codewhale_engine::mcp::McpManagerSnapshot {
1180 config_path: PathBuf::from("mcp.json"),
1181 config_exists: true,
1182 reload_required: false,
1183 servers: vec![codewhale_engine::mcp::McpServerSnapshot {
1184 name: "search".to_string(),
1185 enabled: true,
1186 required: false,
1187 transport: "stdio".to_string(),
1188 command_or_url: "search-server".to_string(),
1189 connect_timeout: 5,
1190 execute_timeout: 5,
1191 read_timeout: 5,
1192 connected: true,
1193 error: None,
1194 auth_required: false,
1195 capability_metadata:
1196 codewhale_engine::mcp::McpServerCapabilityMetadata::LegacyFallback,
1197 tools: vec![codewhale_engine::mcp::McpDiscoveredItem {
1198 name: "web_search".to_string(),
1199 model_name: "mcp_search_web_search".to_string(),
1200 description: Some("Search the web".to_string()),
1201 }],
1202 resources: Vec::new(),
1203 prompts: Vec::new(),
1204 }],
1205 }));
1206 app.hotbar_actions = registry;
1207 let mut view = HotbarSetupView::new(&app, &Config::default());
1208
1209 assert!(
1210 view.source_categories()
1211 .contains(&HotbarActionCategory::Skill)
1212 );
1213 assert!(
1214 view.source_categories()
1215 .contains(&HotbarActionCategory::Mcp)
1216 );
1217
1218 // Skills assign like any direct action; MCP tools stay assignable as
1219 // composer-prefill actions.
1220 assert!(view.select_slot(4));
1221 assert!(view.select_action_by_id("skill.demo"));
1222 assert!(view.assign_selected_action());
1223 assert_eq!(
1224 view.binding_for_slot(4)
1225 .map(|binding| binding.action.as_str()),
1226 Some("skill.demo")
1227 );
1228
1229 assert!(view.select_action_by_id("mcp.search.web_search"));
1230 assert!(
1231 view.status_text().contains("prefill"),
1232 "MCP tools must be labeled as prefill actions: {}",
1233 view.status_text()
1234 );
1235 assert!(view.select_slot(5));
1236 assert!(view.assign_selected_action());
1237 assert_eq!(
1238 view.binding_for_slot(5)
1239 .map(|binding| binding.action.as_str()),
1240 Some("mcp.search.web_search")
1241 );
1242 }
1243
1244 #[test]
1245 fn wizard_chrome_uses_non_english_locale() {
1246 let app = test_app_with_locale(Locale::ZhHant);
1247 let mut view = HotbarSetupView::new(&app, &Config::default());
1248 view.clear_selected_slot();
1249 view.handle_key(key(KeyCode::Char('?')));
1250
1251 let status = view.status_text();
1252 assert!(status.contains("槽位 1"), "status was {status:?}");
1253 // `Config::default()` ships no default bindings, so a freshly-cleared slot
1254 // is clean; assert the localized clean label (dirty localization is covered
1255 // by the wider render checks below) and that no English chrome leaks.
1256 assert!(
1257 status.contains(tr(Locale::ZhHant, MessageId::HotbarSetupDirtyClean).as_ref()),
1258 "status was {status:?}"
1259 );
1260 assert!(!status.contains("slot 1 |"), "status was {status:?}");
1261 assert!(!status.contains("clean"), "status was {status:?}");
1262
1263 let rendered = rendered_text(&view);
1264 let compact_rendered = rendered.replace(' ', "");
1265 // Localized chrome the PR routes through message IDs: title, source tabs
1266 // (the selected tab is bracketed and now carries a count from PR #3987),
1267 // status line, and localized built-in action names.
1268 for expected in [
1269 "Hotbar設定",
1270 "[應用",
1271 "斜線指令",
1272 "就緒",
1273 "槽位",
1274 "Work模式",
1275 "指令面板",
1276 "切換側邊欄",
1277 ] {
1278 assert!(
1279 compact_rendered.contains(expected),
1280 "missing {expected:?} in render:\n{rendered}"
1281 );
1282 }
1283 assert!(
1284 compact_rendered.contains(":空"),
1285 "missing localized empty slot:\n{rendered}"
1286 );
1287
1288 // English must not leak on the surfaces the PR localizes. The keybinding
1289 // footer, filter row, and detail labels are English scaffolding added by
1290 // PR #3987 after this contribution and are intentionally out of scope.
1291 for leaked in [
1292 "Hotbar setup",
1293 "slot 1 |",
1294 "ready",
1295 "modified",
1296 "empty",
1297 "Work mode",
1298 "Command palette",
1299 "Toggle workbar",
1300 "Switch the conversation",
1301 ] {
1302 assert!(
1303 !rendered.contains(leaked),
1304 "leaked {leaked:?} in render:\n{rendered}"
1305 );
1306 }
1307 }
1308
1309 #[test]
1310 fn wizard_assigns_replaces_toggles_and_clears_slots() {
1311 let app = test_app();
1312 let mut view = HotbarSetupView::new(&app, &Config::default());
1313
1314 assert!(view.select_slot(1));
1315 assert!(view.select_action_by_id("mode.plan"));
1316 assert!(view.assign_selected_action());
1317 assert_eq!(
1318 view.binding_for_slot(1)
1319 .map(|binding| binding.action.as_str()),
1320 Some("mode.plan")
1321 );
1322
1323 assert!(view.select_action_by_id("mode.agent"));
1324 assert!(view.assign_selected_action());
1325 assert_eq!(
1326 view.binding_for_slot(1)
1327 .map(|binding| binding.action.as_str()),
1328 Some("mode.agent")
1329 );
1330 assert!(view.is_dirty());
1331
1332 assert!(view.toggle_selected_action());
1333 assert!(view.binding_for_slot(1).is_none());
1334 view.clear_selected_slot();
1335 assert!(view.binding_for_slot(1).is_none());
1336 }
1337
1338 #[test]
1339 fn wizard_save_emits_bindings_but_escape_only_closes() {
1340 let app = test_app();
1341 let mut view = HotbarSetupView::new(&app, &Config::default());
1342 assert!(view.select_slot(8));
1343 assert!(view.select_action_by_id("sidebar.toggle"));
1344 assert!(view.assign_selected_action());
1345
1346 match view.handle_key(key(KeyCode::Char('s'))) {
1347 ViewAction::EmitAndClose(ViewEvent::HotbarSetupSaved { bindings }) => {
1348 assert!(
1349 bindings
1350 .iter()
1351 .any(|binding| { binding.slot == 8 && binding.action == "sidebar.toggle" })
1352 );
1353 }
1354 other => panic!("expected HotbarSetupSaved, got {other:?}"),
1355 }
1356
1357 let mut view = HotbarSetupView::new(&app, &Config::default());
1358 assert!(view.select_slot(1));
1359 assert!(view.select_action_by_id("mode.agent"));
1360 assert!(view.assign_selected_action());
1361 assert!(matches!(
1362 view.handle_key(key(KeyCode::Esc)),
1363 ViewAction::Close
1364 ));
1365 }
1366
1367 #[test]
1368 fn wizard_disable_key_emits_disable_request_and_intro_mentions_it() {
1369 let app = test_app();
1370
1371 // 'd' and 'D' hide the Hotbar from inside the setup flow (mirrors /hotbar
1372 // off), but only after the confirmation is answered. Disabling rewrites
1373 // every slot binding on disk, and this view takes bare letters as its
1374 // filter, so the first keystroke must never be the destructive one.
1375 for ch in ['d', 'D'] {
1376 let mut view = HotbarSetupView::new(&app, &Config::default());
1377 assert!(
1378 matches!(view.handle_key(key(KeyCode::Char(ch))), ViewAction::None),
1379 "{ch} must arm the confirmation, not disable the Hotbar"
1380 );
1381 assert!(
1382 view.status_text().contains("(y/n)"),
1383 "the armed confirmation must be visible, got {:?}",
1384 view.status_text()
1385 );
1386 assert!(matches!(
1387 view.handle_key(key(KeyCode::Char('y'))),
1388 ViewAction::EmitAndClose(ViewEvent::HotbarDisableRequested)
1389 ));
1390 }
1391
1392 // The armed confirmation must survive the header's five-row budget at a
1393 // real terminal width. `status_text()` returning it is not enough: the
1394 // intro wraps to two rows, and the confirmation used to be the sixth
1395 // line into a five-line region, so `d` armed a question the user never
1396 // saw. Assert the painted buffer, not the string.
1397 {
1398 use ratatui::{Terminal, backend::TestBackend};
1399 let mut view = HotbarSetupView::new(&app, &Config::default());
1400 assert!(matches!(
1401 view.handle_key(key(KeyCode::Char('d'))),
1402 ViewAction::None
1403 ));
1404 for (w, h) in [(100u16, 32u16), (80, 24), (140, 40)] {
1405 let mut terminal = Terminal::new(TestBackend::new(w, h)).expect("terminal");
1406 terminal
1407 .draw(|frame| {
1408 let area = frame.area();
1409 view.render(area, frame.buffer_mut());
1410 })
1411 .expect("draw");
1412 let painted = terminal
1413 .backend()
1414 .buffer()
1415 .content()
1416 .iter()
1417 .map(|cell| cell.symbol())
1418 .collect::<String>();
1419 assert!(
1420 painted.contains("(y/n)"),
1421 "{w}x{h}: the armed disable confirmation is not on screen"
1422 );
1423 }
1424 }
1425
1426 // Anything other than y dismisses it, and the keystroke is spent on the
1427 // dismissal rather than falling through to whatever it normally does.
1428 let mut view = HotbarSetupView::new(&app, &Config::default());
1429 assert!(matches!(
1430 view.handle_key(key(KeyCode::Char('d'))),
1431 ViewAction::None
1432 ));
1433 assert!(matches!(
1434 view.handle_key(key(KeyCode::Char('n'))),
1435 ViewAction::None
1436 ));
1437 assert!(!view.status_text().contains("(y/n)"));
1438 assert!(
1439 matches!(view.handle_key(key(KeyCode::Esc)), ViewAction::Close),
1440 "a dismissed confirmation returns the view to its ordinary key table"
1441 );
1442
1443 let view = HotbarSetupView::new(&app, &Config::default());
1444
1445 // The always-visible intro explains what Hotbar is and the disable path.
1446 let joined: String = view
1447 .render_lines()
1448 .iter()
1449 .flat_map(|line| line.spans.iter())
1450 .map(|span| span.content.as_ref())
1451 .collect();
1452 assert!(
1453 joined.contains("shortcuts"),
1454 "intro should explain what Hotbar is: {joined:?}"
1455 );
1456 assert!(
1457 joined.contains("/hotbar off"),
1458 "intro should mention the disable path: {joined:?}"
1459 );
1460 }
1461
1462 #[test]
1463 fn disabled_actions_are_visible_but_not_assignable() {
1464 let app = test_app();
1465 let mut view = HotbarSetupView::new(&app, &Config::default());
1466 let reasoning = view
1467 .actions
1468 .iter_mut()
1469 .find(|row| row.metadata.id == "reasoning.cycle")
1470 .expect("reasoning action");
1471 reasoning.disabled_reason = Some("disabled by test policy".to_string());
1472
1473 assert!(view.select_slot(2));
1474 assert!(view.select_action_by_id("reasoning.cycle"));
1475 assert!(!view.assign_selected_action());
1476
1477 assert_ne!(
1478 view.binding_for_slot(2)
1479 .map(|binding| binding.action.as_str()),
1480 Some("reasoning.cycle")
1481 );
1482 assert!(
1483 view.validation_errors()
1484 .last()
1485 .is_some_and(|error| error.contains("cannot be assigned"))
1486 );
1487 assert!(view.status_text().contains("cannot be assigned"));
1488 }
1489
1490 #[test]
1491 fn args_required_slash_actions_are_visible_and_assignable_as_prefill() {
1492 let app = test_app();
1493 let mut view = HotbarSetupView::new(&app, &Config::default());
1494
1495 assert!(view.select_action_by_id("slash.rename"));
1496 assert!(
1497 view.status_text().contains("prefill"),
1498 "required-arg commands must be labeled as prefill actions"
1499 );
1500 assert!(view.select_slot(3));
1501 assert!(view.assign_selected_action());
1502
1503 assert_eq!(
1504 view.binding_for_slot(3)
1505 .map(|binding| binding.action.as_str()),
1506 Some("slash.rename")
1507 );
1508 }
1509
1510 #[test]
1511 fn wizard_help_documents_runtime_hotbar_shortcut() {
1512 let app = test_app();
1513 let mut view = HotbarSetupView::new(&app, &Config::default());
1514
1515 assert!(matches!(
1516 view.handle_key(key(KeyCode::Char('?'))),
1517 ViewAction::None
1518 ));
1519 let rendered = view
1520 .selected_action()
1521 .map(|row| view.detail_lines(row))
1522 .expect("selected action")
1523 .into_iter()
1524 .map(|line| line.to_string())
1525 .collect::<Vec<_>>()
1526 .join("\n");
1527
1528 assert!(rendered.contains("After save: Alt+1 through Alt+8 dispatch Hotbar slots"));
1529 assert!(rendered.contains("Bare 1-8 stay composer text outside setup"));
1530 }
1531
1532 #[test]
1533 fn action_rows_semantically_truncate_descriptions_at_narrow_width() {
1534 let app = test_app();
1535 let view = HotbarSetupView::new(&app, &Config::default());
1536 let row = HotbarSetupActionRow {
1537 metadata: HotbarActionMetadata {
1538 id: "test.long-description".to_string(),
1539 source_id: "test".to_string(),
1540 display_name: "Open settings row".to_string(),
1541 compact_label: "test".to_string(),
1542 description: "Open a detailed settings panel without clipping".to_string(),
1543 category: HotbarActionCategory::App,
1544 args: HotbarArgsBehavior::None,
1545 safety: HotbarSafetyClass::LocalUi,
1546 recommendation: HotbarRecommendation::Eligible,
1547 },
1548 disabled_reason: None,
1549 };
1550
1551 let text = view
1552 .action_row_line(HotbarActionCategory::App, 0, &row, 58, true)
1553 .to_string();
1554 assert!(codewhale_tui_kit::ui_text::text_display_width(&text) <= 58);
1555 assert!(text.contains("Open a detailed…"), "{text:?}");
1556 assert!(!text.contains("Open a detailed s"), "{text:?}");
1557 }
1558
1559 #[test]
1560 fn action_row_columns_pad_by_display_width() {
1561 let app = test_app_with_locale(Locale::ZhHans);
1562 let view = HotbarSetupView::new(&app, &Config::default());
1563 let row = |id: &str, name: &str, disabled_reason: Option<&str>| HotbarSetupActionRow {
1564 metadata: HotbarActionMetadata {
1565 id: id.to_string(),
1566 source_id: "test".to_string(),
1567 display_name: name.to_string(),
1568 compact_label: "test".to_string(),
1569 description: "DESC".to_string(),
1570 category: HotbarActionCategory::App,
1571 args: HotbarArgsBehavior::None,
1572 safety: HotbarSafetyClass::LocalUi,
1573 recommendation: HotbarRecommendation::Eligible,
1574 },
1575 disabled_reason: disabled_reason.map(str::to_string),
1576 };
1577 assert!(view.recommended_action_ids().contains("mode.agent"));
1578 let desc_column = |row: &HotbarSetupActionRow| {
1579 let text = view
1580 .action_row_line(HotbarActionCategory::App, 0, row, 120, true)
1581 .to_string();
1582 let start = text.find("DESC").expect("description is shown");
1583 codewhale_tui_kit::ui_text::text_display_width(&text[..start])
1584 };
1585
1586 let wide = desc_column(&row("mode.agent", "设置", Some("off")));
1587 let narrow = desc_column(&row("test.plain", "settings", None));
1588 assert_eq!(wide, narrow, "description columns must line up");
1589 }
1590
1591 #[test]
1592 fn keyboard_controls_navigate_source_action_and_slot() {
1593 let mut config = {
1594 let __cw_config_init_0_0 = Some(ProviderKind::Deepseek.as_str().to_string());
1595 let mut __cw_config_init_0_value: Config = Config::default();
1596 __cw_config_init_0_value.provider = __cw_config_init_0_0;
1597 __cw_config_init_0_value
1598 };
1599 config
1600 .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openrouter))
1601 .unwrap()
1602 .model = Some("anthropic/claude-sonnet-4".to_string());
1603 let app = test_app_with_config(&config);
1604 let mut view = HotbarSetupView::new(&app, &config);
1605
1606 assert_eq!(view.selected_source(), Some(HotbarActionCategory::App));
1607 view.handle_key(key(KeyCode::Tab));
1608 assert_eq!(view.selected_source(), Some(HotbarActionCategory::Route));
1609 view.handle_key(key(KeyCode::Tab));
1610 assert_eq!(view.selected_source(), Some(HotbarActionCategory::Slash));
1611 view.handle_key(key(KeyCode::BackTab));
1612 assert_eq!(view.selected_source(), Some(HotbarActionCategory::Route));
1613
1614 let first = view
1615 .selected_action()
1616 .map(|row| row.metadata.id.clone())
1617 .expect("first action");
1618 view.handle_key(key(KeyCode::Down));
1619 let second = view
1620 .selected_action()
1621 .map(|row| row.metadata.id.clone())
1622 .expect("second action");
1623 assert_ne!(first, second);
1624
1625 view.handle_key(key(KeyCode::Char('8')));
1626 assert_eq!(view.selected_slot(), 8);
1627 view.handle_key(key(KeyCode::Left));
1628 assert_eq!(view.selected_slot(), 7);
1629 }
1630
1631 #[test]
1632 fn down_past_export_keeps_the_selected_action_visible() {
1633 let app = test_app();
1634 let mut view = HotbarSetupView::new(&app, &Config::default());
1635 assert!(view.select_action_by_id("slash.export"));
1636
1637 view.handle_key(key(KeyCode::Down));
1638 let selected = view.selected_action().expect("action after /export");
1639 assert_ne!(selected.metadata.id, "slash.export");
1640
1641 let rendered = rendered_text_at(&view, 80, 24);
1642 let marker = codewhale_tui_kit::glyphs::selection_marker(true);
1643 assert!(
1644 rendered.lines().any(|line| {
1645 line.contains(marker) && line.contains(&selected.metadata.display_name)
1646 }),
1647 "focused action {} must remain visible after moving past /export:\n{rendered}",
1648 selected.metadata.id
1649 );
1650 }
1651
1652 #[test]
1653 fn keyboard_filter_searches_catalog_and_escape_clears_it() {
1654 let app = test_app();
1655 let mut view = HotbarSetupView::new(&app, &Config::default());
1656
1657 view.handle_key(key(KeyCode::Tab));
1658 assert_eq!(view.selected_source(), Some(HotbarActionCategory::Route));
1659 let route_label = view
1660 .selected_action()
1661 .map(|row| row.metadata.display_name.clone())
1662 .expect("route action");
1663 let route_query = route_label
1664 .chars()
1665 .take(4)
1666 .collect::<String>()
1667 .to_ascii_lowercase();
1668 view.handle_key(key(KeyCode::Char('/')));
1669 for ch in route_query.chars() {
1670 view.handle_key(key(KeyCode::Char(ch)));
1671 }
1672 assert_eq!(view.query(), route_query);
1673 assert!(view.status_text().contains(&route_label));
1674
1675 let bindings = view.save_bindings();
1676 view.handle_key(key(KeyCode::Char(' ')));
1677 assert_eq!(view.query(), format!("{route_query} "));
1678 assert_eq!(view.save_bindings(), bindings);
1679
1680 view.handle_key(key(KeyCode::Esc));
1681 assert_eq!(view.query(), "");
1682 assert!(matches!(
1683 view.handle_key(key(KeyCode::Esc)),
1684 ViewAction::Close
1685 ));
1686 }
1687
1688 #[test]
1689 fn hotbar_setup_is_usable_and_opaque_at_blocker_sizes() {
1690 use crate::tui::views::ViewStack;
1691 use unicode_width::UnicodeWidthStr;
1692
1693 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
1694 let app = test_app();
1695 for (w, h) in BLOCKER_SIZES {
1696 let area = Rect::new(0, 0, w, h);
1697 let mut buf = Buffer::empty(area);
1698 for y in 0..h {
1699 for x in 0..w {
1700 buf[(x, y)].set_symbol("X");
1701 }
1702 }
1703 let mut stack = ViewStack::new();
1704 stack.push(HotbarSetupView::new(&app, &Config::default()));
1705 stack.render(area, &mut buf);
1706
1707 let rows: Vec<String> = (0..h)
1708 .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
1709 .collect();
1710 let text = rows.join("\n");
1711
1712 // Footer keeps every action.
1713 for label in [
1714 "source", "action", "slot", "filter", "assign", "toggle", "clear", "save",
1715 "disable", "cancel",
1716 ] {
1717 assert!(text.contains(label), "{w}x{h}: footer missing '{label}'");
1718 }
1719
1720 // Composited frame is fully opaque.
1721 assert!(!text.contains('X'), "{w}x{h}: background bleed-through");
1722 assert_eq!(
1723 buf[(w / 2, h / 2)].bg,
1724 palette::WHALE_BG,
1725 "{w}x{h}: modal interior must be opaque"
1726 );
1727
1728 // No horizontal overflow.
1729 for (y, row) in rows.iter().enumerate() {
1730 assert!(
1731 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
1732 "{w}x{h}: row {y} overflows width: {row:?}"
1733 );
1734 }
1735 }
1736 }
1737
1738 #[test]
1739 fn paste_populates_filter_and_respects_disable_confirm() {
1740 let app = test_app();
1741 let mut view = HotbarSetupView::new(&app, &Config::default());
1742 assert!(view.handle_paste("workbar\r\n"));
1743 assert_eq!(view.query(), "workbar");
1744 assert!(view.filter_focused);
1745
1746 view.handle_key(key(KeyCode::Esc));
1747 assert_eq!(view.query(), "");
1748 assert!(!view.filter_focused);
1749
1750 view.handle_key(key(KeyCode::Char('d')));
1751 assert!(view.confirm_disable);
1752 assert!(view.handle_paste("ignored\n"));
1753 assert_eq!(view.query(), "");
1754 }
1755 }
1756
1756 lines RUST