返回 CodeWhale
tui_help.rs
根目录 / crates / engine / src / tools / tui_help.rs
1 //! On-demand command and keybinding reference: `tui_help`.
2 //!
3 //! Every field is read back out of the registries the human-facing help
4 //! renders from — `command_catalog::CommandCatalog`, the user-command registry, and
5 //! `keybinding_table::KEYBINDINGS` — so the model-facing reference cannot
6 //! drift from `/help` and the help overlay.
7
8 use std::path::Path;
9
10 use async_trait::async_trait;
11 use serde::{Deserialize, Serialize};
12 use serde_json::{Value, json};
13
14 use crate::command_catalog::{BuiltinCommand, CommandCatalog};
15 use crate::keybinding_table::KEYBINDINGS;
16 use codewhale_localization::{Locale, tr};
17
18 use super::spec::{
19 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
20 };
21
22 /// Per-section cap. The command catalog is well over a hundred entries; an
23 /// unscoped dump would cost more context than any answer it contains.
24 const MAX_COMMANDS: usize = 12;
25 const MAX_KEYBINDINGS: usize = 12;
26
27 /// Tool for looking up slash commands and keybindings.
28 pub struct TuiHelpTool;
29
30 #[derive(Debug, Clone, Serialize, Deserialize)]
31 struct CommandEntry {
32 command: String,
33 /// Omitted when the usage string carries nothing beyond the command name.
34 #[serde(default, skip_serializing_if = "Option::is_none")]
35 usage: Option<String>,
36 description: String,
37 #[serde(default, skip_serializing_if = "Vec::is_empty")]
38 aliases: Vec<String>,
39 source: String,
40 }
41
42 #[derive(Debug, Clone, Serialize, Deserialize)]
43 struct KeybindingEntry {
44 chord: String,
45 description: String,
46 section: String,
47 }
48
49 #[derive(Debug, Clone, Serialize, Deserialize)]
50 struct HelpOutput {
51 #[serde(default, skip_serializing_if = "Option::is_none")]
52 query: Option<String>,
53 commands: Vec<CommandEntry>,
54 keybindings: Vec<KeybindingEntry>,
55 /// Matches dropped by the cap, so the model narrows the query instead of
56 /// assuming it saw everything.
57 #[serde(default, skip_serializing_if = "is_zero")]
58 omitted_commands: usize,
59 #[serde(default, skip_serializing_if = "is_zero")]
60 omitted_keybindings: usize,
61 note: String,
62 }
63
64 fn is_zero(value: &usize) -> bool {
65 *value == 0
66 }
67
68 #[async_trait]
69 impl ToolSpec for TuiHelpTool {
70 fn name(&self) -> &'static str {
71 "tui_help"
72 }
73
74 fn description(&self) -> &'static str {
75 "Look up Codewhale slash commands and keyboard shortcuts. Pass a query to scope the answer; omit it for a compact cheatsheet."
76 }
77
78 fn input_schema(&self) -> Value {
79 json!({
80 "type": "object",
81 "properties": {
82 "query": {
83 "type": "string",
84 "description": "Topic, command name, or keyword to scope the answer (for example \"mode\", \"compact\", \"Ctrl+R\"). Omit for a compact cheatsheet."
85 }
86 },
87 "required": [],
88 "additionalProperties": false
89 })
90 }
91
92 fn capabilities(&self) -> Vec<ToolCapability> {
93 vec![ToolCapability::ReadOnly]
94 }
95
96 fn approval_requirement(&self) -> ApprovalRequirement {
97 ApprovalRequirement::Auto
98 }
99
100 fn supports_parallel(&self) -> bool {
101 true
102 }
103
104 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
105 let query = match input.get("query") {
106 None | Some(Value::Null) => None,
107 Some(Value::String(query)) => Some(query.clone()),
108 Some(_) => return Err(ToolError::invalid_input("`query` must be a string")),
109 };
110
111 let catalog = crate::command_catalog::installed()
112 .ok_or_else(|| ToolError::execution_failed("command catalog is not installed"))?;
113 let workspace = context.workspace.clone();
114 #[cfg(any(test, feature = "test-support"))]
115 let env_ticket = crate::test_support::env_scope_ticket();
116 let help = tokio::task::spawn_blocking(move || {
117 #[cfg(any(test, feature = "test-support"))]
118 let _membership = crate::test_support::join_env_scope(env_ticket);
119 build_help(catalog.as_ref(), ui_locale(), &workspace, query.as_deref())
120 })
121 .await
122 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
123 ToolResult::json(&help).map_err(|e| ToolError::execution_failed(e.to_string()))
124 }
125 }
126
127 // === Helpers ===
128
129 /// The reference is rendered from the same localized strings the overlay uses,
130 /// so it follows the configured UI locale rather than the model's language.
131 /// `load_read_only` keeps the lookup free of the legacy-settings migration
132 /// write that `Settings::load` performs.
133 fn ui_locale() -> Locale {
134 codewhale_localization::resolve_locale(
135 &codewhale_runtime::settings::Settings::load_read_only()
136 .unwrap_or_default()
137 .locale,
138 )
139 }
140
141 fn build_help(
142 catalog: &dyn CommandCatalog,
143 locale: Locale,
144 workspace: &Path,
145 query: Option<&str>,
146 ) -> HelpOutput {
147 let Some(query) = query.map(str::trim).filter(|query| !query.is_empty()) else {
148 return cheatsheet(catalog, locale, workspace);
149 };
150 let needle = query.to_lowercase();
151
152 let mut commands: Vec<(u8, CommandEntry)> = all_commands(catalog, locale, workspace)
153 .into_iter()
154 .filter_map(|entry| entry.rank(&needle).map(|rank| (rank, entry)))
155 .collect();
156 commands.sort_by_key(|(rank, _)| *rank);
157
158 let mut keybindings: Vec<(u8, KeybindingEntry)> = all_keybindings(locale)
159 .into_iter()
160 .filter_map(|entry| entry.rank(&needle).map(|rank| (rank, entry)))
161 .collect();
162 keybindings.sort_by_key(|(rank, _)| *rank);
163
164 let note = if commands.is_empty() && keybindings.is_empty() {
165 format!(
166 "No command or keybinding matches '{query}'. Call tui_help with no query for the cheatsheet."
167 )
168 } else {
169 format!("Commands and keybindings matching '{query}'.")
170 };
171
172 HelpOutput {
173 query: Some(query.to_string()),
174 omitted_commands: commands.len().saturating_sub(MAX_COMMANDS),
175 omitted_keybindings: keybindings.len().saturating_sub(MAX_KEYBINDINGS),
176 commands: take_entries(commands, MAX_COMMANDS),
177 keybindings: take_entries(keybindings, MAX_KEYBINDINGS),
178 note,
179 }
180 }
181
182 /// Unscoped answer: the commands the help overlay shows at its root, capped
183 /// like every other answer.
184 fn cheatsheet(catalog: &dyn CommandCatalog, locale: Locale, workspace: &Path) -> HelpOutput {
185 // User commands lead: they are workspace-specific and unguessable, where a
186 // built-in is stable enough to be worth querying by name.
187 let mut entries = user_commands(catalog, workspace);
188 entries.extend(
189 catalog
190 .builtins()
191 .into_iter()
192 .filter(|info| info.show_in_empty_discovery)
193 .map(|info| builtin_entry(&info, locale)),
194 );
195 let keybindings = all_keybindings(locale);
196
197 HelpOutput {
198 query: None,
199 omitted_commands: entries.len().saturating_sub(MAX_COMMANDS),
200 omitted_keybindings: keybindings.len().saturating_sub(MAX_KEYBINDINGS),
201 commands: entries.into_iter().take(MAX_COMMANDS).collect(),
202 keybindings: keybindings.into_iter().take(MAX_KEYBINDINGS).collect(),
203 note: "Compact cheatsheet. Pass a query to reach advanced commands and the rest of the keybindings.".to_string(),
204 }
205 }
206
207 fn take_entries<T>(ranked: Vec<(u8, T)>, limit: usize) -> Vec<T> {
208 ranked
209 .into_iter()
210 .take(limit)
211 .map(|(_, entry)| entry)
212 .collect()
213 }
214
215 fn builtin_entry(info: &BuiltinCommand, locale: Locale) -> CommandEntry {
216 let command = format!("/{}", info.name);
217 CommandEntry {
218 usage: Some(info.usage.trim().to_string()).filter(|usage| *usage != command),
219 command,
220 description: tr(locale, info.description_id).into_owned(),
221 aliases: info.aliases.iter().map(|alias| alias.to_string()).collect(),
222 source: "builtin".to_string(),
223 }
224 }
225
226 fn all_commands(
227 catalog: &dyn CommandCatalog,
228 locale: Locale,
229 workspace: &Path,
230 ) -> Vec<CommandEntry> {
231 let mut entries: Vec<CommandEntry> = catalog
232 .builtins()
233 .into_iter()
234 // Unlisted commands still run when typed; help does not teach them.
235 .filter(|info| !info.unlisted)
236 .map(|info| builtin_entry(&info, locale))
237 .collect();
238 entries.extend(user_commands(catalog, workspace));
239 entries
240 }
241
242 /// The user registry is keyed by a hash map, so sort for a stable answer.
243 fn user_commands(catalog: &dyn CommandCatalog, workspace: &Path) -> Vec<CommandEntry> {
244 let mut entries: Vec<CommandEntry> = catalog
245 .user_commands(workspace)
246 .into_iter()
247 .filter(|metadata| !metadata.hidden)
248 .map(|metadata| CommandEntry {
249 command: format!("/{}", metadata.name),
250 usage: metadata.usage,
251 description: metadata.description.unwrap_or_default(),
252 aliases: metadata.aliases,
253 source: "user".to_string(),
254 })
255 .collect();
256 entries.sort_by(|a, b| a.command.cmp(&b.command));
257 entries
258 }
259
260 fn all_keybindings(locale: Locale) -> Vec<KeybindingEntry> {
261 KEYBINDINGS
262 .iter()
263 .map(|binding| KeybindingEntry {
264 chord: binding.chord.to_string(),
265 description: tr(locale, binding.description_id).into_owned(),
266 section: binding.section.label(locale).into_owned(),
267 })
268 .collect()
269 }
270
271 impl CommandEntry {
272 /// Relevance rank, lowest first; `None` when the entry does not match.
273 fn rank(&self, needle: &str) -> Option<u8> {
274 let name = self.command.trim_start_matches('/').to_lowercase();
275 if name == needle
276 || self
277 .aliases
278 .iter()
279 .any(|alias| alias.to_lowercase() == needle)
280 {
281 return Some(0);
282 }
283 if name.starts_with(needle) {
284 return Some(1);
285 }
286 if name.contains(needle) {
287 return Some(2);
288 }
289 if self.description.to_lowercase().contains(needle)
290 || self
291 .usage
292 .as_deref()
293 .is_some_and(|usage| usage.to_lowercase().contains(needle))
294 {
295 return Some(3);
296 }
297 None
298 }
299 }
300
301 impl KeybindingEntry {
302 fn rank(&self, needle: &str) -> Option<u8> {
303 if self.chord.to_lowercase().contains(needle) {
304 return Some(0);
305 }
306 if self.description.to_lowercase().contains(needle)
307 || self.section.to_lowercase().contains(needle)
308 {
309 return Some(1);
310 }
311 None
312 }
313 }
314
315 #[cfg(test)]
316 mod tests {
317 use super::*;
318 use tempfile::tempdir;
319
320 struct Catalog;
321 impl CommandCatalog for Catalog {
322 fn answers_to(&self, _: &str) -> bool {
323 false
324 }
325 fn builtins(&self) -> Vec<BuiltinCommand> {
326 ["mode".to_string(), "compact".to_string()]
327 .into_iter()
328 .chain((0..13).map(|index| format!("edge{index}")))
329 .map(|name| BuiltinCommand {
330 usage: format!("/{name} [value]"),
331 name,
332 aliases: Vec::new(),
333 description_id: codewhale_localization::MessageId::CmdModeDescription,
334 subcommands: Vec::new(),
335 takes_arguments: true,
336 requires_argument: true,
337 requires_required_argument: false,
338 composer_wants_trailing_space: true,
339 palette_runs_directly: false,
340 show_in_empty_discovery: true,
341 discovery: codewhale_command_contract::CommandDiscovery::Primary,
342 unlisted: false,
343 })
344 .collect()
345 }
346 fn user_commands(&self, _: &Path) -> Vec<crate::command_catalog::UserCommand> {
347 Vec::new()
348 }
349 }
350
351 #[test]
352 fn scoped_query_answers_from_the_command_and_keybinding_registries() {
353 let tmp = tempdir().expect("tempdir");
354 let help = build_help(&Catalog, Locale::En, tmp.path(), Some("mode"));
355
356 let mode = help
357 .commands
358 .iter()
359 .find(|entry| entry.command == "/mode")
360 .unwrap_or_else(|| panic!("no /mode in {:?}", help.commands));
361 assert_eq!(mode.usage.as_deref(), Some("/mode [value]"));
362 assert_eq!(
363 mode.description,
364 tr(
365 Locale::En,
366 codewhale_localization::MessageId::CmdModeDescription
367 )
368 );
369
370 assert!(
371 help.keybindings
372 .iter()
373 .all(|entry| KEYBINDINGS.iter().any(|kb| kb.chord == entry.chord)),
374 "chords must come from the keybinding catalog: {:?}",
375 help.keybindings
376 );
377 assert!(
378 !help.keybindings.is_empty(),
379 "the Modes keybinding section should match 'mode'"
380 );
381 }
382
383 #[test]
384 fn exact_command_name_outranks_incidental_mentions() {
385 let tmp = tempdir().expect("tempdir");
386 let help = build_help(&Catalog, Locale::En, tmp.path(), Some("compact"));
387
388 assert_eq!(
389 help.commands.first().map(|entry| entry.command.as_str()),
390 Some("/compact")
391 );
392 }
393
394 #[test]
395 fn unmatched_query_returns_nothing_rather_than_everything() {
396 let tmp = tempdir().expect("tempdir");
397 let help = build_help(&Catalog, Locale::En, tmp.path(), Some("zzzz-no-such-topic"));
398
399 assert!(help.commands.is_empty());
400 assert!(help.keybindings.is_empty());
401 assert!(help.note.starts_with("No command or keybinding matches"));
402 }
403
404 #[test]
405 fn output_stays_bounded_and_reports_what_it_dropped() {
406 let tmp = tempdir().expect("tempdir");
407 // A query every entry matches on the description axis would otherwise
408 // dump the whole catalog.
409 for query in [None, Some("e")] {
410 let help = build_help(&Catalog, Locale::En, tmp.path(), query);
411 assert!(help.commands.len() <= MAX_COMMANDS, "{query:?}");
412 assert!(help.keybindings.len() <= MAX_KEYBINDINGS, "{query:?}");
413 }
414
415 let broad = build_help(&Catalog, Locale::En, tmp.path(), Some("e"));
416 assert!(
417 broad.omitted_commands > 0,
418 "a catalog-wide query must report the dropped matches"
419 );
420 }
421
422 #[test]
423 fn blank_query_falls_back_to_the_cheatsheet() {
424 let tmp = tempdir().expect("tempdir");
425 let help = build_help(&Catalog, Locale::En, tmp.path(), Some(" "));
426
427 assert!(help.query.is_none());
428 assert!(!help.commands.is_empty());
429 }
430
431 #[tokio::test]
432 async fn execute_returns_json_and_rejects_non_string_queries() {
433 let tmp = tempdir().expect("tempdir");
434 let ctx = ToolContext::new(tmp.path());
435 let _catalog = crate::command_catalog::CatalogGuard::install(std::sync::Arc::new(Catalog));
436
437 let result = TuiHelpTool
438 .execute(json!({ "query": "mode" }), &ctx)
439 .await
440 .expect("execute");
441 assert!(result.success);
442 let parsed: HelpOutput =
443 serde_json::from_str(&result.content).expect("tool result should be json");
444 assert_eq!(parsed.query.as_deref(), Some("mode"));
445
446 let error = TuiHelpTool
447 .execute(json!({ "query": 7 }), &ctx)
448 .await
449 .expect_err("non-string query");
450 assert!(error.to_string().contains("`query` must be a string"));
451 }
452 }
453
453 lines RUST