返回 CodeWhale
command_palette.rs
根目录 / crates / tui / src / tui / command_palette.rs
1 //! Command palette modal for quick command/skill insertion.
2 //!
3 //! Product job (#4276): **find and run one action** — not a dense manual.
4 //! Help owns concepts; Config owns settings; Fleet owns worker readiness.
5
6 use std::cell::{Cell, RefCell};
7 use std::collections::HashSet;
8 use std::path::{Component, Path, PathBuf};
9 use std::sync::{Arc, Mutex};
10
11 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
12 use ratatui::{
13 buffer::Buffer,
14 layout::Rect,
15 style::{Modifier, Style},
16 text::{Line, Span},
17 widgets::{Block, Borders, Padding, Paragraph, Widget},
18 };
19
20 use crate::commands;
21 use crate::tui::views::{
22 ActionHint, CommandPaletteAction, ModalKind, ModalView, ViewAction, ViewEvent,
23 centered_modal_area, render_modal_footer, render_modal_surface,
24 };
25 use codewhale_engine::tools::spec::ApprovalRequirement;
26 use codewhale_engine::tools::spec::ToolCapability;
27 use codewhale_engine::tools::{ToolContext, ToolRegistryBuilder};
28 use codewhale_localization::{Locale, MessageId, tr};
29 use codewhale_palette as palette;
30 use codewhale_skills as skills;
31 use codewhale_tui_kit::menu_style;
32
33 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
34 pub enum PaletteSection {
35 Action,
36 Command,
37 Skill,
38 Tool,
39 Mcp,
40 }
41
42 #[derive(Debug, Clone)]
43 pub struct CommandPaletteEntry {
44 section: PaletteSection,
45 pub label: String,
46 pub description: String,
47 pub command: String,
48 pub action: CommandPaletteAction,
49 show_on_empty_query: bool,
50 external_agent: Option<(String, String)>,
51 priority: u8,
52 }
53
54 impl CommandPaletteEntry {
55 fn selection_event(&self) -> ViewEvent {
56 if let Some((agent_id, agent_name)) = &self.external_agent {
57 ViewEvent::ExternalAgentSelected {
58 agent_id: agent_id.clone(),
59 agent_name: agent_name.clone(),
60 }
61 } else {
62 ViewEvent::CommandPaletteSelected {
63 action: self.action.clone(),
64 }
65 }
66 }
67 }
68
69 #[cfg(test)]
70 impl CommandPaletteEntry {
71 #[must_use]
72 pub fn section(&self) -> PaletteSection {
73 self.section
74 }
75 }
76
77 pub struct CommandPaletteView {
78 locale: Locale,
79 entries: Vec<CommandPaletteEntry>,
80 filtered: Vec<usize>,
81 query: String,
82 selected: usize,
83 /// Entry rows from the most recent render. Keeping the absolute filtered
84 /// index here makes mouse activation use the exact same action as Enter.
85 row_hitboxes: RefCell<Vec<(Rect, usize)>>,
86 /// Absolute filtered index under the pointer, tinted with the shared
87 /// hover style. Hover never moves the keyboard selection.
88 hovered: Cell<Option<usize>>,
89 pending_external_agents: Option<Arc<Mutex<Option<Vec<CommandPaletteEntry>>>>>,
90 }
91
92 #[cfg(test)]
93 pub fn build_entries(
94 locale: Locale,
95 skills_dir: &Path,
96 skills_config: &codewhale_runtime::config::SkillsConfig,
97 workspace: &Path,
98 mcp_config_path: &Path,
99 mcp_snapshot: Option<&codewhale_engine::mcp::McpManagerSnapshot>,
100 ) -> Vec<CommandPaletteEntry> {
101 build_entries_with_plugins(
102 locale,
103 skills_dir,
104 skills_config,
105 workspace,
106 mcp_config_path,
107 mcp_snapshot,
108 &codewhale_plugins::PluginRegistry::empty(workspace),
109 )
110 }
111
112 pub fn build_entries_with_plugins(
113 locale: Locale,
114 skills_dir: &Path,
115 skills_config: &codewhale_runtime::config::SkillsConfig,
116 workspace: &Path,
117 mcp_config_path: &Path,
118 mcp_snapshot: Option<&codewhale_engine::mcp::McpManagerSnapshot>,
119 plugins: &codewhale_plugins::PluginRegistry,
120 ) -> Vec<CommandPaletteEntry> {
121 let mut entries = Vec::new();
122 commands::user_registry::with_registry_for_plugins(plugins, |user_registry| {
123 let all_user_commands = user_registry.iter().collect::<Vec<_>>();
124 for command in commands::command_infos() {
125 if command.is_unlisted() {
126 continue;
127 }
128 if commands::discovery::user_command_shadows_builtin_canonical(
129 command,
130 &all_user_commands,
131 ) {
132 continue;
133 }
134 let mut description =
135 palette_description_for_unshadowed_aliases(command, locale, &all_user_commands);
136 if command.requires_argument() {
137 description.push_str(" ");
138 description.push_str(command.usage);
139 }
140 let action = if command.palette_runs_directly() {
141 CommandPaletteAction::ExecuteCommand {
142 command: format!("/{}", command.name),
143 }
144 } else {
145 CommandPaletteAction::InsertText {
146 text: command.palette_command(),
147 }
148 };
149 entries.push(CommandPaletteEntry {
150 section: PaletteSection::Command,
151 label: format!("/{}", command.name),
152 description,
153 command: command.palette_command(),
154 action,
155 show_on_empty_query: command.show_in_empty_discovery(),
156 external_agent: None,
157 priority: 1,
158 });
159 }
160
161 for command in user_registry.iter().filter(|command| !command.hidden) {
162 let mut description = command
163 .description
164 .clone()
165 .unwrap_or_else(|| "User-defined command".to_string());
166 if let Some(hint) = command.display_usage() {
167 description.push_str(" ");
168 description.push_str(hint);
169 }
170 let slash_command = format!("/{}", command.name);
171 let action = if command.takes_arguments() {
172 CommandPaletteAction::InsertText {
173 text: format!("{slash_command} "),
174 }
175 } else {
176 CommandPaletteAction::ExecuteCommand {
177 command: slash_command.clone(),
178 }
179 };
180 entries.push(CommandPaletteEntry {
181 section: PaletteSection::Command,
182 label: slash_command.clone(),
183 description,
184 command: slash_command,
185 action,
186 show_on_empty_query: true,
187 external_agent: None,
188 priority: 1,
189 });
190 }
191 });
192
193 let skills =
194 skills::discover_for_workspace(workspace, Some(skills_dir), skills_config, Some(plugins))
195 .into_enabled();
196 for skill in skills
197 .list()
198 .iter()
199 .filter(|skill| skill.invocation.user_invocable())
200 {
201 entries.push(CommandPaletteEntry {
202 section: PaletteSection::Skill,
203 label: format!("${}", skill.name),
204 description: skill.user_menu_description(),
205 command: format!("${}", skill.name),
206 action: CommandPaletteAction::ExecuteCommand {
207 command: format!("${}", skill.name),
208 },
209 show_on_empty_query: true,
210 external_agent: None,
211 priority: 1,
212 });
213 }
214
215 let context = ToolContext::new(workspace);
216 let registry = ToolRegistryBuilder::new()
217 .with_file_tools()
218 .with_search_tools()
219 .with_shell_tools()
220 .with_web_tools()
221 .with_git_tools()
222 .with_user_input_tool(codewhale_engine::tools::user_input::UserInputLimits::default())
223 .with_patch_tools()
224 .with_test_runner_tool()
225 .build(context);
226
227 let mut tool_entries = registry
228 .all()
229 .into_iter()
230 .filter_map(|tool| {
231 let name = tool.name().to_string();
232 let capabilities = tool.capabilities();
233
234 let mut tags = Vec::new();
235 if tool.is_read_only() {
236 tags.push("read-only");
237 }
238 if capabilities.contains(&ToolCapability::WritesFiles) {
239 tags.push("writes");
240 }
241 if capabilities.contains(&ToolCapability::ExecutesCode) {
242 tags.push("shell");
243 }
244 if capabilities.contains(&ToolCapability::Network) {
245 tags.push("network");
246 }
247 if tool.supports_parallel() {
248 tags.push("parallel");
249 }
250 match tool.approval_requirement() {
251 ApprovalRequirement::Required => tags.push("requires approval"),
252 ApprovalRequirement::Suggest => tags.push("suggest approval"),
253 ApprovalRequirement::Auto => {}
254 }
255
256 let mut description = tool.description().to_string();
257 if !tags.is_empty() {
258 description.push_str(" [");
259 description.push_str(&tags.join(", "));
260 description.push(']');
261 }
262
263 if name.trim().is_empty() {
264 return None;
265 }
266 Some(CommandPaletteEntry {
267 section: PaletteSection::Tool,
268 label: format!("tool:{name}"),
269 description: description.clone(),
270 command: name,
271 action: CommandPaletteAction::OpenTextPager {
272 title: format!("Tool: {}", tool.name()),
273 content: format_tool_details(tool.name(), tool.description(), &tags),
274 },
275 show_on_empty_query: true,
276 external_agent: None,
277 priority: 1,
278 })
279 })
280 .collect::<Vec<_>>();
281 tool_entries.sort_by(|a, b| a.label.cmp(&b.label));
282 entries.extend(tool_entries);
283
284 entries.extend(build_mcp_entries(
285 workspace,
286 mcp_config_path,
287 mcp_snapshot,
288 plugins,
289 ));
290
291 entries.sort_by(|a, b| {
292 a.priority
293 .cmp(&b.priority)
294 .then_with(|| a.section.cmp(&b.section))
295 .then_with(|| a.label.cmp(&b.label))
296 });
297 entries
298 }
299
300 fn palette_description_for_unshadowed_aliases(
301 command: &commands::CommandInfo,
302 locale: Locale,
303 all_user_commands: &[&commands::user_registry::UserCommandMetadata],
304 ) -> String {
305 let desc = command.description_for(locale);
306 let aliases = commands::discovery::unshadowed_builtin_aliases(command, all_user_commands);
307 if aliases.len() == command.aliases.len() {
308 return command.palette_description_for(locale);
309 }
310 if aliases.is_empty() {
311 desc.to_string()
312 } else {
313 format!(
314 "{} {}",
315 desc,
316 tr(locale, MessageId::PaletteAliasesSuffix).replace(
317 "{aliases}",
318 &aliases.join(&tr(locale, MessageId::ListSeparator))
319 )
320 )
321 }
322 }
323
324 fn external_agent_entry(id: &str, name: &str, version: Option<&str>) -> CommandPaletteEntry {
325 let version_suffix = version
326 .map(str::trim)
327 .filter(|v| !v.is_empty())
328 .map(|v| format!(" ({v})"))
329 .unwrap_or_default();
330 CommandPaletteEntry {
331 section: PaletteSection::Action,
332 label: format!("agent:{id}"),
333 description: format!("Launch {name} external ACP agent{version_suffix}"),
334 command: format!("agent {id} {name}"),
335 action: CommandPaletteAction::ExecuteCommand {
336 command: "/model".to_string(),
337 },
338 show_on_empty_query: true,
339 external_agent: Some((id.to_string(), name.to_string())),
340 priority: 1,
341 }
342 }
343
344 #[cfg(test)]
345 pub fn build_external_agent_entries(
346 rows: &[codewhale_app_server::runtime_api::ExternalAgentDiscoveryRow],
347 ) -> Vec<CommandPaletteEntry> {
348 let mut seen = HashSet::new();
349 let mut entries = Vec::new();
350 for row in rows {
351 if !row.runnable {
352 continue;
353 }
354 let id = row.id.trim();
355 if id.is_empty() || !seen.insert(id.to_ascii_lowercase()) {
356 continue;
357 }
358 entries.push(external_agent_entry(id, &row.name, row.version.as_deref()));
359 }
360 entries
361 }
362
363 fn external_agent_search_dirs() -> Vec<PathBuf> {
364 const USER_BIN_DIRS: &[&str] = &[
365 ".local/bin",
366 ".npm-global/bin",
367 ".opencode/bin",
368 ".kimi-code/bin",
369 ".cursor/bin",
370 ".devin/bin",
371 ".bun/bin",
372 ".cargo/bin",
373 ];
374 let mut dirs: Vec<PathBuf> = std::env::var_os("PATH")
375 .map(|path| std::env::split_paths(&path).collect())
376 .unwrap_or_default();
377 let home = std::env::var_os("HOME");
378 #[cfg(windows)]
379 let home = home.or_else(|| std::env::var_os("USERPROFILE"));
380 if let Some(home) = home.map(PathBuf::from) {
381 dirs.extend(USER_BIN_DIRS.iter().map(|dir| home.join(dir)));
382 }
383 #[cfg(windows)]
384 if let Some(appdata) = std::env::var_os("APPDATA") {
385 dirs.push(PathBuf::from(appdata).join("npm"));
386 }
387 #[cfg(not(windows))]
388 dirs.extend(
389 ["/opt/homebrew/bin", "/usr/local/bin"]
390 .iter()
391 .map(PathBuf::from),
392 );
393 dirs.retain(|dir| dir.is_absolute());
394 dirs
395 }
396
397 fn spawn_installed_external_agent_discovery() -> Option<Arc<Mutex<Option<Vec<CommandPaletteEntry>>>>>
398 {
399 if tokio::runtime::Handle::try_current().is_err() {
400 return None;
401 }
402 let cell = Arc::new(Mutex::new(None));
403 let slot = Arc::clone(&cell);
404 codewhale_util::utils::spawn_blocking_supervised("command-palette-agents", move || {
405 let is_executable_file = |path: &Path| -> bool {
406 let Ok(meta) = std::fs::metadata(path) else {
407 return false;
408 };
409 if !meta.is_file() {
410 return false;
411 }
412 #[cfg(unix)]
413 {
414 use std::os::unix::fs::PermissionsExt;
415 meta.permissions().mode() & 0o111 != 0
416 }
417 #[cfg(not(unix))]
418 {
419 true
420 }
421 };
422 let dirs = external_agent_search_dirs();
423 let resolve_in_dirs = |binary: &str| -> bool {
424 let mut components = Path::new(binary).components();
425 if !matches!(
426 (components.next(), components.next()),
427 (Some(Component::Normal(_)), None)
428 ) {
429 return false;
430 }
431 #[cfg(windows)]
432 let exts: Vec<String> = std::env::var("PATHEXT")
433 .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string())
434 .split(';')
435 .map(|s| s.trim().to_string())
436 .filter(|s| !s.is_empty())
437 .collect();
438 for dir in &dirs {
439 #[cfg(not(windows))]
440 if is_executable_file(&dir.join(binary)) {
441 return true;
442 }
443 #[cfg(windows)]
444 {
445 if is_executable_file(&dir.join(binary)) {
446 return true;
447 }
448 for ext in &exts {
449 if is_executable_file(&dir.join(format!("{binary}{ext}"))) {
450 return true;
451 }
452 }
453 }
454 }
455 false
456 };
457 let mut seen = HashSet::new();
458 let mut entries = Vec::new();
459 for agent in codewhale_engine::fleet::agents::AGENTS {
460 let binary_ok = resolve_in_dirs(agent.binary);
461 let runnable = binary_ok
462 && (agent.acp_args.is_some() || agent.adapter_binary.is_some_and(&resolve_in_dirs));
463 if runnable && seen.insert(agent.id.to_ascii_lowercase()) {
464 entries.push(external_agent_entry(agent.id, agent.name, None));
465 }
466 }
467 for custom in codewhale_engine::fleet::agents::custom_agents() {
468 let path = Path::new(&custom.binary);
469 let runnable = if path.is_absolute() {
470 is_executable_file(path)
471 } else {
472 resolve_in_dirs(&custom.binary)
473 };
474 if runnable && seen.insert(custom.id.to_ascii_lowercase()) {
475 entries.push(external_agent_entry(&custom.id, &custom.name, None));
476 }
477 }
478 if let Ok(mut guard) = slot.lock() {
479 *guard = Some(entries);
480 }
481 });
482 Some(cell)
483 }
484
485 fn build_mcp_entries(
486 workspace: &Path,
487 mcp_config_path: &Path,
488 mcp_snapshot: Option<&codewhale_engine::mcp::McpManagerSnapshot>,
489 plugins: &codewhale_plugins::PluginRegistry,
490 ) -> Vec<CommandPaletteEntry> {
491 let owned_snapshot = if mcp_snapshot.is_none() {
492 codewhale_engine::mcp::manager_snapshot_from_config_with_workspace_and_plugins(
493 mcp_config_path,
494 workspace,
495 false,
496 plugins,
497 )
498 .ok()
499 } else {
500 None
501 };
502 let snapshot = mcp_snapshot.or(owned_snapshot.as_ref());
503 let mut entries = vec![CommandPaletteEntry {
504 section: PaletteSection::Mcp,
505 label: "mcp:manager".to_string(),
506 description: format!("Open MCP manager ({})", mcp_config_path.display()),
507 command: "/mcp".to_string(),
508 action: CommandPaletteAction::ExecuteCommand {
509 command: "/mcp".to_string(),
510 },
511 show_on_empty_query: true,
512 external_agent: None,
513 priority: 1,
514 }];
515
516 let Some(snapshot) = snapshot else {
517 return entries;
518 };
519
520 if snapshot.reload_required {
521 entries.push(CommandPaletteEntry {
522 section: PaletteSection::Action,
523 label: "attention:mcp:reload".to_string(),
524 description: "Attention: reload MCP configuration".to_string(),
525 command: "/mcp reload".to_string(),
526 action: CommandPaletteAction::ExecuteCommand {
527 command: "/mcp reload".to_string(),
528 },
529 show_on_empty_query: true,
530 external_agent: None,
531 priority: 0,
532 });
533 }
534
535 for server in &snapshot.servers {
536 if server.enabled && server.error.is_some() {
537 entries.push(CommandPaletteEntry {
538 section: PaletteSection::Action,
539 label: format!("recover:mcp:{}", server.name),
540 description: format!("Recovery: retry failed MCP server {}", server.name),
541 command: format!("/mcp retry {}", server.name),
542 action: CommandPaletteAction::ExecuteCommand {
543 command: format!("/mcp retry {}", server.name),
544 },
545 show_on_empty_query: true,
546 external_agent: None,
547 priority: 0,
548 });
549 } else if server.enabled && server.auth_required && !server.connected {
550 entries.push(CommandPaletteEntry {
551 section: PaletteSection::Action,
552 label: format!("attention:mcp:{}", server.name),
553 description: format!("Attention: sign in to MCP server {}", server.name),
554 command: format!("/mcp login {}", server.name),
555 action: CommandPaletteAction::ExecuteCommand {
556 command: format!("/mcp login {}", server.name),
557 },
558 show_on_empty_query: true,
559 external_agent: None,
560 priority: 0,
561 });
562 }
563 let state = if server.enabled {
564 if server.connected {
565 "connected"
566 } else if server.error.is_some() {
567 "failed"
568 } else {
569 "enabled"
570 }
571 } else {
572 "disabled"
573 };
574 entries.push(CommandPaletteEntry {
575 section: PaletteSection::Mcp,
576 label: format!("mcp:{}", server.name),
577 description: format!(
578 "{} {} [{}] tools={} resources={} prompts={}",
579 server.transport,
580 codewhale_engine::mcp::mcp_display_target(
581 &server.transport,
582 &server.command_or_url
583 ),
584 state,
585 server.tools.len(),
586 server.resources.len(),
587 server.prompts.len()
588 ),
589 command: format!("/mcp show {}", server.name),
590 action: CommandPaletteAction::OpenTextPager {
591 title: format!("MCP Server: {}", server.name),
592 content: format_mcp_server_details(snapshot, server),
593 },
594 show_on_empty_query: true,
595 external_agent: None,
596 priority: 1,
597 });
598
599 for tool in &server.tools {
600 entries.push(CommandPaletteEntry {
601 section: PaletteSection::Mcp,
602 label: format!("mcp:{}:tool:{}", server.name, tool.name),
603 description: format!(
604 "{}{}",
605 tool.model_name,
606 tool.description
607 .as_ref()
608 .map_or(String::new(), |desc| format!(" - {desc}"))
609 ),
610 command: tool.model_name.clone(),
611 action: CommandPaletteAction::OpenTextPager {
612 title: format!("MCP Tool: {}", tool.model_name),
613 content: format!(
614 "Server: {}\nRuntime name: {}\nKind: tool\n\n{}",
615 server.name,
616 tool.model_name,
617 tool.description.as_deref().unwrap_or("(no description)")
618 ),
619 },
620 show_on_empty_query: true,
621 external_agent: None,
622 priority: 1,
623 });
624 // Add a "use" entry that inserts the tool's model_name into the input
625 // so users can quickly reference the tool in their message to the AI.
626 if !tool.model_name.trim().is_empty() {
627 entries.push(CommandPaletteEntry {
628 section: PaletteSection::Mcp,
629 label: format!("mcp:{}:tool:{} > use", server.name, tool.name),
630 description: format!(
631 "Insert {} into input — type args then send{}",
632 tool.model_name,
633 tool.description
634 .as_ref()
635 .map_or(String::new(), |desc| format!(" ({desc})"))
636 ),
637 command: tool.model_name.clone(),
638 action: CommandPaletteAction::InsertText {
639 text: tool.model_name.clone(),
640 },
641 show_on_empty_query: true,
642 external_agent: None,
643 priority: 1,
644 });
645 }
646 }
647
648 for resource in &server.resources {
649 entries.push(CommandPaletteEntry {
650 section: PaletteSection::Mcp,
651 label: format!("mcp:{}:resource:{}", server.name, resource.name),
652 description: resource
653 .description
654 .clone()
655 .unwrap_or_else(|| "MCP resource".to_string()),
656 command: resource.name.clone(),
657 action: CommandPaletteAction::OpenTextPager {
658 title: format!("MCP Resource: {}", resource.name),
659 content: format!(
660 "Server: {}\nResource: {}\nModel helper: list_mcp_resources / read_mcp_resource",
661 server.name, resource.name
662 ),
663 },
664 show_on_empty_query: true,
665 external_agent: None,
666 priority: 1,
667 });
668 }
669
670 for prompt in &server.prompts {
671 entries.push(CommandPaletteEntry {
672 section: PaletteSection::Mcp,
673 label: format!("mcp:{}:prompt:{}", server.name, prompt.name),
674 description: format!(
675 "{}{}",
676 prompt.model_name,
677 prompt
678 .description
679 .as_ref()
680 .map_or(String::new(), |desc| format!(" - {desc}"))
681 ),
682 command: prompt.model_name.clone(),
683 action: CommandPaletteAction::OpenTextPager {
684 title: format!("MCP Prompt: {}", prompt.model_name),
685 content: format!(
686 "Server: {}\nRuntime name: {}\nKind: prompt",
687 server.name, prompt.model_name
688 ),
689 },
690 show_on_empty_query: true,
691 external_agent: None,
692 priority: 1,
693 });
694 }
695 }
696
697 entries
698 }
699
700 fn format_mcp_server_details(
701 snapshot: &codewhale_engine::mcp::McpManagerSnapshot,
702 server: &codewhale_engine::mcp::McpServerSnapshot,
703 ) -> String {
704 let mut lines = vec![
705 format!("Config: {}", snapshot.config_path.display()),
706 format!("Server: {}", server.name),
707 format!("Enabled: {}", server.enabled),
708 format!("Connected: {}", server.connected),
709 format!("Transport: {}", server.transport),
710 format!(
711 "Target: {}",
712 codewhale_engine::mcp::mcp_display_target(&server.transport, &server.command_or_url)
713 ),
714 format!(
715 "Timeouts: connect={}s execute={}s read={}s",
716 server.connect_timeout, server.execute_timeout, server.read_timeout
717 ),
718 ];
719 if let Some(error) = server.error.as_ref() {
720 lines.push(format!("Error: {error}"));
721 }
722 lines.push(String::new());
723 lines.push(format!("Tools ({})", server.tools.len()));
724 for tool in &server.tools {
725 lines.push(format!(" - {}", tool.model_name));
726 }
727 lines.push(format!("Resources ({})", server.resources.len()));
728 for resource in &server.resources {
729 lines.push(format!(" - {}", resource.name));
730 }
731 lines.push(format!("Prompts ({})", server.prompts.len()));
732 for prompt in &server.prompts {
733 lines.push(format!(" - {}", prompt.model_name));
734 }
735 lines.join("\n")
736 }
737
738 fn modal_block() -> Block<'static> {
739 Block::default()
740 .borders(Borders::ALL)
741 .border_style(Style::default().fg(palette::BORDER_COLOR))
742 .style(Style::default().bg(palette::WHALE_BG))
743 .padding(Padding::uniform(1))
744 }
745
746 fn parse_section_term(term: &str) -> Option<(PaletteSection, String)> {
747 let (section, query) = term.split_once(':')?;
748
749 if section.is_empty() || query.is_empty() {
750 return None;
751 }
752
753 let query = query.to_ascii_lowercase();
754 let section = match section {
755 "a" | "action" | "actions" => PaletteSection::Action,
756 "c" | "cmd" | "command" | "commands" => PaletteSection::Command,
757 "s" | "skill" | "skills" => PaletteSection::Skill,
758 "t" | "tool" | "tools" => PaletteSection::Tool,
759 "m" | "mcp" => PaletteSection::Mcp,
760 _ => return None,
761 };
762
763 Some((section, query))
764 }
765
766 fn section_tag(section: PaletteSection) -> &'static str {
767 match section {
768 PaletteSection::Action => "action",
769 PaletteSection::Command => "command",
770 PaletteSection::Skill => "skill",
771 PaletteSection::Tool => "tool",
772 PaletteSection::Mcp => "mcp",
773 }
774 }
775
776 fn section_rank(section: PaletteSection) -> usize {
777 match section {
778 PaletteSection::Action => 0,
779 PaletteSection::Command => 1,
780 PaletteSection::Skill => 2,
781 PaletteSection::Tool => 3,
782 PaletteSection::Mcp => 4,
783 }
784 }
785
786 fn format_tool_details(name: &str, description: &str, tags: &[&str]) -> String {
787 let mut lines = vec![
788 format!("Tool: {name}"),
789 String::new(),
790 description.to_string(),
791 ];
792 if !tags.is_empty() {
793 lines.push(String::new());
794 lines.push(format!("Capabilities: {}", tags.join(", ")));
795 }
796 lines.push(String::new());
797 lines.push(
798 "Use slash commands and skills here for direct actions; use tool entries to inspect what the agent can call."
799 .to_string(),
800 );
801 lines.join("\n")
802 }
803
804 fn term_score(term: &str, label: &str, description: &str, command: &str, haystack: &str) -> usize {
805 if term.is_empty() {
806 return 0;
807 }
808
809 if label == term || command == term || description == term {
810 return 0;
811 }
812
813 if label.starts_with(term) {
814 return 8;
815 }
816
817 if command.starts_with(term) {
818 return 16;
819 }
820
821 if description.contains(term) {
822 return 64;
823 }
824
825 if label.contains(term) {
826 return 32;
827 }
828
829 if command.contains(term) {
830 return 48;
831 }
832
833 if haystack.contains(term) {
834 return 96;
835 }
836
837 128
838 }
839
840 fn entry_match_score(entry: &CommandPaletteEntry, terms: &[&str]) -> Option<usize> {
841 if terms.is_empty() {
842 return Some(0);
843 }
844
845 let section = section_tag(entry.section);
846 let label = entry.label.to_ascii_lowercase();
847 let description = entry.description.to_ascii_lowercase();
848 let command = entry.command.to_ascii_lowercase();
849 let entry_text = format!("{section} {label} {description} {command}");
850
851 let mut total_score = 0usize;
852
853 for term in terms {
854 if let Some((required_section, scoped_query)) = parse_section_term(term) {
855 if entry.section != required_section {
856 return None;
857 }
858 if !entry_text.contains(&scoped_query) {
859 return None;
860 }
861 total_score += term_score(&scoped_query, &label, &description, &command, &entry_text);
862 continue;
863 }
864
865 if !entry_text.contains(term) {
866 return None;
867 }
868 total_score += term_score(term, &label, &description, &command, &entry_text);
869 }
870
871 Some(total_score)
872 }
873
874 /// Number of rendered rows the entry loop consumes for the window
875 /// `sections[start..end]`: one row per entry, plus one section-label row each
876 /// time the section changes, plus a separator blank before every section group
877 /// after the first.
878 fn rendered_entry_rows(sections: &[PaletteSection], start: usize, end: usize) -> usize {
879 let end = end.min(sections.len());
880 if start >= end {
881 return 0;
882 }
883 let mut rows = 0usize;
884 let mut active: Option<PaletteSection> = None;
885 for (slot, sec) in sections[start..end].iter().enumerate() {
886 if active != Some(*sec) {
887 if slot > 0 {
888 rows += 1; // separator blank
889 }
890 rows += 1; // section label
891 active = Some(*sec);
892 }
893 rows += 1; // the entry itself
894 }
895 rows
896 }
897
898 /// Compute the `[start, end)` window of filtered entries to render so that the
899 /// selected entry is always visible and the rendered rows — entries plus the
900 /// per-section labels and separators inserted between them — fit within
901 /// `available` rows.
902 ///
903 /// The previous logic sized the window purely by entry count (`popup_height -
904 /// 7`) while the same fixed-height area also held the header, section labels,
905 /// and separators. Those uncounted rows pushed the selection past the bottom
906 /// clip line, so it vanished and the list appeared frozen until the index
907 /// finally exceeded the (overlarge) entry budget (#2590).
908 fn visible_entry_window(
909 sections: &[PaletteSection],
910 selected: usize,
911 available: usize,
912 ) -> (usize, usize) {
913 let total = sections.len();
914 if total == 0 || available == 0 {
915 return (0, 0);
916 }
917 let selected = selected.min(total - 1);
918 // Always include the selected row, then greedily grow downward and upward
919 // while the fully-rendered window still fits. Growth only ever adds rows,
920 // so the greedy expansion terminates at the largest fitting window.
921 let mut start = selected;
922 let mut end = selected + 1;
923 loop {
924 let mut progressed = false;
925 if end < total && rendered_entry_rows(sections, start, end + 1) <= available {
926 end += 1;
927 progressed = true;
928 }
929 if start > 0 && rendered_entry_rows(sections, start - 1, end) <= available {
930 start -= 1;
931 progressed = true;
932 }
933 if !progressed {
934 break;
935 }
936 }
937 (start, end)
938 }
939
940 impl CommandPaletteView {
941 #[cfg(test)]
942 pub fn new(entries: Vec<CommandPaletteEntry>) -> Self {
943 Self::new_for_locale(Locale::En, entries)
944 }
945
946 pub fn new_for_locale(locale: Locale, entries: Vec<CommandPaletteEntry>) -> Self {
947 let has_external_agents = entries.iter().any(|entry| entry.external_agent.is_some());
948 let pending_external_agents = if has_external_agents {
949 None
950 } else {
951 spawn_installed_external_agent_discovery()
952 };
953 let mut view = Self {
954 locale,
955 entries,
956 filtered: Vec::new(),
957 query: String::new(),
958 selected: 0,
959 row_hitboxes: RefCell::new(Vec::new()),
960 hovered: Cell::new(None),
961 pending_external_agents,
962 };
963 view.refilter();
964 view
965 }
966
967 fn poll_external_agents(&mut self) -> bool {
968 let Some(cell) = self.pending_external_agents.as_ref() else {
969 return false;
970 };
971 let Some(discovered) = cell.lock().ok().and_then(|mut guard| guard.take()) else {
972 return false;
973 };
974 self.pending_external_agents = None;
975 if discovered.is_empty() {
976 return false;
977 }
978 let existing: HashSet<String> = self
979 .entries
980 .iter()
981 .map(|entry| entry.label.to_ascii_lowercase())
982 .collect();
983 let mut added = false;
984 for entry in discovered {
985 if !existing.contains(&entry.label.to_ascii_lowercase()) {
986 self.entries.push(entry);
987 added = true;
988 }
989 }
990 if added {
991 self.entries.sort_by(|a, b| {
992 a.priority
993 .cmp(&b.priority)
994 .then_with(|| a.section.cmp(&b.section))
995 .then_with(|| a.label.cmp(&b.label))
996 });
997 self.refilter();
998 }
999 added
1000 }
1001
1002 fn refilter(&mut self) {
1003 let query = self.query.trim().to_ascii_lowercase();
1004 let terms: Vec<&str> = query
1005 .split_whitespace()
1006 .filter(|term| !term.is_empty())
1007 .collect();
1008
1009 let mut filtered = self
1010 .entries
1011 .iter()
1012 .enumerate()
1013 .filter_map(|(idx, entry)| {
1014 if terms.is_empty() && !entry.show_on_empty_query {
1015 return None;
1016 }
1017 entry_match_score(entry, &terms).map(|score| (idx, score))
1018 })
1019 .collect::<Vec<_>>();
1020
1021 filtered.sort_by_key(|(idx, score)| {
1022 let entry = &self.entries[*idx];
1023 (
1024 entry.priority,
1025 section_rank(entry.section),
1026 *score,
1027 &entry.label,
1028 )
1029 });
1030 // Follow the highlighted entry across the refilter instead of leaving a
1031 // raw index pointing into a freshly re-sorted list. Every keystroke
1032 // refilters, so a clamp alone silently slides the highlight onto an
1033 // unrelated row — and Enter runs whatever it landed on. `filtered` holds
1034 // indices into the stable `entries`, so the entry is its own identity.
1035 let keep = self.filtered.get(self.selected).copied();
1036 self.filtered = filtered.into_iter().map(|(idx, _)| idx).collect();
1037 self.selected = keep
1038 .and_then(|entry| self.filtered.iter().position(|idx| *idx == entry))
1039 .unwrap_or(0);
1040 self.hovered.set(None);
1041 }
1042
1043 fn scope_hint_lines() -> Line<'static> {
1044 let hint = "scope: a:action · c:cmd · s:skill · t:tool · m:mcp";
1045 Line::from(Span::styled(
1046 hint,
1047 Style::default()
1048 .fg(palette::TEXT_DIM)
1049 .add_modifier(Modifier::ITALIC),
1050 ))
1051 }
1052
1053 fn format_section_label(section: PaletteSection, count: usize) -> Line<'static> {
1054 let title = match section {
1055 PaletteSection::Action => "Actions",
1056 PaletteSection::Command => "Commands",
1057 PaletteSection::Skill => "Skills",
1058 PaletteSection::Tool => "Tools",
1059 PaletteSection::Mcp => "MCP",
1060 };
1061 Line::from(vec![Span::styled(
1062 format!(" {title} ({count}) "),
1063 Style::default()
1064 .fg(palette::WHALE_ACTION)
1065 .add_modifier(Modifier::BOLD),
1066 )])
1067 }
1068
1069 fn move_selection(&mut self, delta: isize) {
1070 self.selected =
1071 codewhale_tui_kit::list_nav::wrap_index(self.selected, self.filtered.len(), delta);
1072 self.hovered.set(None);
1073 }
1074
1075 fn selected_entry(&self) -> Option<&CommandPaletteEntry> {
1076 self.filtered
1077 .get(self.selected)
1078 .and_then(|idx| self.entries.get(*idx))
1079 }
1080 }
1081
1082 impl ModalView for CommandPaletteView {
1083 fn kind(&self) -> ModalKind {
1084 ModalKind::CommandPalette
1085 }
1086
1087 fn tick(&mut self) -> ViewAction {
1088 if self.poll_external_agents() {
1089 ViewAction::Redraw
1090 } else {
1091 ViewAction::None
1092 }
1093 }
1094
1095 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
1096 self
1097 }
1098
1099 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
1100 match mouse.kind {
1101 MouseEventKind::Moved => {
1102 let hovered = self.row_hitboxes.borrow().iter().find_map(|(rect, index)| {
1103 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
1104 .then_some(*index)
1105 });
1106 self.hovered.set(hovered);
1107 }
1108 MouseEventKind::ScrollUp => self.move_selection(-1),
1109 MouseEventKind::ScrollDown => self.move_selection(1),
1110 MouseEventKind::Down(MouseButton::Left) => {
1111 let clicked = self.row_hitboxes.borrow().iter().find_map(|(rect, index)| {
1112 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
1113 .then_some(*index)
1114 });
1115 if let Some(index) = clicked {
1116 if self.selected == index {
1117 if let Some(entry) = self.selected_entry() {
1118 return ViewAction::EmitAndClose(entry.selection_event());
1119 }
1120 } else {
1121 self.selected = index;
1122 }
1123 }
1124 }
1125 _ => {}
1126 }
1127 ViewAction::None
1128 }
1129
1130 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
1131 match key.code {
1132 KeyCode::Esc => ViewAction::Close,
1133 KeyCode::Enter => {
1134 if let Some(entry) = self.selected_entry() {
1135 ViewAction::EmitAndClose(entry.selection_event())
1136 } else {
1137 ViewAction::None
1138 }
1139 }
1140 KeyCode::Up => {
1141 self.move_selection(-1);
1142 ViewAction::None
1143 }
1144 KeyCode::Down => {
1145 self.move_selection(1);
1146 ViewAction::None
1147 }
1148 KeyCode::PageUp => {
1149 self.move_selection(-8);
1150 ViewAction::None
1151 }
1152 KeyCode::PageDown => {
1153 self.move_selection(8);
1154 ViewAction::None
1155 }
1156 KeyCode::Backspace => {
1157 self.query.pop();
1158 self.refilter();
1159 ViewAction::None
1160 }
1161 // Ctrl+H is the legacy ASCII backspace many terminals emit.
1162 KeyCode::Char('h')
1163 if key.modifiers.contains(KeyModifiers::CONTROL)
1164 && !key.modifiers.contains(KeyModifiers::ALT) =>
1165 {
1166 self.query.pop();
1167 self.refilter();
1168 ViewAction::None
1169 }
1170 KeyCode::Char(c)
1171 if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT =>
1172 {
1173 self.query.push(c);
1174 self.refilter();
1175 ViewAction::None
1176 }
1177 _ => ViewAction::None,
1178 }
1179 }
1180
1181 fn handle_paste(&mut self, text: &str) -> bool {
1182 self.query.push_str(
1183 &text
1184 .trim_end_matches(['\r', '\n'])
1185 .replace("\r\n", "\n")
1186 .replace(char::is_control, " "),
1187 );
1188 self.refilter();
1189 true
1190 }
1191
1192 fn render(&self, area: Rect, buf: &mut Buffer) {
1193 self.row_hitboxes.borrow_mut().clear();
1194 let popup_area = centered_modal_area(area, 90, 22, 44, 8);
1195 let popup_width = popup_area.width;
1196
1197 render_modal_surface(area, popup_area, buf);
1198
1199 let title = format!(
1200 " {} — {} ",
1201 tr(self.locale, MessageId::CommandPaletteTitle),
1202 tr(self.locale, MessageId::CommandPaletteSubtitle)
1203 );
1204 let block = modal_block().title(Line::from(Span::styled(
1205 title,
1206 Style::default()
1207 .fg(palette::WHALE_ACTION)
1208 .add_modifier(Modifier::BOLD),
1209 )));
1210 let inner = block.inner(popup_area);
1211 block.render(popup_area, buf);
1212
1213 let content = render_modal_footer(
1214 inner,
1215 buf,
1216 &[
1217 ActionHint::new("↑/↓", "move"),
1218 ActionHint::new("Enter", "select"),
1219 ActionHint::new("Esc", "cancel"),
1220 ],
1221 );
1222
1223 let mut lines = Vec::new();
1224 let mut entry_line_indices = Vec::new();
1225 let query_label = if self.query.is_empty() {
1226 tr(self.locale, MessageId::HelpFilterPlaceholder).into_owned()
1227 } else {
1228 format!(
1229 "{}{}",
1230 tr(self.locale, MessageId::HelpFilterPrefix),
1231 self.query
1232 )
1233 };
1234 lines.push(Line::from(Span::styled(
1235 query_label,
1236 Style::default().fg(palette::TEXT_MUTED),
1237 )));
1238 let match_count = if self.query.is_empty() {
1239 tr(self.locale, MessageId::PaletteShownCount)
1240 } else {
1241 tr(self.locale, MessageId::HelpMatchCount)
1242 }
1243 .replace("{shown}", &self.filtered.len().to_string())
1244 .replace("{total}", &self.entries.len().to_string());
1245 lines.push(Line::from(Span::styled(
1246 match_count,
1247 Style::default().fg(palette::TEXT_DIM).italic(),
1248 )));
1249 lines.push(Self::scope_hint_lines());
1250 lines.push(Line::from(""));
1251
1252 // Rows the bordered popup can show for the list, minus the header that
1253 // was already pushed above. The entry loop additionally emits section
1254 // labels and separators, so the scroll window is sized against the real
1255 // rendered cost rather than a flat entry count (#2590).
1256 let header_lines = lines.len();
1257 let available = (content.height as usize).saturating_sub(header_lines);
1258 let mut action_count = 0usize;
1259 let mut command_count = 0usize;
1260 let mut skill_count = 0usize;
1261 let mut tool_count = 0usize;
1262 let mut mcp_count = 0usize;
1263 for idx in &self.filtered {
1264 match self.entries[*idx].section {
1265 PaletteSection::Action => action_count += 1,
1266 PaletteSection::Command => command_count += 1,
1267 PaletteSection::Skill => skill_count += 1,
1268 PaletteSection::Tool => tool_count += 1,
1269 PaletteSection::Mcp => mcp_count += 1,
1270 }
1271 }
1272 if self.filtered.is_empty() {
1273 lines.push(Line::from(Span::styled(
1274 tr(self.locale, MessageId::PaletteNoMatches),
1275 Style::default().fg(palette::TEXT_MUTED).italic(),
1276 )));
1277 } else {
1278 let label_width = 24.min(popup_width.saturating_sub(26) as usize);
1279 let sections: Vec<PaletteSection> = self
1280 .filtered
1281 .iter()
1282 .map(|idx| self.entries[*idx].section)
1283 .collect();
1284 let (start, end) = visible_entry_window(&sections, self.selected, available);
1285 let mut active_section = None;
1286 for (slot, idx) in self.filtered[start..end].iter().enumerate() {
1287 let absolute = start + slot;
1288 let is_selected = absolute == self.selected;
1289 let entry = &self.entries[*idx];
1290
1291 if active_section != Some(entry.section) {
1292 if slot > 0 {
1293 lines.push(Line::from(""));
1294 }
1295 let count = match entry.section {
1296 PaletteSection::Action => action_count,
1297 PaletteSection::Command => command_count,
1298 PaletteSection::Skill => skill_count,
1299 PaletteSection::Tool => tool_count,
1300 PaletteSection::Mcp => mcp_count,
1301 };
1302 lines.push(Self::format_section_label(entry.section, count));
1303 active_section = Some(entry.section);
1304 }
1305
1306 // Hover tints but never steals the keyboard selection.
1307 let hovered = !is_selected && self.hovered.get() == Some(absolute);
1308 let style = if is_selected {
1309 menu_style::selected_row_style()
1310 } else if hovered {
1311 Style::default()
1312 .fg(palette::TEXT_PRIMARY)
1313 .patch(menu_style::hovered_row_style())
1314 } else if entry.priority == 0 {
1315 Style::default()
1316 .fg(palette::STATUS_WARNING)
1317 .add_modifier(Modifier::BOLD)
1318 } else {
1319 Style::default().fg(palette::TEXT_PRIMARY)
1320 };
1321
1322 let pointer = codewhale_tui_kit::glyphs::selection_marker(is_selected);
1323 // `{:<width$}` pads but never truncates, so a long label — every
1324 // `mcp:server:tool` row — ran past the column and pushed the
1325 // description off the card entirely. Truncate first, then pad, so
1326 // the description column stays on one axis.
1327 let label =
1328 codewhale_tui_kit::ui_text::truncate_line_to_width(&entry.label, label_width);
1329 let mut line = format!(
1330 "{pointer} {}",
1331 codewhale_tui_kit::ui_text::pad_to_display_width(&label, label_width)
1332 );
1333 // The rows are drawn into `content`, which is the popup less its
1334 // borders and padding — measuring against `popup_width` overstated
1335 // the room by four columns.
1336 let content_width = (popup_width as usize).saturating_sub(4);
1337 let desc_capacity = content_width.saturating_sub(label_width + 4);
1338 let desc = codewhale_tui_kit::ui_text::truncate_line_to_width(
1339 &entry.description,
1340 desc_capacity,
1341 );
1342 line.push_str(" ");
1343 line.push_str(&desc);
1344 entry_line_indices.push((lines.len(), absolute));
1345 lines.push(Line::from(Span::styled(line, style)));
1346 }
1347 }
1348
1349 // The palette's row-budget logic intentionally treats each logical
1350 // line as one terminal row. Do not wrap here: wrapping a long query or
1351 // label would both hide later entries and make mouse hitboxes lie.
1352 Paragraph::new(lines).render(content, buf);
1353 *self.row_hitboxes.borrow_mut() = entry_line_indices
1354 .into_iter()
1355 .filter_map(|(line, index)| {
1356 let row = content.y.saturating_add(line as u16);
1357 (row < content.bottom())
1358 .then_some((Rect::new(content.x, row, content.width, 1), index))
1359 })
1360 .collect();
1361 }
1362 }
1363
1364 #[cfg(test)]
1365 mod tests {
1366 use super::*;
1367 use std::path::Path;
1368 use tempfile::TempDir;
1369 use unicode_width::UnicodeWidthStr;
1370
1371 #[test]
1372 fn refilter_keeps_the_highlight_on_the_entry_the_user_was_looking_at() {
1373 // Every keystroke refilters and re-sorts. The index used to be clamped
1374 // but never re-anchored, so refining a query could slide the highlight
1375 // onto an unrelated row — and Enter runs whatever is highlighted.
1376 let entries = vec![
1377 palette_entry(PaletteSection::Tool, "tool:one", "alpha", "one"),
1378 palette_entry(PaletteSection::Tool, "tool:two", "shared", "two"),
1379 palette_entry(PaletteSection::Tool, "tool:three", "shared", "three"),
1380 ];
1381 let mut view = CommandPaletteView::new(entries);
1382
1383 view.query = "tool".to_string();
1384 view.refilter();
1385 view.selected = view
1386 .filtered
1387 .iter()
1388 .position(|idx| view.entries[*idx].label == "tool:three")
1389 .expect("tool:three is listed");
1390
1391 // Narrowing to a query `tool:three` still matches. It moves to a lower
1392 // index in the shorter list, which is exactly the case a clamp gets
1393 // wrong: the old code reset to 0 and highlighted `tool:two`.
1394 view.query = "shared".to_string();
1395 view.refilter();
1396 assert_eq!(
1397 view.selected_entry().map(|entry| entry.label.as_str()),
1398 Some("tool:three"),
1399 "the highlight jumped to another row: {:?}",
1400 view.selected_entry().map(|entry| entry.label.clone())
1401 );
1402
1403 // When the highlighted entry filters out entirely, fall back to the top
1404 // rather than to a stale index.
1405 view.query = "alpha".to_string();
1406 view.refilter();
1407 assert_eq!(
1408 view.selected_entry().map(|entry| entry.label.as_str()),
1409 Some("tool:one")
1410 );
1411 }
1412
1413 #[test]
1414 fn visible_window_keeps_selection_in_view_and_fits() {
1415 // Single large section, small budget: every selection must stay visible
1416 // and the rendered window must fit the available rows (#2590).
1417 let sections = vec![PaletteSection::Command; 30];
1418 let available = 10;
1419 for selected in 0..sections.len() {
1420 let (start, end) = visible_entry_window(&sections, selected, available);
1421 assert!(
1422 start <= selected && selected < end,
1423 "selected {selected} must lie within [{start}, {end})"
1424 );
1425 assert!(
1426 rendered_entry_rows(&sections, start, end) <= available,
1427 "window [{start}, {end}) must fit within {available} rows"
1428 );
1429 }
1430 }
1431
1432 #[test]
1433 fn visible_window_scrolls_as_selection_advances() {
1434 let sections = vec![PaletteSection::Command; 30];
1435 let available = 8;
1436 let (start_near, _) = visible_entry_window(&sections, 0, available);
1437 assert_eq!(start_near, 0);
1438 // A far-down selection must advance the window start — the old code
1439 // left it pinned at 0 so the selection scrolled off-screen.
1440 let (start_far, end_far) = visible_entry_window(&sections, 25, available);
1441 assert!(start_far > 0, "window should scroll for a far selection");
1442 assert!(start_far <= 25 && 25 < end_far);
1443 }
1444
1445 #[test]
1446 fn visible_window_accounts_for_section_overhead() {
1447 // Each entry is its own section, so each costs a label (plus a
1448 // separator after the first) on top of the entry row. Far fewer than
1449 // `available` entries fit, and the window must still respect the budget.
1450 let sections = vec![
1451 PaletteSection::Action,
1452 PaletteSection::Command,
1453 PaletteSection::Skill,
1454 PaletteSection::Tool,
1455 PaletteSection::Mcp,
1456 ];
1457 let available = 6;
1458 let (start, end) = visible_entry_window(&sections, 0, available);
1459 assert_eq!(start, 0);
1460 assert!(end >= 1, "at least the selected entry must render");
1461 assert!(rendered_entry_rows(&sections, start, end) <= available);
1462 }
1463
1464 #[test]
1465 fn visible_window_handles_empty_and_zero_budget() {
1466 assert_eq!(visible_entry_window(&[], 0, 10), (0, 0));
1467 let sections = vec![PaletteSection::Command; 5];
1468 assert_eq!(visible_entry_window(&sections, 2, 0), (0, 0));
1469 }
1470
1471 fn palette_entry(
1472 section: PaletteSection,
1473 label: &str,
1474 description: &str,
1475 command: &str,
1476 ) -> CommandPaletteEntry {
1477 CommandPaletteEntry {
1478 section,
1479 label: label.to_string(),
1480 description: description.to_string(),
1481 command: command.to_string(),
1482 action: CommandPaletteAction::InsertText {
1483 text: command.to_string(),
1484 },
1485 show_on_empty_query: true,
1486 external_agent: None,
1487 priority: 1,
1488 }
1489 }
1490
1491 fn assert_palette_search_owns_text(query: &str) {
1492 let entries = ["json", "key", "队列é"]
1493 .map(|text| palette_entry(PaletteSection::Command, text, "", text))
1494 .to_vec();
1495 let mut stack = crate::tui::views::ViewStack::new();
1496 stack.push(CommandPaletteView::new(entries));
1497 for ch in query.chars() {
1498 assert!(
1499 stack
1500 .handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE))
1501 .is_empty()
1502 );
1503 assert_eq!(stack.top_kind(), Some(ModalKind::CommandPalette));
1504 }
1505 let mut modal = stack.pop().unwrap();
1506 let view = modal
1507 .as_any_mut()
1508 .downcast_mut::<CommandPaletteView>()
1509 .unwrap();
1510 assert_eq!(view.query, query);
1511 assert_eq!(view.filtered.len(), 1);
1512 for code in [
1513 KeyCode::Up,
1514 KeyCode::Down,
1515 KeyCode::PageUp,
1516 KeyCode::PageDown,
1517 ] {
1518 assert!(matches!(
1519 view.handle_key(KeyEvent::new(code, KeyModifiers::NONE)),
1520 ViewAction::None
1521 ));
1522 assert_eq!(view.query, query);
1523 }
1524 assert!(matches!(
1525 view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)),
1526 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
1527 action: CommandPaletteAction::InsertText { text }
1528 }) if text == query
1529 ));
1530 assert!(matches!(
1531 view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)),
1532 ViewAction::Close
1533 ));
1534 }
1535
1536 #[test]
1537 fn palette_search_owns_initial_j() {
1538 assert_palette_search_owns_text("json");
1539 }
1540
1541 #[test]
1542 fn palette_search_owns_initial_k() {
1543 assert_palette_search_owns_text("key");
1544 }
1545
1546 #[test]
1547 fn palette_search_owns_unicode() {
1548 assert_palette_search_owns_text("队列é");
1549 }
1550
1551 #[test]
1552 fn palette_search_consumes_bracketed_paste() {
1553 let entries = ["队列é", "队列é review pass"]
1554 .map(|text| palette_entry(PaletteSection::Command, text, "", text))
1555 .to_vec();
1556 let mut stack = crate::tui::views::ViewStack::new();
1557 stack.push(CommandPaletteView::new(entries));
1558 assert!(
1559 stack
1560 .handle_key(KeyEvent::new(KeyCode::Char('队'), KeyModifiers::NONE))
1561 .is_empty()
1562 );
1563 assert!(stack.handle_paste("列é\r\nreview\tpass\r\n"));
1564
1565 let mut modal = stack.pop().unwrap();
1566 let view = modal
1567 .as_any_mut()
1568 .downcast_mut::<CommandPaletteView>()
1569 .unwrap();
1570 assert_eq!(view.query, "队列é review pass");
1571 assert_eq!(view.filtered, vec![1]);
1572 }
1573
1574 #[test]
1575 fn command_palette_filters_with_section_shortcuts() {
1576 let entries = vec![
1577 palette_entry(PaletteSection::Command, "/mode", "mode command", "/mode"),
1578 palette_entry(
1579 PaletteSection::Skill,
1580 "skill:search",
1581 "search skill",
1582 "/skill search",
1583 ),
1584 palette_entry(PaletteSection::Tool, "tool:git", "git tool", "git"),
1585 palette_entry(
1586 PaletteSection::Tool,
1587 "tool:search",
1588 "search utility",
1589 "search",
1590 ),
1591 palette_entry(PaletteSection::Mcp, "mcp:fs", "filesystem", "mcp_fs_read"),
1592 ];
1593 let mut view = CommandPaletteView::new(entries);
1594
1595 view.query = "c:mode".to_string();
1596 view.refilter();
1597 assert_eq!(view.filtered, vec![0]);
1598
1599 view.query = "s:search".to_string();
1600 view.refilter();
1601 assert_eq!(view.filtered, vec![1]);
1602
1603 view.query = "t:search".to_string();
1604 view.refilter();
1605 assert_eq!(view.filtered, vec![3]);
1606
1607 view.query = "m:fs".to_string();
1608 view.refilter();
1609 assert_eq!(view.filtered, vec![4]);
1610 }
1611
1612 #[test]
1613 fn command_palette_ranks_label_matches_before_description_matches() {
1614 let entries = vec![
1615 palette_entry(
1616 PaletteSection::Command,
1617 "/git",
1618 "status summary for repository",
1619 "git",
1620 ),
1621 palette_entry(
1622 PaletteSection::Command,
1623 "/config",
1624 "configure git settings",
1625 "config",
1626 ),
1627 palette_entry(
1628 PaletteSection::Command,
1629 "/sync",
1630 "sync repository state",
1631 "sync",
1632 ),
1633 ];
1634 let mut view = CommandPaletteView::new(entries);
1635
1636 view.query = "git".to_string();
1637 view.refilter();
1638
1639 assert_eq!(view.entries[view.filtered[0]].label, "/git");
1640 assert_eq!(view.entries[view.filtered[1]].label, "/config");
1641 }
1642
1643 #[test]
1644 fn command_palette_supports_multiple_terms() {
1645 let entries = vec![
1646 palette_entry(
1647 PaletteSection::Command,
1648 "/search-code",
1649 "search with ripgrep",
1650 "search code",
1651 ),
1652 palette_entry(
1653 PaletteSection::Tool,
1654 "tool:search",
1655 "search web and files",
1656 "search",
1657 ),
1658 palette_entry(
1659 PaletteSection::Skill,
1660 "skill:search",
1661 "search files and docs",
1662 "/skill search",
1663 ),
1664 ];
1665 let mut view = CommandPaletteView::new(entries);
1666
1667 view.query = "search code".to_string();
1668 view.refilter();
1669 assert_eq!(view.filtered.len(), 1);
1670 assert_eq!(view.entries[view.filtered[0]].label, "/search-code");
1671
1672 view.query = "s:search".to_string();
1673 view.refilter();
1674 assert_eq!(view.filtered.len(), 1);
1675 assert_eq!(view.entries[view.filtered[0]].label, "skill:search");
1676 }
1677
1678 #[test]
1679 fn command_palette_skills_use_workspace_and_configured_directories() {
1680 let tmp = TempDir::new().expect("tempdir");
1681 let workspace = tmp.path().join("workspace");
1682 crate::test_support::trust_workspace(&workspace);
1683 let workspace_skill_dir = workspace
1684 .join(".agents")
1685 .join("skills")
1686 .join("workspace-skill");
1687 std::fs::create_dir_all(&workspace_skill_dir).expect("create workspace skill dir");
1688 std::fs::write(
1689 workspace_skill_dir.join("SKILL.md"),
1690 "---\nname: workspace-skill\ndescription: Workspace skill\ngithub: https://example.com\n---\nbody",
1691 )
1692 .expect("write workspace skill");
1693
1694 let configured_dir = tmp.path().join("configured-skills");
1695 let configured_skill_dir = configured_dir.join("configured-skill");
1696 std::fs::create_dir_all(&configured_skill_dir).expect("create configured skill dir");
1697 std::fs::write(
1698 configured_skill_dir.join("SKILL.md"),
1699 "---\nname: configured-skill\ndescription: Configured skill\n---\nbody",
1700 )
1701 .expect("write configured skill");
1702
1703 let entries = build_entries(
1704 Locale::En,
1705 configured_dir.as_path(),
1706 &Default::default(),
1707 workspace.as_path(),
1708 Path::new("mcp.json"),
1709 None,
1710 );
1711 let skill_labels = entries
1712 .iter()
1713 .filter(|entry| entry.section == PaletteSection::Skill)
1714 .map(|entry| entry.label.as_str())
1715 .collect::<Vec<_>>();
1716
1717 assert!(skill_labels.contains(&"$workspace-skill"));
1718 assert!(skill_labels.contains(&"$configured-skill"));
1719 }
1720
1721 #[test]
1722 fn command_palette_skills_respect_codewhale_only_scan() {
1723 let tmp = TempDir::new().expect("tempdir");
1724 let workspace = tmp.path().join("workspace");
1725 crate::test_support::trust_workspace(&workspace);
1726 let claude_skill_dir = workspace
1727 .join(".claude")
1728 .join("skills")
1729 .join("claude-skill");
1730 std::fs::create_dir_all(&claude_skill_dir).expect("create claude skill dir");
1731 std::fs::write(
1732 claude_skill_dir.join("SKILL.md"),
1733 "---\nname: claude-skill\ndescription: Claude skill\n---\nbody",
1734 )
1735 .expect("write claude skill");
1736 let codewhale_skill_dir = workspace
1737 .join(".codewhale")
1738 .join("skills")
1739 .join("codewhale-skill");
1740 std::fs::create_dir_all(&codewhale_skill_dir).expect("create codewhale skill dir");
1741 std::fs::write(
1742 codewhale_skill_dir.join("SKILL.md"),
1743 "---\nname: codewhale-skill\ndescription: CodeWhale skill\n---\nbody",
1744 )
1745 .expect("write codewhale skill");
1746
1747 let entries = build_entries(
1748 Locale::En,
1749 workspace.join(".codewhale").join("skills").as_path(),
1750 &codewhale_runtime::config::SkillsConfig {
1751 scan_codewhale_only: Some(true),
1752 ..Default::default()
1753 },
1754 workspace.as_path(),
1755 Path::new("mcp.json"),
1756 None,
1757 );
1758 let skill_labels: Vec<&str> = entries
1759 .iter()
1760 .filter(|entry| entry.section == PaletteSection::Skill)
1761 .map(|entry| entry.label.as_str())
1762 .collect();
1763
1764 assert!(skill_labels.contains(&"$codewhale-skill"));
1765 assert!(!skill_labels.contains(&"$claude-skill"));
1766 }
1767
1768 #[test]
1769 fn command_palette_includes_only_active_reviewed_plugin_skills() {
1770 let _env = crate::test_support::lock_test_env();
1771 let tmp = TempDir::new().expect("tempdir");
1772 let _home =
1773 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path().join("home"));
1774 let workspace = tmp.path().join("workspace");
1775 let plugin_root = tmp.path().join("plugins/demo");
1776 std::fs::create_dir_all(plugin_root.join("skills/review")).expect("plugin Skill dir");
1777 std::fs::write(
1778 plugin_root.join("plugin.toml"),
1779 "schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n[skills]\npath = \"skills\"\n",
1780 )
1781 .expect("plugin manifest");
1782 std::fs::write(
1783 plugin_root.join("skills/review/SKILL.md"),
1784 "---\nname: review\ndescription: reviewed plugin Skill\n---\nbody\n",
1785 )
1786 .expect("plugin Skill");
1787 let config = codewhale_plugins::discovery::DiscoveryConfig {
1788 workspace: workspace.clone(),
1789 user_plugins_dir: tmp.path().join("plugins"),
1790 workspace_plugins_dir: workspace.join(".codewhale/plugins"),
1791 builtin_plugin_dirs: Vec::new(),
1792 state_path: tmp.path().join("plugin-state/state.json"),
1793 };
1794 let mut plugins = codewhale_plugins::discovery::discover_with_config(&config);
1795 let entries_before = build_entries_with_plugins(
1796 Locale::En,
1797 tmp.path().join("skills").as_path(),
1798 &Default::default(),
1799 &workspace,
1800 Path::new("mcp.json"),
1801 None,
1802 &plugins,
1803 );
1804 assert!(
1805 !entries_before
1806 .iter()
1807 .any(|entry| entry.label == "$demo:review")
1808 );
1809
1810 plugins.trust("demo").expect("trust plugin");
1811 plugins.enable("demo").expect("enable plugin");
1812 let entries_after = build_entries_with_plugins(
1813 Locale::En,
1814 tmp.path().join("skills").as_path(),
1815 &Default::default(),
1816 &workspace,
1817 Path::new("mcp.json"),
1818 None,
1819 &plugins,
1820 );
1821 let skill = entries_after
1822 .iter()
1823 .find(|entry| entry.label == "$demo:review")
1824 .expect("active reviewed plugin Skill should reach the palette");
1825 assert!(matches!(
1826 &skill.action,
1827 CommandPaletteAction::ExecuteCommand { command } if command == "$demo:review"
1828 ));
1829 }
1830
1831 #[test]
1832 fn command_palette_command_entries_include_links_and_config_but_not_removed_commands() {
1833 let entries = build_entries(
1834 Locale::En,
1835 Path::new("."),
1836 &Default::default(),
1837 Path::new("."),
1838 Path::new("mcp.json"),
1839 None,
1840 );
1841 let command_labels = entries
1842 .iter()
1843 .filter(|entry| entry.section == PaletteSection::Command)
1844 .map(|entry| entry.label.as_str())
1845 .collect::<Vec<_>>();
1846
1847 assert!(command_labels.contains(&"/config"));
1848 assert!(command_labels.contains(&"/links"));
1849 assert!(command_labels.contains(&"/voice"));
1850 assert!(!command_labels.contains(&"/set"));
1851 assert!(!command_labels.contains(&"/deepseek"));
1852 }
1853
1854 #[test]
1855 fn command_palette_includes_workspace_user_commands() {
1856 let tmp = TempDir::new().expect("tempdir");
1857 let workspace = tmp.path().join("workspace");
1858 let commands_dir = workspace.join(".codewhale").join("commands");
1859 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
1860 codewhale_runtime::config::save_workspace_trust(&workspace).expect("trust workspace");
1861 std::fs::write(
1862 commands_dir.join("review.md"),
1863 "---\ndescription: Review with context\nargument-hint: <path>\n---\nReview $ARGUMENTS",
1864 )
1865 .expect("write user command");
1866
1867 let entries = build_entries(
1868 Locale::En,
1869 tmp.path().join("skills").as_path(),
1870 &Default::default(),
1871 workspace.as_path(),
1872 tmp.path().join("mcp.json").as_path(),
1873 None,
1874 );
1875 let user_entry = entries
1876 .iter()
1877 .find(|entry| entry.section == PaletteSection::Command && entry.label == "/review")
1878 .expect("user command should appear in command palette");
1879
1880 assert!(user_entry.description.contains("Review with context"));
1881 assert!(user_entry.description.contains("<path>"));
1882 assert!(matches!(
1883 &user_entry.action,
1884 CommandPaletteAction::InsertText { text } if text == "/review "
1885 ));
1886 }
1887
1888 #[test]
1889 fn command_palette_uses_frontmatter_name_usage_and_arguments() {
1890 let tmp = TempDir::new().expect("tempdir");
1891 let workspace = tmp.path().join("workspace");
1892 crate::test_support::trust_workspace(&workspace);
1893 let commands_dir = workspace.join(".codewhale").join("commands");
1894 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
1895 std::fs::write(
1896 commands_dir.join("workflow-file.md"),
1897 "---\nname: inspect\ndescription: Inspect a target\nusage: /inspect <path>\narguments: <path>\nargument-hint: <legacy>\n---\nInspect $ARGUMENTS",
1898 )
1899 .expect("write user command");
1900
1901 let entries = build_entries(
1902 Locale::En,
1903 tmp.path().join("skills").as_path(),
1904 &Default::default(),
1905 workspace.as_path(),
1906 tmp.path().join("mcp.json").as_path(),
1907 None,
1908 );
1909 let user_entry = entries
1910 .iter()
1911 .find(|entry| entry.section == PaletteSection::Command && entry.label == "/inspect")
1912 .expect("frontmatter name should be the palette command");
1913
1914 assert_eq!(user_entry.description, "Inspect a target /inspect <path>");
1915 assert!(matches!(
1916 &user_entry.action,
1917 CommandPaletteAction::InsertText { text } if text == "/inspect "
1918 ));
1919 assert!(!entries.iter().any(|entry| {
1920 entry.section == PaletteSection::Command && entry.label == "/workflow-file"
1921 }));
1922 }
1923
1924 #[test]
1925 fn command_palette_excludes_hidden_user_commands() {
1926 let tmp = TempDir::new().expect("tempdir");
1927 let workspace = tmp.path().join("workspace");
1928 let commands_dir = workspace.join(".codewhale").join("commands");
1929 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
1930 std::fs::write(
1931 commands_dir.join("secret.md"),
1932 "---\ndescription: Internal workflow\nhidden: true\n---\nsecret",
1933 )
1934 .expect("write hidden user command");
1935
1936 let entries = build_entries(
1937 Locale::En,
1938 tmp.path().join("skills").as_path(),
1939 &Default::default(),
1940 workspace.as_path(),
1941 tmp.path().join("mcp.json").as_path(),
1942 None,
1943 );
1944
1945 assert!(
1946 !entries
1947 .iter()
1948 .any(|entry| entry.section == PaletteSection::Command && entry.label == "/secret")
1949 );
1950 }
1951
1952 #[test]
1953 fn hidden_frontmatter_name_override_suppresses_shadowed_builtin() {
1954 let tmp = TempDir::new().expect("tempdir");
1955 let workspace = tmp.path().join("workspace");
1956 crate::test_support::trust_workspace(&workspace);
1957 let commands_dir = workspace.join(".codewhale").join("commands");
1958 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
1959 std::fs::write(
1960 commands_dir.join("private-help.md"),
1961 "---\nname: help\nhidden: true\n---\nprivate help",
1962 )
1963 .expect("write hidden user command");
1964
1965 let entries = build_entries(
1966 Locale::En,
1967 tmp.path().join("skills").as_path(),
1968 &Default::default(),
1969 workspace.as_path(),
1970 tmp.path().join("mcp.json").as_path(),
1971 None,
1972 );
1973
1974 assert!(!entries.iter().any(|entry| {
1975 entry.section == PaletteSection::Command
1976 && matches!(entry.label.as_str(), "/help" | "/private-help")
1977 }));
1978 }
1979
1980 #[test]
1981 fn command_palette_filters_shadowed_builtin_aliases_from_description() {
1982 let tmp = TempDir::new().expect("tempdir");
1983 let workspace = tmp.path().join("workspace");
1984 crate::test_support::trust_workspace(&workspace);
1985 let commands_dir = workspace.join(".codewhale").join("commands");
1986 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
1987 std::fs::write(
1988 commands_dir.join("image-review.md"),
1989 "---\ndescription: Review an image\nalias: image\n---\nreview image",
1990 )
1991 .expect("write user command");
1992
1993 let entries = build_entries(
1994 Locale::En,
1995 tmp.path().join("skills").as_path(),
1996 &Default::default(),
1997 workspace.as_path(),
1998 tmp.path().join("mcp.json").as_path(),
1999 None,
2000 );
2001 let attach = entries
2002 .iter()
2003 .find(|entry| entry.section == PaletteSection::Command && entry.label == "/attach")
2004 .expect("built-in canonical command should remain visible");
2005
2006 assert!(
2007 !attach.description.contains("aliases: image")
2008 && !attach.description.contains(", image")
2009 && !attach.description.contains("image,"),
2010 "shadowed /image alias must not be advertised by /attach: {}",
2011 attach.description
2012 );
2013 assert!(
2014 entries
2015 .iter()
2016 .any(|entry| entry.section == PaletteSection::Command
2017 && entry.label == "/image-review"),
2018 "user command that owns the /image alias should be visible"
2019 );
2020 }
2021
2022 #[test]
2023 fn command_palette_visible_canonical_shadow_has_exactly_one_user_row() {
2024 // Deep-Dive Q1: a visible user command whose canonical name equals a
2025 // built-in must produce exactly one palette row owned by the user
2026 // command (its metadata and action), never the built-in row.
2027 let tmp = TempDir::new().expect("tempdir");
2028 let workspace = tmp.path().join("workspace");
2029 crate::test_support::trust_workspace(&workspace);
2030 let commands_dir = workspace.join(".codewhale").join("commands");
2031 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
2032 std::fs::write(
2033 commands_dir.join("my-help.md"),
2034 "---\nname: help\ndescription: My private help\nusage: /help <topic>\n---\nhelp $ARGUMENTS",
2035 )
2036 .expect("write user command");
2037
2038 let entries = build_entries(
2039 Locale::En,
2040 tmp.path().join("skills").as_path(),
2041 &Default::default(),
2042 workspace.as_path(),
2043 tmp.path().join("mcp.json").as_path(),
2044 None,
2045 );
2046 let rows = entries
2047 .iter()
2048 .filter(|entry| entry.section == PaletteSection::Command && entry.label == "/help")
2049 .collect::<Vec<_>>();
2050
2051 assert_eq!(rows.len(), 1, "exactly one /help row must exist");
2052 assert!(
2053 rows[0].description.contains("My private help"),
2054 "row must carry the user command metadata: {}",
2055 rows[0].description
2056 );
2057 assert!(
2058 rows[0].description.contains("/help <topic>"),
2059 "row must carry the user command usage: {}",
2060 rows[0].description
2061 );
2062 assert!(
2063 matches!(&rows[0].action, CommandPaletteAction::InsertText { text } if text == "/help "),
2064 "row must carry the user command action"
2065 );
2066 }
2067
2068 #[test]
2069 fn command_palette_accepted_alias_suppresses_builtin_canonical_row() {
2070 // A visible user command whose accepted alias equals a built-in
2071 // canonical token must suppress the built-in row in the palette,
2072 // matching the shared alias-aware contract.
2073 let tmp = TempDir::new().expect("tempdir");
2074 let workspace = tmp.path().join("workspace");
2075 crate::test_support::trust_workspace(&workspace);
2076 let commands_dir = workspace.join(".codewhale").join("commands");
2077 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
2078 std::fs::write(
2079 commands_dir.join("assistant.md"),
2080 "---\ndescription: My assistant\nalias: help\n---\nassistant",
2081 )
2082 .expect("write user command");
2083
2084 let entries = build_entries(
2085 Locale::En,
2086 tmp.path().join("skills").as_path(),
2087 &Default::default(),
2088 workspace.as_path(),
2089 tmp.path().join("mcp.json").as_path(),
2090 None,
2091 );
2092
2093 assert!(
2094 !entries
2095 .iter()
2096 .any(|entry| entry.section == PaletteSection::Command && entry.label == "/help"),
2097 "built-in canonical row must be suppressed when a user alias claims /help"
2098 );
2099 assert!(
2100 entries.iter().any(
2101 |entry| entry.section == PaletteSection::Command && entry.label == "/assistant"
2102 ),
2103 "the user command must appear under its own canonical name"
2104 );
2105 }
2106
2107 #[test]
2108 fn command_palette_hidden_canonical_shadow_exposes_no_discovery_row() {
2109 // A hidden user command claiming a built-in canonical token must not
2110 // surface either row: the hidden command is excluded from output while
2111 // still owning the token (AT-008 boundary in the palette).
2112 let tmp = TempDir::new().expect("tempdir");
2113 let workspace = tmp.path().join("workspace");
2114 crate::test_support::trust_workspace(&workspace);
2115 let commands_dir = workspace.join(".codewhale").join("commands");
2116 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
2117 std::fs::write(
2118 commands_dir.join("private-help.md"),
2119 "---\nname: help\nhidden: true\n---\nprivate help",
2120 )
2121 .expect("write hidden user command");
2122
2123 let entries = build_entries(
2124 Locale::En,
2125 tmp.path().join("skills").as_path(),
2126 &Default::default(),
2127 workspace.as_path(),
2128 tmp.path().join("mcp.json").as_path(),
2129 None,
2130 );
2131
2132 assert!(
2133 !entries
2134 .iter()
2135 .any(|entry| entry.section == PaletteSection::Command && entry.label == "/help"),
2136 "neither the hidden user command nor the shadowed built-in may appear"
2137 );
2138 }
2139
2140 #[test]
2141 fn command_palette_alias_shadow_preserves_canonical_row_without_claimed_alias() {
2142 // A user command claiming only one built-in alias must leave the
2143 // built-in canonical row visible and remove only the claimed alias
2144 // from its description.
2145 let tmp = TempDir::new().expect("tempdir");
2146 let workspace = tmp.path().join("workspace");
2147 crate::test_support::trust_workspace(&workspace);
2148 let commands_dir = workspace.join(".codewhale").join("commands");
2149 std::fs::create_dir_all(&commands_dir).expect("create commands dir");
2150 std::fs::write(
2151 commands_dir.join("image-review.md"),
2152 "---\ndescription: Review an image\nalias: image\n---\nreview image",
2153 )
2154 .expect("write user command");
2155
2156 let entries = build_entries(
2157 Locale::En,
2158 tmp.path().join("skills").as_path(),
2159 &Default::default(),
2160 workspace.as_path(),
2161 tmp.path().join("mcp.json").as_path(),
2162 None,
2163 );
2164 let attach_rows = entries
2165 .iter()
2166 .filter(|entry| entry.section == PaletteSection::Command && entry.label == "/attach")
2167 .collect::<Vec<_>>();
2168
2169 assert_eq!(
2170 attach_rows.len(),
2171 1,
2172 "built-in canonical row must appear once"
2173 );
2174 assert!(
2175 !attach_rows[0].description.contains("aliases: image")
2176 && !attach_rows[0].description.contains(", image")
2177 && !attach_rows[0].description.contains("image,"),
2178 "claimed /image alias must be absent from /attach description: {}",
2179 attach_rows[0].description
2180 );
2181 }
2182
2183 #[test]
2184 fn command_palette_has_one_entry_for_every_registered_command() {
2185 let tmp = TempDir::new().expect("tempdir");
2186 let skills_dir = tmp.path().join("skills");
2187 let mcp_config_path = tmp.path().join("mcp.json");
2188 let entries = build_entries(
2189 Locale::En,
2190 skills_dir.as_path(),
2191 &Default::default(),
2192 tmp.path(),
2193 mcp_config_path.as_path(),
2194 None,
2195 );
2196
2197 let command_entries = entries
2198 .iter()
2199 .filter(|entry| entry.section == PaletteSection::Command)
2200 .collect::<Vec<_>>();
2201 let user_registry = commands::user_registry::registry_for_workspace(Some(tmp.path()));
2202 let visible_user_commands = user_registry
2203 .iter()
2204 .filter(|command| !command.hidden)
2205 .count();
2206 let shadowed_builtins = commands::command_infos()
2207 .iter()
2208 .filter(|command| user_registry.get(command.name).is_some())
2209 .count();
2210 // Unlisted commands run when typed but are never advertised — see
2211 // `commands::traits::UNLISTED_COMMANDS`.
2212 let unlisted = commands::command_infos()
2213 .iter()
2214 .filter(|command| command.is_unlisted() && user_registry.get(command.name).is_none())
2215 .count();
2216 assert_eq!(
2217 command_entries.len(),
2218 commands::command_infos().len() - shadowed_builtins - unlisted + visible_user_commands
2219 );
2220
2221 for command in commands::command_infos() {
2222 if user_registry.get(command.name).is_some() || command.is_unlisted() {
2223 continue;
2224 }
2225 let label = format!("/{}", command.name);
2226 let matching = command_entries
2227 .iter()
2228 .filter(|entry| entry.label == label)
2229 .collect::<Vec<_>>();
2230 assert_eq!(
2231 matching.len(),
2232 1,
2233 "expected one palette entry for /{}",
2234 command.name
2235 );
2236
2237 let entry = matching[0];
2238 assert_eq!(entry.command, command.palette_command());
2239 assert!(
2240 entry
2241 .description
2242 .contains(&*command.description_for(Locale::En)),
2243 "/{} palette description should include command help text",
2244 command.name
2245 );
2246 if command.requires_argument() {
2247 assert!(
2248 entry.description.contains(command.usage),
2249 "/{} palette description should include usage {:?}",
2250 command.name,
2251 command.usage
2252 );
2253 }
2254 }
2255 }
2256
2257 #[test]
2258 fn command_palette_hides_toolbox_commands_until_searched() {
2259 let entries = build_entries(
2260 Locale::En,
2261 Path::new("."),
2262 &Default::default(),
2263 Path::new("."),
2264 Path::new("mcp.json"),
2265 None,
2266 );
2267 let mut view = CommandPaletteView::new(entries);
2268 let root_labels = view
2269 .filtered
2270 .iter()
2271 .map(|idx| view.entries[*idx].label.as_str())
2272 .collect::<Vec<_>>();
2273
2274 assert!(root_labels.contains(&"/provider"));
2275 assert!(root_labels.contains(&"/model"));
2276 assert!(root_labels.contains(&"/fleet"));
2277 assert!(!root_labels.contains(&"/pod"));
2278 assert!(root_labels.contains(&"/config"));
2279 assert!(root_labels.contains(&"/statusline"));
2280 assert!(!root_labels.contains(&"/rlm"));
2281 assert!(!root_labels.contains(&"/modeldb"));
2282 assert!(!root_labels.contains(&"/models"));
2283 assert!(root_labels.contains(&"/subagents"));
2284
2285 view.query = "rlm".to_string();
2286 view.refilter();
2287 assert!(
2288 view.filtered
2289 .iter()
2290 .any(|idx| view.entries[*idx].label == "/rlm"),
2291 "advanced /rlm should still be searchable"
2292 );
2293 }
2294
2295 #[test]
2296 fn command_palette_runs_model_command_to_open_picker() {
2297 let entries = build_entries(
2298 Locale::En,
2299 Path::new("."),
2300 &Default::default(),
2301 Path::new("."),
2302 Path::new("mcp.json"),
2303 None,
2304 );
2305 let model = entries
2306 .iter()
2307 .find(|entry| entry.section == PaletteSection::Command && entry.label == "/model")
2308 .expect("model command entry");
2309
2310 assert_eq!(model.command, "/model ");
2311 assert!(matches!(
2312 &model.action,
2313 CommandPaletteAction::ExecuteCommand { command } if command == "/model"
2314 ));
2315 }
2316
2317 #[test]
2318 fn command_palette_runs_change_without_requiring_version() {
2319 let entries = build_entries(
2320 Locale::En,
2321 Path::new("."),
2322 &Default::default(),
2323 Path::new("."),
2324 Path::new("mcp.json"),
2325 None,
2326 );
2327 let change = entries
2328 .iter()
2329 .find(|entry| entry.section == PaletteSection::Command && entry.label == "/change")
2330 .expect("change command entry");
2331
2332 assert!(matches!(
2333 &change.action,
2334 CommandPaletteAction::ExecuteCommand { command } if command == "/change"
2335 ));
2336 }
2337
2338 #[test]
2339 fn palette_paste_only_names_are_registered_canonical_commands() {
2340 let registered: std::collections::HashSet<&str> = commands::command_infos()
2341 .iter()
2342 .map(|info| info.name)
2343 .collect();
2344 for name in commands::traits::PALETTE_PASTE_ONLY {
2345 assert!(
2346 registered.contains(name),
2347 "PALETTE_PASTE_ONLY entry `{name}` is not a registered command"
2348 );
2349 }
2350 }
2351
2352 #[test]
2353 fn command_palette_direct_execute_follows_command_metadata() {
2354 let tmp = TempDir::new().expect("tempdir");
2355 let skills_dir = tmp.path().join("skills");
2356 let mcp_config_path = tmp.path().join("mcp.json");
2357 let entries = build_entries(
2358 Locale::En,
2359 skills_dir.as_path(),
2360 &Default::default(),
2361 tmp.path(),
2362 mcp_config_path.as_path(),
2363 None,
2364 );
2365 let user_registry = commands::user_registry::registry_for_workspace(Some(tmp.path()));
2366
2367 for command in commands::command_infos() {
2368 if user_registry.get(command.name).is_some() || command.is_unlisted() {
2369 continue;
2370 }
2371 let label = format!("/{}", command.name);
2372 let entry = entries
2373 .iter()
2374 .find(|entry| entry.section == PaletteSection::Command && entry.label == label)
2375 .unwrap_or_else(|| panic!("missing palette entry for {label}"));
2376
2377 if command.palette_runs_directly() {
2378 assert!(
2379 matches!(
2380 &entry.action,
2381 CommandPaletteAction::ExecuteCommand { command: c }
2382 if c == &format!("/{}", command.name)
2383 ),
2384 "/{} should execute directly from the palette (no required arg)",
2385 command.name
2386 );
2387 } else {
2388 assert!(
2389 matches!(
2390 &entry.action,
2391 CommandPaletteAction::InsertText { text }
2392 if text == &command.palette_command()
2393 ),
2394 "/{} should paste for required arguments (usage: {})",
2395 command.name,
2396 command.usage
2397 );
2398 }
2399 }
2400
2401 // Drift traps from #3911: no-arg rows must not silently paste, and
2402 // dead mode-arg names must never reappear as palette allowlist entries.
2403 for no_arg in [
2404 "cost",
2405 "diff",
2406 "edit",
2407 "purge",
2408 "setup",
2409 "hotbar",
2410 "translate",
2411 ] {
2412 let label = format!("/{no_arg}");
2413 let entry = entries
2414 .iter()
2415 .find(|entry| entry.section == PaletteSection::Command && entry.label == label)
2416 .unwrap_or_else(|| panic!("missing palette entry for {label}"));
2417 assert!(
2418 matches!(&entry.action, CommandPaletteAction::ExecuteCommand { .. }),
2419 "/{no_arg} is no-arg and must run directly"
2420 );
2421 }
2422 for required in ["rename", "attach", "profile", "review"] {
2423 let label = format!("/{required}");
2424 let entry = entries
2425 .iter()
2426 .find(|entry| entry.section == PaletteSection::Command && entry.label == label)
2427 .unwrap_or_else(|| panic!("missing palette entry for {label}"));
2428 assert!(
2429 matches!(&entry.action, CommandPaletteAction::InsertText { .. }),
2430 "/{required} requires an argument and must paste"
2431 );
2432 }
2433 }
2434
2435 #[test]
2436 fn command_palette_includes_mcp_discovery_and_failed_servers() {
2437 let snapshot = codewhale_engine::mcp::McpManagerSnapshot {
2438 config_path: Path::new("mcp.json").to_path_buf(),
2439 config_exists: true,
2440 reload_required: false,
2441 servers: vec![
2442 codewhale_engine::mcp::McpServerSnapshot {
2443 name: "fs".to_string(),
2444 enabled: true,
2445 required: false,
2446 transport: "stdio".to_string(),
2447 command_or_url: "node server.js".to_string(),
2448 connect_timeout: 10,
2449 execute_timeout: 60,
2450 read_timeout: 120,
2451 connected: true,
2452 error: None,
2453 auth_required: false,
2454 capability_metadata:
2455 codewhale_engine::mcp::McpServerCapabilityMetadata::LegacyFallback,
2456 tools: vec![codewhale_engine::mcp::McpDiscoveredItem {
2457 name: "read".to_string(),
2458 model_name: "mcp_fs_read".to_string(),
2459 description: Some("Read files".to_string()),
2460 }],
2461 resources: Vec::new(),
2462 prompts: Vec::new(),
2463 },
2464 codewhale_engine::mcp::McpServerSnapshot {
2465 name: "broken".to_string(),
2466 enabled: true,
2467 required: false,
2468 transport: "http/sse".to_string(),
2469 command_or_url: "https://example.invalid/mcp".to_string(),
2470 connect_timeout: 10,
2471 execute_timeout: 60,
2472 read_timeout: 120,
2473 connected: false,
2474 error: Some("connect failed".to_string()),
2475 auth_required: false,
2476 capability_metadata:
2477 codewhale_engine::mcp::McpServerCapabilityMetadata::NotObserved,
2478 tools: Vec::new(),
2479 resources: Vec::new(),
2480 prompts: Vec::new(),
2481 },
2482 ],
2483 };
2484 let entries = build_entries(
2485 Locale::En,
2486 Path::new("."),
2487 &Default::default(),
2488 Path::new("."),
2489 Path::new("mcp.json"),
2490 Some(&snapshot),
2491 );
2492
2493 assert!(entries.iter().any(|entry| entry.label == "mcp:manager"));
2494 assert!(entries.iter().any(|entry| entry.command == "mcp_fs_read"));
2495 let failed = entries
2496 .iter()
2497 .find(|entry| entry.label == "mcp:broken")
2498 .expect("failed server visible");
2499 assert!(failed.description.contains("failed"));
2500
2501 // Verify the "use" insert entry for MCP tools
2502 let use_entry = entries
2503 .iter()
2504 .find(|entry| entry.label == "mcp:fs:tool:read > use")
2505 .expect("MCP tool use entry should exist");
2506 assert!(matches!(
2507 &use_entry.action,
2508 CommandPaletteAction::InsertText { text } if text == "mcp_fs_read"
2509 ));
2510 assert_eq!(use_entry.command, "mcp_fs_read");
2511 }
2512
2513 #[test]
2514 fn command_palette_marks_disabled_servers_visibly() {
2515 // The healthy/failed cases are covered above; disabled was the
2516 // remaining gap from #197's acceptance list. Disabled servers must
2517 // appear in the palette with a `[disabled]` state tag so users can
2518 // see them without opening the MCP manager.
2519 let snapshot = codewhale_engine::mcp::McpManagerSnapshot {
2520 config_path: Path::new("mcp.json").to_path_buf(),
2521 config_exists: true,
2522 reload_required: false,
2523 servers: vec![codewhale_engine::mcp::McpServerSnapshot {
2524 name: "muted".to_string(),
2525 enabled: false,
2526 required: false,
2527 transport: "stdio".to_string(),
2528 command_or_url: "node disabled.js".to_string(),
2529 connect_timeout: 10,
2530 execute_timeout: 60,
2531 read_timeout: 120,
2532 connected: false,
2533 error: None,
2534 auth_required: false,
2535 capability_metadata:
2536 codewhale_engine::mcp::McpServerCapabilityMetadata::NotObserved,
2537 tools: Vec::new(),
2538 resources: Vec::new(),
2539 prompts: Vec::new(),
2540 }],
2541 };
2542 let entries = build_entries(
2543 Locale::En,
2544 Path::new("."),
2545 &Default::default(),
2546 Path::new("."),
2547 Path::new("mcp.json"),
2548 Some(&snapshot),
2549 );
2550
2551 let muted = entries
2552 .iter()
2553 .find(|entry| entry.label == "mcp:muted")
2554 .expect("disabled server should still appear in the palette");
2555 assert!(
2556 muted.description.contains("[disabled]"),
2557 "expected `[disabled]` state tag in description, got: {}",
2558 muted.description
2559 );
2560 }
2561
2562 #[test]
2563 fn command_palette_emits_actions_not_raw_insertions() {
2564 let entries = vec![CommandPaletteEntry {
2565 section: PaletteSection::Command,
2566 label: "/config".to_string(),
2567 description: "open config".to_string(),
2568 command: "/config".to_string(),
2569 action: CommandPaletteAction::ExecuteCommand {
2570 command: "/config".to_string(),
2571 },
2572 show_on_empty_query: true,
2573 external_agent: None,
2574 priority: 1,
2575 }];
2576 let mut view = CommandPaletteView::new(entries);
2577
2578 let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()));
2579 assert!(matches!(
2580 action,
2581 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
2582 action: CommandPaletteAction::ExecuteCommand { .. }
2583 })
2584 ));
2585 }
2586
2587 #[test]
2588 fn command_palette_mouse_runs_the_same_skill_action_as_enter() {
2589 let entries = vec![
2590 palette_entry(PaletteSection::Command, "/config", "open config", "/config"),
2591 CommandPaletteEntry {
2592 section: PaletteSection::Skill,
2593 label: "$plugin:review".to_string(),
2594 description: "review from an enabled plugin".to_string(),
2595 command: "$plugin:review".to_string(),
2596 action: CommandPaletteAction::ExecuteCommand {
2597 command: "$plugin:review".to_string(),
2598 },
2599 show_on_empty_query: true,
2600 external_agent: None,
2601 priority: 1,
2602 },
2603 ];
2604 let mut keyboard = CommandPaletteView::new(entries.clone());
2605 keyboard.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::empty()));
2606 let keyboard_action =
2607 keyboard.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()));
2608
2609 let mut mouse = CommandPaletteView::new(entries);
2610 let area = Rect::new(0, 0, 100, 30);
2611 let mut buf = Buffer::empty(area);
2612 mouse.render(area, &mut buf);
2613 let (rect, _) = mouse
2614 .row_hitboxes
2615 .borrow()
2616 .iter()
2617 .find(|(_, index)| *index == 1)
2618 .copied()
2619 .expect("plugin Skill row should have a mouse hitbox");
2620 let click = MouseEvent {
2621 kind: MouseEventKind::Down(MouseButton::Left),
2622 column: rect.x,
2623 row: rect.y,
2624 modifiers: KeyModifiers::empty(),
2625 };
2626 assert!(matches!(mouse.handle_mouse(click), ViewAction::None));
2627 let mouse_action = mouse.handle_mouse(click);
2628
2629 for action in [keyboard_action, mouse_action] {
2630 assert!(matches!(
2631 action,
2632 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
2633 action: CommandPaletteAction::ExecuteCommand { command }
2634 }) if command == "$plugin:review"
2635 ));
2636 }
2637 }
2638
2639 #[test]
2640 fn zh_hans_palette_localizes_aliases_and_the_entry_count() {
2641 let attach = commands::command_infos()
2642 .into_iter()
2643 .find(|info| info.name == "attach")
2644 .expect("/attach");
2645 assert!(
2646 attach
2647 .palette_description_for(Locale::En)
2648 .ends_with(" aliases: image, media, fujian")
2649 );
2650 assert!(
2651 attach
2652 .palette_description_for(Locale::ZhHans)
2653 .ends_with(" 别名:image、media、fujian")
2654 );
2655
2656 let view = CommandPaletteView::new_for_locale(
2657 Locale::ZhHans,
2658 vec![palette_entry(
2659 PaletteSection::Command,
2660 "/config",
2661 "open config",
2662 "/config",
2663 )],
2664 );
2665 let area = Rect::new(0, 0, 100, 30);
2666 let mut buf = Buffer::empty(area);
2667 view.render(area, &mut buf);
2668 let dump: String = buf
2669 .content()
2670 .iter()
2671 .map(|cell| cell.symbol())
2672 .filter(|symbol| *symbol != " ")
2673 .collect();
2674 assert!(dump.contains("显示1个/共1个条目"), "{dump}");
2675 }
2676
2677 #[test]
2678 fn command_palette_hover_tints_entry_without_moving_selection() {
2679 let mut view = sample_palette_view();
2680 let area = Rect::new(0, 0, 100, 30);
2681 let mut buf = Buffer::empty(area);
2682 view.render(area, &mut buf);
2683 assert_eq!(view.selected, 0);
2684 let (rect, _) = view
2685 .row_hitboxes
2686 .borrow()
2687 .iter()
2688 .find(|(_, index)| *index == 1)
2689 .copied()
2690 .expect("second entry should have a mouse hitbox");
2691 let hover = MouseEvent {
2692 kind: MouseEventKind::Moved,
2693 column: rect.x,
2694 row: rect.y,
2695 modifiers: KeyModifiers::empty(),
2696 };
2697 assert!(matches!(view.handle_mouse(hover), ViewAction::None));
2698 assert_eq!(view.hovered.get(), Some(1));
2699 assert_eq!(view.selected, 0);
2700
2701 let mut hovered_buf = Buffer::empty(area);
2702 view.render(area, &mut hovered_buf);
2703 assert_eq!(
2704 hovered_buf[(rect.x, rect.y)].bg,
2705 codewhale_palette::SURFACE_ELEVATED,
2706 "hovered palette entry must show the shared hover band"
2707 );
2708 }
2709
2710 #[test]
2711 fn command_palette_description_column_pads_by_display_width() {
2712 let view = CommandPaletteView::new(vec![
2713 palette_entry(PaletteSection::Command, "/plain", "DESC_A", "/plain"),
2714 palette_entry(PaletteSection::Command, "/中文命令", "DESC_B", "/zh"),
2715 ]);
2716 let area = Rect::new(0, 0, 100, 30);
2717 let mut buf = Buffer::empty(area);
2718 view.render(area, &mut buf);
2719
2720 let column_of = |needle: &str| {
2721 (0..area.height).find_map(|y| {
2722 let row: String = (0..area.width)
2723 .map(|x| match buf[(x, y)].symbol() {
2724 "" => " ",
2725 symbol => symbol,
2726 })
2727 .collect();
2728 row.find(needle).map(|byte| row[..byte].chars().count())
2729 })
2730 };
2731 let plain = column_of("DESC_A").expect("plain row renders");
2732 let wide = column_of("DESC_B").expect("wide row renders");
2733 assert_eq!(plain, wide, "description columns must line up");
2734 }
2735
2736 /// The four terminal sizes the v0.8.66 modal blocker (#3732) requires every
2737 /// overlay to remain readable and fully operable at.
2738 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
2739
2740 fn sample_palette_view() -> CommandPaletteView {
2741 let entries = vec![
2742 palette_entry(PaletteSection::Command, "/config", "open config", "/config"),
2743 palette_entry(PaletteSection::Command, "/model", "choose model", "/model"),
2744 palette_entry(PaletteSection::Skill, "$search", "search skill", "$search"),
2745 palette_entry(PaletteSection::Tool, "tool:git", "git tool", "git"),
2746 palette_entry(PaletteSection::Mcp, "mcp:fs", "filesystem", "mcp_fs_read"),
2747 ];
2748 CommandPaletteView::new(entries)
2749 }
2750
2751 #[test]
2752 fn command_palette_is_usable_and_opaque_at_blocker_sizes() {
2753 use crate::tui::views::ViewStack;
2754 for (w, h) in BLOCKER_SIZES {
2755 let area = Rect::new(0, 0, w, h);
2756 let mut buf = Buffer::empty(area);
2757 for y in 0..h {
2758 for x in 0..w {
2759 buf[(x, y)].set_symbol("X");
2760 }
2761 }
2762 let mut stack = ViewStack::new();
2763 stack.push(sample_palette_view());
2764 stack.render(area, &mut buf);
2765
2766 let rows: Vec<String> = (0..h)
2767 .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
2768 .collect();
2769 let text = rows.join("\n");
2770
2771 // Footer keeps every action.
2772 assert!(text.contains("move"), "{w}x{h}: missing 'move' hint");
2773 assert!(text.contains("select"), "{w}x{h}: missing 'select' hint");
2774 assert!(text.contains("cancel"), "{w}x{h}: missing 'cancel' hint");
2775
2776 // The selected row carries the charter pointer glyph.
2777 assert!(
2778 text.contains(codewhale_tui_kit::glyphs::SELECTION),
2779 "{w}x{h}: selected row missing charter pointer"
2780 );
2781
2782 // Header stays compact: scope help is a single line, with no
2783 // multi-line "Try:" example block crowding out entries.
2784 assert!(text.contains("Type to filter"), "{w}x{h}: missing prompt");
2785 assert!(
2786 !text.contains("Try:"),
2787 "{w}x{h}: scope example block should stay collapsed"
2788 );
2789
2790 // Composited frame is fully opaque.
2791 assert!(!text.contains('X'), "{w}x{h}: background bleed-through");
2792 assert_eq!(
2793 buf[(w / 2, h / 2)].bg,
2794 palette::WHALE_BG,
2795 "{w}x{h}: modal interior must be opaque"
2796 );
2797
2798 // No horizontal overflow.
2799 for (y, row) in rows.iter().enumerate() {
2800 assert!(
2801 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
2802 "{w}x{h}: row {y} overflows width: {row:?}"
2803 );
2804 }
2805 }
2806 }
2807
2808 #[test]
2809 fn command_palette_selected_row_uses_shared_selection_style_at_blocker_sizes() {
2810 use crate::tui::views::ViewStack;
2811 for (w, h) in BLOCKER_SIZES {
2812 let area = Rect::new(0, 0, w, h);
2813 let mut buf = Buffer::empty(area);
2814 let mut stack = ViewStack::new();
2815 stack.push(sample_palette_view());
2816 stack.render(area, &mut buf);
2817
2818 // The first entry ("/config") is selected by default; find its row.
2819 let selected_y = (0..h)
2820 .find(|&y| {
2821 let row: String = (0..w).map(|x| buf[(x, y)].symbol()).collect();
2822 row.contains("/config")
2823 })
2824 .unwrap_or_else(|| panic!("{w}x{h}: selected entry should render"));
2825 let selected_cells = (0..w)
2826 .filter(|&x| {
2827 let cell = &buf[(x, selected_y)];
2828 !cell.symbol().trim().is_empty()
2829 && cell.bg == palette::SELECTION_BG
2830 && cell.fg == palette::SELECTION_TEXT
2831 })
2832 .count();
2833 assert!(
2834 selected_cells >= "/config".len(),
2835 "{w}x{h}: selected row must render with the shared selection style \
2836 (palette::SELECTION_TEXT on palette::SELECTION_BG)"
2837 );
2838 }
2839 }
2840
2841 #[test]
2842 fn command_palette_external_agents_surface_for_queries_and_emit_external_agent_selected() {
2843 use codewhale_app_server::runtime_api::ExternalAgentDiscoveryRow;
2844 let row = |id: &str, name: &str, runnable: bool| ExternalAgentDiscoveryRow {
2845 id: id.to_string(),
2846 name: name.to_string(),
2847 state: if runnable {
2848 "installed".to_string()
2849 } else {
2850 "not_installed".to_string()
2851 },
2852 version: runnable.then(|| "1.0.0".to_string()),
2853 acp: runnable.then(|| "native".to_string()),
2854 transport: runnable.then(|| "acp".to_string()),
2855 transports: if runnable {
2856 vec!["acp".to_string()]
2857 } else {
2858 Vec::new()
2859 },
2860 website: String::new(),
2861 min_version: None,
2862 upgrade: None,
2863 login: None,
2864 adapter: None,
2865 adapter_installed: false,
2866 needs_update: false,
2867 runnable,
2868 custom: false,
2869 reason_code: None,
2870 reason: None,
2871 };
2872
2873 let mut entries = vec![palette_entry(
2874 PaletteSection::Command,
2875 "/model",
2876 "choose model",
2877 "/model",
2878 )];
2879 entries.extend(build_external_agent_entries(&[
2880 row("codex", "Codex", true),
2881 row("claude", "Claude Agent", true),
2882 row("gemini", "Gemini CLI", true),
2883 row("offline", "Offline Agent", false),
2884 ]));
2885 assert!(
2886 !entries.iter().any(|e| e.label == "agent:offline"),
2887 "non-runnable external agents must be excluded"
2888 );
2889
2890 let mut view = CommandPaletteView::new(entries);
2891 for (query, expected_id) in [
2892 ("codex", "codex"),
2893 ("claude", "claude"),
2894 ("gemini", "gemini"),
2895 ] {
2896 view.query = query.to_string();
2897 view.refilter();
2898 assert_eq!(
2899 view.selected_entry().map(|e| e.label.as_str()),
2900 Some(format!("agent:{expected_id}").as_str()),
2901 "query {query:?} should surface agent:{expected_id}"
2902 );
2903 }
2904
2905 view.query = "agent".to_string();
2906 view.refilter();
2907 let matched_labels: Vec<&str> = view
2908 .filtered
2909 .iter()
2910 .map(|idx| view.entries[*idx].label.as_str())
2911 .collect();
2912 for expected in ["agent:claude", "agent:codex", "agent:gemini"] {
2913 assert!(
2914 matched_labels.contains(&expected),
2915 "query \"agent\" should surface {expected}: {matched_labels:?}"
2916 );
2917 }
2918
2919 view.query = "codex".to_string();
2920 view.refilter();
2921 let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2922 assert!(matches!(
2923 action,
2924 ViewAction::EmitAndClose(ViewEvent::ExternalAgentSelected {
2925 agent_id,
2926 agent_name,
2927 }) if agent_id == "codex" && agent_name == "Codex"
2928 ));
2929 }
2930
2931 #[test]
2932 fn command_palette_prioritizes_active_attention_and_recovery_entries() {
2933 let snapshot = codewhale_engine::mcp::McpManagerSnapshot {
2934 config_path: Path::new("mcp.json").to_path_buf(),
2935 config_exists: true,
2936 reload_required: false,
2937 servers: vec![codewhale_engine::mcp::McpServerSnapshot {
2938 name: "broken".to_string(),
2939 enabled: true,
2940 required: false,
2941 transport: "http/sse".to_string(),
2942 command_or_url: "https://example.invalid/mcp".to_string(),
2943 connect_timeout: 10,
2944 execute_timeout: 60,
2945 read_timeout: 120,
2946 connected: false,
2947 error: Some("connect failed".to_string()),
2948 auth_required: false,
2949 capability_metadata:
2950 codewhale_engine::mcp::McpServerCapabilityMetadata::NotObserved,
2951 tools: Vec::new(),
2952 resources: Vec::new(),
2953 prompts: Vec::new(),
2954 }],
2955 };
2956
2957 let entries = build_entries(
2958 Locale::En,
2959 Path::new("."),
2960 &Default::default(),
2961 Path::new("."),
2962 Path::new("mcp.json"),
2963 Some(&snapshot),
2964 );
2965 let mut view = CommandPaletteView::new(entries);
2966 assert_eq!(
2967 view.selected_entry().map(|e| e.label.as_str()),
2968 Some("recover:mcp:broken"),
2969 "active recovery entry must sort to the top on empty query"
2970 );
2971
2972 view.query = "broken".to_string();
2973 view.refilter();
2974 assert_eq!(
2975 view.selected_entry().map(|e| e.label.as_str()),
2976 Some("recover:mcp:broken")
2977 );
2978 let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
2979 assert!(matches!(
2980 action,
2981 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
2982 action: CommandPaletteAction::ExecuteCommand { command }
2983 }) if command == "/mcp retry broken"
2984 ));
2985 }
2986 }
2987
2987 lines RUST