返回 CodeWhale
hooks.rs
根目录 / crates / tui / src / commands / contract / hooks.rs
1 use super::SharedCommandHost;
2 use crate::tui::app::AppAction;
3 use codewhale_command_contract::hooks::{
4 CommandHooksContext, HookEntrySummary, HooksAction, HooksListSnapshot, ProjectHooksReview,
5 };
6 use codewhale_config::hooks::HookCondition;
7
8 pub(crate) struct HooksAdapter<'a> {
9 pub(super) host: SharedCommandHost<'a>,
10 }
11
12 impl TryFrom<HooksAction> for AppAction {
13 type Error = String;
14
15 fn try_from(action: HooksAction) -> Result<Self, String> {
16 Ok(match action {
17 HooksAction::OpenExtensionsTab => Self::OpenExtensions {
18 tab: crate::tui::views::extensions::ExtensionsTab::Hooks,
19 },
20 HooksAction::EditProjectHooks => Self::EditProjectHooks,
21 })
22 }
23 }
24
25 impl CommandHooksContext for HooksAdapter<'_> {
26 fn list_hooks(&self) -> HooksListSnapshot {
27 let app = self.host.app.borrow();
28 let config = app.hooks.config();
29 let hooks = config
30 .hooks
31 .iter()
32 .map(|hook| HookEntrySummary {
33 event_label: hook.event.as_str().to_string(),
34 label: codewhale_engine::hooks::sanitize_hook_label(hook.name.as_deref()),
35 background: hook.background,
36 honors_background: hook.event.honors_background(),
37 timeout_display: render_timeout(config, hook),
38 condition_summary: match &hook.condition {
39 None | Some(HookCondition::Always) => None,
40 Some(c) => Some(condition_summary(c)),
41 },
42 command_preview: preview_command(&hook.command, 60),
43 })
44 .collect();
45 HooksListSnapshot {
46 enabled: config.enabled,
47 hooks,
48 problem_summaries: problem_summaries(&config.problems),
49 }
50 }
51
52 fn review_project_hooks(&self) -> Result<ProjectHooksReview, String> {
53 let app = self.host.app.borrow();
54 let (authority, contents) =
55 codewhale_engine::hooks::authority::review_project_hooks(&app.workspace)?;
56 Ok(ProjectHooksReview {
57 digest: authority.digest,
58 sanitized_contents: codewhale_engine::hooks::sanitize_hook_text(
59 &contents,
60 contents.chars().count(),
61 ),
62 })
63 }
64
65 fn approve_project_hooks(&mut self, digest: &str) -> Result<(), String> {
66 let app = self.host.app.borrow();
67 codewhale_engine::hooks::authority::approve_project_hooks(&app.workspace, digest)
68 }
69
70 fn revoke_project_hooks(&mut self) -> Result<(), String> {
71 let app = self.host.app.borrow();
72 codewhale_runtime::config::save_workspace_hook_receipt(&app.workspace, "")
73 .map(|_| ())
74 .map_err(|_| "Could not revoke project hook approval".to_string())
75 }
76 }
77
78 fn render_timeout(
79 config: &codewhale_config::hooks::HooksConfig,
80 hook: &codewhale_config::hooks::Hook,
81 ) -> String {
82 let effective = config.effective_timeout_secs(hook);
83 if config.timeout_is_overridden() {
84 format!("{effective}s — `[hooks].default_timeout_secs` override")
85 } else {
86 format!("{effective}s")
87 }
88 }
89
90 fn problem_summaries(problems: &[codewhale_config::hooks::HookConfigProblem]) -> Vec<String> {
91 problems
92 .iter()
93 .map(codewhale_engine::hooks::config::problem_summary)
94 .collect()
95 }
96
97 fn condition_summary(condition: &HookCondition) -> String {
98 match condition {
99 HookCondition::Always => "always".to_string(),
100 HookCondition::ToolName { name } => format!("tool_name=`{}`", condition_value(name)),
101 HookCondition::ToolCategory { category } => {
102 format!("tool_category=`{}`", condition_value(category))
103 }
104 HookCondition::Mode { mode } => format!("mode=`{}`", condition_value(mode)),
105 HookCondition::ExitCode { code } => format!("exit_code={code}"),
106 HookCondition::All { conditions } => format!(
107 "all of [{}]",
108 conditions
109 .iter()
110 .map(condition_summary)
111 .collect::<Vec<_>>()
112 .join(", ")
113 ),
114 HookCondition::Any { conditions } => format!(
115 "any of [{}]",
116 conditions
117 .iter()
118 .map(condition_summary)
119 .collect::<Vec<_>>()
120 .join(", ")
121 ),
122 }
123 }
124
125 fn preview_command(command: &str, max_chars: usize) -> String {
126 let single_line = codewhale_engine::hooks::sanitize_hook_line(command, usize::MAX);
127 if single_line.chars().count() <= max_chars {
128 return single_line;
129 }
130 let mut out: String = single_line
131 .chars()
132 .take(max_chars.saturating_sub(1))
133 .collect();
134 out.push('…');
135 out
136 }
137
138 fn condition_value(value: &str) -> String {
139 codewhale_engine::hooks::sanitize_hook_line(
140 value,
141 codewhale_engine::hooks::HOOK_LABEL_MAX_CHARS,
142 )
143 }
144
145 #[cfg(test)]
146 mod tests {
147 use super::*;
148 use crate::tui::app::{App, AppAction, TuiOptions};
149 use codewhale_config::hooks::{Hook, HookCondition, HookEvent};
150 use codewhale_runtime::config::Config;
151 use tempfile::TempDir;
152
153 fn create_test_app(tmpdir: &TempDir) -> App {
154 let options = TuiOptions {
155 skills_dir: tmpdir.path().join("skills"),
156 memory_path: tmpdir.path().join("memory.md"),
157 mcp_config_path: tmpdir.path().join("mcp.json"),
158 ..crate::tui::test_support::test_tui_options(tmpdir.path())
159 };
160 App::new(options, &Config::default())
161 }
162
163 #[test]
164 fn bare_hooks_command_opens_unified_extensions_modal() {
165 let tmpdir = TempDir::new().unwrap();
166 let mut app = create_test_app(&tmpdir);
167
168 let result = crate::commands::execute("/hooks", &mut app);
169
170 assert!(matches!(
171 result.action,
172 Some(AppAction::OpenExtensions {
173 tab: crate::tui::views::extensions::ExtensionsTab::Hooks
174 })
175 ));
176 assert!(result.message.is_none());
177 }
178
179 #[test]
180 fn preview_command_truncates_to_cap() {
181 let cmd = "x".repeat(200);
182 assert_eq!(preview_command(&cmd, 10).chars().count(), 10);
183 assert!(preview_command(&cmd, 10).ends_with('…'));
184 }
185
186 #[test]
187 fn preview_command_strips_newlines() {
188 assert_eq!(
189 preview_command("line one\nline two", 50),
190 "line one line two"
191 );
192 }
193
194 #[test]
195 fn preview_command_defangs_control_characters() {
196 let preview = preview_command("echo \u{1b}[2Jhi\r\tthere\u{7}", 100);
197 assert!(!preview.contains('\u{1b}'), "{preview:?}");
198 assert!(!preview.contains('\r'), "{preview:?}");
199 assert!(!preview.contains('\u{7}'), "{preview:?}");
200 assert!(!preview.contains('\t'), "{preview:?}");
201 assert!(preview.contains("there"), "{preview:?}");
202 }
203
204 #[test]
205 fn hook_labels_are_bounded_and_defanged() {
206 let noisy = format!("\u{1b}[31mgate\n{}", "x".repeat(500));
207 let label = codewhale_engine::hooks::sanitize_hook_label(Some(&noisy));
208 assert!(!label.contains('\u{1b}'), "{label}");
209 assert!(!label.contains('\n'), "{label}");
210 assert!(
211 label.chars().count() <= codewhale_engine::hooks::HOOK_LABEL_MAX_CHARS + 16,
212 "{} chars",
213 label.chars().count()
214 );
215 assert_eq!(
216 codewhale_engine::hooks::sanitize_hook_label(Some(" ")),
217 "(unnamed)"
218 );
219 assert_eq!(
220 codewhale_engine::hooks::sanitize_hook_label(None),
221 "(unnamed)"
222 );
223 }
224
225 #[test]
226 fn condition_summary_defangs_operator_supplied_values() {
227 let rendered = condition_summary(&HookCondition::ToolName {
228 name: format!("\u{1b}[2Jexec_shell{}", "y".repeat(500)),
229 });
230 assert!(!rendered.contains('\u{1b}'), "{rendered}");
231 assert!(
232 rendered.chars().count() <= codewhale_engine::hooks::HOOK_LABEL_MAX_CHARS + 32,
233 "{} chars",
234 rendered.chars().count()
235 );
236 }
237
238 #[test]
239 fn listed_timeout_ignores_a_rejected_zero_override() {
240 let hook = Hook::new(HookEvent::SessionStart, "echo hi").with_timeout(90);
241 let zeroed = codewhale_config::hooks::HooksConfig {
242 enabled: true,
243 hooks: vec![hook.clone()],
244 default_timeout_secs: Some(0),
245 ..codewhale_config::hooks::HooksConfig::default()
246 };
247 assert_eq!(render_timeout(&zeroed, &hook), "90s");
248
249 let problems = zeroed.validate();
250 let rendered = problem_summaries(&problems).join("\n");
251 assert!(rendered.contains("`[hooks]` setting"), "{rendered}");
252 assert!(rendered.contains("default_timeout_secs = 0"), "{rendered}");
253 }
254
255 #[test]
256 fn preview_command_keeps_short_input_intact() {
257 assert_eq!(preview_command("echo hi", 50), "echo hi");
258 }
259
260 #[test]
261 fn condition_summary_renders_all_variants() {
262 assert_eq!(condition_summary(&HookCondition::Always), "always");
263 assert_eq!(
264 condition_summary(&HookCondition::ToolName {
265 name: "exec_shell".into()
266 }),
267 "tool_name=`exec_shell`"
268 );
269 assert_eq!(
270 condition_summary(&HookCondition::ToolCategory {
271 category: "shell".into()
272 }),
273 "tool_category=`shell`"
274 );
275 assert_eq!(
276 condition_summary(&HookCondition::Mode {
277 mode: "yolo".into()
278 }),
279 "mode=`yolo`"
280 );
281 assert_eq!(
282 condition_summary(&HookCondition::ExitCode { code: 1 }),
283 "exit_code=1"
284 );
285 assert_eq!(
286 condition_summary(&HookCondition::All {
287 conditions: vec![
288 HookCondition::ToolName {
289 name: "exec_shell".into()
290 },
291 HookCondition::Mode {
292 mode: "yolo".into()
293 }
294 ]
295 }),
296 "all of [tool_name=`exec_shell`, mode=`yolo`]"
297 );
298 }
299
300 #[test]
301 fn events_subcommand_lists_every_event_variant_in_documented_order() {
302 let tmpdir = TempDir::new().unwrap();
303 let mut app = create_test_app(&tmpdir);
304 let result = crate::commands::execute("/hooks events", &mut app);
305 let body = result.message.expect("non-empty body");
306 let positions: Vec<(usize, &str)> = [
307 "session_start",
308 "session_end",
309 "turn_end",
310 "message_submit",
311 "tool_call_before",
312 "tool_call_after",
313 "mode_change",
314 "on_error",
315 "subagent_spawn",
316 "subagent_complete",
317 "shell_env",
318 "session_idle",
319 "session_error",
320 "waiting_for_user",
321 "session_busy",
322 "pre_compact",
323 ]
324 .iter()
325 .map(|name| {
326 (
327 body.find(name).unwrap_or_else(|| {
328 panic!("event `{name}` missing from /hooks events output:\n{body}")
329 }),
330 *name,
331 )
332 })
333 .collect();
334 for window in positions.windows(2) {
335 let (a_pos, a_name) = window[0];
336 let (b_pos, b_name) = window[1];
337 assert!(
338 a_pos < b_pos,
339 "expected `{a_name}` before `{b_name}` in events listing"
340 );
341 }
342 assert!(body.contains("fires once when the TUI launches"));
343 assert!(
344 !body.contains("read-only observer"),
345 "stale read-only wording in events listing:\n{body}"
346 );
347 assert!(body.contains("can allow/deny/ask"));
348 assert!(body.contains("docs/HOOKS.md"));
349 }
350
351 #[test]
352 fn list_renders_hooks_grouped_by_event_and_notes_disabled_state() {
353 let cfg = codewhale_config::hooks::HooksConfig {
354 enabled: false,
355 hooks: vec![
356 Hook::new(HookEvent::SessionStart, "echo started").with_name("greet"),
357 Hook::new(HookEvent::ToolCallAfter, "notify-send done")
358 .with_condition(HookCondition::ToolName {
359 name: "exec_shell".into(),
360 })
361 .with_name("notify"),
362 ],
363 ..codewhale_config::hooks::HooksConfig::default()
364 };
365
366 let mut by_event: std::collections::BTreeMap<&str, Vec<&Hook>> =
367 std::collections::BTreeMap::new();
368 for h in &cfg.hooks {
369 by_event.entry(h.event.as_str()).or_default().push(h);
370 }
371 let events: Vec<&&str> = by_event.keys().collect();
372 assert_eq!(events, vec![&"session_start", &"tool_call_after"]);
373 }
374
375 #[test]
376 fn events_listing_states_scope_and_the_steering_allowlist() {
377 let tmpdir = TempDir::new().unwrap();
378 let mut app = create_test_app(&tmpdir);
379 let body = crate::commands::execute("/hooks events", &mut app)
380 .message
381 .expect("non-empty body");
382 assert!(body.contains("TUI runtime feature"), "{body}");
383 assert!(body.contains("codewhale exec"), "{body}");
384 assert!(body.contains("`message_submit`, `tool_call_before`, and `shell_env`"));
385 assert!(body.contains("can have any external side effect"), "{body}");
386 }
387
388 #[test]
389 fn events_listing_covers_every_runtime_event() {
390 let tmpdir = TempDir::new().unwrap();
391 let mut app = create_test_app(&tmpdir);
392 let body = crate::commands::execute("/hooks events", &mut app)
393 .message
394 .expect("non-empty body");
395 let names: Vec<&str> = body
396 .lines()
397 .filter_map(|line| line.strip_prefix(" - `"))
398 .map(|line| line.split('`').next().expect("listed event name"))
399 .collect();
400 assert_eq!(
401 names,
402 codewhale_config::hooks::ALL_HOOK_EVENTS.map(HookEvent::as_str)
403 );
404 }
405
406 #[test]
407 fn listed_timeout_is_the_one_the_runtime_will_apply() {
408 let hook = Hook::new(HookEvent::SessionStart, "echo hi").with_timeout(90);
409
410 let per_hook = codewhale_config::hooks::HooksConfig {
411 enabled: true,
412 hooks: vec![hook.clone()],
413 ..codewhale_config::hooks::HooksConfig::default()
414 };
415 assert_eq!(render_timeout(&per_hook, &hook), "90s");
416
417 let overridden = codewhale_config::hooks::HooksConfig {
418 enabled: true,
419 hooks: vec![hook.clone()],
420 default_timeout_secs: Some(5),
421 ..codewhale_config::hooks::HooksConfig::default()
422 };
423 let rendered = render_timeout(&overridden, &hook);
424 assert!(rendered.starts_with("5s"), "{rendered}");
425 assert!(!rendered.contains("90"), "{rendered}");
426 assert!(rendered.contains("default_timeout_secs"), "{rendered}");
427 }
428
429 #[test]
430 fn rendered_problems_name_the_hook_without_leaking_the_command() {
431 let problems = vec![
432 codewhale_config::hooks::HookConfigProblem {
433 name: Some("gate".to_string()),
434 event: Some(HookEvent::SessionStart),
435 detail: "condition can never match".to_string(),
436 rejected: true,
437 },
438 codewhale_config::hooks::HookConfigProblem {
439 name: None,
440 event: Some(HookEvent::ShellEnv),
441 detail: "`background = true` is not honored".to_string(),
442 rejected: false,
443 },
444 ];
445 let rendered = problem_summaries(&problems).join("\n");
446 assert!(rendered.contains("rejected: `session_start` hook `gate`"));
447 assert!(rendered.contains("warning: `shell_env` hook `(unnamed)`"));
448 assert!(!rendered.contains('$'), "{rendered}");
449 assert!(!rendered.contains('/'), "{rendered}");
450 }
451 }
452
452 lines RUST